@synnaxlabs/client 0.56.2 → 0.57.1
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/dist/client-DDACDVZ-.js +14505 -0
- package/dist/client-DDACDVZ-.js.map +1 -0
- package/dist/client.js +1128 -14876
- package/dist/client.js.map +1 -0
- package/dist/src/access/client.d.ts +10 -1
- package/dist/src/access/client.d.ts.map +1 -1
- package/dist/src/access/enforce.d.ts.map +1 -1
- package/dist/src/access/external.d.ts +1 -0
- package/dist/src/access/external.d.ts.map +1 -1
- package/dist/src/access/granted.d.ts +39 -0
- package/dist/src/access/granted.d.ts.map +1 -0
- package/dist/src/access/policy/client.d.ts +136 -147
- package/dist/src/access/policy/client.d.ts.map +1 -1
- package/dist/src/access/policy/types.gen.d.ts +15 -68
- package/dist/src/access/policy/types.gen.d.ts.map +1 -1
- package/dist/src/access/role/client.d.ts +77 -58
- package/dist/src/access/role/client.d.ts.map +1 -1
- package/dist/src/access/role/types.gen.d.ts +8 -14
- package/dist/src/access/role/types.gen.d.ts.map +1 -1
- package/dist/src/actions/actions.d.ts +5 -6
- package/dist/src/actions/actions.d.ts.map +1 -1
- package/dist/src/actions/controller.d.ts +194 -0
- package/dist/src/actions/controller.d.ts.map +1 -0
- package/dist/src/actions/external.d.ts +1 -0
- package/dist/src/actions/external.d.ts.map +1 -1
- package/dist/src/arc/actions.d.ts +575 -0
- package/dist/src/arc/actions.d.ts.map +1 -0
- package/dist/src/arc/actions.gen.d.ts +1439 -0
- package/dist/src/arc/actions.gen.d.ts.map +1 -0
- package/dist/src/arc/client.d.ts +97 -13
- package/dist/src/arc/client.d.ts.map +1 -1
- package/dist/src/arc/compiler/types.gen.d.ts +3 -3
- package/dist/src/arc/compiler/types.gen.d.ts.map +1 -1
- package/dist/src/arc/external.d.ts +2 -0
- package/dist/src/arc/external.d.ts.map +1 -1
- package/dist/src/arc/graph/types.gen.d.ts +45 -597
- package/dist/src/arc/graph/types.gen.d.ts.map +1 -1
- package/dist/src/arc/ir/index.d.ts +1 -1
- package/dist/src/arc/ir/index.d.ts.map +1 -1
- package/dist/src/arc/ir/ir.d.ts +2 -0
- package/dist/src/arc/ir/ir.d.ts.map +1 -0
- package/dist/src/arc/ir/types.gen.d.ts +58 -2807
- package/dist/src/arc/ir/types.gen.d.ts.map +1 -1
- package/dist/src/arc/module/types.gen.d.ts +18 -1090
- package/dist/src/arc/module/types.gen.d.ts.map +1 -1
- package/dist/src/arc/program/types.gen.d.ts +18 -1090
- package/dist/src/arc/program/types.gen.d.ts.map +1 -1
- package/dist/src/arc/text/types.gen.d.ts +54 -1
- package/dist/src/arc/text/types.gen.d.ts.map +1 -1
- package/dist/src/arc/types/types.gen.d.ts +35 -153
- package/dist/src/arc/types/types.gen.d.ts.map +1 -1
- package/dist/src/arc/types.gen.d.ts +98 -2278
- package/dist/src/arc/types.gen.d.ts.map +1 -1
- package/dist/src/auth/auth.d.ts +14 -2
- package/dist/src/auth/auth.d.ts.map +1 -1
- package/dist/src/channel/client.d.ts +113 -75
- package/dist/src/channel/client.d.ts.map +1 -1
- package/dist/src/channel/external.d.ts +0 -1
- package/dist/src/channel/external.d.ts.map +1 -1
- package/dist/src/channel/payload.d.ts +65 -56
- package/dist/src/channel/payload.d.ts.map +1 -1
- package/dist/src/channel/types.gen.d.ts +26 -73
- package/dist/src/channel/types.gen.d.ts.map +1 -1
- package/dist/src/channel/writer.d.ts +1 -3
- package/dist/src/channel/writer.d.ts.map +1 -1
- package/dist/src/client.d.ts +55 -27
- package/dist/src/client.d.ts.map +1 -1
- package/dist/src/connection/client.d.ts +146 -0
- package/dist/src/connection/client.d.ts.map +1 -0
- package/dist/src/connection/external.d.ts +3 -0
- package/dist/src/connection/external.d.ts.map +1 -0
- package/dist/src/connection/index.d.ts +1 -1
- package/dist/src/connection/index.d.ts.map +1 -1
- package/dist/src/connection/status.d.ts +252 -0
- package/dist/src/connection/status.d.ts.map +1 -0
- package/dist/src/control/client.d.ts +31 -7
- package/dist/src/control/client.d.ts.map +1 -1
- package/dist/src/control/state.d.ts +47 -16
- package/dist/src/control/state.d.ts.map +1 -1
- package/dist/src/device/client.d.ts +59 -17
- package/dist/src/device/client.d.ts.map +1 -1
- package/dist/src/device/types.gen.d.ts +17 -67
- package/dist/src/device/types.gen.d.ts.map +1 -1
- package/dist/src/errors.d.ts +17 -20
- package/dist/src/errors.d.ts.map +1 -1
- package/dist/src/ethercat/external.d.ts +2 -0
- package/dist/src/ethercat/external.d.ts.map +1 -0
- package/dist/src/ethercat/index.d.ts +2 -0
- package/dist/src/ethercat/index.d.ts.map +1 -0
- package/dist/src/ethercat/types.gen.d.ts +243 -0
- package/dist/src/ethercat/types.gen.d.ts.map +1 -0
- package/dist/src/framer/adapter.d.ts +8 -5
- package/dist/src/framer/adapter.d.ts.map +1 -1
- package/dist/src/framer/benchutil.d.ts +19 -0
- package/dist/src/framer/benchutil.d.ts.map +1 -0
- package/dist/src/framer/cache/cache.d.ts +38 -0
- package/dist/src/framer/cache/cache.d.ts.map +1 -0
- package/dist/src/framer/cache/dynamic.d.ts +91 -0
- package/dist/src/framer/cache/dynamic.d.ts.map +1 -0
- package/dist/src/framer/cache/reader.d.ts +57 -0
- package/dist/src/framer/cache/reader.d.ts.map +1 -0
- package/dist/src/framer/cache/static.d.ts +66 -0
- package/dist/src/framer/cache/static.d.ts.map +1 -0
- package/dist/src/framer/cache/streamer.d.ts +86 -0
- package/dist/src/framer/cache/streamer.d.ts.map +1 -0
- package/dist/src/framer/cache/transform.d.ts +18 -0
- package/dist/src/framer/cache/transform.d.ts.map +1 -0
- package/dist/src/framer/cache/unary.d.ts +39 -0
- package/dist/src/framer/cache/unary.d.ts.map +1 -0
- package/dist/src/framer/client.d.ts +35 -14
- package/dist/src/framer/client.d.ts.map +1 -1
- package/dist/src/framer/codec.d.ts.map +1 -1
- package/dist/src/framer/deleter.d.ts +3 -2
- package/dist/src/framer/deleter.d.ts.map +1 -1
- package/dist/src/framer/external.d.ts +6 -0
- package/dist/src/framer/external.d.ts.map +1 -1
- package/dist/src/framer/feed.d.ts +40 -0
- package/dist/src/framer/feed.d.ts.map +1 -0
- package/dist/src/framer/frame.d.ts +16 -20
- package/dist/src/framer/frame.d.ts.map +1 -1
- package/dist/src/framer/hardened.d.ts +70 -0
- package/dist/src/framer/hardened.d.ts.map +1 -0
- package/dist/src/framer/iterator.d.ts +36 -43
- package/dist/src/framer/iterator.d.ts.map +1 -1
- package/dist/src/framer/reader.d.ts +3 -2
- package/dist/src/framer/reader.d.ts.map +1 -1
- package/dist/src/framer/streamer.d.ts +132 -205
- package/dist/src/framer/streamer.d.ts.map +1 -1
- package/dist/src/framer/writer.d.ts +130 -161
- package/dist/src/framer/writer.d.ts.map +1 -1
- package/dist/src/group/client.d.ts +66 -9
- package/dist/src/group/client.d.ts.map +1 -1
- package/dist/src/group/types.gen.d.ts +2 -2
- package/dist/src/http/external.d.ts +2 -0
- package/dist/src/http/external.d.ts.map +1 -0
- package/dist/src/http/index.d.ts +2 -0
- package/dist/src/http/index.d.ts.map +1 -0
- package/dist/src/http/types.gen.d.ts +451 -0
- package/dist/src/http/types.gen.d.ts.map +1 -0
- package/dist/src/imex/client.d.ts +88 -0
- package/dist/src/imex/client.d.ts.map +1 -0
- package/dist/src/imex/index.d.ts +2 -0
- package/dist/src/imex/index.d.ts.map +1 -0
- package/dist/src/index.d.ts +18 -5
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/label/client.d.ts +55 -36
- package/dist/src/label/client.d.ts.map +1 -1
- package/dist/src/label/external.d.ts +2 -0
- package/dist/src/label/external.d.ts.map +1 -1
- package/dist/src/label/payload.d.ts +4 -46
- package/dist/src/label/payload.d.ts.map +1 -1
- package/dist/src/label/store.d.ts +8 -0
- package/dist/src/label/store.d.ts.map +1 -0
- package/dist/src/label/types.gen.d.ts +45 -0
- package/dist/src/label/types.gen.d.ts.map +1 -0
- package/dist/src/labjack/external.d.ts +2 -0
- package/dist/src/labjack/external.d.ts.map +1 -0
- package/dist/src/labjack/index.d.ts +2 -0
- package/dist/src/labjack/index.d.ts.map +1 -0
- package/dist/src/labjack/types.gen.d.ts +442 -0
- package/dist/src/labjack/types.gen.d.ts.map +1 -0
- package/dist/src/lineplot/actions.d.ts +914 -0
- package/dist/src/lineplot/actions.d.ts.map +1 -0
- package/dist/src/lineplot/actions.gen.d.ts +4208 -0
- package/dist/src/lineplot/actions.gen.d.ts.map +1 -0
- package/dist/src/lineplot/client.d.ts +66 -16
- package/dist/src/lineplot/client.d.ts.map +1 -1
- package/dist/src/lineplot/external.d.ts +3 -0
- package/dist/src/lineplot/external.d.ts.map +1 -1
- package/dist/src/lineplot/line.d.ts +16 -0
- package/dist/src/lineplot/line.d.ts.map +1 -0
- package/dist/src/lineplot/types.gen.d.ts +837 -14
- package/dist/src/lineplot/types.gen.d.ts.map +1 -1
- package/dist/src/log/actions.d.ts +271 -0
- package/dist/src/log/actions.d.ts.map +1 -0
- package/dist/src/log/actions.gen.d.ts +1529 -0
- package/dist/src/log/actions.gen.d.ts.map +1 -0
- package/dist/src/log/client.d.ts +66 -16
- package/dist/src/log/client.d.ts.map +1 -1
- package/dist/src/log/external.d.ts +2 -0
- package/dist/src/log/external.d.ts.map +1 -1
- package/dist/src/log/types.gen.d.ts +139 -14
- package/dist/src/log/types.gen.d.ts.map +1 -1
- package/dist/src/modbus/external.d.ts +2 -0
- package/dist/src/modbus/external.d.ts.map +1 -0
- package/dist/src/modbus/index.d.ts +2 -0
- package/dist/src/modbus/index.d.ts.map +1 -0
- package/dist/src/modbus/types.gen.d.ts +280 -0
- package/dist/src/modbus/types.gen.d.ts.map +1 -0
- package/dist/src/ni/external.d.ts +2 -0
- package/dist/src/ni/external.d.ts.map +1 -0
- package/dist/src/ni/index.d.ts +2 -0
- package/dist/src/ni/index.d.ts.map +1 -0
- package/dist/src/ni/types.gen.d.ts +21029 -0
- package/dist/src/ni/types.gen.d.ts.map +1 -0
- package/dist/src/node/index.d.ts +2 -0
- package/dist/src/node/index.d.ts.map +1 -0
- package/dist/src/node/types.gen.d.ts +4 -0
- package/dist/src/node/types.gen.d.ts.map +1 -0
- package/dist/src/ontology/client.d.ts +314 -67
- package/dist/src/ontology/client.d.ts.map +1 -1
- package/dist/src/ontology/external.d.ts +1 -0
- package/dist/src/ontology/external.d.ts.map +1 -1
- package/dist/src/ontology/payload.d.ts +60 -18
- package/dist/src/ontology/payload.d.ts.map +1 -1
- package/dist/src/ontology/store.d.ts +32 -0
- package/dist/src/ontology/store.d.ts.map +1 -0
- package/dist/src/ontology/types.gen.d.ts +3 -2
- package/dist/src/ontology/types.gen.d.ts.map +1 -1
- package/dist/src/ontology/writer.d.ts +16 -10
- package/dist/src/ontology/writer.d.ts.map +1 -1
- package/dist/src/opcua/external.d.ts +2 -0
- package/dist/src/opcua/external.d.ts.map +1 -0
- package/dist/src/opcua/index.d.ts +2 -0
- package/dist/src/opcua/index.d.ts.map +1 -0
- package/dist/src/opcua/types.gen.d.ts +82 -0
- package/dist/src/opcua/types.gen.d.ts.map +1 -0
- package/dist/src/pagerduty/external.d.ts +2 -0
- package/dist/src/pagerduty/external.d.ts.map +1 -0
- package/dist/src/pagerduty/index.d.ts +2 -0
- package/dist/src/pagerduty/index.d.ts.map +1 -0
- package/dist/src/pagerduty/types.gen.d.ts +30 -0
- package/dist/src/pagerduty/types.gen.d.ts.map +1 -0
- package/dist/src/panel/actions.d.ts +273 -0
- package/dist/src/panel/actions.d.ts.map +1 -0
- package/dist/src/panel/actions.gen.d.ts +1255 -0
- package/dist/src/panel/actions.gen.d.ts.map +1 -0
- package/dist/src/panel/client.d.ts +148 -0
- package/dist/src/panel/client.d.ts.map +1 -0
- package/dist/src/panel/external.d.ts +6 -0
- package/dist/src/panel/external.d.ts.map +1 -0
- package/dist/src/panel/index.d.ts +2 -0
- package/dist/src/panel/index.d.ts.map +1 -0
- package/dist/src/panel/tree.d.ts +50 -0
- package/dist/src/panel/tree.d.ts.map +1 -0
- package/dist/src/panel/types.gen.d.ts +370 -0
- package/dist/src/panel/types.gen.d.ts.map +1 -0
- package/dist/src/project/client.d.ts +89 -0
- package/dist/src/project/client.d.ts.map +1 -0
- package/dist/src/project/external.d.ts.map +1 -0
- package/dist/src/project/index.d.ts +2 -0
- package/dist/src/project/index.d.ts.map +1 -0
- package/dist/src/project/types.gen.d.ts +27 -0
- package/dist/src/project/types.gen.d.ts.map +1 -0
- package/dist/src/query/cache.d.ts +132 -0
- package/dist/src/query/cache.d.ts.map +1 -0
- package/dist/src/query/deleted.d.ts +20 -0
- package/dist/src/query/deleted.d.ts.map +1 -0
- package/dist/src/query/derived.d.ts +33 -0
- package/dist/src/query/derived.d.ts.map +1 -0
- package/dist/src/query/external.d.ts +10 -0
- package/dist/src/query/external.d.ts.map +1 -0
- package/dist/src/query/index.d.ts +2 -0
- package/dist/src/query/index.d.ts.map +1 -0
- package/dist/src/query/query.d.ts +235 -0
- package/dist/src/query/query.d.ts.map +1 -0
- package/dist/src/query/retriever.d.ts +135 -0
- package/dist/src/query/retriever.d.ts.map +1 -0
- package/dist/src/query/streamer.d.ts +67 -0
- package/dist/src/query/streamer.d.ts.map +1 -0
- package/dist/src/query/table.d.ts +219 -0
- package/dist/src/query/table.d.ts.map +1 -0
- package/dist/src/query/types.d.ts +35 -0
- package/dist/src/query/types.d.ts.map +1 -0
- package/dist/src/query/write.d.ts +21 -0
- package/dist/src/query/write.d.ts.map +1 -0
- package/dist/src/rack/client.d.ts +58 -20
- package/dist/src/rack/client.d.ts.map +1 -1
- package/dist/src/rack/types.gen.d.ts +11 -12
- package/dist/src/rack/types.gen.d.ts.map +1 -1
- package/dist/src/range/alias/types.gen.d.ts +2 -3
- package/dist/src/range/alias/types.gen.d.ts.map +1 -1
- package/dist/src/ranger/client.d.ts +138 -27
- package/dist/src/ranger/client.d.ts.map +1 -1
- package/dist/src/ranger/kv/client.d.ts +7 -4
- package/dist/src/ranger/kv/client.d.ts.map +1 -1
- package/dist/src/ranger/payload.d.ts +3 -0
- package/dist/src/ranger/payload.d.ts.map +1 -1
- package/dist/src/ranger/types.gen.d.ts +45 -101
- package/dist/src/ranger/types.gen.d.ts.map +1 -1
- package/dist/src/ranger/writer.d.ts +2 -74
- package/dist/src/ranger/writer.d.ts.map +1 -1
- package/dist/src/schematic/actions.d.ts +90 -33
- package/dist/src/schematic/actions.d.ts.map +1 -1
- package/dist/src/schematic/actions.gen.d.ts +207 -114
- package/dist/src/schematic/actions.gen.d.ts.map +1 -1
- package/dist/src/schematic/client.d.ts +70 -68
- package/dist/src/schematic/client.d.ts.map +1 -1
- package/dist/src/schematic/symbol/client.d.ts +133 -27
- package/dist/src/schematic/symbol/client.d.ts.map +1 -1
- package/dist/src/schematic/symbol/types.gen.d.ts +258 -153
- package/dist/src/schematic/symbol/types.gen.d.ts.map +1 -1
- package/dist/src/schematic/types.gen.d.ts +17 -96
- package/dist/src/schematic/types.gen.d.ts.map +1 -1
- package/dist/src/status/client.d.ts +69 -14
- package/dist/src/status/client.d.ts.map +1 -1
- package/dist/src/status/external.d.ts +2 -0
- package/dist/src/status/external.d.ts.map +1 -1
- package/dist/src/status/payload.d.ts +2 -36
- package/dist/src/status/payload.d.ts.map +1 -1
- package/dist/src/status/status.d.ts +65 -0
- package/dist/src/status/status.d.ts.map +1 -0
- package/dist/src/status/types.gen.d.ts +58 -0
- package/dist/src/status/types.gen.d.ts.map +1 -0
- package/dist/src/table/actions.d.ts +72 -13
- package/dist/src/table/actions.d.ts.map +1 -1
- package/dist/src/table/actions.gen.d.ts +221 -137
- package/dist/src/table/actions.gen.d.ts.map +1 -1
- package/dist/src/table/client.d.ts +64 -40
- package/dist/src/table/client.d.ts.map +1 -1
- package/dist/src/table/types.gen.d.ts +20 -55
- package/dist/src/table/types.gen.d.ts.map +1 -1
- package/dist/src/task/client.d.ts +149 -28
- package/dist/src/task/client.d.ts.map +1 -1
- package/dist/src/task/types.gen.d.ts +71 -89
- package/dist/src/task/types.gen.d.ts.map +1 -1
- package/dist/src/testutil/access.d.ts +27 -1
- package/dist/src/testutil/access.d.ts.map +1 -1
- package/dist/src/testutil/channels.d.ts +2 -0
- package/dist/src/testutil/channels.d.ts.map +1 -1
- package/dist/src/testutil/client.d.ts +5 -0
- package/dist/src/testutil/client.d.ts.map +1 -1
- package/dist/src/testutil/connection.d.ts +10 -0
- package/dist/src/testutil/connection.d.ts.map +1 -0
- package/dist/src/testutil/index.d.ts +9 -0
- package/dist/src/testutil/index.d.ts.map +1 -0
- package/dist/src/testutil/panels.d.ts +8 -0
- package/dist/src/testutil/panels.d.ts.map +1 -0
- package/dist/src/testutil/proxy.d.ts +29 -0
- package/dist/src/testutil/proxy.d.ts.map +1 -0
- package/dist/src/testutil/query.d.ts +7 -0
- package/dist/src/testutil/query.d.ts.map +1 -0
- package/dist/src/testutil/telem.d.ts +4 -0
- package/dist/src/testutil/telem.d.ts.map +1 -1
- package/dist/src/transport.d.ts +10 -4
- package/dist/src/transport.d.ts.map +1 -1
- package/dist/src/user/client.d.ts +29 -28
- package/dist/src/user/client.d.ts.map +1 -1
- package/dist/src/user/external.d.ts +1 -1
- package/dist/src/user/external.d.ts.map +1 -1
- package/dist/src/user/types.gen.d.ts +4 -4
- package/dist/src/util/retrieve.d.ts +2 -2
- package/dist/src/util/retrieve.d.ts.map +1 -1
- package/dist/src/util/telem.d.ts.map +1 -1
- package/dist/src/view/client.d.ts +30 -14
- package/dist/src/view/client.d.ts.map +1 -1
- package/dist/src/view/types.gen.d.ts +7 -15
- package/dist/src/view/types.gen.d.ts.map +1 -1
- package/dist/testutil.js +189 -0
- package/dist/testutil.js.map +1 -0
- package/package.json +39 -16
- package/src/access/client.ts +14 -3
- package/src/access/enforce.ts +0 -3
- package/src/access/external.ts +1 -0
- package/src/access/granted.ts +114 -0
- package/src/access/policy/client.ts +135 -43
- package/src/access/policy/types.gen.ts +9 -11
- package/src/access/role/client.ts +160 -38
- package/src/access/role/types.gen.ts +8 -12
- package/src/actions/actions.ts +5 -6
- package/src/actions/controller.ts +626 -0
- package/src/actions/external.ts +11 -0
- package/src/arc/actions.gen.ts +313 -0
- package/src/arc/actions.ts +192 -0
- package/src/arc/client.ts +424 -41
- package/src/arc/compiler/types.gen.ts +5 -6
- package/src/arc/external.ts +2 -0
- package/src/arc/graph/types.gen.ts +24 -22
- package/src/arc/ir/index.ts +1 -1
- package/{eslint.config.ts → src/arc/ir/ir.ts} +1 -4
- package/src/arc/ir/types.gen.ts +42 -41
- package/src/arc/text/types.gen.ts +21 -2
- package/src/arc/types/types.gen.ts +40 -32
- package/src/arc/types.gen.ts +31 -29
- package/src/auth/auth.ts +40 -8
- package/src/channel/client.ts +529 -132
- package/src/channel/external.ts +0 -1
- package/src/channel/payload.ts +30 -3
- package/src/channel/types.gen.ts +37 -48
- package/src/channel/writer.ts +2 -11
- package/src/client.ts +215 -91
- package/src/connection/client.ts +495 -0
- package/src/connection/external.ts +34 -0
- package/src/connection/index.ts +1 -1
- package/src/connection/status.ts +442 -0
- package/src/control/client.ts +84 -12
- package/src/control/state.ts +17 -36
- package/src/device/client.ts +293 -41
- package/src/device/types.gen.ts +15 -26
- package/src/errors.ts +45 -22
- package/src/{workspace → ethercat}/external.ts +1 -2
- package/src/{workspace → ethercat}/index.ts +1 -1
- package/src/ethercat/types.gen.ts +151 -0
- package/src/framer/adapter.ts +60 -37
- package/src/framer/benchutil.ts +67 -0
- package/src/framer/cache/cache.ts +115 -0
- package/src/framer/cache/dynamic.ts +340 -0
- package/src/framer/cache/reader.ts +231 -0
- package/src/framer/cache/static.ts +215 -0
- package/src/framer/cache/streamer.ts +391 -0
- package/src/framer/cache/transform.ts +31 -0
- package/src/framer/cache/unary.ts +108 -0
- package/src/framer/client.ts +71 -43
- package/src/framer/codec.ts +55 -18
- package/src/framer/deleter.ts +4 -6
- package/src/framer/external.ts +10 -0
- package/src/framer/feed.ts +108 -0
- package/src/framer/frame.ts +13 -23
- package/src/framer/hardened.ts +283 -0
- package/src/framer/iterator.ts +31 -42
- package/src/framer/reader.ts +11 -11
- package/src/framer/streamer.ts +18 -178
- package/src/framer/writer.ts +39 -59
- package/src/group/client.ts +158 -23
- package/src/http/external.ts +10 -0
- package/src/{cluster → http}/index.ts +1 -1
- package/src/http/types.gen.ts +245 -0
- package/src/imex/client.ts +125 -0
- package/src/imex/index.ts +10 -0
- package/src/index.ts +19 -6
- package/src/label/client.ts +193 -54
- package/src/label/external.ts +2 -0
- package/src/label/payload.ts +4 -9
- package/src/label/store.ts +28 -0
- package/src/label/types.gen.ts +31 -0
- package/src/labjack/external.ts +10 -0
- package/src/labjack/index.ts +10 -0
- package/src/labjack/types.gen.ts +251 -0
- package/src/lineplot/actions.gen.ts +880 -0
- package/src/lineplot/actions.ts +535 -0
- package/src/lineplot/client.ts +224 -52
- package/src/lineplot/external.ts +3 -0
- package/src/lineplot/line.ts +80 -0
- package/src/lineplot/types.gen.ts +225 -12
- package/src/log/actions.gen.ts +474 -0
- package/src/log/actions.ts +242 -0
- package/src/log/client.ts +223 -52
- package/src/log/external.ts +2 -0
- package/src/log/types.gen.ts +45 -14
- package/src/modbus/external.ts +10 -0
- package/src/modbus/index.ts +10 -0
- package/src/modbus/types.gen.ts +185 -0
- package/src/ni/external.ts +10 -0
- package/src/ni/index.ts +10 -0
- package/src/ni/types.gen.ts +1632 -0
- package/src/node/index.ts +10 -0
- package/src/{cluster → node}/types.gen.ts +2 -2
- package/src/ontology/client.ts +408 -99
- package/src/ontology/external.ts +7 -0
- package/src/ontology/payload.ts +48 -7
- package/src/ontology/store.ts +83 -0
- package/src/ontology/types.gen.ts +2 -1
- package/src/ontology/writer.ts +1 -0
- package/src/opcua/external.ts +10 -0
- package/src/opcua/index.ts +10 -0
- package/src/opcua/types.gen.ts +65 -0
- package/src/pagerduty/external.ts +10 -0
- package/src/pagerduty/index.ts +10 -0
- package/src/pagerduty/types.gen.ts +41 -0
- package/src/panel/actions.gen.ts +267 -0
- package/src/panel/actions.ts +357 -0
- package/src/panel/client.ts +327 -0
- package/src/panel/external.ts +14 -0
- package/src/panel/index.ts +10 -0
- package/src/panel/tree.ts +163 -0
- package/src/panel/types.gen.ts +164 -0
- package/src/project/client.ts +273 -0
- package/src/project/external.ts +11 -0
- package/src/project/index.ts +10 -0
- package/src/project/types.gen.ts +40 -0
- package/src/query/cache.ts +326 -0
- package/src/query/deleted.ts +38 -0
- package/src/query/derived.ts +101 -0
- package/src/query/external.ts +51 -0
- package/src/query/index.ts +10 -0
- package/src/query/query.ts +865 -0
- package/src/query/retriever.ts +308 -0
- package/src/query/streamer.ts +207 -0
- package/src/query/table.ts +625 -0
- package/src/query/types.ts +54 -0
- package/src/query/write.ts +42 -0
- package/src/rack/client.ts +233 -45
- package/src/rack/types.gen.ts +15 -16
- package/src/range/alias/types.gen.ts +2 -3
- package/src/ranger/client.ts +581 -70
- package/src/ranger/kv/client.ts +52 -21
- package/src/ranger/payload.ts +3 -0
- package/src/ranger/types.gen.ts +21 -23
- package/src/ranger/writer.ts +4 -8
- package/src/schematic/actions.gen.ts +62 -53
- package/src/schematic/actions.ts +44 -42
- package/src/schematic/client.ts +226 -70
- package/src/schematic/symbol/client.ts +277 -48
- package/src/schematic/symbol/types.gen.ts +22 -34
- package/src/schematic/types.gen.ts +22 -29
- package/src/status/client.ts +321 -44
- package/src/status/external.ts +2 -0
- package/src/status/payload.ts +1 -23
- package/src/status/status.ts +241 -0
- package/src/status/types.gen.ts +108 -0
- package/src/table/actions.gen.ts +96 -63
- package/src/table/actions.ts +44 -19
- package/src/table/client.ts +220 -56
- package/src/table/types.gen.ts +24 -31
- package/src/task/client.ts +580 -101
- package/src/task/types.gen.ts +68 -75
- package/src/testutil/access.ts +102 -6
- package/src/testutil/channels.ts +29 -0
- package/src/testutil/client.ts +27 -2
- package/src/testutil/connection.ts +47 -0
- package/src/testutil/index.ts +17 -0
- package/src/testutil/panels.ts +26 -0
- package/src/testutil/proxy.ts +106 -0
- package/src/testutil/query.ts +28 -0
- package/src/testutil/telem.ts +17 -1
- package/src/transport.ts +18 -7
- package/src/user/client.ts +165 -64
- package/src/user/external.ts +1 -1
- package/src/user/types.gen.ts +5 -5
- package/src/util/retrieve.ts +4 -4
- package/src/util/telem.ts +0 -1
- package/src/view/client.ts +120 -37
- package/src/view/types.gen.ts +8 -11
- package/.turbo/turbo-build.log +0 -20
- package/.vscode/settings.json +0 -3
- package/CONTRIBUTING.md +0 -47
- package/dist/client.cjs +0 -118
- package/dist/eslint.config.d.ts +0 -4
- package/dist/eslint.config.d.ts.map +0 -1
- package/dist/src/access/enforce.spec.d.ts +0 -2
- package/dist/src/access/enforce.spec.d.ts.map +0 -1
- package/dist/src/access/policy/access.spec.d.ts +0 -2
- package/dist/src/access/policy/access.spec.d.ts.map +0 -1
- package/dist/src/access/role/role.spec.d.ts +0 -2
- package/dist/src/access/role/role.spec.d.ts.map +0 -1
- package/dist/src/actions/actions.spec.d.ts +0 -2
- package/dist/src/actions/actions.spec.d.ts.map +0 -1
- package/dist/src/arc/access.spec.d.ts +0 -2
- package/dist/src/arc/access.spec.d.ts.map +0 -1
- package/dist/src/arc/arc.spec.d.ts +0 -2
- package/dist/src/arc/arc.spec.d.ts.map +0 -1
- package/dist/src/arc/lsp.spec.d.ts +0 -2
- package/dist/src/arc/lsp.spec.d.ts.map +0 -1
- package/dist/src/auth/auth.spec.d.ts +0 -2
- package/dist/src/auth/auth.spec.d.ts.map +0 -1
- package/dist/src/channel/access.spec.d.ts +0 -2
- package/dist/src/channel/access.spec.d.ts.map +0 -1
- package/dist/src/channel/batchRetriever.spec.d.ts +0 -2
- package/dist/src/channel/batchRetriever.spec.d.ts.map +0 -1
- package/dist/src/channel/channel.spec.d.ts +0 -2
- package/dist/src/channel/channel.spec.d.ts.map +0 -1
- package/dist/src/channel/payload.spec.d.ts +0 -2
- package/dist/src/channel/payload.spec.d.ts.map +0 -1
- package/dist/src/channel/retriever.d.ts +0 -64
- package/dist/src/channel/retriever.d.ts.map +0 -1
- package/dist/src/cluster/index.d.ts +0 -2
- package/dist/src/cluster/index.d.ts.map +0 -1
- package/dist/src/cluster/types.gen.d.ts +0 -4
- package/dist/src/cluster/types.gen.d.ts.map +0 -1
- package/dist/src/connection/checker.d.ts +0 -86
- package/dist/src/connection/checker.d.ts.map +0 -1
- package/dist/src/connection/connection.spec.d.ts +0 -2
- package/dist/src/connection/connection.spec.d.ts.map +0 -1
- package/dist/src/connection.spec.d.ts +0 -2
- package/dist/src/connection.spec.d.ts.map +0 -1
- package/dist/src/control/state.spec.d.ts +0 -2
- package/dist/src/control/state.spec.d.ts.map +0 -1
- package/dist/src/device/access.spec.d.ts +0 -2
- package/dist/src/device/access.spec.d.ts.map +0 -1
- package/dist/src/device/device.spec.d.ts +0 -2
- package/dist/src/device/device.spec.d.ts.map +0 -1
- package/dist/src/device/payload.spec.d.ts +0 -2
- package/dist/src/device/payload.spec.d.ts.map +0 -1
- package/dist/src/errors.spec.d.ts +0 -2
- package/dist/src/errors.spec.d.ts.map +0 -1
- package/dist/src/framer/adapter.spec.d.ts +0 -2
- package/dist/src/framer/adapter.spec.d.ts.map +0 -1
- package/dist/src/framer/client.spec.d.ts +0 -2
- package/dist/src/framer/client.spec.d.ts.map +0 -1
- package/dist/src/framer/codec.spec.d.ts +0 -2
- package/dist/src/framer/codec.spec.d.ts.map +0 -1
- package/dist/src/framer/deleter.spec.d.ts +0 -2
- package/dist/src/framer/deleter.spec.d.ts.map +0 -1
- package/dist/src/framer/frame.spec.d.ts +0 -2
- package/dist/src/framer/frame.spec.d.ts.map +0 -1
- package/dist/src/framer/iterator.spec.d.ts +0 -2
- package/dist/src/framer/iterator.spec.d.ts.map +0 -1
- package/dist/src/framer/reader.spec.d.ts +0 -2
- package/dist/src/framer/reader.spec.d.ts.map +0 -1
- package/dist/src/framer/streamer.spec.d.ts +0 -2
- package/dist/src/framer/streamer.spec.d.ts.map +0 -1
- package/dist/src/framer/writer.spec.d.ts +0 -2
- package/dist/src/framer/writer.spec.d.ts.map +0 -1
- package/dist/src/group/access.spec.d.ts +0 -2
- package/dist/src/group/access.spec.d.ts.map +0 -1
- package/dist/src/group/group.spec.d.ts +0 -2
- package/dist/src/group/group.spec.d.ts.map +0 -1
- package/dist/src/label/access.spec.d.ts +0 -2
- package/dist/src/label/access.spec.d.ts.map +0 -1
- package/dist/src/label/label.spec.d.ts +0 -2
- package/dist/src/label/label.spec.d.ts.map +0 -1
- package/dist/src/lineplot/access.spec.d.ts +0 -2
- package/dist/src/lineplot/access.spec.d.ts.map +0 -1
- package/dist/src/lineplot/lineplot.spec.d.ts +0 -2
- package/dist/src/lineplot/lineplot.spec.d.ts.map +0 -1
- package/dist/src/log/access.spec.d.ts +0 -2
- package/dist/src/log/access.spec.d.ts.map +0 -1
- package/dist/src/log/log.spec.d.ts +0 -2
- package/dist/src/log/log.spec.d.ts.map +0 -1
- package/dist/src/ontology/ontology.spec.d.ts +0 -2
- package/dist/src/ontology/ontology.spec.d.ts.map +0 -1
- package/dist/src/rack/access.spec.d.ts +0 -2
- package/dist/src/rack/access.spec.d.ts.map +0 -1
- package/dist/src/rack/rack.spec.d.ts +0 -2
- package/dist/src/rack/rack.spec.d.ts.map +0 -1
- package/dist/src/ranger/access.spec.d.ts +0 -2
- package/dist/src/ranger/access.spec.d.ts.map +0 -1
- package/dist/src/ranger/alias/payload.spec.d.ts +0 -2
- package/dist/src/ranger/alias/payload.spec.d.ts.map +0 -1
- package/dist/src/ranger/ranger.spec.d.ts +0 -2
- package/dist/src/ranger/ranger.spec.d.ts.map +0 -1
- package/dist/src/schematic/access.spec.d.ts +0 -2
- package/dist/src/schematic/access.spec.d.ts.map +0 -1
- package/dist/src/schematic/actions.spec.d.ts +0 -2
- package/dist/src/schematic/actions.spec.d.ts.map +0 -1
- package/dist/src/schematic/schematic.spec.d.ts +0 -2
- package/dist/src/schematic/schematic.spec.d.ts.map +0 -1
- package/dist/src/schematic/symbol/access.spec.d.ts +0 -2
- package/dist/src/schematic/symbol/access.spec.d.ts.map +0 -1
- package/dist/src/schematic/symbol/client.spec.d.ts +0 -2
- package/dist/src/schematic/symbol/client.spec.d.ts.map +0 -1
- package/dist/src/status/access.spec.d.ts +0 -2
- package/dist/src/status/access.spec.d.ts.map +0 -1
- package/dist/src/status/status.spec.d.ts +0 -2
- package/dist/src/status/status.spec.d.ts.map +0 -1
- package/dist/src/table/access.spec.d.ts +0 -2
- package/dist/src/table/access.spec.d.ts.map +0 -1
- package/dist/src/table/table.spec.d.ts +0 -2
- package/dist/src/table/table.spec.d.ts.map +0 -1
- package/dist/src/task/access.spec.d.ts +0 -2
- package/dist/src/task/access.spec.d.ts.map +0 -1
- package/dist/src/task/payload.spec.d.ts +0 -2
- package/dist/src/task/payload.spec.d.ts.map +0 -1
- package/dist/src/task/task.spec.d.ts +0 -2
- package/dist/src/task/task.spec.d.ts.map +0 -1
- package/dist/src/user/access.spec.d.ts +0 -2
- package/dist/src/user/access.spec.d.ts.map +0 -1
- package/dist/src/user/user.spec.d.ts +0 -2
- package/dist/src/user/user.spec.d.ts.map +0 -1
- package/dist/src/util/retrieve.spec.d.ts +0 -2
- package/dist/src/util/retrieve.spec.d.ts.map +0 -1
- package/dist/src/view/view.spec.d.ts +0 -2
- package/dist/src/view/view.spec.d.ts.map +0 -1
- package/dist/src/workspace/access.spec.d.ts +0 -2
- package/dist/src/workspace/access.spec.d.ts.map +0 -1
- package/dist/src/workspace/client.d.ts +0 -36
- package/dist/src/workspace/client.d.ts.map +0 -1
- package/dist/src/workspace/external.d.ts.map +0 -1
- package/dist/src/workspace/index.d.ts +0 -2
- package/dist/src/workspace/index.d.ts.map +0 -1
- package/dist/src/workspace/types.gen.d.ts +0 -34
- package/dist/src/workspace/types.gen.d.ts.map +0 -1
- package/dist/src/workspace/workspace.spec.d.ts +0 -2
- package/dist/src/workspace/workspace.spec.d.ts.map +0 -1
- package/examples/node/basicReadWrite.js +0 -86
- package/examples/node/createChannels.js +0 -50
- package/examples/node/createRange.js +0 -67
- package/examples/node/package-lock.json +0 -133
- package/examples/node/package.json +0 -17
- package/examples/node/readLatest.js +0 -76
- package/examples/node/seriesAndFrames.js +0 -173
- package/examples/node/streamRead.js +0 -50
- package/examples/node/streamWrite.js +0 -87
- package/src/access/enforce.spec.ts +0 -188
- package/src/access/policy/access.spec.ts +0 -147
- package/src/access/role/role.spec.ts +0 -95
- package/src/actions/actions.spec.ts +0 -229
- package/src/arc/access.spec.ts +0 -149
- package/src/arc/arc.spec.ts +0 -44
- package/src/arc/lsp.spec.ts +0 -717
- package/src/auth/auth.spec.ts +0 -101
- package/src/channel/access.spec.ts +0 -116
- package/src/channel/batchRetriever.spec.ts +0 -115
- package/src/channel/channel.spec.ts +0 -352
- package/src/channel/payload.spec.ts +0 -117
- package/src/channel/retriever.ts +0 -252
- package/src/connection/checker.ts +0 -203
- package/src/connection/connection.spec.ts +0 -152
- package/src/connection.spec.ts +0 -145
- package/src/control/state.spec.ts +0 -22
- package/src/device/access.spec.ts +0 -159
- package/src/device/device.spec.ts +0 -461
- package/src/device/payload.spec.ts +0 -142
- package/src/errors.spec.ts +0 -71
- package/src/framer/adapter.spec.ts +0 -620
- package/src/framer/client.spec.ts +0 -180
- package/src/framer/codec.spec.ts +0 -383
- package/src/framer/deleter.spec.ts +0 -103
- package/src/framer/frame.spec.ts +0 -973
- package/src/framer/iterator.spec.ts +0 -169
- package/src/framer/reader.spec.ts +0 -865
- package/src/framer/streamer.spec.ts +0 -871
- package/src/framer/writer.spec.ts +0 -486
- package/src/group/access.spec.ts +0 -77
- package/src/group/group.spec.ts +0 -65
- package/src/label/access.spec.ts +0 -109
- package/src/label/label.spec.ts +0 -83
- package/src/lineplot/access.spec.ts +0 -134
- package/src/lineplot/lineplot.spec.ts +0 -120
- package/src/log/access.spec.ts +0 -132
- package/src/log/log.spec.ts +0 -106
- package/src/ontology/ontology.spec.ts +0 -521
- package/src/rack/access.spec.ts +0 -102
- package/src/rack/rack.spec.ts +0 -171
- package/src/ranger/access.spec.ts +0 -115
- package/src/ranger/alias/payload.spec.ts +0 -52
- package/src/ranger/ranger.spec.ts +0 -343
- package/src/schematic/access.spec.ts +0 -134
- package/src/schematic/actions.spec.ts +0 -699
- package/src/schematic/schematic.spec.ts +0 -340
- package/src/schematic/symbol/access.spec.ts +0 -172
- package/src/schematic/symbol/client.spec.ts +0 -160
- package/src/status/access.spec.ts +0 -129
- package/src/status/status.spec.ts +0 -448
- package/src/table/access.spec.ts +0 -128
- package/src/table/table.spec.ts +0 -651
- package/src/task/access.spec.ts +0 -131
- package/src/task/payload.spec.ts +0 -113
- package/src/task/task.spec.ts +0 -657
- package/src/user/access.spec.ts +0 -107
- package/src/user/user.spec.ts +0 -290
- package/src/util/retrieve.spec.ts +0 -49
- package/src/view/view.spec.ts +0 -165
- package/src/workspace/access.spec.ts +0 -108
- package/src/workspace/client.ts +0 -112
- package/src/workspace/types.gen.ts +0 -46
- package/src/workspace/workspace.spec.ts +0 -111
- package/tsconfig.json +0 -5
- package/tsconfig.vite.json +0 -4
- package/vite.config.ts +0 -29
- /package/dist/src/{workspace → project}/external.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-DDACDVZ-.js","names":["errors","isPlainObject","finalize","_a","F","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","duration","uuid","_emoji","date","time","datetime","string","boolean","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","util.mergeDefs","core.clone","checks.overwrite","array","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.enumProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine"],"sources":["../src/access/action/types.gen.ts","../src/access/enforce.ts","../src/errors.ts","../src/ontology/types.gen.ts","../src/ontology/payload.ts","../src/query/derived.ts","../src/query/deleted.ts","../src/query/query.ts","../src/framer/hardened.ts","../src/query/streamer.ts","../src/query/table.ts","../src/query/cache.ts","../src/query/retriever.ts","../src/query/write.ts","../src/query/external.ts","../src/ontology/store.ts","../src/ontology/writer.ts","../src/ontology/client.ts","../src/ontology/external.ts","../src/access/granted.ts","../src/access/policy/types.gen.ts","../src/access/policy/client.ts","../src/access/policy/external.ts","../src/access/role/types.gen.ts","../src/user/types.gen.ts","../src/user/client.ts","../src/user/external.ts","../src/access/role/client.ts","../src/access/role/external.ts","../src/access/client.ts","../src/access/external.ts","../../../node_modules/.pnpm/immer@11.1.15/node_modules/immer/dist/immer.mjs","../src/actions/actions.ts","../src/actions/controller.ts","../src/actions/external.ts","../src/arc/types/types.gen.ts","../src/arc/ir/types.gen.ts","../src/arc/ir/ir.ts","../src/arc/graph/types.gen.ts","../src/arc/compiler/types.gen.ts","../src/arc/program/types.gen.ts","../src/arc/text/types.gen.ts","../src/label/payload.ts","../src/label/store.ts","../src/label/types.gen.ts","../src/label/client.ts","../src/label/external.ts","../src/status/payload.ts","../src/status/types.gen.ts","../src/util/retrieve.ts","../src/status/client.ts","../src/status/status.ts","../src/status/external.ts","../src/rack/types.gen.ts","../src/rack/client.ts","../src/rack/external.ts","../src/device/types.gen.ts","../src/device/client.ts","../src/device/external.ts","../src/task/types.gen.ts","../src/task/client.ts","../src/task/external.ts","../src/arc/types.gen.ts","../src/arc/actions.gen.ts","../src/arc/actions.ts","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../src/arc/client.ts","../src/arc/module/types.gen.ts","../src/arc/external.ts","../src/node/types.gen.ts","../src/channel/types.gen.ts","../src/channel/payload.ts","../src/group/types.gen.ts","../src/group/client.ts","../src/group/external.ts","../src/ranger/alias/payload.ts","../src/ranger/types.gen.ts","../src/channel/client.ts","../src/channel/writer.ts","../src/channel/external.ts","../src/auth/auth.ts","../src/connection/status.ts","../src/transport.ts","../src/connection/client.ts","../src/connection/external.ts","../src/control/state.ts","../src/control/client.ts","../src/control/external.ts","../src/framer/cache/transform.ts","../src/framer/deleter.ts","../src/framer/cache/static.ts","../src/framer/cache/dynamic.ts","../src/framer/cache/unary.ts","../src/framer/cache/cache.ts","../src/framer/cache/reader.ts","../src/framer/cache/streamer.ts","../src/framer/feed.ts","../src/framer/frame.ts","../src/framer/types.gen.ts","../src/framer/codec.ts","../src/framer/adapter.ts","../src/framer/streamProxy.ts","../src/framer/iterator.ts","../src/framer/reader.ts","../src/framer/streamer.ts","../src/framer/writer.ts","../src/framer/client.ts","../src/framer/external.ts","../src/imex/client.ts","../src/lineplot/types.gen.ts","../src/lineplot/actions.gen.ts","../src/lineplot/line.ts","../src/lineplot/actions.ts","../src/project/types.gen.ts","../src/project/client.ts","../src/project/external.ts","../src/lineplot/client.ts","../src/lineplot/external.ts","../src/log/types.gen.ts","../src/log/actions.gen.ts","../src/log/actions.ts","../src/log/client.ts","../src/log/external.ts","../src/panel/types.gen.ts","../src/panel/actions.gen.ts","../src/panel/tree.ts","../src/panel/actions.ts","../src/panel/client.ts","../src/panel/external.ts","../src/ranger/alias/client.ts","../src/ranger/alias/types.gen.ts","../src/ranger/alias/external.ts","../src/ranger/kv/types.gen.ts","../src/ranger/kv/payload.ts","../src/ranger/kv/client.ts","../src/ranger/kv/external.ts","../src/ranger/payload.ts","../src/ranger/writer.ts","../src/ranger/client.ts","../src/ranger/external.ts","../src/schematic/types.gen.ts","../src/schematic/actions.gen.ts","../src/schematic/actions.ts","../src/schematic/symbol/types.gen.ts","../src/schematic/symbol/client.ts","../src/schematic/symbol/external.ts","../src/schematic/client.ts","../src/schematic/external.ts","../src/table/types.gen.ts","../src/table/actions.gen.ts","../src/table/actions.ts","../src/table/client.ts","../src/table/external.ts","../src/view/types.gen.ts","../src/view/client.ts","../src/view/external.ts","../src/client.ts"],"sourcesContent":["// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nexport const ACTIONS = [\"create\", \"delete\", \"retrieve\", \"update\"] as const;\nexport const actionZ = z.enum(ACTIONS);\nexport type Action = z.infer<typeof actionZ>;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { array } from \"@synnaxlabs/x\";\n\nimport { type Action } from \"@/access/action/types.gen\";\nimport { type Policy } from \"@/access/policy/types.gen\";\nimport { type ontology } from \"@/ontology\";\n\n/**\n * Request represents an access control request to check if a subject\n * can perform an action on one or more objects.\n */\nexport interface Request {\n /** The subject making the request (typically a user) */\n subject: ontology.ID;\n /** The action being requested */\n action: Action;\n /** The objects being accessed */\n objects: ontology.ID | ontology.ID[];\n}\n\n/**\n * Checks if a request is allowed based on the provided policies.\n * This is the client-side equivalent of the Go allowRequest function.\n *\n * @param req - The access request to check\n * @param policies - The policies to check against\n * @returns true if the request is allowed, false otherwise\n *\n * @remarks\n * This function implements the following logic:\n * - For each requested object, check if any policy allows the action\n * - A policy allows an action if:\n * 1. The policy's actions include the requested action or \"all\"\n * 2. The policy's objects include the requested object, either:\n * - Type-level match: policy object has empty key and matching type\n * - Instance-level match: policy object has matching type and key\n * - ALL requested objects must be allowed for the request to succeed\n */\nexport const allowRequest = (req: Request, policies: Policy[]): boolean => {\n const objs = array.toArray(req.objects);\n const { action } = req;\n for (const requestedObj of objs) {\n let allowed = false;\n\n for (const policy of policies) {\n const actionAllowed = policy.actions.includes(action);\n if (!actionAllowed) continue;\n\n // Check if any object in the policy matches the requested object\n // Type-level match: empty key means the policy applies to all instances of this type\n for (const policyObj of policy.objects)\n if (policyObj.key === \"\") {\n if (policyObj.type === requestedObj.type) {\n allowed = true;\n break;\n }\n } else if (\n policyObj.type === requestedObj.type &&\n policyObj.key === requestedObj.key\n ) {\n // Instance-level match: both type and key must match\n allowed = true;\n break;\n }\n\n if (allowed) break;\n }\n\n if (!allowed) return false;\n }\n\n return true;\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Middleware, Unreachable } from \"@synnaxlabs/freighter\";\nimport { array, errors } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nexport class SynnaxError extends errors.createTyped(\"sy\") {}\n\n/** Raised when a validation error occurs. */\nexport class ValidationError extends SynnaxError.sub(\"validation\") {}\n\nexport class PathError extends ValidationError.sub(\"path\") {\n readonly path: string[];\n readonly error: Error;\n static readonly encodedSchema = z.object({\n path: z.string().array(),\n error: errors.payloadZ,\n });\n\n constructor(path: string | string[], error: Error) {\n const arrPath = array.toArray(path);\n super(`${arrPath.join(\".\")}: ${error.message}`);\n this.path = arrPath.flatMap((p) => p.split(\".\"));\n this.error = error;\n }\n\n static decode(payload: errors.Payload): PathError {\n const decoded = PathError.encodedSchema.parse(JSON.parse(payload.data));\n return new PathError(decoded.path, errors.decode(decoded.error) as Error);\n }\n\n static matchExact(e: unknown): e is PathError {\n return (\n e != null &&\n typeof e === \"object\" &&\n \"path\" in e &&\n \"error\" in e &&\n \"type\" in e &&\n typeof e.type === \"string\" &&\n e.type === PathError.TYPE\n );\n }\n}\n\n/** AuthError is raised when an authentication error occurs. */\nexport class AuthError extends SynnaxError.sub(\"auth\") {}\n\n/** InvalidTokenError is raised when an authentication token is invalid. */\nexport class InvalidTokenError extends AuthError.sub(\"invalid_token\") {}\n\nexport class ExpiredTokenError extends AuthError.sub(\"expired_token\") {}\n\n/** Raised when the caller's policies do not permit the action. */\nexport class AccessDeniedError extends AuthError.sub(\"access_denied\") {\n toStatus() {\n return {\n message: \"You do not have permission to do that\",\n description: this.message,\n };\n }\n}\n\n/** UnexpectedError is raised when an unexpected error occurs. */\nexport class UnexpectedError extends SynnaxError.sub(\"unexpected\") {\n constructor(message: string) {\n super(`\n Unexpected error encountered:\n\n ${message}\n\n Please report this to the Synnax team.\n `);\n }\n}\n\n/** QueryError is raised when a query error occurs. */\nexport class QueryError extends SynnaxError.sub(\"query\") {}\n\nexport class NotFoundError extends QueryError.sub(\"not_found\") {}\n\nexport class MultipleFoundError extends QueryError.sub(\"multiple_results\") {}\n\n/** RouteError is raised when a routing error occurs. */\nexport class RouteError extends SynnaxError.sub(\"route\") {\n path: string;\n\n constructor(message: string, path: string) {\n super(message);\n this.path = path;\n }\n}\n\nexport class ControlError extends SynnaxError.sub(\"control\") {}\n\nexport class UnauthorizedError extends ControlError.sub(\"unauthorized\") {}\n\nexport class DisconnectedError extends SynnaxError.sub(\"disconnected\") {\n constructor(message: string = \"Operation failed because no Core is connected.\") {\n super(message);\n }\n}\n\n/**\n * Whether the error means the Core could not be reached: a request that failed on\n * the wire, or one short-circuited while the connection is known unreachable.\n */\nexport const isConnectionError = (err: unknown): boolean =>\n Unreachable.matches(err) || DisconnectedError.matches(err);\n\n/** Raised when time-series data is not contiguous. */\nexport class ContiguityError extends SynnaxError.sub(\"contiguity\") {}\n\nconst decode = (payload: errors.Payload): Error | null => {\n if (!payload.type.startsWith(SynnaxError.TYPE)) return null;\n if (payload.type.startsWith(ValidationError.TYPE)) {\n if (payload.type === PathError.TYPE) return PathError.decode(payload);\n return new ValidationError(payload.data);\n }\n\n if (payload.type.startsWith(AuthError.TYPE)) {\n if (payload.type.startsWith(InvalidTokenError.TYPE))\n return new InvalidTokenError(payload.data);\n if (payload.type.startsWith(ExpiredTokenError.TYPE))\n return new ExpiredTokenError(payload.data);\n if (payload.type.startsWith(AccessDeniedError.TYPE))\n return new AccessDeniedError(payload.data);\n return new AuthError(payload.data);\n }\n\n if (payload.type.startsWith(UnexpectedError.TYPE))\n return new UnexpectedError(payload.data);\n\n if (payload.type.startsWith(QueryError.TYPE)) {\n if (payload.type.startsWith(NotFoundError.TYPE))\n return new NotFoundError(payload.data);\n if (payload.type.startsWith(MultipleFoundError.TYPE))\n return new MultipleFoundError(payload.data);\n return new QueryError(payload.data);\n }\n\n if (payload.type.startsWith(ControlError.TYPE)) {\n if (payload.type.startsWith(UnauthorizedError.TYPE))\n return new UnauthorizedError(payload.data);\n return new ControlError(payload.data);\n }\n\n if (payload.type.startsWith(RouteError.TYPE))\n return new RouteError(payload.data, payload.data);\n\n return new UnexpectedError(payload.data);\n};\n\nconst encode: errors.Encoder = (error) => {\n if (!error.type.startsWith(SynnaxError.TYPE)) return null;\n if (PathError.matchExact(error)) {\n const { path, error: cause } = error;\n return {\n type: PathError.TYPE,\n data: JSON.stringify({ path, error: errors.encode(cause) }),\n };\n }\n return { type: error.type, data: error.message };\n};\n\nerrors.register({ encode, decode });\n\nexport const validateFieldNotNull = (\n key: string,\n value: unknown,\n message: string = \"must be provided\",\n): void => {\n if (value == null) throw new PathError(key, new ValidationError(message));\n};\n\nexport const errorsMiddleware: Middleware = async (ctx, next) => {\n try {\n return await next(ctx);\n } catch (err) {\n if (err instanceof Unreachable)\n throw new Unreachable({\n message: `Cannot reach Core at ${err.url.host}:${err.url.port}`,\n url: err.url,\n cause: err.cause ?? err,\n });\n throw errors.fromUnknown(err);\n }\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nexport const RESOURCE_TYPES = [\n \"arc\",\n \"builtin\",\n \"channel\",\n \"device\",\n \"framer\",\n \"group\",\n \"label\",\n \"lineplot\",\n \"log\",\n \"node\",\n \"panel\",\n \"policy\",\n \"project\",\n \"rack\",\n \"range\",\n \"range-alias\",\n \"role\",\n \"schematic\",\n \"schematic_symbol\",\n \"status\",\n \"table\",\n \"task\",\n \"user\",\n \"view\",\n] as const;\nexport const resourceTypeZ = z.enum(RESOURCE_TYPES);\nexport type ResourceType = z.infer<typeof resourceTypeZ>;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { array, type change, primitive, record, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { RESOURCE_TYPES, type ResourceType, resourceTypeZ } from \"@/ontology/types.gen\";\n\nexport { RESOURCE_TYPES, type ResourceType, resourceTypeZ };\n\n/** A resource created, updated, or deleted. */\nexport type ResourceChange = change.Change<ID, Resource>;\nexport interface ResourceSet extends change.Set<ID, Resource> {}\nexport interface ResourceDelete extends change.Delete<ID, Resource> {}\n/** A relationship created or deleted. Relationships carry no value of their own. */\nexport type RelationshipChange = change.Change<Relationship, undefined>;\nexport interface RelationshipSet extends change.Set<Relationship, undefined> {}\nexport interface RelationshipDelete extends change.Delete<Relationship, undefined> {}\n\nexport interface RelationshipDelete extends change.Delete<Relationship, undefined> {}\n\n/** Zod schema parsing a `\"type:key\"` string into an {@link ID}. */\nexport const stringIDZ = z.string().transform((v, ctx) => {\n const [type, key] = v.split(\":\");\n const res = resourceTypeZ.safeParse(type);\n if (!res.success) {\n ctx.addIssue({ code: \"custom\", message: `invalid resource type: ${type}` });\n return z.NEVER;\n }\n return { type: res.data, key: key ?? \"\" };\n});\n\n/** Zod schema for {@link ID}, accepting either the object or the `\"type:key\"` string. */\nexport const idZ = z.object({ type: resourceTypeZ, key: z.string() }).or(stringIDZ);\n\n/** Names one resource in the ontology: what kind it is, and which one. */\nexport type ID = z.infer<typeof idZ>;\n\n/** The root of the ontology. Every other resource descends from it. */\nexport const ROOT_ID: ID = { type: \"builtin\", key: \"root\" };\n\n/** Builds {@link ID}s of one resource type, singly or in bulk. */\nexport interface CreateID<K extends record.Key> {\n (key: K): ID;\n (keys: K[]): ID[];\n (keys: K | K[]): ID | ID[];\n}\n\n/**\n * @returns a {@link CreateID} that stamps the given resource type onto keys. Each\n * resource package exports one as `ontologyID`.\n *\n * @example const ontologyID = createIDFactory<Key>(\"channel\");\n */\nexport const createIDFactory = <K extends record.Key>(\n type: ResourceType,\n): CreateID<K> => {\n const id = (key: K) => ({ type, key: primitive.isZero(key) ? \"\" : key.toString() });\n return ((key: K | K[]) => {\n if (Array.isArray(key)) return key.map(id);\n return id(key);\n }) as CreateID<K>;\n};\n\nexport interface IDToString {\n (id: ID | string): string;\n (ids: (ID | string)[]): string[];\n}\n\n/** Renders an {@link ID} as `\"type:key\"`, the form used as a map key. */\nexport const idToString = ((id: ID | string | (ID | string)[]) => {\n if (typeof id === \"string\") id = zod.parse(stringIDZ, id, { label: \"ontology ID\" });\n if (Array.isArray(id)) return id.map((id) => idToString(id));\n return `${id.type}:${id.key}`;\n}) as IDToString;\n\n/** @returns whether the two IDs name the same resource. */\nexport const idsEqual = (a: ID, b: ID) => a.type === b.type && a.key === b.key;\n\n/**\n * Parses a crude ID (an object or a \"type:key\" string) into an ID.\n * @throws {zod.ParseError} if the value is not a valid ontology ID.\n */\nexport const parseID = (id: unknown): ID =>\n zod.parse(idZ, id, { label: \"ontology ID\" });\n\n/**\n * Resolves IDs, `\"type:key\"` strings, or whole resources into an {@link ID} array.\n * @throws {zod.ParseError} if a value is not a valid ontology ID.\n */\nexport const parseIDs = (\n ids: ID | string | Resource | (ID | string | Resource)[],\n): ID[] => {\n const arr = array.toArray(ids);\n if (arr.length === 0) return [];\n if (typeof arr[0] === \"object\" && \"id\" in arr[0])\n return (arr as Resource[]).map(({ id }) => id);\n return arr.map(parseID);\n};\n\n/** Zod schema for {@link Resource}. */\nexport const resourceZ = z\n .object({\n id: idZ,\n name: z.string(),\n data: record.unknownZ().optional().nullable(),\n })\n .transform((resource) => ({ key: idToString(resource.id), ...resource }));\n/** A node in the ontology: its ID, its display name, and the payload it stands for. */\nexport interface Resource<T extends record.Unknown = record.Unknown> extends Omit<\n z.infer<typeof resourceZ>,\n \"data\"\n> {\n data?: T | null;\n}\n\n/** Which end of a relationship a traversal starts from. */\nexport type RelationshipDirection = \"to\" | \"from\";\n\n/** @returns the other end of a relationship. */\nexport const oppositeRelationshipDirection = (\n direction: RelationshipDirection,\n): RelationshipDirection => (direction === \"to\" ? \"from\" : \"to\");\n\n/** Zod schema for {@link Relationship}, accepting the `\"from->type->to\"` string too. */\nexport const relationshipZ = z.object({ from: idZ, type: z.string(), to: idZ }).or(\n z.string().transform((v) => {\n const [from, type, to] = v.split(\"->\");\n return { from: idZ.parse(from), type, to: idZ.parse(to) };\n }),\n);\n/** A directed edge between two resources, such as a group and its child. */\nexport type Relationship = z.infer<typeof relationshipZ>;\n\n/** Renders a {@link Relationship} as `\"from->type->to\"`. */\nexport const relationshipToString = (relationship: Relationship) =>\n `${idToString(relationship.from)}->${relationship.type}->${idToString(relationship.to)}`;\n\n/** Relationship type joining a parent resource to its children. */\nexport const PARENT_OF_RELATIONSHIP_TYPE = \"parent\";\n\n/** A relationship pattern. An absent field, or field part, matches anything. */\nexport interface MatchRelationshipParams {\n from?: Partial<ID>;\n type: string;\n to?: Partial<ID>;\n}\n\n/** @returns whether the relationship fits the pattern. */\nexport const matchRelationship = (\n relationship: Relationship,\n match: MatchRelationshipParams,\n) => {\n if (match.type != null && match.type !== relationship.type) return false;\n if (match.from?.type != null && match.from.type !== relationship.from.type)\n return false;\n if (match.to?.type != null && match.to.type !== relationship.to.type) return false;\n if (match.from?.key != null && match.from.key !== relationship.from.key) return false;\n if (match.to?.key != null && match.to.key !== relationship.to.key) return false;\n return true;\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type destructor, type record, type state } from \"@synnaxlabs/x\";\n\nimport { type Keyed, type Table, type TableEvent } from \"@/query/table\";\n\n/**\n * A foreign-table trigger for a derived table: projects that table's events onto the\n * source keys whose composition they change. Build with {@link deriveWatch}.\n */\nexport interface DeriveWatch<K extends record.Key> {\n attach: (recompose: (keys: K[] | \"all\") => void) => destructor.Destructor;\n}\n\n/**\n * Declares that events on the given table change composed entries. `affects`\n * maps an event to the source keys whose composition it touches, \"all\" to\n * recompose every entry, or null when unaffected.\n */\nexport const deriveWatch = <\n K extends record.Key,\n ForeignKey extends record.Key,\n ForeignValue extends state.State,\n>(\n table: Table<ForeignKey, ForeignValue>,\n affects: (event: TableEvent<ForeignKey, ForeignValue>) => K[] | \"all\" | null,\n): DeriveWatch<K> => ({\n attach: (recompose) =>\n // Batched so one foreign write recomposes once: an \"all\" verdict for any event\n // supersedes the batch's keys, which otherwise union.\n table.subscribeBatch((events) => {\n let keys: K[] = [];\n for (const event of events) {\n const result = affects(event);\n if (result == null) continue;\n if (result === \"all\") return recompose(\"all\");\n keys = keys.concat(result);\n }\n if (keys.length > 0) recompose(keys);\n }),\n});\n\n/** Derivation wiring shared by {@link Cache.derive}. */\nexport interface DeriveParams<\n K extends record.Key,\n V extends Keyed<K>,\n CV extends Keyed<K>,\n> {\n /** The table owning the raw records the derivation reads. */\n source: Table<K, V>;\n /** Builds the composed entry for one source record. Pure; no network. */\n compose: (record: V) => CV;\n /** Foreign tables whose events change composition. */\n watch?: Array<DeriveWatch<K>>;\n}\n\n/**\n * Keeps a derived table materialized from its source: composed entries are\n * replaced (never mutated) on source and watch events, so an entry's identity\n * changes exactly when its composition changes, with equal recompositions\n * silenced by the table's equality check. Existing source entries are composed\n * immediately. Returns a destructor that detaches every subscription.\n */\nexport const bindDerived = <\n K extends record.Key,\n V extends Keyed<K>,\n CV extends Keyed<K>,\n>(\n into: Table<K, CV>,\n { source, compose, watch }: DeriveParams<K, V, CV>,\n): destructor.Destructor => {\n const recompose = (keys: K[] | \"all\"): void => {\n const targets = keys === \"all\" ? source.get() : source.get(keys);\n if (targets.length > 0) into.set(targets.map(compose));\n };\n const detach = [\n // Batched so a source batch flushes the derived table once, preserving per-key\n // set/delete order within the batch.\n source.subscribeBatch((events) =>\n into.batch(() =>\n events.forEach((event) => {\n if (event.variant === \"set\") into.set(compose(event.value));\n // A source that keeps no corpse never held the record: mirroring that keeps a\n // derived tombstone from outliving a deletion that never was.\n else if (source.status(event.key) === \"tombstoned\") into.delete(event.key);\n else into.evict(event.key);\n }),\n ),\n ),\n ...(watch ?? []).map((w) => w.attach(recompose)),\n ];\n recompose(\"all\");\n return () => detach.forEach((d) => d());\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type TimeStamp } from \"@synnaxlabs/x\";\n\n// Brands instances through the global symbol registry so matches() holds across\n// duplicated module instances (dual CJS/ESM builds), where instanceof does not.\nconst BRAND = Symbol.for(\"synnaxlabs.client.query.deleted\");\n\n/**\n * The last value of a deleted record, delivered wherever a cached answer would be, so\n * deletion can never be mistaken for live data. One instance exists per deletion:\n * repeated reads of a deleted answer return the same reference.\n */\nexport class Deleted<D = unknown> {\n /** The record's value at the moment it was deleted. */\n readonly corpse: D;\n /** When the deletion was applied. */\n readonly deletedAt: TimeStamp;\n protected readonly [BRAND] = true;\n\n constructor(corpse: D, deletedAt: TimeStamp) {\n this.corpse = corpse;\n this.deletedAt = deletedAt;\n }\n\n /** Narrows a cached answer to the deleted case, carrying its record type\n * onto the corpse. */\n static matches<D>(value: D | Deleted<D> | undefined): value is Deleted<D> {\n return typeof value === \"object\" && value !== null && BRAND in value;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n compare,\n type destructor,\n errors,\n primitive,\n type record,\n type state,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\n\nimport { AccessDeniedError, NotFoundError } from \"@/errors\";\nimport { Deleted } from \"@/query/deleted\";\nimport { type Table, type TableEvent } from \"@/query/table\";\nimport { type Data, type FetchOptions, type Params } from \"@/query/types\";\n\nconst hashes = new WeakMap<object, string>();\n\n/**\n * Deterministically serializes query params to a stable string. Keys are sorted\n * recursively so `{a: 1, b: 2}` and `{b: 2, a: 1}` collapse to the same key, and\n * explicitly-undefined fields hash like absent ones (matching JSON semantics). Class\n * instances implementing {@link primitive.Hashable} delegate to their `hash()` method;\n * plain objects and arrays recurse structurally, memoized per object identity ({@link\n * Params} is readonly, so an object's hash never changes).\n */\nexport const hash = (params: Params): string => {\n if (params === null) return \"null\";\n if (params === undefined) return \"undefined\";\n if (typeof params === \"bigint\") return `${params.toString()}n`;\n if (typeof params !== \"object\") return JSON.stringify(params);\n if (primitive.isHashable(params)) return params.hash();\n const held = hashes.get(params);\n if (held !== undefined) return held;\n let result: string;\n if (Array.isArray(params)) result = `[${params.map(hash).join(\",\")}]`;\n else {\n const fields = Object.entries(params)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n result = `{${fields.map(([k, v]) => `${JSON.stringify(k)}:${hash(v)}`).join(\",\")}}`;\n }\n hashes.set(params, result);\n return result;\n};\n\n/**\n * A cached answer as delivered to consumers: the query's current data, or the\n * {@link Deleted} corpse of a record that was deleted. A corpse is never\n * delivered as bare data, so deletion cannot be mistaken for a live result.\n * Narrow with {@link isLive}, or {@link Deleted.matches} to reach the corpse.\n */\nexport type Cached<D extends Data> = D | Deleted<D>;\n\n/** True when a cached answer is live: cached at all, and not a deletion. */\nexport const isLive = <D extends Data>(value: Cached<D> | undefined): value is D =>\n value != null && !Deleted.matches<D>(value);\n\n/**\n * Returns the corpse of a deleted answer, for callers that need the record's\n * last value (restoring it, say) and have no use for any other outcome.\n * @throws {NotFoundError} if the answer is live or nothing is cached.\n */\nexport const requireCorpse = <D extends Data>(value: Cached<D> | undefined): D => {\n if (!Deleted.matches<D>(value))\n throw new NotFoundError(\"the deleted record is no longer cached\");\n return value.corpse;\n};\n\n/**\n * Receives the new cached answer for a query. `undefined` means the answer was\n * invalidated; the next read refetches.\n */\nexport interface ChangeHandler<D extends Data> {\n (result: Cached<D> | undefined): void;\n}\n\n/**\n * The read surface of one query space: fetch, subscribe, snapshot. The public\n * face of every answer space, including the named spaces domain clients\n * expose (children, parents, kv).\n */\nexport interface Retrieves<P extends Params, D extends Data> {\n retrieve: (params: P, options?: FetchOptions) => Promise<D>;\n onChange: (params: P, handler: ChangeHandler<D>) => destructor.Destructor;\n getCached: (params: P) => Cached<D> | undefined;\n}\n\n/**\n * A foreign-table subscription for an answer space: projects that table's\n * events onto the space's primary keys. Build with {@link watch}.\n */\nexport interface Watch<P extends Params, K extends record.Key> {\n attach: (\n params: P,\n onEvent: (result: K[] | \"refetch\") => void,\n ) => destructor.Destructor;\n}\n\n/**\n * Declares that events on the given table affect answers in this space.\n * `affects` maps an event to the primary keys whose membership or content it\n * touches, \"refetch\" to invalidate wholesale, or null when unaffected.\n */\nexport const watch = <\n P extends Params,\n K extends record.Key,\n ForeignKey extends record.Key,\n ForeignValue extends state.State,\n>(\n table: Table<ForeignKey, ForeignValue>,\n affects: (\n event: TableEvent<ForeignKey, ForeignValue>,\n params: P,\n ) => K[] | \"refetch\" | null,\n): Watch<P, K> => ({\n attach: (params, onEvent) =>\n // Batched so one foreign write fires onEvent once: a refetch verdict for any event\n // supersedes the batch's keys, which otherwise union.\n table.subscribeBatch((events) => {\n let keys: K[] = [];\n for (const event of events) {\n const result = affects(event, params);\n if (result == null) continue;\n if (result === \"refetch\") return onEvent(\"refetch\");\n keys = keys.concat(result);\n }\n if (keys.length > 0) onEvent(keys);\n }),\n});\n\n/**\n * Declaration of one query space: which table owns its records, how to fetch\n * an answer's keys, how to assemble content, and how membership is maintained.\n *\n * Maintenance is chosen per query instance:\n * 1. exact-key — `keyOf` returns a key: track that entry; deletion flips the\n * answer to deleted.\n * 2. client-checkable — `matches` compares a record against the query:\n * admit/evict exactly, no network.\n * 3. server-computed — any field named in `serverFields` is set on the query\n * (or neither `keyOf` nor `matches` applies): debounced wholesale refetch.\n */\nexport interface SpaceConfig<\n P extends Params,\n D extends Data,\n K extends record.Key = record.Key,\n V extends state.State = state.State,\n> {\n /** Resource name used in error messages, e.g. \"range\". */\n name: string;\n /** The table owning this space's record content. */\n table: Table<K, V>;\n /**\n * Fetches the answer from the cluster: writes fetched records into their\n * tables and returns the member keys.\n */\n fetch: (params: P, options?: FetchOptions) => Promise<K[]>;\n /** Assembles the answer from resolved member records at read time. */\n compose: (records: V[], params: P) => D;\n /** Rule 1: the single key a query addresses, or null when it doesn't. */\n keyOf?: (params: P) => K | null;\n /**\n * The exact key set a keys-only query addresses, or null when it doesn't. Lets\n * getCached compose the answer straight from the table (params order, deduped,\n * tombstoned members omitted) and lets maintenance seed a ready answer on\n * subscribe, so a fully cached key set never fetches.\n */\n keysOf?: (params: P) => K[] | null;\n /** Rule 2: whether a record satisfies the query. Pure; no network. */\n matches?: (record: V, params: P) => boolean;\n /**\n * Query fields only the server can evaluate (searchTerm, limit, offset).\n * A query instance with any of them set is maintained by rule 3.\n */\n serverFields?: readonly string[];\n /** Foreign tables whose events affect this space's answers. */\n watch?: Watch<P, K>[];\n /**\n * Marks a space whose answer addresses one record and cannot compose an\n * empty membership: rule-2 eviction of the last member flips the query to\n * deleted (when the entry tombstoned) or invalidates it, instead of\n * composing []. Leave unset for spaces where [] is a valid answer.\n */\n single?: boolean;\n}\n\n/** Wiring a {@link Space} receives from the cache that owns it. */\nexport interface SpaceHooks {\n /** Started (not awaited) on reads and subscriptions to open change delivery. */\n ensureStreaming?: () => Promise<void>;\n /** Subscribes to connection-epoch changes; maintained answers refetch on bump. */\n onEpoch?: (callback: (epoch: number) => void) => destructor.Destructor;\n /**\n * Whether change delivery keeps subscribed answers current. False when the\n * cache is detached or the cluster refused the stream. Defaults to true.\n */\n maintained?: () => boolean;\n /** Reports maintenance errors that have no caller to throw to. Defaults to\n * console logging. */\n onError?: (error: Error) => void;\n /**\n * How long maintenance survives the last unsubscribe, so a quick remount finds\n * the answer still maintained and skips the reconfirm refetch. Zero tears down\n * synchronously. Defaults to 5 seconds.\n */\n teardownGrace?: TimeSpan;\n}\n\nconst DEFAULT_DEBOUNCE = TimeSpan.milliseconds(100);\nconst DEFAULT_TEARDOWN_GRACE = TimeSpan.seconds(5);\n\ntype QueryState<K extends record.Key, D extends Data> =\n | { variant: \"unfetched\" }\n | { variant: \"loading\"; promise: Promise<D> }\n | { variant: \"ready\"; keys: K[] }\n | { variant: \"error\"; error: Error }\n | { variant: \"deleted\"; key: K };\n\ninterface Query<\n P extends Params,\n K extends record.Key,\n D extends Data,\n V extends state.State,\n> {\n params: P;\n state: QueryState<K, D>;\n handlers: Set<ChangeHandler<D>>;\n /** Rule teardown; present exactly while the query is maintained. */\n teardown?: destructor.Destructor[];\n /** Set when maintenance ends: changes since then went unobserved. */\n unmaintained?: boolean;\n /** Keys whose membership a fetch in flight deferred; drained on settle. */\n pendingRechecks?: Set<K>;\n /** Set when a fetch in flight deferred a refetch; honored on settle. */\n refetchOnSettle?: boolean;\n refetchTimer?: ReturnType<typeof setTimeout>;\n /** When the last subscriber left; the sweep tears the query down once this\n * outlives the grace window. Cleared on resubscribe. */\n idleSince?: TimeStamp;\n /** Answer interned against the records it was composed from, so repeated\n * reads stay referentially stable for useSyncExternalStore consumers. A\n * table replaces an entry only when its content changes, so a surviving entry\n * set means a surviving answer. */\n composed?: { records: V[]; value: D };\n}\n\n/**\n * Cached read path for one query space of a domain client: deduped fetches, per-query\n * lifecycle, subscriptions, and deletion delivery. Answers hold only key lists; record\n * content lives in tables and is assembled at read time, so answer content cannot\n * diverge from the record cache. Answers are maintained only while subscribed. An\n * unsubscribed read refetches; an unsubscribed getCached serves the retained (possibly\n * stale) answer, recomposed against live tables.\n */\nexport class Space<\n P extends Params,\n D extends Data,\n K extends record.Key = record.Key,\n V extends state.State = state.State,\n> {\n private readonly queries = new Map<string, Query<P, K, D, V>>();\n /** Composed corpses interned per tombstone and params, so deleted answers\n * stay referentially stable. Identity composes reuse the tombstone. */\n private readonly corpses = new WeakMap<Deleted<V>, Map<string, Deleted<D>>>();\n /** Answers for reads with no live query, interned per entry and params. */\n private readonly entryAnswers = new WeakMap<object, Map<string, D>>();\n private readonly config: SpaceConfig<P, D, K, V>;\n private readonly hooks: SpaceHooks & {\n onError: NonNullable<SpaceHooks[\"onError\"]>;\n };\n private readonly detachEpoch?: destructor.Destructor;\n private readonly grace: TimeSpan;\n private sweepTimer?: ReturnType<typeof setTimeout>;\n\n constructor(config: SpaceConfig<P, D, K, V>, hooks: SpaceHooks = {}) {\n this.config = config;\n this.hooks = { ...hooks, onError: hooks.onError ?? console.error };\n this.grace = hooks.teardownGrace ?? DEFAULT_TEARDOWN_GRACE;\n this.detachEpoch = hooks.onEpoch?.((epoch) => {\n // 0 is a return to cold (cluster replacement): the fresh stream's own\n // epoch bump refetches, not the reset itself.\n if (epoch === 0) return;\n this.queries.forEach((query) => {\n if (query.teardown != null) void this.refetch(query);\n });\n });\n }\n\n /**\n * Returns the answer to the query: instantly when cached and subscribed,\n * joining the in-flight fetch when one exists, fetching otherwise. Settled\n * answers are kept fresh only while maintained (subscribed, or within the teardown\n * grace window after the last unsubscribe, and only while change delivery is on),\n * so an unmaintained read always refetches. A previously failed query refetches.\n * @throws {NotFoundError} if the queried record was deleted.\n */\n retrieve(params: P, options?: FetchOptions): Promise<D> {\n const query = this.ensure(params);\n const { state } = query;\n if (state.variant === \"loading\") return state.promise;\n if (query.teardown != null && this.hooks.maintained?.() !== false)\n switch (state.variant) {\n case \"ready\":\n return Promise.resolve(this.composedOf(query, state.keys));\n case \"deleted\":\n return Promise.reject(new NotFoundError(`${this.config.name} was deleted`));\n }\n void this.startStreaming();\n return this.fetch(query, options);\n }\n\n /**\n * Returns the cached answer without touching the network: the current data,\n * the corpse of a deleted record, or undefined when nothing is cached.\n * Exact-key queries also resolve from a table entry cached by any other\n * query. May be stale for queries nothing subscribes to.\n */\n getCached(params: P): Cached<D> | undefined {\n const query = this.queries.get(hash(params));\n if (query != null) {\n const cached = this.cachedOf(query);\n if (cached != null) return cached;\n }\n // Rule-1 queries read straight through to the table: an entry (or tombstone)\n // answers the query even before any fetch or subscription exists.\n const key = this.config.keyOf?.(params);\n if (key != null) {\n const { table } = this.config;\n const entry = table.get(key);\n if (entry != null) return this.entryAnswerOf(entry, params);\n const tombstone = table.getTombstone(key);\n if (tombstone == null) return undefined;\n return this.deletedOf(tombstone, params);\n }\n // Keys-only queries compose from the table the same way, when every key resolves.\n // The answer matches what the fetch would return.\n const keys = this.config.keysOf?.(params);\n if (keys == null) return undefined;\n const members = this.composableMembersOf(keys);\n if (members == null) return undefined;\n return this.composedOf(this.ensure(params), members);\n }\n\n /**\n * Resolves a keys-only query's key list against the table: deduped, in params order,\n * tombstoned keys omitted to match the fetch answer. Returns null when any key is\n * unknown, since only a fetch can tell an uncached record from a nonexistent one.\n */\n private composableMembersOf(keys: K[]): K[] | null {\n const { table } = this.config;\n const members: K[] = [];\n const seen = new Set<K>();\n for (const key of keys) {\n if (seen.has(key)) continue;\n seen.add(key);\n const status = table.status(key);\n if (status === \"unknown\") return null;\n if (status === \"present\") members.push(key);\n }\n return members;\n }\n\n /**\n * Subscribes to changes in the query's cached answer. The handler fires with the new\n * answer on every change or deletion. Maintenance for the query runs while at least\n * one subscriber exists and survives the last unsubscribe by the grace window, so a\n * quick remount skips the reconfirm refetch. Returns a destructor that unsubscribes.\n */\n onChange(params: P, handler: ChangeHandler<D>): destructor.Destructor {\n void this.startStreaming();\n const query = this.ensure(params);\n query.handlers.add(handler);\n query.idleSince = undefined;\n if (query.teardown == null) this.maintain(query);\n return () => {\n query.handlers.delete(handler);\n if (query.handlers.size > 0) return;\n if (this.grace.isZero) return this.teardownQuery(query);\n query.idleSince = TimeStamp.now();\n this.armSweep();\n };\n }\n\n /**\n * Resets every answer to unfetched and notifies subscribers that their answer was\n * invalidated, so the next read refetches. Maintenance subscriptions stay mounted.\n * Called by the cache when the cluster behind the connection is replaced.\n */\n reset(): void {\n this.queries.forEach((query) => {\n if (query.refetchTimer != null) {\n clearTimeout(query.refetchTimer);\n query.refetchTimer = undefined;\n }\n query.state = { variant: \"unfetched\" };\n query.handlers.forEach((handler) => {\n try {\n handler(undefined);\n } catch (exc) {\n this.report(exc, `failed to notify ${this.config.name} answer subscriber`);\n }\n });\n });\n }\n\n /** Detaches the epoch subscription. Queries and handlers are dropped. */\n close(): void {\n this.detachEpoch?.();\n if (this.sweepTimer != null) {\n clearTimeout(this.sweepTimer);\n this.sweepTimer = undefined;\n }\n this.queries.forEach((query) => {\n query.teardown?.forEach((d) => d());\n if (query.refetchTimer != null) clearTimeout(query.refetchTimer);\n });\n this.queries.clear();\n }\n\n private teardownQuery(query: Query<P, K, D, V>): void {\n query.idleSince = undefined;\n query.teardown?.forEach((d) => d());\n query.teardown = undefined;\n query.unmaintained = true;\n query.pendingRechecks = undefined;\n query.refetchOnSettle = false;\n if (query.refetchTimer != null) {\n clearTimeout(query.refetchTimer);\n query.refetchTimer = undefined;\n }\n }\n\n /** Arms the sweep while any query sits in the grace window. One timer per\n * space, no matter how many queries go idle at once. */\n private armSweep(): void {\n this.sweepTimer ??= setTimeout(() => {\n this.sweepTimer = undefined;\n this.sweep();\n }, this.grace.milliseconds / 2);\n }\n\n private sweep(): void {\n let anyIdle = false;\n const now = TimeStamp.now();\n this.queries.forEach((query) => {\n if (query.idleSince == null) return;\n if (query.handlers.size > 0) {\n query.idleSince = undefined;\n return;\n }\n if (now.span(query.idleSince).lessThan(this.grace)) {\n anyIdle = true;\n return;\n }\n this.teardownQuery(query);\n });\n if (anyIdle) this.armSweep();\n }\n\n private ensure(params: P): Query<P, K, D, V> {\n const hashed = hash(params);\n let query = this.queries.get(hashed);\n if (query == null) {\n query = { params, state: { variant: \"unfetched\" }, handlers: new Set() };\n this.queries.set(hashed, query);\n }\n return query;\n }\n\n // Streaming failure must never block reads, so the change stream opens in the\n // background rather than being awaited. A denial belongs to the connection, which\n // reports it once, not to every query that reads. Never rejects.\n private async startStreaming(): Promise<void> {\n try {\n await this.hooks.ensureStreaming?.();\n } catch (exc) {\n if (AccessDeniedError.matches(exc)) return;\n this.report(exc);\n }\n }\n\n private report(\n exc: unknown,\n message = `failed to maintain ${this.config.name} answers`,\n ): void {\n this.hooks.onError(new Error(message, { cause: exc }));\n }\n\n /** Composes a ready answer, interned against the records it was built from. */\n private composedOf(query: Query<P, K, D, V>, keys: K[]): D {\n const records = this.config.table.get(keys);\n const { composed } = query;\n if (composed != null && compare.arraysEqual(composed.records, records))\n return composed.value;\n const value = this.config.compose(records, query.params);\n query.composed = { records, value };\n return value;\n }\n\n private cachedOf(query: Query<P, K, D, V>): Cached<D> | undefined {\n const { state } = query;\n if (state.variant === \"ready\") return this.composedOf(query, state.keys);\n if (state.variant === \"deleted\") {\n const tombstone = this.config.table.getTombstone(state.key);\n if (tombstone == null) return undefined;\n return this.deletedOf(tombstone, query.params);\n }\n return undefined;\n }\n\n /** Composes a rule-1 answer for a read with no live query, interned per entry\n * and params. The memo dies with the entry it is keyed on, which a table\n * replaces on every content change. */\n private entryAnswerOf(entry: V, params: P): D {\n if (typeof entry !== \"object\" || entry === null)\n return this.config.compose([entry], params);\n const hashed = hash(params);\n let perEntry = this.entryAnswers.get(entry);\n if (perEntry == null) {\n perEntry = new Map();\n this.entryAnswers.set(entry, perEntry);\n }\n if (perEntry.has(hashed)) return perEntry.get(hashed) as D;\n const value = this.config.compose([entry], params);\n perEntry.set(hashed, value);\n return value;\n }\n\n private deletedOf(tombstone: Deleted<V>, params: P): Deleted<D> {\n const hashed = hash(params);\n let perTombstone = this.corpses.get(tombstone);\n if (perTombstone == null) {\n perTombstone = new Map();\n this.corpses.set(tombstone, perTombstone);\n }\n let deleted = perTombstone.get(hashed);\n if (deleted == null) {\n deleted = new Deleted(\n this.config.compose([tombstone.corpse], params),\n tombstone.deletedAt,\n );\n perTombstone.set(hashed, deleted);\n }\n return deleted;\n }\n\n /** Notifies subscribers when any of the keys is a member of the ready\n * answer; otherwise just drops the memo so the next read recomposes. */\n private touchMembers(query: Query<P, K, D, V>, keys: K[]): void {\n query.composed = undefined;\n if (query.state.variant !== \"ready\") return;\n const members = new Set(query.state.keys);\n if (keys.some((key) => members.has(key))) this.touch(query);\n }\n\n /** Notifies every subscriber with the query's current answer. */\n private touch(query: Query<P, K, D, V>): void {\n // A watched foreign table is an input the records do not carry, so an\n // event is the only signal that a composed answer changed.\n query.composed = undefined;\n if (query.handlers.size === 0) return;\n const result = this.cachedOf(query);\n query.handlers.forEach((handler) => {\n try {\n handler(result);\n } catch (exc) {\n this.report(exc, `failed to notify ${this.config.name} answer subscriber`);\n }\n });\n }\n\n private settle(\n query: Query<P, K, D, V>,\n expected: QueryState<K, D>,\n next: QueryState<K, D>,\n ): void {\n // A late promise resolution must not clobber a maintenance update.\n if (query.state !== expected) return;\n query.state = next;\n this.drainRechecks(query);\n if (next.variant === \"error\") {\n query.refetchOnSettle = false;\n return;\n }\n if (query.refetchOnSettle === true) {\n query.refetchOnSettle = false;\n if (query.teardown != null) this.scheduleRefetch(query);\n }\n this.touch(query);\n }\n\n /**\n * Replays membership changes a fetch in flight deferred. The fetch answers the query\n * as of when it ran, so a change that raced it would otherwise be lost under the keys\n * it publishes. Applies quietly: the settle that calls this notifies once for the\n * whole answer.\n */\n private drainRechecks(query: Query<P, K, D, V>): void {\n const pending = query.pendingRechecks;\n if (pending == null) return;\n query.pendingRechecks = undefined;\n this.applyRechecks(query, pending);\n }\n\n private fetch(query: Query<P, K, D, V>, options?: FetchOptions): Promise<D> {\n const promise = this.config.fetch(query.params, options).then(\n (keys) => {\n this.settle(query, loading, { variant: \"ready\", keys });\n // The settle drains membership changes that raced the fetch, so the answer\n // comes off the query: the keys the fetch returned are already stale.\n const { state } = query;\n return this.composedOf(query, state.variant === \"ready\" ? state.keys : keys);\n },\n (reason: unknown) => {\n const error = errors.fromUnknown(reason);\n this.settle(query, loading, { variant: \"error\", error });\n throw error;\n },\n );\n const loading: QueryState<K, D> = { variant: \"loading\", promise };\n query.state = loading;\n return promise;\n }\n\n /** Never rejects: a failed refetch leaves the previous answer in place. */\n private async refetch(query: Query<P, K, D, V>): Promise<void> {\n if (query.refetchTimer != null) {\n clearTimeout(query.refetchTimer);\n query.refetchTimer = undefined;\n }\n const before = query.state;\n let keys: K[];\n try {\n keys = await this.config.fetch(query.params);\n } catch (reason) {\n if (query.state !== before) return;\n // A refetch revalidates an answer the caller already has. Failing to\n // confirm it is not grounds for taking it away.\n if (before.variant === \"ready\") return;\n query.state = { variant: \"error\", error: errors.fromUnknown(reason) };\n return;\n }\n // Only apply if maintenance hasn't been torn down and no newer fetch\n // superseded this one.\n if (query.state !== before) return;\n query.state = { variant: \"ready\", keys };\n this.touch(query);\n }\n\n private scheduleRefetch(query: Query<P, K, D, V>): void {\n // A fetch in flight publishes its own keys on settle, and a refetch racing\n // it resolves into a state its result no longer matches, so it is dropped.\n if (query.state.variant === \"loading\") {\n query.refetchOnSettle = true;\n return;\n }\n if (query.refetchTimer != null) clearTimeout(query.refetchTimer);\n const wait = DEFAULT_DEBOUNCE.milliseconds;\n query.refetchTimer = setTimeout(() => {\n query.refetchTimer = undefined;\n void this.refetch(query);\n }, wait);\n }\n\n private isServerComputed(params: P): boolean {\n const { serverFields } = this.config;\n if (serverFields == null || serverFields.length === 0) return false;\n if (typeof params !== \"object\" || params === null) return false;\n return Object.entries(params).some(\n ([field, value]) => value != null && serverFields.includes(field),\n );\n }\n\n private maintain(query: Query<P, K, D, V>): void {\n const teardown: destructor.Destructor[] = [];\n query.teardown = teardown;\n const { table, keyOf, matches, watch: watches } = this.config;\n const { params } = query;\n // Rules 2 and 3 build membership from events, and an unmaintained query\n // received none, so its answer must be reconfirmed. Rule 1 re-seeds from the\n // table below and needs no network.\n if (\n query.unmaintained === true &&\n query.state.variant === \"ready\" &&\n keyOf?.(params) == null\n )\n this.scheduleRefetch(query);\n query.unmaintained = false;\n\n // A keys-only query whose members the table already holds seeds a ready answer:\n // rules 2 and 3 gate notifications on a ready state, so without the seed an\n // answer getCached composes would look live while never updating.\n const composableKeys = this.config.keysOf?.(params);\n if (\n composableKeys != null &&\n query.state.variant !== \"loading\" &&\n query.state.variant !== \"ready\"\n ) {\n const members = this.composableMembersOf(composableKeys);\n if (members != null) {\n query.state = { variant: \"ready\", keys: members };\n this.touch(query);\n }\n }\n\n if (this.isServerComputed(params) || (keyOf?.(params) == null && matches == null)) {\n // Rule 3: server-computed — any relevant event triggers a debounced\n // wholesale refetch; membership is never patched locally. A change to a\n // current member's entry notifies immediately, so optimistic writes render\n // without waiting on the refetch.\n teardown.push(\n table.subscribeBatch((events) => {\n this.scheduleRefetch(query);\n this.touchMembers(\n query,\n events.map((event) => event.key),\n );\n }),\n );\n watches?.forEach((w) =>\n teardown.push(\n w.attach(params, (result) => {\n this.scheduleRefetch(query);\n if (result !== \"refetch\") this.touchMembers(query, result);\n }),\n ),\n );\n return;\n }\n\n const key = keyOf?.(params);\n if (key != null) {\n // Rule 1: exact-key — track one entry; deletion flips the answer. An entry\n // already in the table answers the query without a fetch. The state is a\n // cache of the table's presence for this key and goes stale while\n // unsubscribed (a delete observed, then a recreate), so maintenance\n // re-seeds from the table instead of trusting the last answer. A loading\n // query owns an in-flight promise its own settle will resolve.\n if (query.state.variant !== \"loading\") {\n const status = table.status(key);\n if (status === \"present\" && query.state.variant !== \"ready\") {\n query.state = { variant: \"ready\", keys: [key] };\n this.touch(query);\n } else if (status === \"tombstoned\" && query.state.variant !== \"deleted\") {\n query.state = { variant: \"deleted\", key };\n this.touch(query);\n }\n }\n teardown.push(\n table.subscribe((event) => {\n if (event.variant === \"set\") query.state = { variant: \"ready\", keys: [key] };\n else\n query.state =\n table.status(key) === \"tombstoned\"\n ? { variant: \"deleted\", key }\n : { variant: \"unfetched\" };\n this.touch(query);\n }, key),\n );\n watches?.forEach((w) =>\n teardown.push(\n w.attach(params, (result) => {\n if (result === \"refetch\") return this.scheduleRefetch(query);\n if (result.includes(key) && query.state.variant === \"ready\")\n this.touch(query);\n }),\n ),\n );\n return;\n }\n\n // Rule 2: client-checkable — admit/evict exactly against `matches`.\n teardown.push(\n table.subscribeBatch((events) =>\n this.recheckKeys(\n query,\n events.map((event) => event.key),\n ),\n ),\n );\n watches?.forEach((w) =>\n teardown.push(\n w.attach(params, (result) => {\n if (result === \"refetch\") return this.scheduleRefetch(query);\n void this.recheckMany(query, result);\n }),\n ),\n );\n }\n\n /**\n * Applies membership rechecks for the given keys against the table's current entries,\n * without notifying. Admissions append in iteration order; evicting a single space's\n * last member flips the query to deleted or unfetched. Returns whether the answer\n * changed: membership moved, or a member's content was touched.\n */\n private applyRechecks(query: Query<P, K, D, V>, keys: Iterable<K>): boolean {\n if (query.state.variant === \"loading\") {\n const pending = (query.pendingRechecks ??= new Set<K>());\n for (const key of keys) pending.add(key);\n return false;\n }\n if (query.state.variant !== \"ready\") return false;\n const { table, matches, single } = this.config;\n const memberSet = new Set(query.state.keys);\n const admitted: K[] = [];\n let lastEvicted: K | null = null;\n let touched = false;\n for (const key of new Set(keys)) {\n const entry = table.get(key);\n const matched = entry != null && matches!(entry, query.params);\n if (matched === memberSet.has(key)) {\n touched ||= matched;\n continue;\n }\n if (matched) {\n memberSet.add(key);\n admitted.push(key);\n } else {\n memberSet.delete(key);\n lastEvicted = key;\n }\n }\n if (admitted.length === 0 && lastEvicted == null) return touched;\n const next = [...query.state.keys.filter((k) => memberSet.has(k)), ...admitted];\n if (single === true && next.length === 0 && lastEvicted != null)\n query.state =\n table.status(lastEvicted) === \"tombstoned\"\n ? { variant: \"deleted\", key: lastEvicted }\n : { variant: \"unfetched\" };\n else query.state = { variant: \"ready\", keys: next };\n return true;\n }\n\n /** Applies rechecks for the keys, then notifies once when anything changed. */\n private recheckKeys(query: Query<P, K, D, V>, keys: Iterable<K>): void {\n if (this.applyRechecks(query, keys)) this.touch(query);\n }\n\n /** Never rejects: a failed backfill is reported and the recheck is skipped. */\n private async recheckMany(query: Query<P, K, D, V>, keys: K[]): Promise<void> {\n const { table } = this.config;\n this.recheckKeys(query, keys);\n const missing = keys.filter((key) => table.status(key) === \"unknown\");\n if (missing.length === 0) return;\n // Backfill through the table's fetch so membership can be rechecked;\n // fetch-less tables serve cached entries only and the recheck is a no-op.\n try {\n await table.retrieve(missing);\n this.recheckKeys(query, missing);\n } catch (exc) {\n this.report(exc, `failed to hydrate ${this.config.name} answers`);\n }\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// The query cache value-imports this module, so a runtime edge back into\n// channel or ontology re-creates the import cycle this file exists to break.\n// Runtime imports must stay on leaf modules (external packages, @/errors).\n\nimport { EOF } from \"@synnaxlabs/freighter\";\nimport { breaker, errors, observe, sync, TimeSpan, TimeStamp } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { AccessDeniedError, NotFoundError, ValidationError } from \"@/errors\";\nimport { type Frame } from \"@/framer/frame\";\nimport {\n type Streamer,\n type StreamerConfig,\n type StreamOpener,\n} from \"@/framer/streamer\";\n\ntype NormalizedStreamerConfig = Extract<StreamerConfig, { channels: unknown }>;\n\n// Copies object configs: update() reassigns channels, and the caller's config must\n// not observe that.\nconst normalizeConfig = (config: StreamerConfig): NormalizedStreamerConfig =>\n typeof config === \"object\" && !Array.isArray(config) && \"channels\" in config\n ? { ...config }\n : { channels: config };\n\n/**\n * A hardened streamer that automatically reconnects on failure.\n * This streamer wraps a regular streamer and adds automatic reconnection\n * logic when the connection is lost or errors occur.\n */\nexport class HardenedStreamer implements Streamer {\n private current: Streamer | null = null;\n private readonly breaker: breaker.Breaker;\n private readonly opener: StreamOpener;\n private readonly config: NormalizedStreamerConfig;\n private readonly onReopen?: () => void;\n private readonly onDrop?: (error: Error) => void;\n private readonly closeNotifier = new sync.Notifier();\n // A stream that outlives this span proves the incident over; a shorter\n // life keeps the reconnect backoff escalating.\n private readonly stableAfter: TimeSpan;\n private openedAt = TimeStamp.now();\n private closed = false;\n private reconnecting: Promise<void> | null = null;\n\n constructor(\n opener: StreamOpener,\n config: StreamerConfig,\n breakerConfig: breaker.Config = {},\n onReopen?: () => void,\n onDrop?: (error: Error) => void,\n ) {\n this.opener = opener;\n this.config = normalizeConfig(config);\n const {\n maxRetries = Infinity,\n baseInterval = TimeSpan.seconds(1),\n // reconnect attempts are cheap: a low cap bounds how long a returned\n // cluster goes unnoticed while backoff is escalated\n maxInterval = TimeSpan.seconds(5),\n scale = 2,\n jitter = 0.25,\n } = breakerConfig ?? {};\n this.breaker = new breaker.Breaker({\n maxRetries,\n baseInterval,\n maxInterval,\n scale,\n jitter,\n // close() interrupts a pending backoff so a retired streamer's\n // reconnect loop ends promptly instead of sleeping through it\n sleepFn: async (duration) => {\n await this.closeNotifier.wait(duration);\n },\n });\n this.stableAfter = new TimeSpan(maxInterval);\n this.onReopen = onReopen;\n this.onDrop = onDrop;\n }\n\n /**\n * Opens a new hardened streamer with the given configuration.\n * @param breakerConfig - Retry behavior for reconnect attempts. Defaults to retrying\n * forever on capped, jittered exponential backoff.\n * @param onReopen - Called after every successful reconnect (not the initial open).\n * Frames may have been dropped between the failure and the reopen.\n * @param onDrop - Called when the stream fails and reconnection begins.\n * @returns A promise that resolves to a new hardened streamer\n */\n static async open(\n opener: StreamOpener,\n config: StreamerConfig,\n breakerConfig?: breaker.Config,\n onReopen?: () => void,\n onDrop?: (error: Error) => void,\n ): Promise<HardenedStreamer> {\n const h = new HardenedStreamer(opener, config, breakerConfig, onReopen, onDrop);\n await h.start();\n return h;\n }\n\n /**\n * Opens the underlying stream, retrying connectivity failures under the breaker.\n * Call once after construction; {@link open} does both.\n * @throws the open failure when it is not retriable or the breaker is exhausted.\n */\n async start(): Promise<void> {\n await this.runStreamer(false);\n }\n\n private async runStreamer(notifyReopen: boolean = true): Promise<void> {\n // A long-lived stream that dropped is a fresh incident: reconnect immediately. A\n // short-lived one is a failing cycle (e.g. a server that accepts streams and\n // instantly ends them): keep backing off, or the loop dials hot.\n if (notifyReopen)\n if (TimeStamp.since(this.openedAt).greaterThan(this.stableAfter))\n this.breaker.reset();\n else if (!(await this.breaker.wait())) throw new EOF();\n while (!this.closed)\n try {\n if (this.current != null) this.current.close();\n this.current = null;\n const next = await this.opener(this.config);\n // closed while the open was in flight: the fresh stream is already\n // retired and must not be handed to callers\n if (this.closed) {\n next.close();\n break;\n }\n this.current = next;\n this.openedAt = TimeStamp.now();\n if (notifyReopen) this.onReopen?.();\n return;\n } catch (e) {\n this.current = null;\n if (this.closed) break;\n const err = errors.fromUnknown(e);\n // Retrying only fixes connectivity; a definitive rejection recurs on every\n // attempt. Expired and invalid tokens are not definitive: the auth\n // middleware refreshes them, and a later attempt gets a fresh budget.\n if (\n AccessDeniedError.matches(err) ||\n ValidationError.matches(err) ||\n NotFoundError.matches(err)\n )\n throw err;\n if (!(await this.breaker.wait())) throw err;\n // close() interrupts the backoff above, so re-check: a retired\n // streamer's failed reconnect is expected, not a fault to report.\n if (this.closed) break;\n console.error(\"failed to open streamer\", e);\n }\n throw new EOF();\n }\n\n private get wrapped(): Streamer {\n if (this.current == null) throw new Error(\"stream closed\");\n return this.current;\n }\n\n // A failure during an in-flight reconnect joins it; a second run would open a\n // competing stream and leak the loser.\n private async reconnect(error: Error): Promise<void> {\n if (this.reconnecting == null) {\n this.onDrop?.(error);\n this.reconnecting = this.runStreamer().finally(() => {\n this.reconnecting = null;\n });\n }\n await this.reconnecting;\n }\n\n async update(channels: channel.Params): Promise<void> {\n if (this.closed) throw new EOF();\n this.config.channels = channels;\n try {\n await this.wrapped.update(channels);\n } catch (e) {\n if (this.closed || EOF.matches(e)) throw errors.fromUnknown(e);\n await this.reconnect(errors.fromUnknown(e));\n return await this.update(channels);\n }\n }\n\n async next(): Promise<IteratorResult<Frame>> {\n try {\n return { done: false, value: await this.read() };\n } catch (e) {\n if (EOF.matches(e)) return { done: true, value: undefined };\n throw errors.fromUnknown(e);\n }\n }\n\n async read(): Promise<Frame> {\n if (this.closed) throw new EOF();\n try {\n return await this.wrapped.read();\n } catch (e) {\n if (this.closed) throw new EOF();\n // an EOF the client did not ask for is a drop: the server ended the\n // stream, so reconnect like any other failure\n await this.reconnect(errors.fromUnknown(e));\n return await this.read();\n }\n }\n\n /** Stops reconnecting and closes the stream. Idempotent; never throws. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n this.closeNotifier.notify();\n this.current?.close();\n }\n\n get keys(): channel.Key[] {\n return this.wrapped.keys;\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Frame> {\n return this;\n }\n}\n\n/**\n * Wraps a standard streamer to implement an observable interface for handling changes\n * to channel values through an onChange handler.\n */\nexport class ObservableStreamer<V = Frame>\n extends observe.Observer<Frame, V>\n implements observe.ObservableAsyncCloseable<V>\n{\n private readonly streamer: Streamer;\n private readonly closePromise: Promise<void>;\n private readonly onDead?: (error: Error) => void;\n private closeRequested = false;\n\n /**\n * Creates a new observable streamer.\n * @param transform - An optional transform function to apply to each frame\n * @param onDead - Called when the stream ends on a failure the wrapped streamer will\n * not recover from. No frames follow.\n */\n constructor(\n streamer: Streamer,\n transform?: observe.Transform<Frame, V>,\n onDead?: (error: Error) => void,\n ) {\n super(transform);\n this.streamer = streamer;\n this.onDead = onDead;\n // Nothing awaits closePromise until close(), so a failure would go unhandled.\n this.closePromise = this.stream().catch(console.error);\n }\n\n async update(channels: channel.Params): Promise<void> {\n await this.streamer.update(channels);\n }\n\n async close(): Promise<void> {\n this.closeRequested = true;\n this.streamer.close();\n await this.closePromise;\n }\n\n private async stream(): Promise<void> {\n try {\n for await (const frame of this.streamer) this.notify(frame);\n } catch (exc) {\n this.onDead?.(errors.fromUnknown(exc));\n return;\n }\n if (!this.closeRequested) this.onDead?.(new EOF());\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { EOF } from \"@synnaxlabs/freighter\";\nimport { type breaker, DataType, errors, zod } from \"@synnaxlabs/x\";\nimport type z from \"zod\";\n\nimport { isConnectionError, NotFoundError } from \"@/errors\";\nimport { type framer } from \"@/framer\";\nimport { HardenedStreamer, ObservableStreamer } from \"@/framer/hardened\";\n\n/**\n * A raw channel reaction: parses frames from the channel with the schema and invokes\n * onChange once per frame with every parsed value, in order. Mirror listeners bind to\n * this shape internally; domains register reactions via the cache's listen.\n */\nexport interface Listener<Z extends z.ZodType = z.ZodType> {\n /** The name of the Synnax channel to listen to */\n channel: string;\n /** Zod schema for parsing and validating channel data */\n schema: Z;\n /** Receives the frame's parsed values for the channel as one batch. */\n onChange(this: void, changed: z.output<Z>[]): Promise<unknown> | unknown;\n}\n\n/**\n * Sorts channel names to ensure deletions are processed before other changes. This\n * ensures that modifications to things like relationships (delete followed by create)\n * are processed in the correct order.\n * @returns Sort order (-1, 0, or 1)\n */\nconst channelNameSort = (a: string, b: string) => {\n const aHasDelete = a.includes(\"delete\");\n const bHasDelete = b.includes(\"delete\");\n if (aHasDelete && !bHasDelete) return -1;\n if (!aHasDelete && bHasDelete) return 1;\n return 0;\n};\n\n/** Arguments for opening a cache streamer. */\nexport interface StreamerParams {\n /** Receives frame-handling and listener errors. */\n onError: (error: Error) => void;\n /** The channel listeners to drive with streamed changes. */\n listeners: Listener[];\n /** Opens the raw frame stream; hardening is applied internally. */\n openStreamer: framer.StreamOpener;\n /** Retry behavior for stream reconnect attempts. */\n breaker?: breaker.Config;\n /** Called once when the stream first opens, before any frame is processed. */\n onOpen?: () => void;\n /**\n * Called after every successful reconnect of the underlying stream (not the\n * initial open). Changes may have been missed while disconnected.\n */\n onReopen?: () => void;\n /**\n * Called whenever the stream goes live: after the initial open and before every\n * onReopen, so reconciliation fetches never race a stale liveness verdict.\n */\n onLive?: () => void;\n /** Called when the underlying stream fails and reconnection begins. */\n onDrop?: (error: Error) => void;\n /**\n * Called when the stream ends on a failure it cannot recover from. The next\n * demand opens a new stream.\n */\n onDead?: (error: Error) => void;\n}\n\n/**\n * A lazily-opened change stream over the channels named in a table config.\n * Construction is synchronous and network-free; the underlying stream opens\n * on the first {@link Streamer.demand} call.\n */\nexport interface Streamer {\n /**\n * Ensures the underlying stream is open, opening it on first call. Resolves\n * once streaming is live. Safe to call concurrently and repeatedly.\n */\n demand: () => Promise<void>;\n /** Closes the stream. A no-op when the stream was never demanded. */\n close: () => Promise<void>;\n}\n\n/**\n * Creates a lazy streamer that, once demanded, listens to configured channels and\n * invokes the appropriate listeners when data changes.\n * @returns The lazy streamer handle\n */\nexport const createStreamer = ({\n openStreamer,\n breaker: breakerConfig,\n listeners: allListeners,\n onError,\n onOpen,\n onReopen,\n onLive,\n onDrop,\n onDead,\n}: StreamerParams): Streamer => {\n let opened: Promise<ObservableStreamer> | null = null;\n let hardened: HardenedStreamer | null = null;\n let closed = false;\n const report = (exc: unknown, message: string) => {\n if (NotFoundError.matches(exc)) return;\n // A connectivity failure mid-change is repaired by the reconcile that\n // follows the stream's reopen, so it is churn, not a defect.\n if (isConnectionError(exc)) return;\n onError(new Error(message, { cause: exc }));\n };\n const open = async (): Promise<ObservableStreamer> => {\n if (closed) throw new EOF();\n const listenersForChannels = Map.groupBy(allListeners, ({ channel }) => channel);\n const channels = Array.from(listenersForChannels.keys());\n const h = new HardenedStreamer(\n openStreamer,\n { channels },\n breakerConfig,\n // onLive first: onReopen's reconcile fetches must not hit a stale\n // liveness short circuit\n () => {\n onLive?.();\n onReopen?.();\n },\n onDrop,\n );\n // Held outside so close() can interrupt the retry loop while this call\n // is still waiting on a first successful open.\n hardened = h;\n await h.start();\n // ObservableStreamer construction below starts reads, so onOpen precedes any frame.\n onOpen?.();\n onLive?.();\n const handleChange = (frame: framer.Frame) => {\n const namesInFrame = frame.uniqueNames.sort(channelNameSort);\n void (async () => {\n for (const name of namesInFrame) {\n const series = frame.get(name);\n const listeners = listenersForChannels.get(name);\n if (listeners == null) continue;\n const parseOpts = { label: `${name} sample` };\n for (const { onChange, schema } of listeners) {\n let parsed: z.output<typeof schema>[];\n try {\n if (!series.dataType.equals(DataType.JSON))\n parsed = Array.from(series).map((s) => zod.parse(schema, s, parseOpts));\n else parsed = series.parseJSON(schema);\n } catch (exc) {\n report(exc, `failed to parse streamer change for ${name}`);\n continue;\n }\n if (parsed.length === 0) continue;\n try {\n await onChange(parsed);\n } catch (exc) {\n report(exc, `failed to handle streamer change for ${name}`);\n }\n }\n }\n })();\n };\n const stream = new ObservableStreamer(h, undefined, (error) => {\n // drop the memoized stream so the next demand opens a fresh one\n opened = null;\n onDead?.(error);\n });\n stream.onChange(handleChange);\n return stream;\n };\n return {\n demand: async () => {\n if (opened == null) {\n const { promise, resolve, reject } =\n Promise.withResolvers<ObservableStreamer>();\n // Assigned before open runs: opening resolves channels through the cached\n // read path, which re-enters demand synchronously. An unset memo there\n // recurses instead of joining. Keep these two statements in this order.\n opened = promise;\n open().then(resolve, reject);\n }\n try {\n await opened;\n } catch (exc) {\n // clear the memoized failure so a later demand can retry the open\n opened = null;\n // a close mid-open retires the stream; the demand did not fail\n if (closed) return;\n throw errors.fromUnknown(exc);\n }\n },\n close: async () => {\n closed = true;\n // Interrupts an in-flight open's retry loop; opened then settles.\n hardened?.close();\n if (opened == null) return;\n const streamer = await opened.catch(() => null);\n if (streamer != null) await streamer.close();\n },\n };\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n array,\n type CrudeTimeSpan,\n debounce,\n deep,\n destructor,\n errors,\n type record,\n state,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport type z from \"zod\";\n\nimport { NotFoundError } from \"@/errors\";\nimport { Deleted } from \"@/query/deleted\";\nimport { type Listener } from \"@/query/streamer\";\n\n/**\n * Presence of a key in a table: \"present\" when a live entry exists, \"tombstoned\"\n * when the entry was deleted and its corpse is retained, \"unknown\" when the\n * table has never seen the key or the corpse was cleared.\n */\nexport type EntryStatus = \"present\" | \"tombstoned\" | \"unknown\";\n\n/** A change to a single entry of a {@link Table}. */\nexport type TableEvent<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> = { variant: \"set\"; key: Key; value: Value } | { variant: \"delete\"; key: Key };\n\n/** Receives {@link TableEvent}s. Must be synchronous; thrown errors are\n * reported to the table's error sink and do not stop delivery. */\nexport interface TableSubscriber<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> {\n (event: TableEvent<Key, Value>): void;\n}\n\n/**\n * Receives every event of a batched write as one call, in event order. A single write\n * delivers a batch of one. Same synchrony and error contract as\n * {@link TableSubscriber}.\n */\nexport interface BatchSubscriber<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> {\n (events: TableEvent<Key, Value>[]): void;\n}\n\n/**\n * How fetched records hydrate a table: \"set\" overwrites entries, \"if-absent\"\n * preserves existing entries.\n */\nexport type HydrateMode = \"set\" | \"if-absent\";\n\n/** A table value carrying its entry key, so batch writes and fetches can derive\n * each entry's key from the record itself. */\nexport type Keyed<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> = Value & record.Keyed<Key>;\n\n/** Construction arguments for a {@link Table}. */\nexport interface TableParams<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> {\n /** Receives subscriber and fetch errors that have no caller to throw to. */\n onError: (error: Error) => void;\n /** Overrides the deep-equality default used to silence redundant sets. */\n equal?: (a: Value, b: Value, key: Key) => boolean;\n /**\n * Fetches the current records for the given keys from the cluster,\n * returning only the entries that still exist. Powers {@link Table.retrieve},\n * key-announce listeners, and reconciliation. Omit for tables with no\n * server backing (they are skipped by all three).\n */\n fetch?: (keys: Key[]) => Promise<Array<Keyed<Key, Value>>>;\n /**\n * Hydration mode, \"set\" by default. Dispatch-backed document tables use\n * \"if-absent\" so fetches never clobber locally replayed edits.\n */\n hydrate?: HydrateMode;\n /**\n * Window for coalescing concurrent miss fetches into one fetch call.\n * @default TimeSpan.milliseconds(10)\n */\n fetchDebounce?: CrudeTimeSpan;\n}\n\n/**\n * Retrieves by key are strict: a batch containing any vanished key rejects\n * with NotFound instead of returning the survivors. Falls back to probing\n * keys one at a time so survivors are still distinguishable.\n */\nconst fetchSurvivors = async <Key extends record.Key, Value extends state.State>(\n fetch: NonNullable<TableParams<Key, Value>[\"fetch\"]>,\n keys: Key[],\n): Promise<Array<Keyed<Key, Value>>> => {\n try {\n return await fetch(keys);\n } catch (exc) {\n if (!NotFoundError.matches(exc)) throw errors.fromUnknown(exc);\n }\n if (keys.length === 1) return [];\n const probed = await Promise.all(\n keys.map(async (key) => {\n try {\n return await fetch([key]);\n } catch (exc) {\n if (NotFoundError.matches(exc)) return [];\n throw errors.fromUnknown(exc);\n }\n }),\n );\n return probed.flat();\n};\n\nconst DEFAULT_FETCH_DEBOUNCE = TimeSpan.milliseconds(10);\n\n/**\n * The sole owner of one resource's record content and tombstones. Everything else in\n * the cache holds keys into it: answers store key lists, dispatch bookkeeping rides\n * entry deletion, and consumers assemble content at read time. An equal-value set\n * announces nothing: writers echoing state the table already holds (server echoes of\n * optimistic writes, idempotent backfills) are silenced by the equality check rather\n * than by writer identity.\n */\nexport class Table<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> {\n private readonly entries = new Map<Key, Value>();\n private readonly tombstones = new Map<Key, Deleted<Value>>();\n private readonly broadSubscribers = new Set<TableSubscriber<Key, Value>>();\n private readonly batchSubscribers = new Set<BatchSubscriber<Key, Value>>();\n private readonly keyedSubscribers = new Map<Key, Set<TableSubscriber<Key, Value>>>();\n private batching: TableEvent<Key, Value>[] | null = null;\n private readonly onError: (error: Error) => void;\n private readonly equal: (a: Value, b: Value, key: Key) => boolean;\n private readonly fetchEntries?: (keys: Key[]) => Promise<Array<Keyed<Key, Value>>>;\n private readonly hydrateMode: HydrateMode;\n private readonly fetchBatcher: debounce.Batcher<\n Key[],\n Array<Keyed<Key, Value>>\n > | null;\n private gen = 0;\n\n constructor({\n onError,\n equal = deep.equal,\n fetch,\n hydrate = \"set\",\n fetchDebounce = DEFAULT_FETCH_DEBOUNCE,\n }: TableParams<Key, Value>) {\n this.onError = onError;\n this.equal = equal;\n this.fetchEntries = fetch;\n this.hydrateMode = hydrate;\n this.fetchBatcher =\n fetch == null\n ? null\n : new debounce.Batcher({\n interval: fetchDebounce,\n exec: async (requests) => {\n const keys = new Set<Key>();\n requests.forEach(({ req }) => req.forEach((key) => keys.add(key)));\n const fetched = await fetch(Array.from(keys));\n // The window's fetch carries other callers' keys too; each caller\n // hydrates only the entries it asked for.\n requests.forEach(({ req, resolve }) => {\n const mine = new Set(req);\n resolve(fetched.filter(({ key }) => mine.has(key)));\n });\n },\n });\n }\n\n private setOne(\n key: Key,\n value: state.SetArg<Value | undefined>,\n ): destructor.Destructor | undefined {\n const prev = this.entries.get(key);\n const next = state.executeSetter(value, prev);\n if (next == null || (prev != null && this.equal(next, prev, key))) return undefined;\n const prevTombstone = this.tombstones.get(key);\n this.tombstones.delete(key);\n this.entries.set(key, next);\n this.notify({ variant: \"set\", key, value: next });\n\n return () => {\n if (prev === undefined) {\n this.entries.delete(key);\n if (prevTombstone != null) this.tombstones.set(key, prevTombstone);\n this.notify({ variant: \"delete\", key });\n } else {\n this.entries.set(key, prev);\n this.notify({ variant: \"set\", key, value: prev });\n }\n };\n }\n\n /**\n * Sets the value for the given key, or applies a setter to the previous value. A\n * setter producing null/undefined, or a value equal to the current one, is a no-op.\n * @returns A rollback that undoes the set.\n */\n set(key: Key, value: state.SetArg<Value | undefined>): destructor.Destructor;\n /**\n * Sets every given keyed value, keying each entry by its key property.\n * @returns A rollback that undoes the inserted values in reverse order.\n */\n set(values: Keyed<Key, Value> | Array<Keyed<Key, Value>>): destructor.Destructor;\n set(\n keyOrValues: Key | Keyed<Key, Value> | Array<Keyed<Key, Value>>,\n value?: state.SetArg<Value | undefined>,\n ): destructor.Destructor {\n if (typeof keyOrValues !== \"object\")\n return this.setOne(keyOrValues as Key, value) ?? destructor.NOOP;\n const rollbacks: destructor.Destructor[] = [];\n this.batch(() =>\n array.toArray(keyOrValues).forEach((val) => {\n const rollback = this.setOne(val.key, val);\n if (rollback != null) rollbacks.push(rollback);\n }),\n );\n return () => this.batch(() => rollbacks.reverse().forEach((r) => r()));\n }\n\n private setIfAbsent(values: Array<Keyed<Key, Value>>): destructor.Destructor {\n const rollbacks: destructor.Destructor[] = [];\n this.batch(() =>\n values.forEach((val) => {\n if (this.entries.has(val.key)) return;\n const rollback = this.setOne(val.key, val);\n if (rollback != null) rollbacks.push(rollback);\n }),\n );\n return () => this.batch(() => rollbacks.reverse().forEach((r) => r()));\n }\n\n /**\n * Writes fetched records into the table under its declared hydrate mode:\n * \"set\" overwrites entries, \"if-absent\" leaves existing entries untouched.\n * @returns A rollback that undoes the entries this call wrote.\n */\n ingest(values: Keyed<Key, Value> | Array<Keyed<Key, Value>>): destructor.Destructor {\n const arr = array.toArray(values);\n if (this.hydrateMode === \"if-absent\") return this.setIfAbsent(arr);\n return this.set(arr);\n }\n\n /** Returns every entry in the table. */\n get(): Value[];\n get(key: Key): Value | undefined;\n get(keys: Key[]): Value[];\n get(filter: (value: Value) => boolean): Value[];\n get(keys?: Key | Key[] | ((value: Value) => boolean)): Value | Value[] | undefined {\n if (keys === undefined) return Array.from(this.entries.values());\n if (typeof keys === \"function\")\n return Array.from(this.entries.values()).filter(keys);\n if (Array.isArray(keys))\n return keys\n .map((key) => this.entries.get(key))\n .filter((e): e is Value => e != null);\n return this.entries.get(keys);\n }\n\n has(key: Key): boolean {\n return this.entries.has(key);\n }\n\n /** Returns the key of every live entry. */\n keys(): Key[] {\n return Array.from(this.entries.keys());\n }\n\n /**\n * Returns the presence of the given key: present, tombstoned, or unknown.\n * Cache-internal surface: consumed by the query machinery, not domain code.\n */\n status(key: Key): EntryStatus {\n if (this.entries.has(key)) return \"present\";\n if (this.tombstones.has(key)) return \"tombstoned\";\n return \"unknown\";\n }\n\n /**\n * Returns the tombstone for the given key, or undefined if none exists.\n * Cache-internal surface: consumed by the query machinery, not domain code.\n */\n getTombstone(key: Key): Deleted<Value> | undefined {\n return this.tombstones.get(key);\n }\n\n /**\n * Resolves the given keys to records: serves cached entries and fetches the misses\n * through the table's fetch, hydrating results under the declared mode. With refresh,\n * every key is fetched regardless of presence. Returns the table's entries for the\n * found keys in input order, deduplicated; keys the cluster no longer has are\n * omitted. Tables without a fetch serve cached entries only.\n */\n async retrieve(keys: Key[], opts: { refresh?: boolean } = {}): Promise<Value[]> {\n if (this.fetchBatcher != null) {\n const misses =\n opts.refresh === true ? keys : keys.filter((key) => !this.entries.has(key));\n if (misses.length > 0) {\n const gen = this.gen;\n const fetched = await this.fetchBatcher.enqueue(misses);\n if (gen === this.gen && fetched.length > 0)\n if (opts.refresh === true) this.set(fetched);\n else this.ingest(fetched);\n }\n }\n const seen = new Set<Key>();\n const results: Value[] = [];\n for (const key of keys) {\n if (seen.has(key)) continue;\n seen.add(key);\n const entry = this.entries.get(key);\n if (entry != null) results.push(entry);\n }\n return results;\n }\n\n /**\n * Deletes entries and notifies subscribers. Deleted values are retained as\n * tombstones until a subsequent set for the key.\n * @param key - The key(s) to delete or a filter function\n * @returns A rollback that restores the deleted entries\n */\n delete(\n key: Key | Key[] | ((value: Value, key: Key) => boolean),\n ): destructor.Destructor {\n return this.remove(key, true);\n }\n\n /**\n * Removes entries and notifies subscribers, retaining no corpses: the undo of a write\n * the record never survived, not a deletion. A reader finds the key unknown rather\n * than deleted.\n * @returns A rollback that restores the removed entries\n */\n evict(key: Key | Key[]): destructor.Destructor {\n return this.remove(key, false);\n }\n\n private remove(\n key: Key | Key[] | ((value: Value, key: Key) => boolean),\n tombstone: boolean,\n ): destructor.Destructor {\n const toDelete: Array<{ key: Key; value?: Value }> = [];\n\n if (typeof key === \"function\")\n this.entries.forEach((value, k) => {\n if (key(value, k)) toDelete.push({ key: k, value });\n });\n else\n array.toArray(key).forEach((k) => {\n const value = this.entries.get(k);\n toDelete.push({ key: k, value });\n });\n\n this.batch(() =>\n toDelete.forEach(({ key: k, value }) => {\n this.entries.delete(k);\n if (tombstone && value != null)\n this.tombstones.set(k, new Deleted(value, TimeStamp.now()));\n this.notify({ variant: \"delete\", key: k });\n }),\n );\n\n return () =>\n this.batch(() =>\n toDelete.forEach(({ key: k, value }) => {\n if (value == null) return;\n this.tombstones.delete(k);\n this.entries.set(k, value);\n this.notify({ variant: \"set\", key: k, value });\n }),\n );\n }\n\n /**\n * Re-checks every cached entry against the cluster through the table's\n * fetch: refreshes entries that still exist and tombstones entries that\n * vanished. A no-op for empty tables and tables without a fetch.\n */\n async reconcile(): Promise<void> {\n const { fetchEntries } = this;\n if (fetchEntries == null) return;\n const keys = this.keys();\n if (keys.length === 0) return;\n const gen = this.gen;\n const values = await fetchSurvivors(fetchEntries, keys);\n // A reset mid-fetch means the cluster was replaced: writing the fetched\n // entries would repopulate the cleared table with old-cluster records.\n if (gen !== this.gen) return;\n const present = new Set<Key>(values.map(({ key }) => key));\n const vanished = keys.filter((k) => !present.has(k));\n this.batch(() => {\n if (vanished.length > 0) this.delete(vanished);\n if (values.length > 0) this.set(values);\n });\n }\n\n /**\n * Discards every entry and tombstone without notifying subscribers. Called\n * only by the cache's reset, which resets the answer spaces itself:\n * per-entry delete events would masquerade as deletions of live records.\n * Fetches in flight when the reset runs discard their results.\n */\n reset(): void {\n this.gen++;\n this.entries.clear();\n this.tombstones.clear();\n }\n\n /**\n * Subscribes to entry changes delivered per batched write: one call carrying every\n * event of the batch, in order, after all of the batch's entries have applied.\n * Cache-internal surface: consumed by the query machinery, not domain code;\n * per-record consumers use {@link subscribe}.\n * @returns A destructor that unsubscribes.\n */\n subscribeBatch(subscriber: BatchSubscriber<Key, Value>): destructor.Destructor {\n this.batchSubscribers.add(subscriber);\n return () => this.batchSubscribers.delete(subscriber);\n }\n\n /**\n * Subscribes to entry changes. With a key, only changes to that entry fire.\n * @returns A destructor that unsubscribes.\n */\n subscribe(subscriber: TableSubscriber<Key, Value>, key?: Key): destructor.Destructor {\n if (key == null) {\n this.broadSubscribers.add(subscriber);\n return () => this.broadSubscribers.delete(subscriber);\n }\n let held = this.keyedSubscribers.get(key);\n if (held == null) {\n held = new Set();\n this.keyedSubscribers.set(key, held);\n }\n held.add(subscriber);\n return () => {\n held.delete(subscriber);\n // Guarded on identity so a stale destructor cannot drop a set a later\n // subscription re-created under the same key.\n if (held.size === 0 && this.keyedSubscribers.get(key) === held)\n this.keyedSubscribers.delete(key);\n };\n }\n\n /**\n * Runs fn with event delivery deferred: writes apply to entries immediately, and\n * every event they produce is delivered as one batch when the outermost batch\n * exits. Delivery stays synchronous, inside this call. Nested batches join the\n * outermost one. Events flush even when fn throws, since the entries they describe\n * were already applied.\n */\n batch<T>(fn: () => T): T {\n if (this.batching != null) return fn();\n const events: TableEvent<Key, Value>[] = [];\n this.batching = events;\n try {\n return fn();\n } finally {\n this.batching = null;\n if (events.length > 0) this.flush(events);\n }\n }\n\n private notify(event: TableEvent<Key, Value>) {\n if (this.batching != null) {\n this.batching.push(event);\n return;\n }\n this.flush([event]);\n }\n\n private flush(events: TableEvent<Key, Value>[]) {\n for (const event of events) {\n this.deliver(this.keyedSubscribers.get(event.key), event);\n this.deliver(this.broadSubscribers, event);\n }\n for (const subscriber of this.batchSubscribers)\n try {\n subscriber(events);\n } catch (exc) {\n this.onError(new Error(\"failed to notify table subscriber\", { cause: exc }));\n }\n }\n\n private deliver(\n subscribers: Iterable<TableSubscriber<Key, Value>> | undefined,\n event: TableEvent<Key, Value>,\n ) {\n if (subscribers == null) return;\n for (const subscriber of subscribers)\n try {\n subscriber(event);\n } catch (exc) {\n this.onError(new Error(\"failed to notify table subscriber\", { cause: exc }));\n }\n }\n}\n\n/**\n * A mirror listener declaration: keeps the owning table current from one stream\n * channel. Built with {@link createSetListener}, {@link createDeleteListener}, or\n * {@link createFetchListener}; bound to its table by the cache.\n */\nexport interface ListenerSpec<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> {\n /** Binds the declaration to the owning table as a raw channel listener. */\n bind: (table: Table<Key, Value>) => Listener;\n}\n\n/**\n * Declares that the channel broadcasts records to mirror into the table.\n * By default the parsed record keys itself (`changed.key`) and is stored\n * as-is; `key` derives the entry key, `value` transforms the record and may\n * merge with the previous entry (return null/undefined to skip the write).\n */\nexport const createSetListener = <\n Z extends z.ZodType,\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n>(\n channel: string,\n schema: Z,\n opts: {\n key?: (changed: z.output<Z>) => Key;\n value?: (changed: z.output<Z>, prev: Value | undefined) => Value | null | undefined;\n } = {},\n): ListenerSpec<Key, Value> => {\n const {\n key = (changed) => (changed as record.Keyed<Key>).key,\n value = (changed) => changed as Value,\n } = opts;\n return {\n bind: (table): Listener<Z> => ({\n channel,\n schema,\n onChange: (changed) => {\n table.batch(() =>\n changed.forEach((c) =>\n table.set(key(c), (prev) => value(c, prev) ?? undefined),\n ),\n );\n },\n }),\n };\n};\n\n/**\n * Declares that the channel broadcasts deletions to mirror into the table.\n * By default the parsed value is the entry key; `key` derives it instead.\n */\nexport const createDeleteListener = <\n Z extends z.ZodType,\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n>(\n channel: string,\n schema: Z,\n opts: { key?: (changed: z.output<Z>) => Key } = {},\n): ListenerSpec<Key, Value> => {\n const { key = (changed) => changed as Key } = opts;\n return {\n bind: (table): Listener<Z> => ({\n channel,\n schema,\n onChange: (changed) => {\n table.delete(changed.map((c) => key(c)));\n },\n }),\n };\n};\n\n/**\n * Declares that the channel announces keys whose records changed. Announced\n * keys are refetched through the table's fetch and overwrite their entries.\n */\nexport const createFetchListener = <\n Z extends z.ZodType<Key | Key[]>,\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n>(\n channel: string,\n schema: Z,\n): ListenerSpec<Key, Value> => ({\n bind: (table): Listener<Z> => ({\n channel,\n schema,\n onChange: async (changed) => {\n await table.retrieve(\n changed.flatMap((c) => array.toArray(c)),\n { refresh: true },\n );\n },\n }),\n});\n\nexport const partialUpdate = <Key extends record.Key, Value extends object>(\n table: Table<Key, Value>,\n key: Key,\n value: Partial<Value>,\n): destructor.Destructor =>\n table.set(key, (p) => (p == null ? undefined : { ...p, ...value }));\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type breaker,\n type destructor,\n errors,\n observe,\n type record,\n type state,\n} from \"@synnaxlabs/x\";\nimport type z from \"zod\";\n\nimport { AccessDeniedError, isConnectionError } from \"@/errors\";\nimport { type framer } from \"@/framer\";\nimport { bindDerived, type DeriveParams } from \"@/query/derived\";\nimport { type Retrieves, Space, type SpaceConfig } from \"@/query/query\";\nimport { createStreamer, type Listener, type Streamer } from \"@/query/streamer\";\nimport { type Keyed, type ListenerSpec, Table, type TableParams } from \"@/query/table\";\nimport { type Data, type Params } from \"@/query/types\";\n\nexport interface CacheParams {\n /**\n * Opens the raw frame streamer used to receive change signals; reconnect hardening is\n * applied internally. Null constructs a detached cache: purely local tables and no\n * change stream. Used for clients constructed with `cache: false`.\n */\n openStreamer: framer.StreamOpener | null;\n /** Retry behavior for change-stream reconnect attempts. */\n breaker?: breaker.Config;\n /** Called whenever the change stream goes live, before reconciliation begins. */\n onStreamLive?: () => void;\n /** Called when the change stream fails and reconnection begins. */\n onStreamDrop?: (error: Error) => void;\n /**\n * Called when the change stream is refused because the caller lacks access to\n * the mirrored channels. Only a policy change lifts a denial.\n */\n onStreamDenied?: (error: Error) => void;\n /**\n * Receives errors that have no caller to throw to: listener fan-out, streamer frame\n * handling, and background reconciliation. Defaults to console logging.\n */\n onError?: (error: Error) => void;\n}\n\n/** Configuration for a derived table owned by a {@link Cache}. */\nexport interface DerivedConfig<\n Key extends record.Key,\n Value extends Keyed<Key>,\n Composed extends Keyed<Key>,\n> extends DeriveParams<Key, Value, Composed> {\n /** Names the table in diagnostics. */\n name: string;\n /** Overrides the deep-equality default used to silence redundant sets. */\n equal?: (a: Composed, b: Composed, key: Key) => boolean;\n}\n\n/** Configuration for a table owned by a {@link Cache}. */\nexport interface TableConfig<\n Key extends record.Key = record.Key,\n Value extends state.State = state.State,\n> extends Omit<TableParams<Key, Value>, \"onError\"> {\n /** Names the table in diagnostics (reconciliation errors). */\n name: string;\n /** Mirror listeners keeping this table current from stream channels. */\n listen?: Array<ListenerSpec<Key, Value>>;\n}\n\ninterface RegisteredTable {\n name: string;\n listeners: Listener[];\n reconcile?: () => Promise<void>;\n reset: () => void;\n}\n\n/** The cache-facing lifecycle of an answer space, generics erased. */\ninterface SpaceLifecycle {\n close: () => void;\n reset: () => void;\n}\n\n/**\n * The client's local mirror of cluster state: keyed tables, the change-stream loop,\n * connection epochs, and reconciliation. Holds zero domain knowledge — domain clients\n * create their tables here and expose typed query spaces. Always present on a client; a\n * null {@link CacheParams.openStreamer} stands in for \"disabled\" or \"not yet connected\"\n * rather than a null cache. The change stream opens lazily: nothing touches the network\n * until the first {@link ensureStreaming} call. All tables and listeners must be\n * declared before streaming starts.\n */\nexport class Cache {\n private readonly tables: RegisteredTable[] = [];\n private readonly reactions: Listener[] = [];\n private readonly spaces: SpaceLifecycle[] = [];\n private readonly detachers: destructor.Destructor[] = [];\n private readonly epochObserver = new observe.Observer<number>();\n private readonly params: CacheParams;\n private streamer: Streamer | null = null;\n private epochCount = 0;\n private unmaintained = false;\n\n /**\n * Stable error sink for machinery built on this cache (dispatch\n * controllers, answer spaces).\n */\n readonly onError: (error: Error) => void;\n\n constructor(params: CacheParams) {\n this.params = params;\n this.onError = params.onError ?? console.error;\n }\n\n /**\n * Creates a table owned by this cache and returns it, binding its declared mirror\n * listeners. Must be called before streaming starts; creating after {@link\n * ensureStreaming} throws, as the new table's channels would never be streamed.\n */\n createTable<Key extends record.Key, Value extends state.State>(\n config: TableConfig<Key, Value>,\n ): Table<Key, Value> {\n if (this.streamer != null)\n throw new Error(`cannot create table ${config.name} after streaming has started`);\n const { name, listen, ...params } = config;\n const table = new Table<Key, Value>({ ...params, onError: this.onError });\n this.tables.push({\n name,\n listeners: (listen ?? []).map((spec) => spec.bind(table)),\n reconcile: config.fetch == null ? undefined : async () => await table.reconcile(),\n reset: () => table.reset(),\n });\n return table;\n }\n\n /**\n * Creates a table materialized from another table owned by this cache. Composed\n * entries are replaced on source and watch events, so entry identity changes exactly\n * when composition changes; misses on read fetch through the source. Resets with the\n * cache. No stream listeners of its own, so it may be created at any time.\n */\n derive<Key extends record.Key, Value extends Keyed<Key>, Composed extends Keyed<Key>>(\n config: DerivedConfig<Key, Value, Composed>,\n ): Table<Key, Composed> {\n const { name, source, compose, watch, equal } = config;\n const table = new Table<Key, Composed>({\n onError: this.onError,\n equal,\n fetch: async (keys) => (await source.retrieve(keys)).map(compose),\n });\n this.detachers.push(bindDerived(table, { source, compose, watch }));\n this.tables.push({ name, listeners: [], reset: () => table.reset() });\n return table;\n }\n\n /**\n * Registers a channel reaction: a listener that is not a table mirror\n * (dispatch wires, cross-table side effects). Same pre-streaming\n * constraint as {@link createTable}.\n */\n listen<Z extends z.ZodType>(listener: Listener<Z>): void {\n if (this.streamer != null)\n throw new Error(\n `cannot listen to ${listener.channel} after streaming has started`,\n );\n this.reactions.push(listener);\n }\n\n /**\n * Constructs an answer space wired to this cache: reads open the change\n * stream, maintained answers refetch on epoch bumps, maintenance errors\n * report to the cache's error sink, and the space closes with the cache.\n */\n queries<\n Q extends Params,\n D extends Data,\n K extends record.Key = record.Key,\n V extends state.State = state.State,\n >(config: SpaceConfig<Q, D, K, V>): Retrieves<Q, D> {\n const space = new Space(config, {\n ensureStreaming: async () => await this.ensureStreaming(),\n onEpoch: (callback) => this.onEpoch(callback),\n maintained: () => !this.unmaintained && this.params.openStreamer != null,\n onError: this.onError,\n });\n this.spaces.push(space);\n return space;\n }\n\n /**\n * Ensures the change stream is open, opening it on first call. Callers that\n * populate or read tables await this first so no change is missed between a\n * fetch and the stream opening.\n * @throws {AccessDeniedError} if the caller cannot stream the mirrored\n * channels. Answers stop being maintained until a later call succeeds.\n */\n async ensureStreaming(): Promise<void> {\n const { openStreamer, breaker, onStreamLive, onStreamDrop, onStreamDenied } =\n this.params;\n if (openStreamer == null) return;\n if (this.streamer == null) {\n // A reset can retire the streamer while its open is in flight; a\n // retired streamer's lifecycle callbacks must not touch the epoch.\n const streamer = createStreamer({\n openStreamer,\n breaker,\n listeners: [\n ...this.tables.flatMap(({ listeners }) => listeners),\n ...this.reactions,\n ],\n onError: this.onError,\n onLive: onStreamLive,\n onDrop: onStreamDrop,\n onOpen: () => {\n if (this.streamer !== streamer) return;\n this.unmaintained = false;\n this.epochCount = 1;\n this.epochObserver.notify(this.epochCount);\n },\n onReopen: () => {\n if (this.streamer !== streamer) return;\n this.bumpEpoch();\n },\n onDead: (error) => {\n if (this.streamer !== streamer) return;\n this.unmaintained = true;\n if (AccessDeniedError.matches(error)) onStreamDenied?.(error);\n },\n });\n this.streamer = streamer;\n }\n try {\n await this.streamer.demand();\n } catch (exc) {\n this.unmaintained = true;\n const error = errors.fromUnknown(exc);\n // The first open never reaches onDead: the stream dies before there is\n // one to observe.\n if (AccessDeniedError.matches(error)) onStreamDenied?.(error);\n throw error;\n }\n }\n\n /**\n * The connection epoch: 0 before streaming starts, 1 once live, incremented\n * on every reconnect. Changes may have been missed between epochs.\n */\n get epoch(): number {\n return this.epochCount;\n }\n\n /** Subscribes to epoch changes. Returns a destructor that unsubscribes. */\n onEpoch(callback: (epoch: number) => void): destructor.Destructor {\n return this.epochObserver.onChange(callback);\n }\n\n /**\n * Re-checks every cached entry against the cluster: refreshes entries that\n * still exist and tombstones entries that vanished. Runs after every\n * reconnect for tables that declare a fetch.\n */\n private async reconcile(): Promise<void> {\n await Promise.all(\n this.tables.map(async ({ name, reconcile }) => {\n if (reconcile == null) return;\n try {\n await reconcile();\n } catch (exc) {\n // The next reopen reconciles again, so an unreachable cluster is churn.\n if (isConnectionError(exc)) return;\n this.onError(new Error(`failed to reconcile ${name} cache`, { cause: exc }));\n }\n }),\n );\n }\n\n /**\n * Discards every cached entry, tombstone, and answer, closes the change\n * stream so it reopens fresh, and returns the epoch to 0. Called when the\n * cluster behind the connection is replaced: no cached record, corpse, or\n * answer remains meaningful, so nothing is tombstoned or diffed.\n */\n async reset(): Promise<void> {\n const { streamer } = this;\n this.streamer = null;\n // Drain the retired stream first so a late frame cannot repopulate the\n // tables cleared below. A close failure must not block the reset: the\n // stream is retired either way.\n try {\n await streamer?.close();\n } catch (exc) {\n console.error(\"failed to close retired stream\", exc);\n }\n this.tables.forEach(({ reset }) => reset());\n this.spaces.forEach((space) => space.reset());\n this.unmaintained = false;\n this.epochCount = 0;\n this.epochObserver.notify(0);\n }\n\n private bumpEpoch(): void {\n this.epochCount++;\n this.epochObserver.notify(this.epochCount);\n this.reconcile().catch((exc: unknown) =>\n this.onError(\n new Error(\"failed to reconcile caches after reconnect\", { cause: exc }),\n ),\n );\n }\n\n /**\n * Closes the change stream and every answer space this cache constructed.\n * A no-op for the stream when streaming never started.\n */\n async close(): Promise<void> {\n this.detachers.forEach((detach) => detach());\n this.spaces.forEach((space) => space.close());\n if (this.streamer == null) return;\n await this.streamer.close();\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type destructor, type record, zod } from \"@synnaxlabs/x\";\nimport z from \"zod\";\n\nimport { NotFoundError, ValidationError } from \"@/errors\";\nimport { type Cache } from \"@/query/cache\";\nimport {\n type Cached,\n type ChangeHandler,\n type Retrieves,\n type Watch,\n} from \"@/query/query\";\nimport { type Keyed, type Table } from \"@/query/table\";\nimport { type Data, type FetchOptions, type Params } from \"@/query/types\";\n\n/** Query fields only the server can evaluate, shared by most request shapes. */\nconst DEFAULT_SERVER_FIELDS = [\"searchTerm\", \"limit\", \"offset\"] as const;\n\n/**\n * Returns the keys of a request that addresses keys and nothing else: a\n * non-empty `keys` field with every other field nullish. Such requests resolve\n * through the table's fetch primitive instead of the request fetch. Returns\n * null for any other request.\n */\nconst keysOnly = (query: unknown): unknown[] | null => {\n if (typeof query !== \"object\" || query === null || Array.isArray(query)) return null;\n const { keys } = query as { keys?: unknown };\n if (!Array.isArray(keys) || keys.length === 0) return null;\n if (!Object.entries(query).every(([k, v]) => k === \"keys\" || v == null)) return null;\n return keys;\n};\n\n/** True for params that are a bare record key rather than a query object. */\nconst isBareKey = (params: unknown): params is record.Key =>\n typeof params === \"string\" || typeof params === \"number\";\n\n/**\n * Request schema arm reading a bare key list as `{ keys }`. Union it onto a\n * domain's request schema to opt that domain into the shorthand:\n * `retrieveRequestZ.or(keyListZ(keyZ))`.\n */\nexport const keyListZ = <K extends z.ZodType<record.Key>>(key: K) =>\n z.array(key).transform((keys) => ({ keys }));\n\ninterface ComposeProp<V, D> {\n /**\n * Per-record enrichment applied to every answer, receiving the normalized\n * query the record answers. Defaults to identity.\n */\n compose: (record: V, query: Params) => D;\n}\n\n/** Optional only when a record is a valid answer as-is (V assignable to D):\n * the identity default is unsound for any narrower D. */\ntype ComposeParam<V, D> = [V] extends [D]\n ? Partial<ComposeProp<V, D>>\n : ComposeProp<V, D>;\n\n/**\n * Declaration of a domain client's read surface. The single space is derived\n * from the table and its fetch: `{ key }` params resolve one record, with\n * deletion flipping the answer to deleted. Declare `single` only when the\n * domain's single query is richer than a key.\n */\nexport type RetrieverParams<\n Z extends z.ZodType<Params>,\n K extends record.Key,\n V extends Keyed<K>,\n D extends Data = V,\n SingleInput = { key: K },\n SingleQuery extends Params = K,\n> = ComposeParam<V, D> & {\n /** Resource name used in error messages, e.g. \"range\". */\n name: string;\n /** The table owning this domain's record content. */\n table: Table<K, V>;\n /** The space answering every non-single query shape. */\n request: {\n /**\n * Parses and canonicalizes request params so equivalent queries hash\n * identically; its output type is the space's query type.\n */\n schema: Z;\n /**\n * Fetches matching records from the cluster. Keys-only requests never\n * reach it; they resolve through the table's fetch. Results hydrate the\n * table under its declared mode.\n */\n fetch: (query: z.output<Z>, options?: FetchOptions) => Promise<V[]>;\n /** Rule 2: whether a record satisfies the query. Pure; no network. */\n matches?: (record: V, query: z.output<Z>) => boolean;\n /** Overrides {@link DEFAULT_SERVER_FIELDS} for this request shape. */\n serverFields?: readonly string[];\n /** Foreign tables whose events affect this space's answers. */\n watch?: Array<Watch<z.output<Z>, K>>;\n };\n /** Custom single space for domains whose single query is richer than a key. */\n single?: {\n /**\n * Discriminates and canonicalizes single params: parse success routes the\n * query to the single space, and the output is the space's query. Object\n * schemas must reject unknown keys so request params fall through. Union\n * in a bare-key arm to accept `retrieve(key)`.\n */\n schema: z.ZodType<SingleQuery, SingleInput | record.Key>;\n /** The space answering single queries, built via the cache. */\n space: Retrieves<SingleQuery, D>;\n };\n};\n\n/**\n * A domain client's cached read surface, routing each query to the single or\n * request answer space. The arity of the result follows the query: params\n * addressing one record yield a record, every other shape yields an array.\n *\n * Extend it and call `super(cache, { ... })`:\n *\n * ```ts\n * export class Client extends query.Retriever<typeof requestZ, Key, Label> {\n * constructor(client: UnaryClient, cache: query.Cache) {\n * const store = cache.createTable({ ... });\n * super(cache, { name: \"label\", table: store, request: { ... } });\n * }\n * }\n * ```\n *\n * Anything evaluated eagerly inside `super` must come from a local, since\n * `this` is unavailable until it returns. Closures may reference `this`: an\n * arrow captures it lexically and does not read it until called.\n *\n * The read surface is not designed for overriding: a domain with more query\n * kinds exposes them as named {@link Retrieves} members instead.\n */\nexport abstract class Retriever<\n Z extends z.ZodType<Params>,\n K extends record.Key,\n V extends Keyed<K>,\n D extends Data = V,\n SingleInput = { key: K },\n SingleQuery extends Params = K,\n> {\n private readonly singleSpace: Retrieves<Params, D | D[]>;\n private readonly requestSpace: Retrieves<Params, D | D[]>;\n private readonly trySingle: (params: unknown) => { query: SingleQuery } | null;\n private readonly normalizeRequest: (params: unknown) => z.output<Z>;\n private readonly routes = new WeakMap<object, [Retrieves<Params, D | D[]>, Params]>();\n\n constructor(\n cache: Cache,\n params: RetrieverParams<Z, K, V, D, SingleInput, SingleQuery>,\n ) {\n const {\n name,\n table,\n request,\n compose = (record: V) => record as unknown as D,\n single,\n } = params;\n const {\n schema,\n fetch,\n matches,\n serverFields = DEFAULT_SERVER_FIELDS,\n watch,\n } = request;\n this.requestSpace = cache.queries<z.output<Z>, D[], K, V>({\n name,\n table,\n fetch: async (query, options) => {\n const keys = keysOnly(query);\n if (keys != null) return (await table.retrieve(keys as K[])).map((r) => r.key);\n const records = await fetch(query, options);\n table.ingest(records);\n return records.map((r) => r.key);\n },\n compose: (records, q) => records.map((r) => compose(r, q)),\n keysOf: (query) => keysOnly(query) as K[] | null,\n matches,\n serverFields,\n watch,\n }) as Retrieves<Params, D | D[]>;\n this.normalizeRequest = (p) => zod.parse(schema, p, { label: `${name} query` });\n if (single != null) {\n this.singleSpace = single.space as Retrieves<Params, D | D[]>;\n const singleSchema = single.schema;\n // Params carrying `key` that fail the single schema are malformed\n // single queries; falling through would silently fetch every record.\n this.trySingle = (p) => {\n const res = singleSchema.safeParse(p);\n if (res.success) return { query: res.data };\n if (isBareKey(p) || (typeof p === \"object\" && p !== null && \"key\" in p)) {\n const cause = new zod.ParseError({\n issues: res.error.issues,\n input: p,\n label: `${name} single query params`,\n cause: res.error,\n });\n throw new ValidationError(\n `${name} params address a single key but do not match the ` +\n `single-query schema.\\n${cause.message}`,\n { cause },\n );\n }\n return null;\n };\n } else {\n // The default path binds SingleQuery = K: `{ key }` params resolve through the\n // table's fetch. The casts are the one seam the defaults can't prove.\n this.singleSpace = cache.queries<K, D, K, V>({\n name,\n table,\n fetch: async (key) => {\n const records = await table.retrieve([key]);\n if (records.length === 0)\n throw new NotFoundError(`${name} with key ${key} not found`);\n return [key];\n },\n compose: (records, q) => compose(records[0], q),\n keyOf: (query) => query,\n single: true,\n }) as Retrieves<Params, D | D[]>;\n this.trySingle = (p) => {\n if (isBareKey(p)) return { query: p as Params as SingleQuery };\n return typeof p === \"object\" && p !== null && \"key\" in p\n ? { query: (p as { key: K }).key as Params as SingleQuery }\n : null;\n };\n }\n }\n\n /**\n * Routes params to their answer space, memoized per params object identity.\n * {@link Params} is readonly, so a given object always routes identically;\n * repeat reads of the same object skip schema validation entirely.\n */\n private route(params: unknown): [Retrieves<Params, D | D[]>, Params] {\n const cacheable = typeof params === \"object\" && params !== null;\n if (cacheable) {\n const held = this.routes.get(params);\n if (held !== undefined) return held;\n }\n const single = this.trySingle(params);\n const route: [Retrieves<Params, D | D[]>, Params] =\n single != null\n ? [this.singleSpace, single.query]\n : [this.requestSpace, this.normalizeRequest(params)];\n if (cacheable) this.routes.set(params, route);\n return route;\n }\n\n /**\n * Reads the record the params address, or every record matching them.\n * Serves the cache when the answer is fresh, fetching otherwise. A bare key\n * is shorthand for `{ key }`; a bare key list is accepted by domains whose\n * request schema unions in {@link keyListZ}.\n * @throws {NotFoundError} if a single-record query matches nothing or the\n * record was deleted.\n * @throws {ValidationError} if params contain `key` (or are a bare key)\n * but fail the single-query schema.\n */\n retrieve(params: K | SingleInput, options?: FetchOptions): Promise<D>;\n retrieve(params: K[] | z.input<Z>, options?: FetchOptions): Promise<D[]>;\n async retrieve(\n params: K | K[] | SingleInput | z.input<Z>,\n options?: FetchOptions,\n ): Promise<D | D[]> {\n const [space, query] = this.route(params);\n return await space.retrieve(query, options);\n }\n\n /**\n * Subscribes to changes in the cached answer to the given query. The handler\n * fires on every change or deletion. Returns a destructor that unsubscribes.\n */\n onChange(params: K | SingleInput, handler: ChangeHandler<D>): destructor.Destructor;\n onChange(\n params: K[] | z.input<Z>,\n handler: ChangeHandler<D[]>,\n ): destructor.Destructor;\n onChange(\n params: K | K[] | SingleInput | z.input<Z>,\n handler: ChangeHandler<D> | ChangeHandler<D[]>,\n ): destructor.Destructor {\n const [space, query] = this.route(params);\n return space.onChange(query, handler as ChangeHandler<D | D[]>);\n }\n\n /**\n * Returns the cached answer to the given query without touching the network, or\n * undefined when nothing is cached. May be stale for unsubscribed queries.\n */\n getCached(params: K | SingleInput): Cached<D> | undefined;\n getCached(params: K[] | z.input<Z>): Cached<D[]> | undefined;\n getCached(\n params: K | K[] | SingleInput | z.input<Z>,\n ): Cached<D> | Cached<D[]> | undefined {\n const [space, query] = this.route(params);\n return space.getCached(query) as Cached<D> | Cached<D[]> | undefined;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { destructor } from \"@synnaxlabs/x\";\n\nexport interface OptimisticParams<R> {\n /**\n * Rollbacks for the already-applied optimistic cache changes, run in\n * reverse order when commit fails.\n */\n rollbacks: destructor.Destructor[];\n /**\n * Notified after the rollbacks are captured and before commit runs. Value-bearing\n * writes close over their optimistic value: `() => opts.onOptimistic?.(value)`.\n */\n onOptimistic?: () => Promise<void> | void;\n /** The network send. Its result is returned when it succeeds. */\n commit: () => Promise<R>;\n}\n\n/**\n * Runs an optimistic write. When commit or `onOptimistic` fails the rollbacks\n * run and the error rethrows; on success the cache keeps the optimistic state.\n */\nexport const optimistic = async <R>({\n rollbacks,\n onOptimistic,\n commit,\n}: OptimisticParams<R>): Promise<R> => {\n const rollback = new destructor.Chain();\n rollback.add(...rollbacks);\n return await rollback.guard(async () => {\n await onOptimistic?.();\n return await commit();\n });\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport {\n Cache,\n type CacheParams,\n type DerivedConfig,\n type TableConfig,\n} from \"@/query/cache\";\nexport { Deleted } from \"@/query/deleted\";\nexport { type DeriveWatch, deriveWatch } from \"@/query/derived\";\nexport {\n type Cached,\n type ChangeHandler,\n hash,\n isLive,\n requireCorpse,\n type Retrieves,\n type SpaceConfig,\n type Watch,\n watch,\n} from \"@/query/query\";\nexport { keyListZ, Retriever, type RetrieverParams } from \"@/query/retriever\";\nexport { type Listener } from \"@/query/streamer\";\nexport {\n createDeleteListener,\n createFetchListener,\n createSetListener,\n type EntryStatus,\n type HydrateMode,\n type Keyed,\n type ListenerSpec,\n partialUpdate,\n Table,\n type TableEvent,\n type TableParams,\n type TableSubscriber,\n} from \"@/query/table\";\nexport {\n type Data,\n type FetchOptions,\n type Params,\n type WriteOptions,\n} from \"@/query/types\";\nexport { optimistic, type OptimisticParams } from \"@/query/write\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type destructor } from \"@synnaxlabs/x\";\n\nimport {\n type ID,\n idsEqual,\n idToString,\n matchRelationship,\n PARENT_OF_RELATIONSHIP_TYPE,\n type Relationship,\n type Resource,\n} from \"@/ontology/payload\";\nimport { query } from \"@/query\";\n\n/** Channels the Core writes ontology changes to. */\nexport const RESOURCE_SET_CHANNEL_NAME = \"sy_ontology_resource_set\";\nexport const RESOURCE_DELETE_CHANNEL_NAME = \"sy_ontology_resource_delete\";\nexport const RELATIONSHIP_SET_CHANNEL_NAME = \"sy_ontology_relationship_set\";\nexport const RELATIONSHIP_DELETE_CHANNEL_NAME = \"sy_ontology_relationship_delete\";\n\n/** The ontology record tables: resources and the relationships between them. */\nexport class Cache {\n readonly relationships: query.Table<string, Relationship>;\n readonly resources: query.Table<string, Resource>;\n\n constructor(\n relationships: query.Table<string, Relationship>,\n resources: query.Table<string, Resource>,\n ) {\n this.relationships = relationships;\n this.resources = resources;\n }\n\n /** Returns the cached parent ID of the given ontology ID, or null if unknown. */\n parentID(id: ID): ID | null {\n const res = this.relationships.get((r) =>\n matchRelationship(r, { type: PARENT_OF_RELATIONSHIP_TYPE, to: id }),\n );\n if (res.length === 0) return null;\n return res[0].from;\n }\n\n /**\n * Optimistically renames the cached resource for the given ID. Returns a\n * rollback restoring the prior name. A no-op when the resource isn't cached.\n */\n renameResource(id: ID, name: string): destructor.Destructor {\n return query.partialUpdate(this.resources, idToString(id), { name });\n }\n\n /**\n * Optimistically drops every cached relationship touching the given IDs.\n * Returns a rollback restoring them.\n */\n deleteRelationships(ids: ID | ID[]): destructor.Destructor {\n const idsArr = Array.isArray(ids) ? ids : [ids];\n return this.relationships.delete((rel) =>\n idsArr.some((id) => idsEqual(rel.to, id) || idsEqual(rel.from, id)),\n );\n }\n\n /**\n * Optimistically drops the cached resources for the given IDs along with\n * every relationship touching them. Returns a rollback restoring both.\n */\n deleteResources(ids: ID | ID[]): destructor.Destructor {\n const idsArr = Array.isArray(ids) ? ids : [ids];\n const undoRels = this.deleteRelationships(idsArr);\n const undoResources = this.resources.delete(idToString(idsArr));\n return () => {\n undoResources();\n undoRels();\n };\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { z } from \"zod\";\n\nimport { type ID, idZ } from \"@/ontology/payload\";\n\nexport const addRemoveChildrenReqZ = z.object({ id: idZ, children: idZ.array() });\nexport const moveChildrenReqZ = z.object({ from: idZ, to: idZ, children: idZ.array() });\nexport const emptyResZ = z.object({});\n\n/** Edits the parent-child relationships in the ontology. Reach it through the client. */\nexport class Writer {\n client: UnaryClient;\n\n constructor(client: UnaryClient) {\n this.client = client;\n }\n\n async addChildren(id: ID, ...children: ID[]): Promise<void> {\n await this.client.send(\n \"/ontology/add-children\",\n { id, children },\n addRemoveChildrenReqZ,\n emptyResZ,\n );\n }\n\n async removeChildren(id: ID, ...children: ID[]): Promise<void> {\n await this.client.send(\n \"/ontology/remove-children\",\n { id, children },\n addRemoveChildrenReqZ,\n emptyResZ,\n );\n }\n\n async moveChildren(from: ID, to: ID, ...children: ID[]): Promise<void> {\n await this.client.send(\n \"/ontology/move-children\",\n { from, to, children },\n moveChildrenReqZ,\n emptyResZ,\n );\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { deep, type destructor, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { NotFoundError } from \"@/errors\";\nimport {\n type ID,\n idsEqual,\n idToString,\n idZ,\n oppositeRelationshipDirection,\n PARENT_OF_RELATIONSHIP_TYPE,\n parseID,\n parseIDs,\n type Relationship,\n type RelationshipDirection,\n relationshipToString,\n relationshipZ,\n type Resource,\n type ResourceType,\n resourceTypeZ,\n resourceZ,\n stringIDZ,\n} from \"@/ontology/payload\";\nimport {\n Cache,\n RELATIONSHIP_DELETE_CHANNEL_NAME,\n RELATIONSHIP_SET_CHANNEL_NAME,\n RESOURCE_DELETE_CHANNEL_NAME,\n RESOURCE_SET_CHANNEL_NAME,\n} from \"@/ontology/store\";\nimport { Writer } from \"@/ontology/writer\";\nimport { query } from \"@/query\";\n\nconst wireReqZ = z.object({\n ids: idZ.array().optional(),\n children: z.boolean().optional(),\n parents: z.boolean().optional(),\n excludeFieldData: z.boolean().optional(),\n types: resourceTypeZ.array().optional(),\n searchTerm: z.string().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\n/** Everything an ontology retrieval can filter on. */\nexport interface RetrieveRequest extends z.infer<typeof wireReqZ> {}\n\n/** The filters a retrieval accepts alongside its IDs. */\nexport interface RetrieveOptions extends Pick<\n RetrieveRequest,\n \"excludeFieldData\" | \"types\"\n> {}\n\nconst retrieveResZ = z.object({ resources: resourceZ.array() });\n\nconst parentRel = (from: ID, to: ID): Relationship => ({\n from,\n type: PARENT_OF_RELATIONSHIP_TYPE,\n to,\n});\n\n/** A retrieve request with IDs normalized to stable, sorted strings. */\ntype NormalizedRequest = {\n ids?: string[];\n excludeFieldData?: boolean;\n types?: ResourceType[];\n searchTerm?: string;\n limit?: number;\n offset?: number;\n};\n\n/** Request key for children/parents listings of a set of resources. */\ntype DependentRequest = {\n ids: string[];\n types?: ResourceType[];\n searchTerm?: string;\n offset?: number;\n limit?: number;\n excludeFieldData?: boolean;\n};\n\n/** Query addressing the children or parents of a set of resources. */\nexport type DependentParams = {\n ids: ID | ID[];\n types?: ResourceType[];\n searchTerm?: string;\n offset?: number;\n limit?: number;\n excludeFieldData?: boolean;\n};\n\nconst DEPENDENT_SERVER_FIELDS = [\"searchTerm\", \"limit\", \"offset\"] as const;\n\nconst normalizeIDs = (ids: ID | ID[]): string[] =>\n [...new Set(idToString(parseIDs(ids)))].sort();\n\nconst normalizeDependents = (\n ids: ID | ID[],\n options?: Omit<DependentParams, \"ids\">,\n): DependentRequest => {\n const out: DependentRequest = { ids: normalizeIDs(ids) };\n const { types, searchTerm, offset, limit, excludeFieldData } = options ?? {};\n if (types != null) out.types = [...types].sort();\n if (searchTerm != null) out.searchTerm = searchTerm;\n if (offset != null) out.offset = offset;\n if (limit != null) out.limit = limit;\n if (excludeFieldData != null) out.excludeFieldData = excludeFieldData;\n return out;\n};\n\nconst retrieveRequestZ = z\n .object({\n ids: idZ.array().optional(),\n excludeFieldData: z.boolean().optional(),\n types: resourceTypeZ.array().optional(),\n searchTerm: z.string().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n })\n .transform((req): NormalizedRequest => {\n const out: NormalizedRequest = {};\n if (req.ids != null) out.ids = normalizeIDs(req.ids);\n if (req.excludeFieldData != null) out.excludeFieldData = req.excludeFieldData;\n if (req.types != null) out.types = [...req.types].sort();\n if (req.searchTerm != null) out.searchTerm = req.searchTerm;\n if (req.limit != null) out.limit = req.limit;\n if (req.offset != null) out.offset = req.offset;\n return out;\n });\n\n/** Resources are addressed by `ids`, so a bare key list is that shorthand. */\nconst retrieveMultiParamsZ = retrieveRequestZ.or(\n idZ.array().transform((ids): NormalizedRequest => ({ ids: normalizeIDs(ids) })),\n);\n\n/** Params for an ontology retrieval. A bare ID array is shorthand for `{ ids }`. */\nexport type RetrieveParams = z.input<typeof retrieveRequestZ>;\n\nconst singleParamsZ = z\n .union([z.strictObject({ type: resourceTypeZ, key: z.string() }), stringIDZ])\n .transform((id) => idToString(id));\n\n/**\n * Client-side matching for a request: exact for id and type sets. Server-computed\n * shapes (search, limit/offset) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: NormalizedRequest): ((r: Resource) => boolean) => {\n const idSet = primitive.isNonZero(req.ids) ? new Set(req.ids) : undefined;\n const typeSet = primitive.isNonZero(req.types) ? new Set(req.types) : undefined;\n return (r) => {\n if (idSet != null && !idSet.has(r.key)) return false;\n if (typeSet != null && !typeSet.has(r.id.type)) return false;\n return true;\n };\n};\n\n/** Config for {@link Client}. */\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n}\n\n/**\n * Reads the ontology on a Core: the resources and the relationships that join them.\n * Reach it through `client.ontology`. Reads are served from a cache that a change\n * stream keeps current.\n */\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n string,\n Resource,\n Resource,\n z.input<typeof singleParamsZ>\n> {\n readonly type: string = \"ontology\";\n /** Read surface of the ontology record tables. */\n readonly cache: Cache;\n /** Cached read surface for the children of a set of resources. */\n readonly children: query.Retrieves<DependentParams, Resource[]>;\n /** Cached read surface for the parents of a set of resources. */\n readonly parents: query.Retrieves<DependentParams, Resource[]>;\n private readonly cfg: ClientConfig;\n private readonly writer: Writer;\n\n constructor(cfg: ClientConfig) {\n const { unary, cache } = cfg;\n const relationships = cache.createTable<string, Relationship>({\n name: \"relationships\",\n equal: (a, b) =>\n idsEqual(a.from, b.from) && idsEqual(a.to, b.to) && a.type === b.type,\n listen: [\n query.createSetListener(RELATIONSHIP_SET_CHANNEL_NAME, relationshipZ, {\n key: (changed) => relationshipToString(changed),\n }),\n query.createDeleteListener(RELATIONSHIP_DELETE_CHANNEL_NAME, relationshipZ, {\n key: (changed) => relationshipToString(changed),\n }),\n ],\n });\n const resources = cache.createTable<string, Resource>({\n name: \"resources\",\n equal: (a, b) => deep.equal(a, b),\n // Fetches bypass the query cache: sibling domain deletes never write\n // through to the resource store, so cached entries may be stale.\n fetch: async (keys) =>\n await this.execRetrieve({ ids: parseIDs(keys), ignoreNotFoundError: true }),\n listen: [\n query.createSetListener(RESOURCE_SET_CHANNEL_NAME, resourceZ, {\n value: (changed, prev) => (prev == null ? changed : { ...prev, ...changed }),\n }),\n // The store is keyed by the full \"type:key\" string, not the bare key.\n query.createDeleteListener(RESOURCE_DELETE_CHANNEL_NAME, idZ, {\n key: (changed) => idToString(changed),\n }),\n ],\n });\n const single = cache.queries<string, Resource, string, Resource>({\n name: \"resource\",\n table: resources,\n fetch: async (q) => [(await this.fetchSingle(q)).key],\n compose: (records) => records[0],\n keyOf: (q) => q,\n single: true,\n });\n super(cache, {\n name: \"resource\",\n table: resources,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.fetchRequest(req),\n matches: (resource, req) => requestFilter(req)(resource),\n },\n single: { schema: singleParamsZ, space: single },\n });\n this.cfg = cfg;\n this.writer = new Writer(unary);\n this.cache = new Cache(relationships, resources);\n this.children = this.dependentSurface(cache, \"children\", \"to\");\n this.parents = this.dependentSurface(cache, \"parents\", \"from\");\n }\n\n /**\n * Reads the resources the params address. The ID-array form remains for migration\n * only: query with `{ ids }`, `children.retrieve`, or `parents.retrieve` instead.\n */\n retrieve(\n ids: Array<ID | string>,\n options?: RetrieveOptions & { children?: boolean; parents?: boolean },\n ): Promise<Resource[]>;\n retrieve(\n params: string | z.input<typeof singleParamsZ>,\n options?: query.FetchOptions,\n ): Promise<Resource>;\n retrieve(params: RetrieveParams, options?: query.FetchOptions): Promise<Resource[]>;\n async retrieve(\n params:\n Array<ID | string> | string | z.input<typeof singleParamsZ> | RetrieveParams,\n options?:\n | query.FetchOptions\n | (RetrieveOptions & { children?: boolean; parents?: boolean }),\n ): Promise<Resource | Resource[]> {\n if (Array.isArray(params)) {\n const ids = parseIDs(params);\n const {\n children = false,\n parents = false,\n ...rest\n } = (options ?? {}) as RetrieveOptions & {\n children?: boolean;\n parents?: boolean;\n };\n if (children) return await this.children.retrieve({ ids, ...rest });\n if (parents) return await this.parents.retrieve({ ids, ...rest });\n return await super.retrieve({ ids, ...rest });\n }\n return await super.retrieve(\n params as z.input<typeof singleParamsZ>,\n options as query.FetchOptions,\n );\n }\n\n /** Migration-only alias for `children.retrieve({ ids })`. */\n async retrieveChildren(\n ids: ID | ID[],\n options?: RetrieveOptions,\n ): Promise<Resource[]> {\n return await this.children.retrieve({ ids, ...options });\n }\n\n /** Migration-only alias for `parents.retrieve({ ids })`. */\n async retrieveParents(\n ids: ID | ID[],\n options?: RetrieveOptions,\n ): Promise<Resource[]> {\n return await this.parents.retrieve({ ids, ...options });\n }\n\n /** Adds children to a resource in the ontology. */\n async addChildren(id: ID, ...children: ID[]): Promise<void> {\n await this.writer.addChildren(id, ...children);\n children.forEach((child) => {\n const rel = parentRel(id, child);\n this.cache.relationships.set(relationshipToString(rel), rel);\n });\n }\n\n /** Removes children from a resource in the ontology. */\n async removeChildren(id: ID, ...children: ID[]): Promise<void> {\n await this.writer.removeChildren(id, ...children);\n children.forEach((child) =>\n this.cache.relationships.delete(relationshipToString(parentRel(id, child))),\n );\n }\n\n /** Moves children from one resource to another in the ontology. */\n async moveChildren(from: ID, to: ID, ...children: ID[]): Promise<void> {\n const move = (): destructor.Destructor[] => {\n const deletions = children.map((child) =>\n this.cache.relationships.delete(relationshipToString(parentRel(from, child))),\n );\n const insertions = children.map((child) => {\n const rel = parentRel(to, child);\n return this.cache.relationships.set(relationshipToString(rel), rel);\n });\n return [...deletions, ...insertions];\n };\n await query.optimistic({\n rollbacks: move(),\n commit: async () => await this.writer.moveChildren(from, to, ...children),\n });\n move();\n }\n\n /** Subscribes to every resource set delivered to the cache. */\n onResourceSet(handler: (resource: Resource) => void): destructor.Destructor {\n return this.cache.resources.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every resource delete delivered to the cache. */\n onResourceDelete(handler: (id: ID) => void): destructor.Destructor {\n return this.cache.resources.subscribe((event) => {\n if (event.variant === \"delete\") handler(parseID(event.key));\n });\n }\n\n /** Subscribes to every relationship set delivered to the cache. */\n onRelationshipSet(handler: (rel: Relationship) => void): destructor.Destructor {\n return this.cache.relationships.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every relationship delete delivered to the cache. */\n onRelationshipDelete(handler: (rel: Relationship) => void): destructor.Destructor {\n return this.cache.relationships.subscribe((event) => {\n if (event.variant === \"delete\") handler(relationshipZ.parse(event.key));\n });\n }\n\n /** Merges a fetched resource with cached field data it may lack. */\n private mergeFieldData(r: Resource): Resource {\n const p = this.cache.resources.get(r.key);\n return p == null ? r : { ...r, data: r.data ?? p.data };\n }\n\n private writeResources(resources: Resource[]): void {\n this.cache.resources.set(resources.map((r) => this.mergeFieldData(r)));\n }\n\n // Resources are deleted through other domain clients whose write-through\n // never reaches the resource store, so fetches always hit the network\n // rather than serving a possibly stale cached entry.\n private async fetchSingle(q: string): Promise<Resource> {\n const resources = await this.execRetrieve({\n ids: [parseID(q)],\n });\n if (resources.length === 0)\n throw new NotFoundError(`No resource found with ID ${q}`);\n this.writeResources(resources);\n return resources[0];\n }\n\n private async fetchRequest(req: NormalizedRequest): Promise<Resource[]> {\n const { ids, ...rest } = req;\n const resources = await this.execRetrieve(\n ids == null ? rest : { ids: parseIDs(ids), ...rest },\n );\n return resources.map((r) => this.mergeFieldData(r));\n }\n\n private async fetchDependents(\n q: DependentRequest,\n direction: RelationshipDirection,\n ): Promise<Resource[]> {\n const { ids, ...rest } = q;\n const resources = await this.execRetrieve({\n ids: parseIDs(ids),\n children: direction === \"to\",\n parents: direction === \"from\",\n ...rest,\n });\n this.writeResources(resources);\n // Multi-anchor answers can't attribute members to an anchor, so only\n // single-anchor queries write relationships through.\n if (ids.length === 1) {\n const anchor = parseID(ids[0]);\n resources.forEach(({ id }) => {\n const rel = direction === \"to\" ? parentRel(anchor, id) : parentRel(id, anchor);\n this.cache.relationships.set(relationshipToString(rel), rel);\n });\n }\n return resources;\n }\n\n private dependentSurface(\n cache: query.Cache,\n name: string,\n direction: RelationshipDirection,\n ): query.Retrieves<DependentParams, Resource[]> {\n const anchor = oppositeRelationshipDirection(direction);\n const space = cache.queries<DependentRequest, Resource[], string, Resource>({\n name,\n table: this.cache.resources,\n fetch: async (q) => (await this.fetchDependents(q, direction)).map((r) => r.key),\n compose: (records) => records,\n matches: (resource, q) => this.isDependent(resource, q, direction),\n serverFields: DEPENDENT_SERVER_FIELDS,\n watch: [\n query.watch(this.cache.relationships, (event, q: DependentRequest) => {\n const rel =\n event.variant === \"set\" ? event.value : relationshipZ.parse(event.key);\n if (rel.type !== PARENT_OF_RELATIONSHIP_TYPE) return null;\n if (!q.ids.includes(idToString(rel[anchor]))) return null;\n if (q.types != null && !q.types.includes(rel[direction].type)) return null;\n return [idToString(rel[direction])];\n }),\n ],\n });\n return {\n retrieve: async ({ ids, ...options }, opts) =>\n await space.retrieve(normalizeDependents(ids, options), opts),\n onChange: ({ ids, ...options }, handler) =>\n space.onChange(normalizeDependents(ids, options), handler),\n getCached: ({ ids, ...options }) =>\n space.getCached(normalizeDependents(ids, options)),\n };\n }\n\n /** Whether a cached relationship makes the resource a dependent of the query. */\n private isDependent(\n resource: Resource,\n q: DependentRequest,\n direction: RelationshipDirection,\n ): boolean {\n if (q.types != null && !q.types.includes(resource.id.type)) return false;\n const anchor = oppositeRelationshipDirection(direction);\n return (\n this.cache.relationships.get(\n (rel) =>\n rel.type === PARENT_OF_RELATIONSHIP_TYPE &&\n q.ids.includes(idToString(rel[anchor])) &&\n idsEqual(rel[direction], resource.id),\n ).length > 0\n );\n }\n\n private async execRetrieve(request: RetrieveRequest): Promise<Resource[]> {\n const { resources } = await this.cfg.unary.send(\n \"/ontology/retrieve\",\n request,\n wireReqZ,\n retrieveResZ,\n );\n return resources;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/ontology/client\";\nexport * from \"@/ontology/payload\";\nexport {\n Cache,\n RELATIONSHIP_DELETE_CHANNEL_NAME,\n RELATIONSHIP_SET_CHANNEL_NAME,\n RESOURCE_DELETE_CHANNEL_NAME,\n RESOURCE_SET_CHANNEL_NAME,\n} from \"@/ontology/store\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type destructor } from \"@synnaxlabs/x\";\n\nimport { type Action } from \"@/access/action/types.gen\";\nimport { allowRequest } from \"@/access/enforce\";\nimport { type policy } from \"@/access/policy\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\n\n/** A permission question: may the subject apply the action to the objects? */\nexport interface GrantedQuery {\n objects: ontology.ID | ontology.ID[];\n action: Action;\n}\n\ninterface Verdict {\n subject: string;\n policies: policy.Policy[];\n verdict: boolean;\n}\n\ninterface SubjectEntry {\n key: string;\n query: { for: ontology.ID };\n}\n\nexport interface GrantedConfig {\n policies: policy.Client;\n}\n\n/**\n * The cached read surface for permission checks, answering {@link GrantedQuery}\n * questions against the subject's cached policies. Snapshot reads memoize the\n * verdict per query object, so render-hot callers pay a policy evaluation only\n * when the policies actually change.\n */\nexport class Granted {\n private readonly policies: policy.Client;\n private readonly subjects = new Map<string, SubjectEntry>();\n private readonly verdicts = new WeakMap<GrantedQuery, Verdict>();\n\n constructor(cfg: GrantedConfig) {\n this.policies = cfg.policies;\n }\n\n // A subject's entry holds its canonical key and a stable `{ for }` query, so\n // repeat reads stringify once and stay on the retriever's normalization memo.\n private subjectFor(subject: ontology.ID): SubjectEntry {\n const key = ontology.idToString(subject);\n let held = this.subjects.get(key);\n if (held == null) {\n held = { key, query: { for: subject } };\n this.subjects.set(key, held);\n }\n return held;\n }\n\n /** Fetches the subject's policies and answers the question. */\n async retrieve(subject: ontology.ID, q: GrantedQuery): Promise<boolean> {\n const policies = await this.policies.retrieveForSubject(subject);\n return allowRequest({ subject, objects: q.objects, action: q.action }, policies);\n }\n\n /**\n * Subscribes to the verdict, firing only when it flips: policy churn that\n * cannot change the answer never reaches the handler.\n */\n onChange(\n subject: ontology.ID,\n q: GrantedQuery,\n handler: (granted: boolean) => void,\n ): destructor.Destructor {\n const { query: policiesQuery } = this.subjectFor(subject);\n const evaluate = (policies: policy.Policy[]): boolean =>\n allowRequest({ subject, objects: q.objects, action: q.action }, policies);\n const cached = this.policies.getCached(policiesQuery);\n let prev = query.isLive(cached) ? evaluate(cached) : undefined;\n return this.policies.onChange(policiesQuery, (result) => {\n if (!query.isLive(result)) return;\n const next = evaluate(result);\n if (next === prev) return;\n prev = next;\n handler(next);\n });\n }\n\n /**\n * Returns the cached verdict, or undefined when the subject's policies are\n * not cached. Repeat calls with the same query object skip the policy\n * evaluation until the cached policies change.\n */\n getCached(subject: ontology.ID, q: GrantedQuery): boolean | undefined {\n const { key: subjectKey, query: policiesQuery } = this.subjectFor(subject);\n const cached = this.policies.getCached(policiesQuery);\n if (!query.isLive(cached)) return undefined;\n const held = this.verdicts.get(q);\n if (held != null && held.policies === cached && held.subject === subjectKey)\n return held.verdict;\n const verdict = allowRequest(\n { subject, objects: q.objects, action: q.action },\n cached,\n );\n this.verdicts.set(q, { subject: subjectKey, policies: cached, verdict });\n return verdict;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { access } from \"@/access/action\";\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Policy is an access control policy that defines which actions are permitted on which\n * resources. Policies are attached to roles, and roles are assigned to users via\n * ontology relationships.\n */\nexport const policyZ = z.object({\n /** key is the unique identifier for this policy. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the policy. */\n name: z.string(),\n /** objects is the list of ontology resources this policy applies to. */\n objects: ontology.idZ.array().default(() => []),\n /** actions is the list of actions this policy permits. */\n actions: access.actionZ.array().default(() => []),\n /** internal is true if this is a built-in system policy that cannot be deleted. */\n internal: z.boolean().default(false),\n});\nexport interface Policy extends z.infer<typeof policyZ> {}\nexport interface New extends z.input<typeof policyZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"policy\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Policy,\n policyZ,\n} from \"@/access/policy/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_policy_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_policy_delete\";\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n subjects: ontology.idZ.array().optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n internal: z.boolean().optional(),\n});\n\nconst listRetrieveParamsZ = z.union([\n z\n .object({ for: ontology.idZ })\n .transform(({ for: forId }) => ({ subjects: [forId] })),\n z\n .object({ for: ontology.idZ.array() })\n .transform(({ for: forIds }) => ({ subjects: forIds })),\n retrieveRequestZ,\n]);\nconst retrieveMultiParamsZ = listRetrieveParamsZ.or(query.keyListZ(keyZ));\n\nexport type RetrieveSingleParams = { key: Key };\nexport type RetrieveMultipleParams = z.input<typeof listRetrieveParamsZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst retrieveResZ = z.object({ policies: policyZ.array().default(() => []) });\n\nconst singleCreateParamsZ = policyZ.transform((p) => ({ policies: [p] }));\nexport type SingleCreateParams = z.input<typeof singleCreateParamsZ>;\n\nexport const multipleCreateParamsZ = policyZ\n .array()\n .transform((policies) => ({ policies }));\n\nexport const createParamsZ = z.union([singleCreateParamsZ, multipleCreateParamsZ]);\nexport type CreateParams = z.input<typeof createParamsZ>;\n\nconst createResZ = z.object({ policies: policyZ.array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\n\n/**\n * Query fields only the server can evaluate: policy records do not carry\n * their subjects, so subject membership cannot be checked locally.\n */\nconst SERVER_FIELDS = [\"subjects\", \"limit\", \"offset\"] as const;\n\n/**\n * Client-side matching for a request: key sets and the internal flag. Server-computed\n * shapes (subjects, pagination) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((p: Policy) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (p) => {\n if (keySet != null && !keySet.has(p.key)) return false;\n if (req.internal != null && p.internal !== req.internal) return false;\n return true;\n };\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Policy> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Policy>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n const store = cache.createTable<Key, Policy>({\n name: \"policies\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, policyZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"policy\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (policy, req) => requestFilter(req)(policy),\n serverFields: SERVER_FIELDS,\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(policy: New): Promise<Policy>;\n async create(policies: New[]): Promise<Policy[]>;\n async create(policies: CreateParams): Promise<Policy | Policy[]> {\n const isMany = Array.isArray(policies);\n const res = await this.cfg.unary.send(\n \"/access/policy/create\",\n policies,\n createParamsZ,\n createResZ,\n );\n this.store.set(res.policies);\n return isMany ? res.policies : res.policies[0];\n }\n\n async delete(key: Key, opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key[], opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const ids = ontologyID(keysArr);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ids),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/access/policy/delete\",\n { keys: keysArr },\n deleteReqZ,\n deleteResZ,\n ),\n });\n drop();\n this.cfg.ontology.cache.relationships.delete((r) =>\n ids.some((id) => ontology.idsEqual(r.from, id) || ontology.idsEqual(r.to, id)),\n );\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const existing = await this.retrieve(key);\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n await this.create({ ...existing, name });\n },\n });\n rename();\n }\n\n /**\n * Retrieves every policy governing the subject, warming the role links of\n * the subject and its policies so role reads resolve from the cache.\n */\n async retrieveForSubject(subject: ontology.ID): Promise<Policy[]> {\n const policies = await this.retrieve({ for: subject });\n const { parents } = this.cfg.ontology;\n const warms = [parents.retrieve({ ids: subject, types: [\"role\"] })];\n if (policies.length > 0)\n warms.push(\n parents.retrieve({\n ids: policies.map((p) => ontologyID(p.key)),\n types: [\"role\"],\n }),\n );\n await Promise.all(warms);\n return policies;\n }\n\n private async execRetrieve(params: RetrieveRequest): Promise<Policy[]> {\n const res = await this.cfg.unary.send(\n \"/access/policy/retrieve\",\n params,\n retrieveRequestZ,\n retrieveResZ,\n );\n return res.policies;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/access/policy/client\";\nexport * from \"@/access/policy/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Role is a named collection of policies that can be assigned to users, enabling\n * group-based permission management. Roles define what actions users can perform on\n * resources.\n */\nexport const roleZ = z.object({\n /** key is the unique identifier for this role. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the role (e.g., 'Administrator', 'Engineer'). */\n name: z.string(),\n /**\n * description is an optional description explaining what permissions the role\n * provides.\n */\n description: z.string().default(\"\"),\n /** internal is true if this is a built-in system role that cannot be deleted. */\n internal: z.boolean().default(false),\n});\nexport interface Role extends z.infer<typeof roleZ> {}\nexport interface New extends z.input<typeof roleZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"role\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * User is an account entity representing a person accessing the Synnax system. Users\n * can have roles assigned for permission management.\n */\nexport const userZ = z.object({\n /** key is the unique identifier for this user. */\n key: keyZ,\n /** username is the unique login name for the user. */\n username: z.string().min(1, \"username is required\"),\n /** firstName is the user's first name. */\n firstName: z.string(),\n /** lastName is the user's last name. */\n lastName: z.string(),\n /**\n * rootUser is true if this is a root/admin user with full system access. Root users\n * cannot be deleted.\n */\n rootUser: z.boolean().default(false),\n});\nexport interface User extends z.infer<typeof userZ> {}\n\nexport const newZ = userZ\n .omit({ rootUser: true })\n .partial({ key: true, firstName: true, lastName: true })\n .extend({\n password: z.string().min(1),\n });\nexport interface New extends z.input<typeof newZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"user\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, primitive, record } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { MultipleFoundError, NotFoundError } from \"@/errors\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { type Key, keyZ, type New, newZ, type User, userZ } from \"@/user/types.gen\";\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n usernames: z.string().array().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nconst keyRetrieveRequestZ = z\n .object({\n key: keyZ,\n })\n .transform(({ key }) => ({ keys: [key] }));\n\nconst usernameRetrieveRequestZ = z\n .object({\n username: z.string(),\n })\n .transform(({ username }) => ({ usernames: [username] }));\n\nexport type KeyRetrieveRequest = z.input<typeof keyRetrieveRequestZ>;\nexport type UsernameRetrieveRequest = z.input<typeof usernameRetrieveRequestZ>;\nexport type UsernamesRetrieveRequest = { usernames: string[] };\n\nconst retrieveParamsZ = z.union([\n keyRetrieveRequestZ,\n usernameRetrieveRequestZ,\n retrieveRequestZ,\n]);\n\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\nexport interface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst retrieveResZ = z.object({ users: userZ.array().default(() => []) });\n\nconst createReqZ = z.object({ users: newZ.array() });\nconst createResZ = z.object({ users: userZ.array() });\nconst changeUsernameReqZ = z.object({ key: keyZ, username: z.string().min(1) });\nconst changeUsernameResZ = z.object({});\nconst renameReqZ = z.object({\n key: keyZ,\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n});\nconst renameResZ = z.object({});\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\n\nexport const SET_CHANNEL_NAME = \"sy_user_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_user_delete\";\n\ntype SingleParams = KeyRetrieveRequest | UsernameRetrieveRequest;\n\nconst singleParamsZ = z.union([\n z.strictObject({ key: keyZ }),\n z.strictObject({ username: z.string() }),\n keyZ.transform((key) => ({ key })),\n]);\n\nconst singleIdentifier = (params: SingleParams): string =>\n \"key\" in params ? `key ${params.key}` : `username ${params.username}`;\n\nconst requestFilter = (req: RetrieveRequest): ((u: User) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const usernameSet = primitive.isNonZero(req.usernames)\n ? new Set(req.usernames)\n : undefined;\n return (u) => {\n if (keySet != null && !keySet.has(u.key)) return false;\n if (usernameSet != null && !usernameSet.has(u.username)) return false;\n return true;\n };\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n User,\n User,\n SingleParams,\n SingleParams\n> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, User>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n const store = cache.createTable<Key, User>({\n name: \"users\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n });\n const single = cache.queries<SingleParams, User, Key, User>({\n name: \"user\",\n table: store,\n fetch: async (params) => {\n if (!(\"key\" in params)) {\n const [cached] = store.get((u) => u.username === params.username);\n if (cached != null) return [cached.key];\n }\n const users = await this.execRetrieve(params);\n checkSingle(params, users);\n store.ingest(users);\n return users.map((u) => u.key);\n },\n compose: (records) => records[0],\n keyOf: (params) => (\"key\" in params ? params.key : null),\n matches: (u, params) =>\n \"key\" in params ? u.key === params.key : u.username === params.username,\n single: true,\n });\n super(cache, {\n name: \"user\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (u, req) => requestFilter(req)(u),\n },\n single: { schema: singleParamsZ, space: single },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(user: New): Promise<User>;\n async create(users: New[]): Promise<User[]>;\n async create(users: New | New[]): Promise<User | User[]> {\n const isMany = Array.isArray(users);\n const res = await this.cfg.unary.send(\n \"/user/create\",\n { users: array.toArray(users) },\n createReqZ,\n createResZ,\n );\n this.store.set(res.users);\n return isMany ? res.users : res.users[0];\n }\n\n async changeUsername(\n key: Key,\n newUsername: string,\n opts: query.WriteOptions = {},\n ): Promise<void> {\n const update = () => [\n query.partialUpdate(this.store, key, { username: newUsername }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), newUsername),\n ];\n await query.optimistic({\n rollbacks: update(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/user/change-username\",\n { key, username: newUsername },\n changeUsernameReqZ,\n changeUsernameResZ,\n ),\n });\n update();\n }\n\n async rename(\n key: Key,\n firstName?: string,\n lastName?: string,\n opts: query.WriteOptions = {},\n ): Promise<void> {\n await query.optimistic({\n rollbacks: [\n query.partialUpdate(\n this.store,\n key,\n record.purgeUndefined({ firstName, lastName }),\n ),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/user/rename\",\n { key, firstName, lastName },\n renameReqZ,\n renameResZ,\n ),\n });\n }\n\n async delete(key: Key, opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key[], opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/user/delete\",\n { keys: keysArr },\n deleteReqZ,\n deleteResZ,\n ),\n });\n drop();\n }\n\n private async execRetrieve(params: RetrieveParams): Promise<User[]> {\n const res = await this.cfg.unary.send(\n \"/user/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ,\n );\n return res.users;\n }\n}\n\nconst checkSingle = (params: SingleParams, users: User[]): void => {\n if (users.length === 0)\n throw new NotFoundError(`No user with ${singleIdentifier(params)} found`);\n if (users.length > 1)\n throw new MultipleFoundError(\n `Multiple users found with ${singleIdentifier(params)}`,\n );\n};\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"user\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport {\n Client,\n DELETE_CHANNEL_NAME,\n type KeyRetrieveRequest,\n ontologyID,\n type RetrieveParams,\n type RetrieveRequest,\n SET_CHANNEL_NAME,\n TYPE_ONTOLOGY_ID,\n type UsernameRetrieveRequest,\n type UsernamesRetrieveRequest,\n} from \"@/user/client\";\nexport * from \"@/user/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Role,\n roleZ,\n} from \"@/access/role/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { user } from \"@/user\";\n\nexport const SET_CHANNEL_NAME = \"sy_role_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_role_delete\";\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n searchTerm: z.string().optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n internal: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nconst keyRetrieveRequestZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nconst singleCreateParamsZ = roleZ.transform((r) => ({ roles: [r] }));\nexport type SingleCreateParams = z.input<typeof singleCreateParamsZ>;\n\nexport const multipleCreateParamsZ = roleZ.array().transform((roles) => ({ roles }));\n\nexport const createParamsZ = z.union([singleCreateParamsZ, multipleCreateParamsZ]);\nexport type CreateParams = z.input<typeof createParamsZ>;\n\nconst createResZ = z.object({ roles: roleZ.array() });\nconst retrieveResZ = z.object({ roles: roleZ.array().default(() => []) });\n\nexport type RetrieveSingleParams = z.input<typeof keyRetrieveRequestZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveRequestZ>;\n\nexport const retrieveParamsZ = z.union([keyRetrieveRequestZ, retrieveRequestZ]);\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst deleteResZ = z.object({});\n\nconst deleteParamsZ = keyZ\n .transform((key) => ({ keys: [key] }))\n .or(keyZ.array().transform((keys) => ({ keys })));\nexport type DeleteParams = z.input<typeof deleteParamsZ>;\n\nconst assignReqZ = z.object({\n user: user.keyZ,\n role: keyZ,\n});\nexport type AssignParams = z.input<typeof assignReqZ>;\n\nconst assignResZ = z.object({});\n\nconst unassignReqZ = z.object({\n user: user.keyZ,\n role: keyZ,\n});\nexport type UnassignParams = z.input<typeof unassignReqZ>;\n\nconst unassignResZ = z.object({});\n\n/**\n * Client-side matching for a request: key sets and the internal flag. Server-computed\n * shapes (search, limit/offset) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((r: Role) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (r) => {\n if (keySet != null && !keySet.has(r.key)) return false;\n if (req.internal != null && r.internal !== req.internal) return false;\n return true;\n };\n};\n\nconst assignmentRel = (role: Key, userKey: user.Key): ontology.Relationship => ({\n from: ontologyID(role),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: user.ontologyID(userKey),\n});\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Role> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Role>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n const store = cache.createTable<Key, Role>({\n name: \"roles\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, roleZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"role\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (role, req) => requestFilter(req)(role),\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(role: New): Promise<Role>;\n async create(roles: New[]): Promise<Role[]>;\n async create(roles: New | New[]): Promise<Role | Role[]> {\n const isMany = Array.isArray(roles);\n const res = await this.cfg.unary.send(\n \"/access/role/create\",\n roles,\n createParamsZ,\n createResZ,\n );\n this.store.set(res.roles);\n return isMany ? res.roles : res.roles[0];\n }\n\n async delete(params: DeleteParams, opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(params);\n const ids = ontologyID(keysArr);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ids),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/access/role/delete\",\n params,\n deleteParamsZ,\n deleteResZ,\n ),\n });\n drop();\n this.cfg.ontology.cache.relationships.delete((r) =>\n ids.some((id) => ontology.idsEqual(r.from, id) || ontology.idsEqual(r.to, id)),\n );\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const existing = await this.retrieve(key);\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n await this.create({ ...existing, name });\n },\n });\n rename();\n }\n\n async assign(params: AssignParams, opts: query.WriteOptions = {}): Promise<void> {\n const rel = assignmentRel(params.role, params.user);\n await query.optimistic({\n rollbacks: [\n this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n ),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/access/role/assign\",\n params,\n assignReqZ,\n assignResZ,\n ),\n });\n }\n\n async unassign(params: UnassignParams, opts: query.WriteOptions = {}): Promise<void> {\n await query.optimistic({\n rollbacks: [\n this.cfg.ontology.cache.relationships.delete(\n ontology.relationshipToString(assignmentRel(params.role, params.user)),\n ),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/access/role/unassign\",\n params,\n unassignReqZ,\n unassignResZ,\n ),\n });\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<Role[]> {\n const res = await this.cfg.unary.send(\n \"/access/role/retrieve\",\n params,\n retrieveRequestZ,\n retrieveResZ,\n );\n return res.roles;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/access/role/client\";\nexport * from \"@/access/role/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\n\nimport { Granted } from \"@/access/granted\";\nimport { policy } from \"@/access/policy\";\nimport { role } from \"@/access/role\";\nimport { type ontology } from \"@/ontology\";\nimport { type query } from \"@/query\";\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client {\n readonly policies: policy.Client;\n readonly roles: role.Client;\n readonly granted: Granted;\n\n constructor(cfg: ClientConfig) {\n this.policies = new policy.Client(cfg);\n this.roles = new role.Client(cfg);\n this.granted = new Granted({ policies: this.policies });\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport { type Action, ACTIONS, actionZ } from \"@/access/action/types.gen\";\nexport * from \"@/access/client\";\nexport * from \"@/access/enforce\";\nexport * from \"@/access/granted\";\nexport * from \"@/access/policy\";\nexport * from \"@/access/role\";\n","// src/utils/env.ts\nvar NOTHING = Symbol.for(\"immer-nothing\");\nvar DRAFTABLE = Symbol.for(\"immer-draftable\");\nvar DRAFT_STATE = Symbol.for(\"immer-state\");\n\n// src/utils/errors.ts\nvar errors = process.env.NODE_ENV !== \"production\" ? [\n // All error codes, starting by 0:\n function(plugin) {\n return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`;\n },\n function(thing) {\n return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;\n },\n \"This object has been frozen and should not be mutated\",\n function(data) {\n return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n },\n \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n \"Immer forbids circular references\",\n \"The first or second argument to `produce` must be a function\",\n \"The third argument to `produce` must be a function or undefined\",\n \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n function(thing) {\n return `'current' expects a draft, got: ${thing}`;\n },\n \"Object.defineProperty() cannot be used on an Immer draft\",\n \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n \"Immer only supports deleting array indices\",\n \"Immer only supports setting array indices and the 'length' property\",\n function(thing) {\n return `'original' expects a draft, got: ${thing}`;\n }\n // Note: if more errors are added, the errorOffset in Patches.ts should be increased\n // See Patches.ts for additional errors\n] : [];\nfunction die(error, ...args) {\n if (process.env.NODE_ENV !== \"production\") {\n const e = errors[error];\n const msg = isFunction(e) ? e.apply(null, args) : e;\n throw new Error(`[Immer] ${msg}`);\n }\n throw new Error(\n `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n );\n}\n\n// src/utils/common.ts\nvar O = Object;\nvar getPrototypeOf = O.getPrototypeOf;\nvar CONSTRUCTOR = \"constructor\";\nvar PROTOTYPE = \"prototype\";\nvar CONFIGURABLE = \"configurable\";\nvar ENUMERABLE = \"enumerable\";\nvar WRITABLE = \"writable\";\nvar VALUE = \"value\";\nvar isDraft = (value) => !!value && !!value[DRAFT_STATE];\nfunction isDraftable(value) {\n if (!value)\n return false;\n return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);\n}\nvar objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();\nvar cachedCtorStrings = /* @__PURE__ */ new WeakMap();\nfunction isPlainObject(value) {\n if (!value || !isObjectish(value))\n return false;\n const proto = getPrototypeOf(value);\n if (proto === null || proto === O[PROTOTYPE])\n return true;\n const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];\n if (Ctor === Object)\n return true;\n if (!isFunction(Ctor))\n return false;\n let ctorString = cachedCtorStrings.get(Ctor);\n if (ctorString === void 0) {\n ctorString = Function.toString.call(Ctor);\n cachedCtorStrings.set(Ctor, ctorString);\n }\n return ctorString === objectCtorString;\n}\nfunction original(value) {\n if (!isDraft(value))\n die(15, value);\n return value[DRAFT_STATE].base_;\n}\nfunction each(obj, iter, strict = true) {\n if (getArchtype(obj) === 0 /* Object */) {\n const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);\n keys.forEach((key) => {\n iter(key, obj[key], obj);\n });\n } else {\n obj.forEach((entry, index) => iter(index, entry, obj));\n }\n}\nfunction getArchtype(thing) {\n const state = thing[DRAFT_STATE];\n return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;\n}\nvar has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);\nvar get = (thing, prop, type = getArchtype(thing)) => (\n // @ts-ignore\n type === 2 /* Map */ ? thing.get(prop) : thing[prop]\n);\nvar set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {\n if (type === 2 /* Map */)\n thing.set(propOrOldValue, value);\n else if (type === 3 /* Set */) {\n thing.add(value);\n } else\n thing[propOrOldValue] = value;\n};\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\nvar isArray = Array.isArray;\nvar isMap = (target) => target instanceof Map;\nvar isSet = (target) => target instanceof Set;\nvar isObjectish = (target) => typeof target === \"object\";\nvar isFunction = (target) => typeof target === \"function\";\nvar isBoolean = (target) => typeof target === \"boolean\";\nfunction isArrayIndex(value) {\n const n = +value;\n return Number.isInteger(n) && String(n) === value;\n}\nvar getProxyDraft = (value) => {\n if (!isObjectish(value))\n return null;\n return value?.[DRAFT_STATE];\n};\nvar latest = (state) => state.copy_ || state.base_;\nvar getValue = (value) => {\n const proxyDraft = getProxyDraft(value);\n return proxyDraft ? proxyDraft.copy_ ?? proxyDraft.base_ : value;\n};\nvar getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;\nfunction shallowCopy(base, strict) {\n if (isMap(base)) {\n return new Map(base);\n }\n if (isSet(base)) {\n return new Set(base);\n }\n if (isArray(base))\n return Array[PROTOTYPE].slice.call(base);\n const isPlain = isPlainObject(base);\n if (strict === true || strict === \"class_only\" && !isPlain) {\n const descriptors = O.getOwnPropertyDescriptors(base);\n delete descriptors[DRAFT_STATE];\n let keys = Reflect.ownKeys(descriptors);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const desc = descriptors[key];\n if (desc[WRITABLE] === false) {\n desc[WRITABLE] = true;\n desc[CONFIGURABLE] = true;\n }\n if (desc.get || desc.set)\n descriptors[key] = {\n [CONFIGURABLE]: true,\n [WRITABLE]: true,\n // could live with !!desc.set as well here...\n [ENUMERABLE]: desc[ENUMERABLE],\n [VALUE]: base[key]\n };\n }\n return O.create(getPrototypeOf(base), descriptors);\n } else {\n const proto = getPrototypeOf(base);\n if (proto !== null && isPlain) {\n return { ...base };\n }\n const obj = O.create(proto);\n return O.assign(obj, base);\n }\n}\nfunction freeze(obj, deep = false) {\n if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))\n return obj;\n if (getArchtype(obj) > 1) {\n O.defineProperties(obj, {\n set: dontMutateMethodOverride,\n add: dontMutateMethodOverride,\n clear: dontMutateMethodOverride,\n delete: dontMutateMethodOverride\n });\n }\n O.freeze(obj);\n if (deep)\n each(\n obj,\n (_key, value) => {\n freeze(value, true);\n },\n false\n );\n return obj;\n}\nfunction dontMutateFrozenCollections() {\n die(2);\n}\nvar dontMutateMethodOverride = {\n [VALUE]: dontMutateFrozenCollections\n};\nfunction isFrozen(obj) {\n if (obj === null || !isObjectish(obj))\n return true;\n return O.isFrozen(obj);\n}\n\n// src/utils/plugins.ts\nvar PluginMapSet = \"MapSet\";\nvar PluginPatches = \"Patches\";\nvar PluginArrayMethods = \"ArrayMethods\";\nvar plugins = {};\nfunction getPlugin(pluginKey) {\n const plugin = plugins[pluginKey];\n if (!plugin) {\n die(0, pluginKey);\n }\n return plugin;\n}\nvar isPluginLoaded = (pluginKey) => !!plugins[pluginKey];\nfunction loadPlugin(pluginKey, implementation) {\n if (!plugins[pluginKey])\n plugins[pluginKey] = implementation;\n}\n\n// src/core/scope.ts\nvar currentScope;\nvar getCurrentScope = () => currentScope;\nvar createScope = (parent_, immer_) => ({\n drafts_: [],\n parent_,\n immer_,\n // Whenever the modified draft contains a draft from another scope, we\n // need to prevent auto-freezing so the unowned draft can be finalized.\n canAutoFreeze_: true,\n unfinalizedDrafts_: 0,\n handledSet_: /* @__PURE__ */ new Set(),\n processedForPatches_: /* @__PURE__ */ new Set(),\n mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,\n arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0\n});\nfunction usePatchesInScope(scope, patchListener) {\n if (patchListener) {\n scope.patchPlugin_ = getPlugin(PluginPatches);\n scope.patches_ = [];\n scope.inversePatches_ = [];\n scope.patchListener_ = patchListener;\n }\n}\nfunction revokeScope(scope) {\n leaveScope(scope);\n scope.drafts_.forEach(revokeDraft);\n scope.drafts_ = null;\n}\nfunction leaveScope(scope) {\n if (scope === currentScope) {\n currentScope = scope.parent_;\n }\n}\nvar enterScope = (immer2) => currentScope = createScope(currentScope, immer2);\nfunction revokeDraft(draft) {\n const state = draft[DRAFT_STATE];\n if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)\n state.revoke_();\n else\n state.revoked_ = true;\n}\n\n// src/core/finalize.ts\nfunction processResult(result, scope) {\n scope.unfinalizedDrafts_ = scope.drafts_.length;\n const baseDraft = scope.drafts_[0];\n const isReplaced = result !== void 0 && result !== baseDraft;\n if (isReplaced) {\n if (baseDraft[DRAFT_STATE].modified_) {\n revokeScope(scope);\n die(4);\n }\n if (isDraftable(result)) {\n result = finalize(scope, result);\n }\n const { patchPlugin_ } = scope;\n if (patchPlugin_) {\n patchPlugin_.generateReplacementPatches_(\n baseDraft[DRAFT_STATE].base_,\n result,\n scope\n );\n }\n } else {\n result = finalize(scope, baseDraft);\n }\n maybeFreeze(scope, result, true);\n revokeScope(scope);\n if (scope.patches_) {\n scope.patchListener_(scope.patches_, scope.inversePatches_);\n }\n return result !== NOTHING ? result : void 0;\n}\nfunction finalize(rootScope, value) {\n if (isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n if (!state) {\n const finalValue = handleValue(value, rootScope.handledSet_, rootScope);\n return finalValue;\n }\n if (!isSameScope(state, rootScope)) {\n return value;\n }\n if (!state.modified_) {\n return state.base_;\n }\n if (!state.finalized_) {\n const { callbacks_ } = state;\n if (callbacks_) {\n while (callbacks_.length > 0) {\n const callback = callbacks_.pop();\n callback(rootScope);\n }\n }\n generatePatchesAndFinalize(state, rootScope);\n }\n return state.copy_;\n}\nfunction maybeFreeze(scope, value, deep = false) {\n if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n freeze(value, deep);\n }\n}\nfunction markStateFinalized(state) {\n state.finalized_ = true;\n state.scope_.unfinalizedDrafts_--;\n}\nvar isSameScope = (state, rootScope) => state.scope_ === rootScope;\nvar EMPTY_LOCATIONS_RESULT = [];\nfunction updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {\n const parentCopy = latest(parent);\n const parentType = parent.type_;\n if (originalKey !== void 0) {\n const currentValue = get(parentCopy, originalKey, parentType);\n if (currentValue === draftValue) {\n set(parentCopy, originalKey, finalizedValue, parentType);\n return;\n }\n }\n if (!parent.draftLocations_) {\n const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();\n each(parentCopy, (key, value) => {\n if (isDraft(value)) {\n const keys = draftLocations.get(value) || [];\n keys.push(key);\n draftLocations.set(value, keys);\n }\n });\n }\n const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;\n for (const location of locations) {\n set(parentCopy, location, finalizedValue, parentType);\n }\n}\nfunction registerChildFinalizationCallback(parent, child, key) {\n parent.callbacks_.push(function childCleanup(rootScope) {\n const state = child;\n if (!state || !isSameScope(state, rootScope)) {\n return;\n }\n rootScope.mapSetPlugin_?.fixSetContents(state);\n const finalizedValue = getFinalValue(state);\n updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);\n generatePatchesAndFinalize(state, rootScope);\n });\n}\nfunction generatePatchesAndFinalize(state, rootScope) {\n const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);\n if (shouldFinalize) {\n const { patchPlugin_ } = rootScope;\n if (patchPlugin_) {\n const basePath = patchPlugin_.getPath(state);\n if (basePath) {\n patchPlugin_.generatePatches_(state, basePath, rootScope);\n }\n }\n markStateFinalized(state);\n }\n}\nfunction handleCrossReference(target, key, value) {\n const { scope_ } = target;\n if (isDraft(value)) {\n const state = value[DRAFT_STATE];\n if (isSameScope(state, scope_)) {\n state.callbacks_.push(function crossReferenceCleanup() {\n prepareCopy(target);\n const finalizedValue = getFinalValue(state);\n updateDraftInParent(target, value, finalizedValue, key);\n });\n }\n } else if (isDraftable(value)) {\n target.callbacks_.push(function nestedDraftCleanup() {\n const targetCopy = latest(target);\n if (target.type_ === 3 /* Set */) {\n if (targetCopy.has(value)) {\n handleValue(value, scope_.handledSet_, scope_);\n }\n } else {\n if (get(targetCopy, key, target.type_) === value) {\n if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {\n handleValue(\n get(target.copy_, key, target.type_),\n scope_.handledSet_,\n scope_\n );\n }\n }\n }\n });\n }\n}\nfunction handleValue(target, handledSet, rootScope) {\n if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n return target;\n }\n if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {\n return target;\n }\n handledSet.add(target);\n each(target, (key, value) => {\n if (isDraft(value)) {\n const state = value[DRAFT_STATE];\n if (isSameScope(state, rootScope)) {\n const updatedValue = getFinalValue(state);\n set(target, key, updatedValue, target.type_);\n markStateFinalized(state);\n }\n } else if (isDraftable(value)) {\n handleValue(value, handledSet, rootScope);\n }\n });\n return target;\n}\n\n// src/core/proxy.ts\nfunction createProxyProxy(base, parent) {\n const baseIsArray = isArray(base);\n const state = {\n type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,\n // Track which produce call this is associated with.\n scope_: parent ? parent.scope_ : getCurrentScope(),\n // True for both shallow and deep changes.\n modified_: false,\n // Used during finalization.\n finalized_: false,\n // Track which properties have been assigned (true) or deleted (false).\n // actually instantiated in `prepareCopy()`\n assigned_: void 0,\n // The parent draft state.\n parent_: parent,\n // The base state.\n base_: base,\n // The base proxy.\n draft_: null,\n // set below\n // The base copy with any updated values.\n copy_: null,\n // Called by the `produce` function.\n revoke_: null,\n isManual_: false,\n // `callbacks` actually gets assigned in `createProxy`\n callbacks_: void 0\n };\n let target = state;\n let traps = objectTraps;\n if (baseIsArray) {\n target = [state];\n traps = arrayTraps;\n }\n const { revoke, proxy } = Proxy.revocable(target, traps);\n state.draft_ = proxy;\n state.revoke_ = revoke;\n return [proxy, state];\n}\nvar objectTraps = {\n get(state, prop) {\n if (prop === DRAFT_STATE)\n return state;\n let arrayPlugin = state.scope_.arrayMethodsPlugin_;\n const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === \"string\";\n if (isArrayWithStringProp) {\n if (arrayPlugin?.isArrayOperationMethod(prop)) {\n return arrayPlugin.createMethodInterceptor(state, prop);\n }\n }\n const source = latest(state);\n if (!has(source, prop, state.type_)) {\n return readPropFromProto(state, source, prop);\n }\n const value = source[prop];\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(\n state.operationMethod\n ) && isArrayIndex(prop)) {\n return value;\n }\n if (value === peek(state.base_, prop) || isRelocatedBaseRef(state, prop, value)) {\n prepareCopy(state);\n const childKey = state.type_ === 1 /* Array */ ? +prop : prop;\n const childDraft = createProxy(state.scope_, value, state, childKey);\n return state.copy_[childKey] = childDraft;\n }\n return value;\n },\n has(state, prop) {\n return prop in latest(state);\n },\n ownKeys(state) {\n return Reflect.ownKeys(latest(state));\n },\n set(state, prop, value) {\n const desc = getDescriptorFromProto(latest(state), prop);\n if (desc?.set) {\n desc.set.call(state.draft_, value);\n return true;\n }\n if (!state.modified_) {\n const current2 = peek(latest(state), prop);\n const currentState = current2?.[DRAFT_STATE];\n if (currentState && currentState.base_ === value) {\n state.copy_[prop] = value;\n state.assigned_.set(prop, false);\n return true;\n }\n if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))\n return true;\n prepareCopy(state);\n markChanged(state);\n }\n if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'\n (value !== void 0 || has(state.copy_, prop, state.type_)) || // special case: NaN\n Number.isNaN(value) && Number.isNaN(state.copy_[prop]))\n return true;\n state.copy_[prop] = value;\n state.assigned_.set(prop, true);\n handleCrossReference(state, prop, value);\n return true;\n },\n deleteProperty(state, prop) {\n prepareCopy(state);\n if (peek(state.base_, prop) !== void 0 || prop in state.base_) {\n state.assigned_.set(prop, false);\n markChanged(state);\n } else {\n state.assigned_.delete(prop);\n }\n if (state.copy_) {\n delete state.copy_[prop];\n }\n return true;\n },\n // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n // the same guarantee in ES5 mode.\n getOwnPropertyDescriptor(state, prop) {\n const owner = latest(state);\n const desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n if (!desc)\n return desc;\n return {\n [WRITABLE]: true,\n [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== \"length\",\n [ENUMERABLE]: desc[ENUMERABLE],\n [VALUE]: owner[prop]\n };\n },\n defineProperty() {\n die(11);\n },\n getPrototypeOf(state) {\n return getPrototypeOf(state.base_);\n },\n setPrototypeOf() {\n die(12);\n }\n};\nvar arrayTraps = {};\nfor (let key in objectTraps) {\n let fn = objectTraps[key];\n arrayTraps[key] = function() {\n const args = arguments;\n args[0] = args[0][0];\n return fn.apply(this, args);\n };\n}\narrayTraps.deleteProperty = function(state, prop) {\n if (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop)))\n die(13);\n return arrayTraps.set.call(this, state, prop, void 0);\n};\narrayTraps.set = function(state, prop, value) {\n if (process.env.NODE_ENV !== \"production\" && prop !== \"length\" && isNaN(parseInt(prop)))\n die(14);\n return objectTraps.set.call(this, state[0], prop, value, state[0]);\n};\nfunction peek(draft, prop) {\n const state = draft[DRAFT_STATE];\n const source = state ? latest(state) : draft;\n return source[prop];\n}\nfunction isRelocatedBaseRef(state, prop, value) {\n if (state.type_ !== 1 /* Array */ || !state.allIndicesReassigned_ || state.assigned_?.get(prop) || !isDraftable(value) || value[DRAFT_STATE]) {\n return false;\n }\n return state.baseRefs_.has(value);\n}\nfunction readPropFromProto(state, source, prop) {\n const desc = getDescriptorFromProto(source, prop);\n return desc ? VALUE in desc ? desc[VALUE] : (\n // This is a very special case, if the prop is a getter defined by the\n // prototype, we should invoke it with the draft as context!\n desc.get?.call(state.draft_)\n ) : void 0;\n}\nfunction getDescriptorFromProto(source, prop) {\n if (!(prop in source))\n return void 0;\n let proto = getPrototypeOf(source);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc)\n return desc;\n proto = getPrototypeOf(proto);\n }\n return void 0;\n}\nfunction markChanged(state) {\n if (!state.modified_) {\n state.modified_ = true;\n if (state.parent_) {\n markChanged(state.parent_);\n }\n }\n}\nfunction prepareCopy(state) {\n if (!state.copy_) {\n state.assigned_ = /* @__PURE__ */ new Map();\n state.copy_ = shallowCopy(\n state.base_,\n state.scope_.immer_.useStrictShallowCopy_\n );\n }\n}\n\n// src/core/immerClass.ts\nvar Immer2 = class {\n constructor(config) {\n this.autoFreeze_ = true;\n this.useStrictShallowCopy_ = false;\n this.useStrictIteration_ = false;\n /**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\n this.produce = (base, recipe, patchListener) => {\n if (isFunction(base) && !isFunction(recipe)) {\n const defaultBase = recipe;\n recipe = base;\n const self = this;\n return function curriedProduce(base2 = defaultBase, ...args) {\n return self.produce(base2, (draft) => recipe.call(this, draft, ...args));\n };\n }\n if (!isFunction(recipe))\n die(6);\n if (patchListener !== void 0 && !isFunction(patchListener))\n die(7);\n let result;\n if (isDraftable(base)) {\n const scope = enterScope(this);\n const proxy = createProxy(scope, base, void 0);\n let hasError = true;\n try {\n result = recipe(proxy);\n hasError = false;\n } finally {\n if (hasError)\n revokeScope(scope);\n else\n leaveScope(scope);\n }\n usePatchesInScope(scope, patchListener);\n return processResult(result, scope);\n } else if (!base || !isObjectish(base)) {\n result = recipe(base);\n if (result === void 0)\n result = base;\n if (result === NOTHING)\n result = void 0;\n if (this.autoFreeze_)\n freeze(result, true);\n if (patchListener) {\n const p = [];\n const ip = [];\n getPlugin(PluginPatches).generateReplacementPatches_(base, result, {\n patches_: p,\n inversePatches_: ip\n });\n patchListener(p, ip);\n }\n return result;\n } else\n die(1, base);\n };\n this.produceWithPatches = (base, recipe) => {\n if (isFunction(base)) {\n return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));\n }\n let patches, inversePatches;\n const result = this.produce(base, recipe, (p, ip) => {\n patches = p;\n inversePatches = ip;\n });\n return [result, patches, inversePatches];\n };\n if (isBoolean(config?.autoFreeze))\n this.setAutoFreeze(config.autoFreeze);\n if (isBoolean(config?.useStrictShallowCopy))\n this.setUseStrictShallowCopy(config.useStrictShallowCopy);\n if (isBoolean(config?.useStrictIteration))\n this.setUseStrictIteration(config.useStrictIteration);\n }\n createDraft(base) {\n if (!isDraftable(base))\n die(8);\n if (isDraft(base))\n base = current(base);\n const scope = enterScope(this);\n const proxy = createProxy(scope, base, void 0);\n proxy[DRAFT_STATE].isManual_ = true;\n leaveScope(scope);\n return proxy;\n }\n finishDraft(draft, patchListener) {\n const state = draft && draft[DRAFT_STATE];\n if (!state || !state.isManual_)\n die(9);\n const { scope_: scope } = state;\n usePatchesInScope(scope, patchListener);\n return processResult(void 0, scope);\n }\n /**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * By default, auto-freezing is enabled.\n */\n setAutoFreeze(value) {\n this.autoFreeze_ = value;\n }\n /**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\n setUseStrictShallowCopy(value) {\n this.useStrictShallowCopy_ = value;\n }\n /**\n * Pass false to use faster iteration that skips non-enumerable properties\n * but still handles symbols for compatibility.\n *\n * By default, strict iteration is enabled (includes all own properties).\n */\n setUseStrictIteration(value) {\n this.useStrictIteration_ = value;\n }\n shouldUseStrictIteration() {\n return this.useStrictIteration_;\n }\n applyPatches(base, patches) {\n let i;\n for (i = patches.length - 1; i >= 0; i--) {\n const patch = patches[i];\n if (patch.path.length === 0 && patch.op === \"replace\") {\n base = patch.value;\n break;\n }\n }\n if (i > -1) {\n patches = patches.slice(i + 1);\n }\n const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;\n if (isDraft(base)) {\n return applyPatchesImpl(base, patches);\n }\n return this.produce(\n base,\n (draft) => applyPatchesImpl(draft, patches)\n );\n }\n};\nfunction createProxy(rootScope, value, parent, key) {\n const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);\n const scope = parent?.scope_ ?? getCurrentScope();\n scope.drafts_.push(draft);\n state.callbacks_ = parent?.callbacks_ ?? [];\n state.key_ = key;\n if (parent && key !== void 0) {\n registerChildFinalizationCallback(parent, state, key);\n } else {\n state.callbacks_.push(function rootDraftCleanup(rootScope2) {\n rootScope2.mapSetPlugin_?.fixSetContents(state);\n const { patchPlugin_ } = rootScope2;\n if (state.modified_ && patchPlugin_) {\n patchPlugin_.generatePatches_(state, [], rootScope2);\n }\n });\n }\n return draft;\n}\n\n// src/core/current.ts\nfunction current(value) {\n if (!isDraft(value))\n die(10, value);\n return currentImpl(value);\n}\nfunction currentImpl(value) {\n if (!isDraftable(value) || isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n let copy;\n let strict = true;\n if (state) {\n if (!state.modified_)\n return state.base_;\n state.finalized_ = true;\n copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);\n strict = state.scope_.immer_.shouldUseStrictIteration();\n } else {\n copy = shallowCopy(value, true);\n }\n each(\n copy,\n (key, childValue) => {\n set(copy, key, currentImpl(childValue));\n },\n strict\n );\n if (state) {\n state.finalized_ = false;\n }\n return copy;\n}\n\n// src/plugins/patches.ts\nfunction enablePatches() {\n const errorOffset = 16;\n if (process.env.NODE_ENV !== \"production\") {\n errors.push(\n 'Sets cannot have \"replace\" patches.',\n function(op) {\n return \"Unsupported patch operation: \" + op;\n },\n function(path) {\n return \"Cannot apply patch, path doesn't resolve: \" + path;\n },\n \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n );\n }\n function getPath(state, path = []) {\n if (state.key_ !== void 0) {\n const parentCopy = state.parent_.copy_ ?? state.parent_.base_;\n const proxyDraft = getProxyDraft(get(parentCopy, state.key_));\n const valueAtKey = get(parentCopy, state.key_);\n if (valueAtKey === void 0) {\n return null;\n }\n if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {\n return null;\n }\n if (proxyDraft != null && proxyDraft.base_ !== state.base_) {\n return null;\n }\n const isSet2 = state.parent_.type_ === 3 /* Set */;\n let key;\n if (isSet2) {\n const setParent = state.parent_;\n key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);\n } else {\n key = state.key_;\n }\n if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {\n return null;\n }\n path.push(key);\n }\n if (state.parent_) {\n return getPath(state.parent_, path);\n }\n path.reverse();\n try {\n resolvePath(state.copy_, path);\n } catch (e) {\n return null;\n }\n return path;\n }\n function resolvePath(base, path) {\n let current2 = base;\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n current2 = get(current2, key);\n if (!isObjectish(current2) || current2 === null) {\n throw new Error(`Cannot resolve path at '${path.join(\"/\")}'`);\n }\n }\n return current2;\n }\n const REPLACE = \"replace\";\n const ADD = \"add\";\n const REMOVE = \"remove\";\n function generatePatches_(state, basePath, scope) {\n if (state.scope_.processedForPatches_.has(state)) {\n return;\n }\n state.scope_.processedForPatches_.add(state);\n const { patches_, inversePatches_ } = scope;\n switch (state.type_) {\n case 0 /* Object */:\n case 2 /* Map */:\n return generatePatchesFromAssigned(\n state,\n basePath,\n patches_,\n inversePatches_\n );\n case 1 /* Array */:\n return generateArrayPatches(\n state,\n basePath,\n patches_,\n inversePatches_\n );\n case 3 /* Set */:\n return generateSetPatches(\n state,\n basePath,\n patches_,\n inversePatches_\n );\n }\n }\n function generateArrayPatches(state, basePath, patches, inversePatches) {\n let { base_, assigned_ } = state;\n let copy_ = state.copy_;\n if (copy_.length < base_.length) {\n ;\n [base_, copy_] = [copy_, base_];\n [patches, inversePatches] = [inversePatches, patches];\n }\n const allReassigned = state.allIndicesReassigned_ === true;\n for (let i = 0; i < base_.length; i++) {\n const copiedItem = copy_[i];\n const baseItem = base_[i];\n const isAssigned = allReassigned || assigned_?.get(i.toString());\n if (isAssigned && copiedItem !== baseItem) {\n const childState = copiedItem?.[DRAFT_STATE];\n if (childState && childState.modified_) {\n continue;\n }\n const path = basePath.concat([i]);\n patches.push({\n op: REPLACE,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copiedItem)\n });\n inversePatches.push({\n op: REPLACE,\n path,\n value: clonePatchValueIfNeeded(baseItem)\n });\n }\n }\n for (let i = base_.length; i < copy_.length; i++) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n }\n for (let i = copy_.length - 1; base_.length <= i; --i) {\n const path = basePath.concat([i]);\n inversePatches.push({\n op: REMOVE,\n path\n });\n }\n }\n function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n const { base_, copy_, type_ } = state;\n each(state.assigned_, (key, assignedValue) => {\n const origValue = get(base_, key, type_);\n const value = get(copy_, key, type_);\n const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n if (origValue === value && op === REPLACE)\n return;\n const path = basePath.concat(key);\n patches.push(\n op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }\n );\n inversePatches.push(\n op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }\n );\n });\n }\n function generateSetPatches(state, basePath, patches, inversePatches) {\n let { base_, copy_ } = state;\n let i = 0;\n base_.forEach((value) => {\n if (!copy_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: REMOVE,\n path,\n value\n });\n inversePatches.unshift({\n op: ADD,\n path,\n value\n });\n }\n i++;\n });\n i = 0;\n copy_.forEach((value) => {\n if (!base_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n value\n });\n inversePatches.unshift({\n op: REMOVE,\n path,\n value\n });\n }\n i++;\n });\n }\n function generateReplacementPatches_(baseValue, replacement, scope) {\n const { patches_, inversePatches_ } = scope;\n patches_.push({\n op: REPLACE,\n path: [],\n value: replacement === NOTHING ? void 0 : replacement\n });\n inversePatches_.push({\n op: REPLACE,\n path: [],\n value: baseValue\n });\n }\n function applyPatches_(draft, patches) {\n patches.forEach((patch) => {\n const { path, op } = patch;\n let base = draft;\n for (let i = 0; i < path.length - 1; i++) {\n const parentType = getArchtype(base);\n let p = path[i];\n if (typeof p !== \"string\" && typeof p !== \"number\") {\n p = \"\" + p;\n }\n if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === \"__proto__\" || p === CONSTRUCTOR))\n die(errorOffset + 3);\n if (isFunction(base) && p === PROTOTYPE)\n die(errorOffset + 3);\n base = get(base, p);\n if (base === null || !isObjectish(base))\n die(errorOffset + 2, path.join(\"/\"));\n }\n const type = getArchtype(base);\n const value = deepClonePatchValue(patch.value);\n const key = path[path.length - 1];\n switch (op) {\n case REPLACE:\n switch (type) {\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n die(errorOffset);\n default:\n return base[key] = value;\n }\n case ADD:\n switch (type) {\n case 1 /* Array */:\n return key === \"-\" ? base.push(value) : base.splice(key, 0, value);\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n return base.add(value);\n default:\n return base[key] = value;\n }\n case REMOVE:\n switch (type) {\n case 1 /* Array */:\n return base.splice(key, 1);\n case 2 /* Map */:\n return base.delete(key);\n case 3 /* Set */:\n return base.delete(patch.value);\n default:\n return delete base[key];\n }\n default:\n die(errorOffset + 1, op);\n }\n });\n return draft;\n }\n function deepClonePatchValue(obj) {\n if (!isDraftable(obj))\n return obj;\n if (isArray(obj))\n return obj.map(deepClonePatchValue);\n if (isMap(obj))\n return new Map(\n Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n );\n if (isSet(obj))\n return new Set(Array.from(obj).map(deepClonePatchValue));\n const cloned = Object.create(getPrototypeOf(obj));\n for (const key in obj)\n cloned[key] = deepClonePatchValue(obj[key]);\n if (has(obj, DRAFTABLE))\n cloned[DRAFTABLE] = obj[DRAFTABLE];\n return cloned;\n }\n function clonePatchValueIfNeeded(obj) {\n if (isDraft(obj)) {\n return deepClonePatchValue(obj);\n } else\n return obj;\n }\n loadPlugin(PluginPatches, {\n applyPatches_,\n generatePatches_,\n generateReplacementPatches_,\n getPath\n });\n}\n\n// src/plugins/mapset.ts\nfunction enableMapSet() {\n class DraftMap extends Map {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 2 /* Map */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n assigned_: void 0,\n base_: target,\n draft_: this,\n isManual_: false,\n revoked_: false,\n callbacks_: []\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(key) {\n return latest(this[DRAFT_STATE]).has(key);\n }\n set(key, value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!latest(state).has(key) || latest(state).get(key) !== value) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_.set(key, true);\n state.copy_.set(key, value);\n state.assigned_.set(key, true);\n handleCrossReference(state, key, value);\n }\n return this;\n }\n delete(key) {\n if (!this.has(key)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareMapCopy(state);\n markChanged(state);\n if (state.base_.has(key)) {\n state.assigned_.set(key, false);\n } else {\n state.assigned_.delete(key);\n }\n state.copy_.delete(key);\n return true;\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_ = /* @__PURE__ */ new Map();\n each(state.base_, (key) => {\n state.assigned_.set(key, false);\n });\n state.copy_.clear();\n }\n }\n forEach(cb, thisArg) {\n const state = this[DRAFT_STATE];\n latest(state).forEach((_value, key, _map) => {\n cb.call(thisArg, this.get(key), key, this);\n });\n }\n get(key) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n const value = latest(state).get(key);\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value !== state.base_.get(key)) {\n return value;\n }\n const draft = createProxy(state.scope_, value, state, key);\n prepareMapCopy(state);\n state.copy_.set(key, draft);\n return draft;\n }\n keys() {\n return latest(this[DRAFT_STATE]).keys();\n }\n values() {\n const iterator = this.keys();\n return iteratorFrom({\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value\n };\n }\n });\n }\n entries() {\n const iterator = this.keys();\n return iteratorFrom({\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value: [r.value, value]\n };\n }\n });\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.entries();\n }\n }\n function iteratorFrom(iterable) {\n if (typeof Iterator !== \"undefined\") {\n return Iterator.from(iterable);\n }\n const iterator = {\n ...iterable,\n [Symbol.iterator]: () => iterator\n };\n return iterator;\n }\n function proxyMap_(target, parent) {\n const map = new DraftMap(target, parent);\n return [map, map[DRAFT_STATE]];\n }\n function prepareMapCopy(state) {\n if (!state.copy_) {\n state.assigned_ = /* @__PURE__ */ new Map();\n state.copy_ = new Map(state.base_);\n }\n }\n class DraftSet extends Set {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 3 /* Set */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n base_: target,\n draft_: this,\n drafts_: /* @__PURE__ */ new Map(),\n revoked_: false,\n isManual_: false,\n assigned_: void 0,\n callbacks_: []\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!state.copy_) {\n return state.base_.has(value);\n }\n if (state.copy_.has(value))\n return true;\n if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n return true;\n return false;\n }\n add(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!this.has(value)) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.add(value);\n handleCrossReference(state, value, value);\n }\n return this;\n }\n delete(value) {\n if (!this.has(value)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n markChanged(state);\n return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (\n /* istanbul ignore next */\n false\n ));\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.clear();\n }\n }\n values() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.values();\n }\n entries() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.entries();\n }\n keys() {\n return this.values();\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.values();\n }\n forEach(cb, thisArg) {\n const iterator = this.values();\n let result = iterator.next();\n while (!result.done) {\n cb.call(thisArg, result.value, result.value, this);\n result = iterator.next();\n }\n }\n }\n function proxySet_(target, parent) {\n const set2 = new DraftSet(target, parent);\n return [set2, set2[DRAFT_STATE]];\n }\n function prepareSetCopy(state) {\n if (!state.copy_) {\n state.copy_ = /* @__PURE__ */ new Set();\n state.base_.forEach((value) => {\n if (isDraftable(value)) {\n const draft = createProxy(state.scope_, value, state, value);\n state.drafts_.set(value, draft);\n state.copy_.add(draft);\n } else {\n state.copy_.add(value);\n }\n });\n }\n }\n function assertUnrevoked(state) {\n if (state.revoked_)\n die(3, JSON.stringify(latest(state)));\n }\n function fixSetContents(target) {\n if (target.type_ === 3 /* Set */ && target.copy_) {\n const copy = new Set(target.copy_);\n target.copy_.clear();\n copy.forEach((value) => {\n target.copy_.add(getValue(value));\n });\n }\n }\n loadPlugin(PluginMapSet, { proxyMap_, proxySet_, fixSetContents });\n}\n\n// src/plugins/arrayMethods.ts\nfunction enableArrayMethods() {\n const SHIFTING_METHODS = /* @__PURE__ */ new Set([\"shift\", \"unshift\"]);\n const QUEUE_METHODS = /* @__PURE__ */ new Set([\"push\", \"pop\"]);\n const RESULT_RETURNING_METHODS = /* @__PURE__ */ new Set([\n ...QUEUE_METHODS,\n ...SHIFTING_METHODS\n ]);\n const REORDERING_METHODS = /* @__PURE__ */ new Set([\"reverse\", \"sort\"]);\n const MUTATING_METHODS = /* @__PURE__ */ new Set([\n ...RESULT_RETURNING_METHODS,\n ...REORDERING_METHODS,\n \"splice\"\n ]);\n const FIND_METHODS = /* @__PURE__ */ new Set([\"find\", \"findLast\"]);\n const NON_MUTATING_METHODS = /* @__PURE__ */ new Set([\n \"filter\",\n \"slice\",\n \"concat\",\n \"flat\",\n ...FIND_METHODS,\n \"findIndex\",\n \"findLastIndex\",\n \"some\",\n \"every\",\n \"indexOf\",\n \"lastIndexOf\",\n \"includes\",\n \"join\",\n \"toString\",\n \"toLocaleString\"\n ]);\n function isMutatingArrayMethod(method) {\n return MUTATING_METHODS.has(method);\n }\n function isNonMutatingArrayMethod(method) {\n return NON_MUTATING_METHODS.has(method);\n }\n function isArrayOperationMethod(method) {\n return isMutatingArrayMethod(method) || isNonMutatingArrayMethod(method);\n }\n function enterOperation(state, method) {\n state.operationMethod = method;\n }\n function exitOperation(state) {\n state.operationMethod = void 0;\n }\n function executeArrayMethod(state, operation, markLength = true) {\n prepareCopy(state);\n const result = operation();\n markChanged(state);\n if (markLength)\n state.assigned_.set(\"length\", true);\n return result;\n }\n function markAllIndicesReassigned(state) {\n state.allIndicesReassigned_ = true;\n state.baseRefs_ = new Set(state.base_);\n }\n function normalizeSliceIndex(index, length) {\n if (index < 0) {\n return Math.max(length + index, 0);\n }\n return Math.min(index, length);\n }\n function handleInsertedValues(state, startIndex, values) {\n for (let i = 0; i < values.length; i++) {\n const index = startIndex + i;\n state.assigned_.set(index, true);\n handleCrossReference(state, index, values[i]);\n }\n }\n function handleSimpleOperation(state, method, args) {\n return executeArrayMethod(state, () => {\n const lengthBefore = state.copy_.length;\n const result = state.copy_[method](...args);\n if (SHIFTING_METHODS.has(method)) {\n markAllIndicesReassigned(state);\n }\n if (method === \"push\" && args.length > 0) {\n handleInsertedValues(state, lengthBefore, args);\n } else if (method === \"unshift\" && args.length > 0) {\n handleInsertedValues(state, 0, args);\n }\n return RESULT_RETURNING_METHODS.has(method) ? result : state.draft_;\n });\n }\n function handleReorderingOperation(state, method, args) {\n return executeArrayMethod(\n state,\n () => {\n ;\n state.copy_[method](...args);\n markAllIndicesReassigned(state);\n return state.draft_;\n },\n false\n );\n }\n function createMethodInterceptor(state, originalMethod) {\n return function interceptedMethod(...args) {\n const method = originalMethod;\n enterOperation(state, method);\n try {\n if (isMutatingArrayMethod(method)) {\n if (RESULT_RETURNING_METHODS.has(method)) {\n return handleSimpleOperation(state, method, args);\n }\n if (REORDERING_METHODS.has(method)) {\n return handleReorderingOperation(state, method, args);\n }\n if (method === \"splice\") {\n const res = executeArrayMethod(\n state,\n () => state.copy_.splice(...args)\n );\n markAllIndicesReassigned(state);\n if (args.length > 2) {\n const startIndex = normalizeSliceIndex(\n args[0] ?? 0,\n state.copy_.length\n );\n handleInsertedValues(state, startIndex, args.slice(2));\n }\n return res;\n }\n } else {\n return handleNonMutatingOperation(state, method, args);\n }\n } finally {\n exitOperation(state);\n }\n };\n }\n function handleNonMutatingOperation(state, method, args) {\n const source = latest(state);\n if (method === \"filter\") {\n const predicate = args[0];\n const result = [];\n for (let i = 0; i < source.length; i++) {\n if (predicate(source[i], i, source)) {\n result.push(state.draft_[i]);\n }\n }\n return result;\n }\n if (FIND_METHODS.has(method)) {\n const predicate = args[0];\n const isForward = method === \"find\";\n const step = isForward ? 1 : -1;\n const start = isForward ? 0 : source.length - 1;\n for (let i = start; i >= 0 && i < source.length; i += step) {\n if (predicate(source[i], i, source)) {\n return state.draft_[i];\n }\n }\n return void 0;\n }\n if (method === \"slice\") {\n const rawStart = args[0] ?? 0;\n const rawEnd = args[1] ?? source.length;\n const start = normalizeSliceIndex(rawStart, source.length);\n const end = normalizeSliceIndex(rawEnd, source.length);\n const result = [];\n for (let i = start; i < end; i++) {\n result.push(state.draft_[i]);\n }\n return result;\n }\n return source[method](...args);\n }\n loadPlugin(PluginArrayMethods, {\n createMethodInterceptor,\n isArrayOperationMethod,\n isMutatingArrayMethod\n });\n}\n\n// src/immer.ts\nvar immer = new Immer2();\nvar produce = immer.produce;\nvar produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(immer);\nvar setAutoFreeze = /* @__PURE__ */ immer.setAutoFreeze.bind(immer);\nvar setUseStrictShallowCopy = /* @__PURE__ */ immer.setUseStrictShallowCopy.bind(immer);\nvar setUseStrictIteration = /* @__PURE__ */ immer.setUseStrictIteration.bind(immer);\nvar applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);\nvar createDraft = /* @__PURE__ */ immer.createDraft.bind(immer);\nvar finishDraft = /* @__PURE__ */ immer.finishDraft.bind(immer);\nvar castDraft = (value) => value;\nvar castImmutable = (value) => value;\nexport {\n Immer2 as Immer,\n applyPatches,\n castDraft,\n castImmutable,\n createDraft,\n current,\n enableArrayMethods,\n enableMapSet,\n enablePatches,\n finishDraft,\n freeze,\n DRAFTABLE as immerable,\n isDraft,\n isDraftable,\n NOTHING as nothing,\n original,\n produce,\n produceWithPatches,\n setAutoFreeze,\n setUseStrictIteration,\n setUseStrictShallowCopy\n};\n//# sourceMappingURL=immer.mjs.map","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { current, type Draft, isDraft, produce } from \"immer\";\nimport { z } from \"zod\";\n\n/**\n * Result returned by a single per-variant action handler. `inverse` is the\n * action sequence the undo stack should replay to revert the handler's effect.\n * `targets` is the set of document keys the handler touched, used by consumers\n * to invalidate undoables targeting overlapping resources when a remote\n * session emits a competing action.\n */\nexport interface HandlerResult<A> {\n inverse: A[];\n targets: readonly string[];\n}\n\n/**\n * NO_OP_RESULT is the zero-value HandlerResult. Return it from a handler that\n * declined to mutate state (e.g. lookup miss) so it neither contributes to the\n * undo stack nor invalidates undoables targeting the same resource.\n */\nexport const NO_OP_RESULT: HandlerResult<never> = { inverse: [], targets: [] };\n\n/**\n * Result returned by a reduceAll application: the new state, the inverse\n * sequence that reverts the whole batch, and the union of all targets touched.\n */\nexport interface ReduceAllResult<S, A> {\n next: S;\n inverse: A[];\n targets: readonly string[];\n}\n\n/**\n * Returns a plain-object snapshot of an Immer draft so the result is safe to embed in\n * an action stored on the undo stack. Returns non-draft inputs unchanged. The non-draft\n * passthrough exists because when a reducer applies multiple actions in one produce(),\n * an earlier action's wholesale assignment leaves the slot as a plain object, so the\n * next action would crash if it called `current` unconditionally.\n */\nexport const snapshotDraft = <T>(v: T): T => (isDraft(v) ? current(v as Draft<T>) : v);\n\n/**\n * createReduceAll lifts a per-variant `reduceOne` switch into a batched\n * reducer. The returned function applies each action against an Immer draft of\n * `state` in order, accumulates the inverses in reverse application order so a\n * single undo replays them correctly, and unions the touched targets.\n */\nexport const createReduceAll =\n <S, A>(reduceOne: (draft: Draft<S>, action: A) => HandlerResult<A>) =>\n (state: S, actions: A[]): ReduceAllResult<S, A> => {\n const inverse: A[] = [];\n const targetsSet = new Set<string>();\n const next = produce(state, (draft) => {\n for (const action of actions) {\n const result = reduceOne(draft, action);\n if (result.inverse.length > 0) inverse.unshift(...result.inverse);\n for (const t of result.targets) targetsSet.add(t);\n }\n });\n return { next, inverse, targets: Array.from(targetsSet) };\n };\n\n/**\n * scopedZ builds the schema for envelopes broadcast on the sy_<service>_set\n * cluster signals channel. The framer's JSON codec runs snakeToCamel before\n * handing the value to the schema, so `dispatchKey` and `seq` are camelCase\n * here even though the server emits them as snake_case. `seq` defaults to 0 so\n * frames from servers that predate the field stay parseable.\n */\nexport const scopedZ = <K extends z.ZodType, A extends z.ZodType>(\n keyZ: K,\n actionZ: A,\n) =>\n z.object({\n key: keyZ,\n dispatchKey: z.string(),\n seq: z.number().int().nonnegative().default(0),\n actions: actionZ.array(),\n });\n\n/**\n * dispatchReqZ builds the request body schema for the per-service dispatch\n * endpoint. Stays camelCase; the JSON codec runs camelToSnake on encode so the\n * wire ends up snake_case without per-field conversion here.\n */\nexport const dispatchReqZ = <K extends z.ZodType, A extends z.ZodType>(\n keyZ: K,\n actionZ: A,\n) =>\n z.object({\n key: keyZ,\n dispatchKey: z.string(),\n actions: actionZ.array(),\n });\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n compare,\n destructor,\n errors,\n id,\n type record,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport type z from \"zod\";\n\nimport { type query } from \"@/query\";\nimport { Table } from \"@/query/table\";\n\nconst DEFAULT_COALESCE_WINDOW = TimeSpan.milliseconds(500);\nconst DEFAULT_STACK_CAP = 200;\nconst STALE_AUTO_ADVANCE_CAP = 10;\n\nexport interface StackEntry<Action> {\n forward: Action[];\n inverse: Action[];\n kind: string;\n /** Wall-clock push time, used only for coalescing. */\n ts: TimeStamp;\n /** Tick of the earliest push, used to order the entry against remote touches. */\n tick: number;\n targets: readonly string[];\n}\n\ninterface UndoState<Action> {\n undo: StackEntry<Action>[];\n redo: StackEntry<Action>[];\n remoteTouched: Record<string, number>;\n}\n\nconst ZERO_UNDO = <A>(): UndoState<A> => ({ undo: [], redo: [], remoteTouched: {} });\n\nconst pushOnto = <A>(\n stack: StackEntry<A>[],\n next: StackEntry<A>,\n window: TimeSpan,\n cap: number,\n): StackEntry<A>[] => {\n const top = stack[stack.length - 1];\n const merged =\n top != null &&\n top.kind === next.kind &&\n next.ts.span(top.ts).lessThanOrEqual(window) &&\n compare.unorderedPrimitiveArrays(top.targets, next.targets) === compare.EQUAL\n ? {\n forward: [...top.forward, ...next.forward],\n inverse: [...next.inverse, ...top.inverse],\n kind: next.kind,\n ts: next.ts,\n tick: top.tick,\n targets: top.targets,\n }\n : null;\n const out = merged != null ? [...stack.slice(0, -1), merged] : [...stack, next];\n return out.length > cap ? out.slice(out.length - cap) : out;\n};\n\nexport interface Reducer<State extends query.Data, Action> {\n (\n state: State,\n actions: Action[],\n ): { next: State; inverse: Action[]; targets: readonly string[] };\n}\n\n/** Result of replaying a set of actions locally. The caller commits the\n * matching server send and runs `rollback` on failure. */\nexport interface ReplayResult<Action> {\n processed: Action[];\n inverse: Action[];\n targets: readonly string[];\n // changed reports whether the replay produced a different state. Reducers\n // return the input state by reference when no action touched it, so a false\n // value means the entire vector was a no-op and need not reach the server.\n changed: boolean;\n rollback: destructor.Destructor;\n}\n\n/** Result of preparing to undo or redo. The caller applies `actions` and runs\n * `commit` on success (which itself returns a destructor for failure-rollback). */\nexport interface Reversal<Action> {\n actions: Action[];\n commit: () => destructor.Destructor;\n}\n\n/**\n * A staged set of dispatches committed atomically as one undoable. Commit\n * resolves false when there is nothing to send; a send failure rolls back the\n * staged state and rethrows.\n */\nexport interface Transaction<Action> {\n add: (actions: Action | Action[]) => void;\n commit: () => Promise<boolean>;\n abort: () => void;\n}\n\n/** Sends an already-processed action list to the server. Supplied by the\n * caller so the controller stays free of network concerns. */\nexport type Send<Action> = (actions: Action[]) => Promise<void>;\n\n/**\n * Network send used by the dispatch/undo/redo loops. Receives the\n * controller-generated dispatch key that was registered as outstanding before\n * the call, so the broadcast echo is recognized as own.\n */\nexport type SendDispatch<Action> = (\n actions: Action[],\n dispatchKey: string,\n) => Promise<void>;\n\n/** Rewrites an action batch against the current document before replay. */\nexport type Preprocess<State, Action> = (state: State, actions: Action[]) => Action[];\n\n/** Options accepted by domain-client dispatch methods. */\nexport interface Options<State, Action> {\n /**\n * Per-call action rewrite requiring caller context the domain client lacks\n * (e.g. diagram geometry). Runs against the cached doc before replay.\n */\n preprocess?: Preprocess<State, Action>;\n}\n\n/** The action-dispatch surface a document domain client exposes. */\nexport interface Domain<Key extends record.Key, State extends query.Data, Action> {\n dispatch(\n key: Key,\n actions: Action | Action[],\n opts?: Options<State, Action>,\n ): Promise<boolean>;\n undo(key: Key): Promise<boolean>;\n redo(key: Key): Promise<boolean>;\n hasUndo(key: Key): boolean;\n hasRedo(key: Key): boolean;\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor;\n beginTransaction(key: Key, kind?: string): Transaction<Action>;\n}\n\n/**\n * The canonical wire shape for a broadcast action frame. The consumer's `schema` must\n * produce this shape (use a zod transform if the server emits differently-named\n * fields). `seq` is a per-key monotonic sequence stamped by the originating server node\n * and is used to skip echoes that are stale relative to the high-water mark — see\n * `applyRemote`. `dispatchKey` is the client-generated batch identifier the originator\n * registered as outstanding before sending; it is used to recognize own echoes\n * race-safely so a redundant reduce can be skipped when no foreign action interleaved.\n */\nexport interface Frame<Key, Action> {\n key: Key;\n dispatchKey: string;\n seq: number;\n actions: Action[];\n}\n\nexport interface ControllerParams<\n Key extends record.Key,\n State extends query.Data,\n Action,\n> {\n /** The table holding the documents this controller dispatches over. */\n store: Table<Key, State>;\n /** Reports listener errors that have no caller to throw to. */\n onError: (error: Error) => void;\n reduce: Reducer<State, Action>;\n preprocess?: (state: State, actions: Action[]) => Action[];\n isUndoable?: (action: Action) => boolean;\n kindOf?: (actions: Action[]) => string;\n /**\n * Returns the document carried by a create action, undefined otherwise.\n * Lets remote frames for never-cached documents ingest instead of drop.\n */\n createOf?: (action: Action) => State | undefined;\n coalesceWindow?: TimeSpan;\n stackCap?: number;\n /** Clock stamping entries for the coalesce window. Defaults to TimeStamp.now. */\n now?: () => TimeStamp;\n}\n\n/**\n * Owns the action-dispatch loop for one document table: local replay with\n * rollback, per-doc undo/redo stacks, echo recognition, and remote-frame\n * application. Operates on a plain cache table; all dispatch bookkeeping is\n * session-local and dropped when a document's row is deleted (tombstoned).\n */\nexport class Controller<Key extends record.Key, State extends query.Data, Action> {\n private readonly docs: Table<Key, State>;\n private readonly undos: Table<Key, UndoState<Action>>;\n private readonly params: Required<\n Omit<ControllerParams<Key, State, Action>, \"store\">\n >;\n // lastAppliedSeq tracks the highest broadcast sequence number applied for each key.\n // Echoes whose seq does not exceed this are stale (a fresher value already overwrote\n // them on the server) and are dropped. A seq of 0 is treated as \"unstamped\" and\n // always applies — that covers frames from servers that predate the field.\n private readonly lastAppliedSeq = new Map<Key, number>();\n // outstandingDispatches tracks per-key dispatches the originator has applied locally\n // via replay but whose broadcast echo has not yet arrived. Each entry's `disturbed`\n // flag is flipped to true when a foreign echo lands during the outstanding window; on\n // own-echo arrival, an entry that is not disturbed skips the reduce (the local replay\n // was authoritative) and an entry that is disturbed re-runs to recover from the\n // foreign overwrite.\n private readonly outstandingDispatches = new Map<\n Key,\n Map<string, { disturbed: boolean }>\n >();\n // Monotonic counter ordering entry pushes against remote touches. Program\n // order is the ground truth here; the wall clock ties within a millisecond\n // and steps on sleep/wake or NTP resync, so it cannot be trusted for this.\n private tick = 0;\n\n constructor(opts: ControllerParams<Key, State, Action>) {\n this.params = {\n onError: opts.onError,\n reduce: opts.reduce,\n preprocess: opts.preprocess ?? ((_, a) => a),\n isUndoable: opts.isUndoable ?? (() => true),\n kindOf: opts.kindOf ?? (() => \"default\"),\n createOf: opts.createOf ?? (() => undefined),\n coalesceWindow: opts.coalesceWindow ?? DEFAULT_COALESCE_WINDOW,\n stackCap: opts.stackCap ?? DEFAULT_STACK_CAP,\n now: opts.now ?? (() => TimeStamp.now()),\n };\n this.docs = opts.store;\n // Undo states are rebuilt objects on every update; comparing them would\n // be pure waste, so equality is disabled.\n this.undos = new Table<Key, UndoState<Action>>({\n onError: this.params.onError,\n equal: () => false,\n });\n // Stacks are session-local: when a document is deleted (tombstoned), its\n // dispatch bookkeeping goes with it.\n this.docs.subscribe((event) => {\n if (event.variant === \"delete\") this.drop(event.key);\n });\n }\n\n private drop(key: Key): void {\n this.undos.delete(key);\n this.lastAppliedSeq.delete(key);\n this.outstandingDispatches.delete(key);\n }\n\n private updateUndo(\n key: Key,\n fn: (s: UndoState<Action>) => UndoState<Action>,\n ): destructor.Destructor {\n return this.undos.set(key, (prev) => fn(prev ?? ZERO_UNDO<Action>()));\n }\n\n /**\n * Run preprocess + reduce against the cached doc and write the result.\n * Returns the reducer output and a rollback that restores the prior doc\n * state. Returns null if the doc isn't cached.\n */\n replay(\n key: Key,\n actions: Action[],\n opts: { skipPreprocess?: boolean } = {},\n ): ReplayResult<Action> | null {\n const current = this.docs.get(key);\n if (current == null) return null;\n const processed = opts.skipPreprocess\n ? actions\n : this.params.preprocess(current, actions);\n const { next, inverse, targets } = this.params.reduce(current, processed);\n return {\n processed,\n inverse,\n targets,\n changed: next !== current,\n rollback: this.docs.set(key, next),\n };\n }\n\n /**\n * Append an undoable entry to the stack. Filters non-undoable actions,\n * derives the kind, and coalesces with the prior entry if it falls within\n * the configured window with matching kind/targets. Clears redo.\n */\n recordEntry(\n key: Key,\n forward: Action[],\n inverse: Action[],\n targets: readonly string[],\n kindOverride?: string,\n ): destructor.Destructor {\n if (targets.length === 0) return destructor.NOOP;\n const undoableForward = forward.filter(this.params.isUndoable);\n if (undoableForward.length === 0) return destructor.NOOP;\n const entry: StackEntry<Action> = {\n forward: undoableForward,\n inverse,\n kind: kindOverride ?? this.params.kindOf(forward),\n ts: this.params.now(),\n tick: ++this.tick,\n targets,\n };\n return this.updateUndo(key, (s) => ({\n ...s,\n undo: pushOnto(s.undo, entry, this.params.coalesceWindow, this.params.stackCap),\n redo: [],\n }));\n }\n\n // Walks the chosen stack from the top, skipping entries whose targets were\n // remote-touched after the entry was pushed. Caps the walk at\n // STALE_AUTO_ADVANCE_CAP and drops a fully stale tail. On hit, returns the\n // entry's reversal actions (inverse for undo, forward for redo) and a\n // commit that moves the entry to the opposite stack.\n private prepareReversal(key: Key, side: \"undo\" | \"redo\"): Reversal<Action> | null {\n const state = this.undos.get(key);\n if (state == null) return null;\n const stack = state[side];\n if (stack.length === 0) return null;\n let stale = 0;\n let idx = -1;\n for (let i = stack.length - 1; i >= 0; i--) {\n const e = stack[i];\n if (e.targets.some((t) => (state.remoteTouched[t] ?? 0) > e.tick)) {\n stale++;\n if (stale >= STALE_AUTO_ADVANCE_CAP) break;\n } else {\n idx = i;\n break;\n }\n }\n if (idx === -1) {\n if (stale > 0)\n this.updateUndo(key, (s) => ({\n ...s,\n [side]: s[side].slice(0, s[side].length - stale),\n }));\n return null;\n }\n const entry = stack[idx];\n const other = side === \"undo\" ? \"redo\" : \"undo\";\n return {\n actions: side === \"undo\" ? entry.inverse : entry.forward,\n commit: () =>\n this.updateUndo(key, (s) => ({\n ...s,\n [side]: s[side].slice(0, idx),\n [other]: [...s[other], entry],\n })),\n };\n }\n\n // Reduce + send with rollback: replay locally, run the per-op stack\n // mutation, register the batch as outstanding *before* the network send\n // (the broadcast echo can race the HTTP response), and roll back stack and\n // state when the send fails. Returns false when the doc isn't cached.\n private async applySend(\n key: Key,\n actions: Action[],\n commitStack: (r: ReplayResult<Action>) => destructor.Destructor,\n send: SendDispatch<Action>,\n preprocess?: Preprocess<State, Action>,\n ): Promise<boolean> {\n const current = this.docs.get(key);\n if (current == null) return false;\n const processed = preprocess == null ? actions : preprocess(current, actions);\n const r = this.replay(key, processed, { skipPreprocess: true });\n if (r == null) return false;\n const stackRollback = commitStack(r);\n // A replay that left the state untouched has nothing for the server: no\n // document change, no broadcast worth echoing. The stack mutation still\n // runs above so undo/redo consume their entry instead of pinning it.\n if (!r.changed) return true;\n const dispatchKey = id.create();\n this.registerOutstandingDispatch(key, dispatchKey);\n try {\n await send(r.processed, dispatchKey);\n return true;\n } catch (e) {\n stackRollback();\n r.rollback();\n throw errors.fromUnknown(e);\n }\n }\n\n /**\n * Apply an action batch to the cached doc and send it to the server,\n * recording an undoable entry. Returns false without side effects when the\n * doc isn't cached. Rolls back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action[],\n send: SendDispatch<Action>,\n opts: Options<State, Action> = {},\n ): Promise<boolean> {\n if (actions.length === 0) return true;\n return await this.applySend(\n key,\n actions,\n ({ processed, inverse, targets }) =>\n this.recordEntry(key, processed, inverse, targets),\n send,\n opts.preprocess,\n );\n }\n\n /**\n * Apply and send the top live undo entry, moving it to the redo stack. Returns false\n * when nothing is undoable. Rolls back and rethrows on send failure.\n */\n async undo(key: Key, send: SendDispatch<Action>): Promise<boolean> {\n const prepared = this.prepareUndo(key);\n if (prepared == null) return false;\n return await this.applySend(key, prepared.actions, () => prepared.commit(), send);\n }\n\n /** Mirror of {@link undo} for the redo stack. */\n async redo(key: Key, send: SendDispatch<Action>): Promise<boolean> {\n const prepared = this.prepareRedo(key);\n if (prepared == null) return false;\n return await this.applySend(key, prepared.actions, () => prepared.commit(), send);\n }\n\n /**\n * Stage actions committed atomically as one undoable entry, registering the batch as\n * outstanding before the send so the broadcast echo is recognized as own.\n */\n transaction(\n key: Key,\n send: SendDispatch<Action>,\n kind?: string,\n ): Transaction<Action> {\n return this.beginTransaction(\n key,\n async (actions) => {\n const dispatchKey = id.create();\n this.registerOutstandingDispatch(key, dispatchKey);\n await send(actions, dispatchKey);\n },\n kind,\n );\n }\n\n prepareUndo(key: Key): Reversal<Action> | null {\n return this.prepareReversal(key, \"undo\");\n }\n\n prepareRedo(key: Key): Reversal<Action> | null {\n return this.prepareReversal(key, \"redo\");\n }\n\n beginTransaction(key: Key, send: Send<Action>, kind?: string): Transaction<Action> {\n const initial = this.docs.get(key);\n const accumulated: Action[] = [];\n let done = false;\n return {\n add: (actions) => {\n if (done) throw new Error(\"transaction finalized\");\n if (initial == null) return;\n const arr = Array.isArray(actions) ? actions : [actions];\n const r = this.replay(key, arr);\n if (r != null) accumulated.push(...r.processed);\n },\n commit: async () => {\n if (done) return false;\n done = true;\n if (accumulated.length === 0 || initial == null) return false;\n // Inverse must be computed against the pre-transaction snapshot so\n // undo restores to where the user started, not the last-add post-state.\n const { inverse, targets } = this.params.reduce(initial, accumulated);\n const stackRollback = this.recordEntry(\n key,\n accumulated,\n inverse,\n targets,\n kind,\n );\n try {\n await send(accumulated);\n return true;\n } catch (e) {\n stackRollback();\n this.docs.set(key, initial);\n throw errors.fromUnknown(e);\n }\n },\n abort: () => {\n if (done) return;\n done = true;\n if (initial != null) this.docs.set(key, initial);\n },\n };\n }\n\n markRemoteTouched(key: Key, targets: readonly string[]): destructor.Destructor {\n if (targets.length === 0) return destructor.NOOP;\n const tick = ++this.tick;\n return this.updateUndo(key, (s) => {\n const remoteTouched = { ...s.remoteTouched };\n for (const t of targets) remoteTouched[t] = tick;\n return { ...s, remoteTouched };\n });\n }\n\n /** Whether any locally replayed dispatch for the key still awaits its echo. */\n hasOutstanding(key: Key): boolean {\n return (this.outstandingDispatches.get(key)?.size ?? 0) > 0;\n }\n\n /**\n * Register a dispatch as outstanding so when its broadcast echo arrives it\n * can be recognized as own and a redundant reduce skipped. Called by the\n * dispatcher *before* the network send so the registration always wins the\n * race against a fast echo. A registration whose echo has already been\n * applied (seq advanced past it) is silently dropped; that's the safe\n * fallback when the echo arrives before the dispatch promise resolves.\n */\n registerOutstandingDispatch(key: Key, dispatchKey: string): void {\n let bucket = this.outstandingDispatches.get(key);\n if (bucket == null) {\n bucket = new Map();\n this.outstandingDispatches.set(key, bucket);\n }\n bucket.set(dispatchKey, { disturbed: false });\n }\n\n /**\n * Apply a remote frame. The frame is dropped if its seq does not exceed the\n * high-water mark previously applied for this key. If `dispatchKey` matches an entry\n * the originator registered as outstanding, these actions were already applied via\n * replay: if no foreign action interleaved during the outstanding window, skip the\n * reduce; otherwise re-run it to recover from the foreign overwrite. A foreign frame\n * (one whose dispatchKey is unknown) always reduces and marks every outstanding own\n * dispatch with a greater seq as needing recovery.\n */\n applyRemote(key: Key, seq: number, dispatchKey: string, actions: Action[]): void {\n if (seq !== 0) {\n const last = this.lastAppliedSeq.get(key) ?? 0;\n if (seq <= last) return;\n this.lastAppliedSeq.set(key, seq);\n }\n // Create frames carry no dispatch key, so the originator cannot recognize\n // its own echo; applying one to a cached doc would revert local edits to\n // the creation state. Drop the create and keep any trailing actions.\n if (\n actions.length > 0 &&\n this.params.createOf(actions[0]) != null &&\n this.docs.get(key) != null\n ) {\n actions = actions.slice(1);\n if (actions.length === 0) return;\n }\n const bucket = this.outstandingDispatches.get(key);\n const ownEntry = bucket?.get(dispatchKey);\n const isOwnEcho = ownEntry != null;\n if (ownEntry != null) {\n bucket?.delete(dispatchKey);\n // Local replay was authoritative; nothing interleaved.\n if (!ownEntry.disturbed) return;\n // Fall through to reduce: a foreign echo overwrote state during the\n // outstanding window, so we must re-apply to recover.\n } else if (bucket != null)\n // Foreign echo: any outstanding own dispatch represents a local replay that the\n // server has not yet broadcast back. We don't know each entry's server-stamped\n // seq yet (the echo carrying it hasn't arrived), so we can't tell whether the\n // foreign was applied before or after it on the server — mark every outstanding\n // entry as disturbed. Entries whose seq turns out to be greater than this\n // foreign's seq genuinely need recovery; entries whose seq was lower will re-run\n // idempotently and converge to the same value.\n for (const entry of bucket.values()) entry.disturbed = true;\n const current = this.docs.get(key);\n if (current == null) {\n // A create-headed frame seeds the document; anything else predates our\n // knowledge of the doc and is unreconstructable, so it drops.\n const created = actions.length > 0 ? this.params.createOf(actions[0]) : undefined;\n if (created == null) return;\n const { next } = this.params.reduce(created, actions.slice(1));\n this.docs.set(key, next);\n return;\n }\n const { next, targets } = this.params.reduce(current, actions);\n this.docs.set(key, next);\n if (!isOwnEcho) this.markRemoteTouched(key, targets);\n }\n\n hasUndo(key: Key): boolean {\n const s = this.undos.get(key);\n return (s?.undo.length ?? 0) > 0;\n }\n\n hasRedo(key: Key): boolean {\n const s = this.undos.get(key);\n return (s?.redo.length ?? 0) > 0;\n }\n\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.undos.subscribe(() => callback(), key);\n }\n\n /**\n * Builds a channel listener that applies broadcast action frames from the\n * given channel to this controller. Registered via {@link query.Cache.listen}.\n */\n listener(\n channel: string,\n schema: z.ZodType<Frame<Key, Action>>,\n ): query.Listener<z.ZodType<Frame<Key, Action>>> {\n return {\n channel,\n schema,\n onChange: (frames) => {\n frames.forEach(({ key, seq, dispatchKey, actions }) =>\n this.applyRemote(key, seq, dispatchKey, actions),\n );\n },\n };\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/actions/actions\";\nexport {\n Controller,\n type ControllerParams,\n type Domain,\n type Options,\n type Preprocess,\n type Reducer,\n type SendDispatch,\n type StackEntry,\n type Transaction,\n} from \"@/actions/controller\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nexport enum Kind {\n invalid = 0,\n u8 = 1,\n u16 = 2,\n u32 = 3,\n u64 = 4,\n i8 = 5,\n i16 = 6,\n i32 = 7,\n i64 = 8,\n f32 = 9,\n f64 = 10,\n string = 11,\n chan = 12,\n series = 13,\n variable = 14,\n numeric_constant = 15,\n integer_constant = 16,\n float_constant = 17,\n exact_integer_float_constant = 18,\n function = 19,\n sequence = 20,\n stage = 21,\n var_ref = 22,\n bool = 23,\n}\nexport const kindZ = z.enum(Kind);\n\nexport enum ChanDirection {\n none = 0,\n read = 1,\n write = 2,\n read_write = 3,\n}\nexport const chanDirectionZ = z.enum(ChanDirection);\n\n/**\n * Channels contains channel declarations for reading from and writing to Synnax\n * channels.\n */\nexport const channelsZ = z.object({\n /** read contains readable channel indices mapped to parameter names. */\n read: z.record(z.uint32(), z.string()).default(() => ({})),\n /** write contains writable channel indices mapped to parameter names. */\n write: z.record(z.uint32(), z.string()).default(() => ({})),\n});\nexport interface Channels extends z.infer<typeof channelsZ> {}\n\n/** Dimensions contains dimension exponents for dimensional analysis. */\nexport const dimensionsZ = z.object({\n /** length is the length dimension exponent (meters). */\n length: zod.int8,\n /** mass is the mass dimension exponent (kilograms). */\n mass: zod.int8,\n /** time is the time dimension exponent (seconds). */\n time: zod.int8,\n /** current is the electric current dimension exponent (Amperes). */\n current: zod.int8,\n /** temperature is the temperature dimension exponent (Kelvin). */\n temperature: zod.int8,\n /** angle is the angle dimension exponent (radians). */\n angle: zod.int8,\n /** count is the count dimension exponent. */\n count: zod.int8,\n /** data is the data size dimension exponent (bytes). */\n data: zod.int8,\n});\nexport interface Dimensions extends z.infer<typeof dimensionsZ> {}\n\n/**\n * Unit is a physical unit with dimensions and scale factor for unit-aware computation.\n */\nexport const unitZ = z.object({\n /** dimensions contains physical dimension exponents. */\n dimensions: dimensionsZ,\n /** scale is the scale factor relative to SI base units. */\n scale: z.number(),\n /** name is the unit name (e.g., 'psi', 'ns', 'm/s'). */\n name: z.string(),\n});\nexport interface Unit extends z.infer<typeof unitZ> {}\n\n/** FunctionProperties contains common parameter definitions for function-like types. */\nexport const functionPropertiesZ = z.object({\n /** inputs contains input parameter definitions. */\n get inputs(): z.ZodDefault<typeof paramsZ> {\n return paramsZ.default([]);\n },\n /** outputs contains output parameter definitions. */\n get outputs(): z.ZodDefault<typeof paramsZ> {\n return paramsZ.default([]);\n },\n});\nexport interface FunctionProperties extends z.infer<typeof functionPropertiesZ> {}\n\nexport const typeZ = functionPropertiesZ.extend({\n kind: kindZ,\n name: z.string(),\n get elem(): z.ZodOptional<typeof typeZ> {\n return typeZ.optional();\n },\n unit: unitZ.optional(),\n get constraint(): z.ZodOptional<typeof typeZ> {\n return typeZ.optional();\n },\n chanDirection: chanDirectionZ,\n});\nexport interface Type extends z.infer<typeof typeZ> {}\n\n/** Param is a named, typed parameter with optional default value. */\nexport interface Param {\n name: string;\n type: Type;\n value: unknown;\n}\nexport const paramZ: z.ZodType<Param> = z.object({\n /** name is the parameter name. */\n name: z.string(),\n /** type is the parameter type. */\n type: typeZ,\n /** value is an optional default value. */\n value: z.unknown(),\n});\n\nexport const paramsZ = paramZ.array().default(() => []);\nexport type Params = z.infer<typeof paramsZ>;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { types } from \"@/arc/types\";\n\nexport enum EdgeKind {\n unspecified = 0,\n continuous = 1,\n conditional = 2,\n}\nexport const edgeKindZ = z.enum(EdgeKind);\n\nexport enum ScopeMode {\n unspecified = 0,\n parallel = 1,\n sequential = 2,\n}\nexport const scopeModeZ = z.enum(ScopeMode);\n\nexport enum Liveness {\n unspecified = 0,\n always = 1,\n gated = 2,\n}\nexport const livenessZ = z.enum(Liveness);\n\n/**\n * Handle is a reference to a specific parameter on a specific node in the dataflow\n * graph.\n */\nexport const handleZ = z.object({\n /** node is the node identifier. */\n node: z.string(),\n /** param is the parameter name (input or output). */\n param: z.string(),\n});\nexport interface Handle extends z.infer<typeof handleZ> {}\n\n/** Body is raw function body source code with optional parsed AST. */\nexport const bodyZ = z.object({\n /** raw is the raw source code text. */\n raw: z.string(),\n});\nexport interface Body extends z.infer<typeof bodyZ> {}\n\n/** Node is a concrete instantiation of a function with typed parameters and values. */\nexport const nodeZ = z.object({\n /** key is the unique identifier for this node instance. */\n key: z.string(),\n /** type is the function type being instantiated. */\n type: z.string(),\n /** inputs contains input parameter type signatures. */\n inputs: types.paramsZ,\n /** outputs contains output parameter type signatures. */\n outputs: types.paramsZ,\n /** channels contains channel read/write mappings. */\n channels: types.channelsZ,\n});\nexport interface Node extends z.infer<typeof nodeZ> {}\n\n/** Authorities holds the static authority declarations from an Arc program. */\nexport const authoritiesZ = z.object({\n /** default is the default authority for all write channels not explicitly listed. */\n default: zod.uint8.optional(),\n /** channels maps channel keys to their specific authority values. */\n channels: z.record(z.uint32(), zod.uint8).default(() => ({})),\n});\nexport interface Authorities extends z.infer<typeof authoritiesZ> {}\n\n/** Edge is a dataflow connection between node parameters in the Arc graph. */\nexport const edgeZ = z.object({\n /** source is the source node parameter producing data. */\n source: handleZ,\n /** target is the target node parameter consuming data. */\n target: handleZ,\n /** kind defines execution semantics for this connection. */\n kind: edgeKindZ,\n});\nexport interface Edge extends z.infer<typeof edgeZ> {}\n\n/** Transition is a declarative state-transition rule on a sequential Scope. */\nexport const transitionZ = z.object({\n /** on is the dataflow handle whose truthy value fires this transition. */\n on: handleZ,\n /**\n * targetKey is the sibling step key to activate. Null when the transition exits the\n * scope, yielding to the parent.\n */\n targetKey: z.string().optional(),\n});\nexport interface Transition extends z.infer<typeof transitionZ> {}\n\n/**\n * Function is a function template definition with typed parameters, serving as a\n * blueprint for node instantiation.\n */\nexport const functionZ = z.object({\n /** key is the function identifier (template name). */\n key: z.string(),\n /** body is raw source code for user-defined functions. */\n body: bodyZ,\n /** inputs contains input parameter definitions. */\n inputs: types.paramsZ,\n /** outputs contains output parameter definitions. */\n outputs: types.paramsZ,\n /** channels contains channel read/write declarations. */\n channels: types.channelsZ,\n});\nexport interface Function extends z.infer<typeof functionZ> {}\n\nexport const nodesZ = nodeZ.array().default(() => []);\nexport type Nodes = z.infer<typeof nodesZ>;\n\nexport const edgesZ = edgeZ.array().default(() => []);\nexport type Edges = z.infer<typeof edgesZ>;\n\nexport const functionsZ = functionZ.array().default(() => []);\nexport type Functions = z.infer<typeof functionsZ>;\n\n/**\n * Member is a tagged union representing a single child of a Scope. Exactly one of\n * nodeKey or scope is set. The member's lookup key (used as the target of `=> name`\n * transitions) is derived from the set variant via Member.key().\n */\nexport interface Member {\n nodeKey?: string;\n scope?: Scope;\n}\nexport const memberZ: z.ZodType<Member> = z.object({\n /**\n * nodeKey is the key of the referenced node in IR.nodes. Null when this member is a\n * nested scope.\n */\n nodeKey: z.string().optional(),\n /** scope is set when this member is a nested scope. */\n get scope() {\n return scopeZ.optional();\n },\n});\n\n/**\n * Scope is the unified Layer 2 execution primitive. Parameterized by mode (parallel or\n * sequential) and liveness (always-live or gated). Parallel scopes organize members\n * into strata; sequential scopes run one step at a time and advance via transitions.\n */\nexport interface Scope {\n key: string;\n mode: ScopeMode;\n liveness: Liveness;\n activation?: Handle;\n strata: Members[];\n steps: Members;\n transitions: Transition[];\n}\nexport const scopeZ: z.ZodType<Scope> = z.object({\n /** key is the scope identifier. */\n key: z.string(),\n /** mode defines whether this scope runs steps in parallel or sequentially. */\n mode: scopeModeZ,\n /**\n * liveness defines whether this scope is continuously active or must be activated.\n */\n liveness: livenessZ,\n /**\n * activation is the handle whose truthy value activates a gated scope. Unset for\n * always-live scopes.\n */\n activation: handleZ.optional(),\n /**\n * strata contains stratified execution layers for parallel scopes. On sequential\n * scopes, strata hold variable nodes that run every pass alongside the active step.\n * Stratum N depends only on strata 0 to N-1.\n */\n get strata() {\n return membersZ.array().default(() => []);\n },\n /** steps contains ordered steps for sequential scopes. Empty for parallel scopes. */\n get steps() {\n return membersZ;\n },\n /**\n * transitions contains state-transition rules for sequential scopes. Empty for\n * parallel scopes.\n */\n transitions: transitionZ.array().default(() => []),\n});\n\n/**\n * IR is the intermediate representation of an Arc program as a dataflow graph with\n * stratified execution, bridging semantic analysis and WebAssembly compilation.\n */\nexport const irZ = z.object({\n /** functions contains function template definitions. */\n functions: functionsZ,\n /** nodes contains node instantiations. */\n nodes: nodesZ,\n /** edges contains dataflow connections. */\n edges: edgesZ,\n /** authorities contains the static authority declarations for this program. */\n authorities: authoritiesZ,\n /**\n * root is the top-level execution context. The root is always a parallel, always-live\n * Scope whose strata mix module-scope reactive flow with top-level gated scopes.\n */\n root: scopeZ,\n});\nexport interface IR extends z.infer<typeof irZ> {}\n\nexport const membersZ = memberZ.array().default(() => []);\nexport type Members = z.infer<typeof membersZ>;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/arc/ir/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, record, spatial } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ir } from \"@/arc/ir\";\n\n/**\n * Node is a visual node in the Arc graph editor representing a function instantiation\n * with position data. The function type and input parameter values are stored in the\n * graph's inputs map, keyed by the node key.\n */\nexport const nodeZ = z.object({\n /** key is the unique identifier for this node instance. */\n key: z.string(),\n /** position is the canvas position (x, y) for visual layout. */\n position: spatial.xyZ,\n});\nexport interface Node extends z.infer<typeof nodeZ> {}\n\nexport const edgeZ = ir.edgeZ.extend({\n key: z.string(),\n});\nexport interface Edge extends z.infer<typeof edgeZ> {}\n\nexport const nodesZ = nodeZ.array().default(() => []);\nexport type Nodes = z.infer<typeof nodesZ>;\n\nexport const edgesZ = edgeZ.array().default(() => []);\nexport type Edges = z.infer<typeof edgesZ>;\n\n/**\n * Graph is a visual dataflow graph representation combining IR elements with canvas\n * layout for the Arc graph editor.\n */\nexport const graphZ = z.object({\n /** functions contains function definitions available in this graph. */\n functions: ir.functionsZ.default([]),\n /** edges contains dataflow connections between node parameters. */\n edges: edgesZ.default([]),\n /** nodes contains visual nodes with canvas positions. */\n nodes: nodesZ.default([]),\n /**\n * inputs contains per-node inputs keyed by node key. Each value is a JSON object\n * holding the node's function type under \"type\" plus its input parameter values. The\n * wire format stores it as an opaque record; the client types it per function.\n */\n inputs: caseconv.preserveCase(\n z.record(z.string(), record.unknownZ()).default(() => ({})),\n ),\n});\nexport interface Graph extends z.infer<typeof graphZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\n/**\n * Output is compiled output from the Arc compiler including WebAssembly bytecode and\n * memory layout.\n */\nexport const outputZ = z.object({\n /** wasm is compiled WebAssembly bytecode for sandboxed execution. */\n wasm: z.instanceof(Uint8Array),\n /**\n * outputMemoryBases contains memory base addresses for multi-output functions,\n * mapping function keys to their base addresses.\n */\n outputMemoryBases: z.record(z.string(), z.uint32()).default(() => ({})),\n});\nexport interface Output extends z.infer<typeof outputZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { type z } from \"zod\";\n\nimport { compiler } from \"@/arc/compiler\";\nimport { ir } from \"@/arc/ir\";\n\nexport const programZ = ir.irZ.extend(compiler.outputZ.shape);\nexport interface Program extends z.infer<typeof programZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { crdt } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\n/**\n * Document is the conflict-free replicated representation of the text: the operations\n * that reconstruct it when applied to an empty replica. It is the durable source of\n * truth from which raw is materialized.\n */\nexport const documentZ = z.object({\n /** inserts are the operations that reconstruct the document's characters. */\n inserts: crdt.insertZ.array().default(() => []),\n /** deletes are the operations that tombstone deleted characters. */\n deletes: crdt.deleteZ.array().default(() => []),\n});\nexport interface Document extends z.infer<typeof documentZ> {}\n\n/** Text is text-based Arc source code with optional parsed AST for compilation. */\nexport const textZ = z.object({\n /**\n * doc is the replicated source of truth for the text. It defaults to empty on create,\n * in which case the server seeds it from raw.\n */\n doc: documentZ.prefault({}),\n /** raw is the materialized Arc source code, derived from doc and not persisted. */\n raw: z.string().default(\"\"),\n});\nexport interface Text extends z.infer<typeof textZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Key } from \"@/label/types.gen\";\n\n/** One or many labels, by key. */\nexport type Params = Key | Key[];\n\n/** Relationship type joining a resource to the labels on it. */\nexport const LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE = \"labeled_by\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE } from \"@/label/payload\";\nimport { type Key, type Label } from \"@/label/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { type query } from \"@/query\";\n\n/** Reports whether the relationship labels the given ontology ID. */\nexport const matchLabeledBy = (rel: ontology.Relationship, id: ontology.ID): boolean =>\n ontology.matchRelationship(rel, {\n from: id,\n type: LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n });\n\n/** Returns the cached labels attached to the given ontology ID. */\nexport const cachedLabelsOf = (\n relationships: query.Table<string, ontology.Relationship>,\n labels: query.Table<Key, Label>,\n id: ontology.ID,\n): Label[] =>\n labels.get(relationships.get((r) => matchLabeledBy(r, id)).map((r) => r.to.key));\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { color, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Label is a tagging and categorization entity with a name and associated color. Labels\n * can be attached to resources like ranges for organization and filtering.\n */\nexport const labelZ = z.object({\n /** key is the unique identifier for this label. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the label. */\n name: z.string().min(1),\n /** color is the display color for visual identification of the label. */\n color: color.colorZ,\n});\nexport interface Label extends z.infer<typeof labelZ> {}\nexport interface New extends z.input<typeof labelZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, primitive, zod } from \"@synnaxlabs/x\";\nimport z from \"zod\";\n\nimport { LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE } from \"@/label/payload\";\nimport { matchLabeledBy } from \"@/label/store\";\nimport { type Key, keyZ, type Label, labelZ, type New } from \"@/label/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_label_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_label_delete\";\n\nconst createReqZ = z.object({ labels: labelZ.array() });\nconst createResZ = z.object({ labels: labelZ.array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst setReqZ = z.object({\n id: ontology.idZ,\n labels: keyZ.array(),\n replace: z.boolean().optional(),\n});\n\ninterface SetReq extends z.infer<typeof setReqZ> {}\n/** Options for `Client.set`. Set `replace` to swap the whole label set at once. */\nexport interface SetOptions extends Pick<SetReq, \"replace\"> {}\n\nconst removeReqZ = setReqZ.omit({ replace: true });\nconst emptyResZ = z.object({});\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n for: ontology.idZ.optional(),\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\n/** Names one label. */\nexport type RetrieveSingleParams = { key: Key };\n/** Everything a multi-label retrieval can filter on, including the resource labeled. */\nexport type RetrieveMultipleParams = z.input<typeof retrieveRequestZ>;\n/** Params for a label retrieval, single or multiple. */\nexport type RetrieveParams = RetrieveSingleParams | RetrieveMultipleParams;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\n/** Config for {@link Client}. */\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\n/**\n * Creates, reads, deletes, and attaches labels on a Core. Reach it through\n * `client.labels`.\n */\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Label> {\n readonly type: string = \"label\";\n /** The label record table; injected into sibling clients at wiring. */\n readonly store: query.Table<Key, Label>;\n private readonly cfg: ClientConfig;\n\n constructor(cfg: ClientConfig) {\n const { cache, ontology: ontologyClient } = cfg;\n const { relationships } = ontologyClient.cache;\n const store = cache.createTable<Key, Label>({\n name: \"labels\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, labelZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"label\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (label, req) => this.requestFilter(req)(label),\n watch: [\n query.watch(relationships, (event, req: RetrieveRequest) => {\n if (req.for == null) return null;\n const rel =\n event.variant === \"set\"\n ? event.value\n : ontology.relationshipZ.parse(event.key);\n if (!matchLabeledBy(rel, req.for)) return null;\n return [rel.to.key];\n }),\n ],\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async label(\n id: ontology.ID,\n labels: Key[],\n opts: SetOptions & query.WriteOptions = {},\n ): Promise<void> {\n await query.optimistic({\n rollbacks: [\n ...(opts.replace === true\n ? [this.cfg.ontology.cache.relationships.delete((r) => matchLabeledBy(r, id))]\n : []),\n ...labels.map((key) => {\n const rel = labeledByRel(id, key);\n return this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n );\n }),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/label/set\",\n { id, labels, replace: opts.replace },\n setReqZ,\n emptyResZ,\n ),\n });\n }\n\n async remove(\n id: ontology.ID,\n labels: Key[],\n opts: query.WriteOptions = {},\n ): Promise<void> {\n await query.optimistic({\n rollbacks: [\n this.cfg.ontology.cache.relationships.delete(\n (r) => matchLabeledBy(r, id) && labels.includes(r.to.key),\n ),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/label/remove\",\n { id, labels },\n removeReqZ,\n emptyResZ,\n ),\n });\n }\n\n async create(label: New, opts?: query.WriteOptions<Label[]>): Promise<Label>;\n async create(labels: New[], opts?: query.WriteOptions<Label[]>): Promise<Label[]>;\n async create(\n labels: New | New[],\n opts: query.WriteOptions<Label[]> = {},\n ): Promise<Label | Label[]> {\n const isMany = Array.isArray(labels);\n const optimistic = array\n .toArray(labels)\n .map((l) => zod.parse(labelZ, l, { label: \"label\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/label/create\",\n { labels: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.labels);\n return isMany ? res.labels : res.labels[0];\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.store.delete(keysArr),\n this.cfg.ontology.cache.relationships.delete(\n (r) =>\n r.type === LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE &&\n r.to.type === \"label\" &&\n keysArr.includes(r.to.key),\n ),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/label/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<Label[]> {\n const res = await this.cfg.unary.send(\n \"/label/retrieve\",\n params,\n retrieveRequestZ,\n retrieveResponseZ,\n );\n return res.labels;\n }\n\n /**\n * Client-side matching for a request: key sets, names, and labeled-entity\n * membership via the relationship table. Server-computed shapes (search,\n * limit/offset) never reach this filter; they refetch instead.\n */\n private requestFilter(req: RetrieveRequest): (l: Label) => boolean {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameSet = primitive.isNonZero(req.names) ? new Set(req.names) : undefined;\n return (l) => {\n if (keySet != null && !keySet.has(l.key)) return false;\n if (nameSet != null && !nameSet.has(l.name)) return false;\n if (req.for != null && !this.isLabelOf(req.for, l.key)) return false;\n return true;\n };\n }\n\n private isLabelOf(id: ontology.ID, key: Key): boolean {\n return this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString(labeledByRel(id, key)),\n );\n }\n}\n\nconst retrieveResponseZ = z.object({ labels: labelZ.array().default(() => []) });\n\nconst labeledByRel = (id: ontology.ID, key: Key): ontology.Relationship => ({\n from: id,\n type: LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n to: ontologyID(key),\n});\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"label\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/label/client\";\nexport * from \"@/label/payload\";\nexport { cachedLabelsOf, matchLabeledBy } from \"@/label/store\";\nexport * from \"@/label/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { ontology } from \"@/ontology\";\nimport { type Key } from \"@/status/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_status_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_status_delete\";\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"status\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { id, type optional, telem, TimeStamp, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { label } from \"@/label\";\n\nexport const VARIANTS = [\n \"success\",\n \"info\",\n \"warning\",\n \"error\",\n \"loading\",\n \"disabled\",\n] as const;\nexport const variantZ = z.enum(VARIANTS);\nexport const successVariantZ = z.literal(\"success\");\nexport const infoVariantZ = z.literal(\"info\");\nexport const warningVariantZ = z.literal(\"warning\");\nexport const errorVariantZ = z.literal(\"error\");\nexport const loadingVariantZ = z.literal(\"loading\");\nexport const disabledVariantZ = z.literal(\"disabled\");\nexport type Variant = z.infer<typeof variantZ>;\n\nexport const keyZ = z.string();\nexport type Key = z.infer<typeof keyZ>;\n\nexport interface StatusSchemas<\n Details extends z.ZodType = z.ZodType,\n V extends z.ZodType<Variant> = z.ZodType<Variant>,\n> {\n details: Details;\n v: V;\n}\n\nexport type StatusZodObject<\n Details extends z.ZodType = z.ZodNever,\n V extends z.ZodType<Variant> = typeof variantZ,\n> = z.ZodObject<{\n key: z.ZodDefault<typeof keyZ>;\n name: z.ZodDefault<z.ZodString>;\n variant: V;\n message: z.ZodString;\n description: z.ZodDefault<z.ZodString>;\n time: z.ZodDefault<typeof telem.timeStampZ>;\n labels: ReturnType<typeof zod.nullToUndefined<z.ZodArray<typeof label.labelZ>>>;\n details: [Details] extends [z.ZodNever] ? z.ZodOptional<z.ZodUnknown> : Details;\n}>;\n\nexport interface StatusZFunction {\n <\n Details extends z.ZodType = z.ZodNever,\n V extends z.ZodType<Variant> = typeof variantZ,\n >(args: {\n details?: Details;\n v?: V;\n }): StatusZodObject<Details, V>;\n <\n Details extends z.ZodType = z.ZodNever,\n V extends z.ZodType<Variant> = typeof variantZ,\n >(\n args?: Partial<StatusSchemas<Details, V>>,\n ): StatusZodObject<Details, V>;\n}\n\nexport const statusZ: StatusZFunction = <\n Details extends z.ZodType,\n V extends z.ZodType<Variant>,\n>({ details, v }: Partial<StatusSchemas<Details, V>> = {}) =>\n z.object({\n key: keyZ.default(id.create),\n name: z.string().default(\"\"),\n variant: v ?? variantZ,\n message: z.string(),\n description: z.string().default(\"\"),\n time: telem.timeStampZ.default(() => TimeStamp.now()),\n details: details ?? z.unknown().optional(),\n labels: zod.nullToUndefined(label.labelZ.array()),\n });\nexport type Status<\n Details extends z.ZodType = z.ZodNever,\n V extends z.ZodType<Variant> = typeof variantZ,\n> = {\n key: Key;\n name: string;\n variant: z.infer<V>;\n message: string;\n description: string;\n time: telem.TimeStamp;\n labels?: label.Label[];\n} & ([Details] extends [z.ZodNever] ? {} : { details: z.infer<Details> });\nexport type New<\n Details extends z.ZodType = z.ZodNever,\n V extends z.ZodType<Variant> = typeof variantZ,\n> = Omit<\n optional.Optional<Status<Details, V>, \"key\" | \"name\" | \"description\" | \"time\">,\n \"details\"\n> &\n ([Details] extends [z.ZodNever] ? {} : { details: z.input<Details> });\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { array, type primitive } from \"@synnaxlabs/x\";\n\nimport { MultipleFoundError, NotFoundError } from \"@/errors\";\n\nexport type SingleParamAnalysisResult<\n T extends primitive.Value,\n K extends PartialTypeNameRecord<T>,\n> = T extends unknown\n ? { single: true; variant: K[TypeName<T>]; normalized: T[]; actual: T }\n : never;\n\nexport type MultiParamAnalysisResult<\n T extends primitive.Value,\n K extends PartialTypeNameRecord<T>,\n> = T extends unknown\n ? { single: false; variant: K[TypeName<T>]; normalized: T[]; actual: T[] }\n : never;\n\ntype TypeName<T> = T extends string\n ? \"string\"\n : T extends number\n ? \"number\"\n : T extends boolean\n ? \"boolean\"\n : T extends undefined\n ? \"undefined\"\n : T extends (...args: any[]) => any\n ? \"function\"\n : \"object\";\n\nexport type PartialTypeNameRecord<T extends primitive.Value> = Partial<\n Record<TypeName<T>, string>\n>;\n\nexport type ParamAnalysisResult<\n T extends primitive.Value,\n K extends PartialTypeNameRecord<T> = PartialTypeNameRecord<T>,\n> = SingleParamAnalysisResult<T, K> | MultiParamAnalysisResult<T, K>;\n\nexport interface AnalyzeParamsOptions {\n convertNumericStrings?: boolean;\n}\n\nexport const analyzeParams = <\n T extends primitive.Value = primitive.Value,\n K extends PartialTypeNameRecord<T> = PartialTypeNameRecord<T>,\n>(\n args: T extends unknown ? T | T[] : never,\n variantMap: K,\n { convertNumericStrings = true }: AnalyzeParamsOptions = {},\n): ParamAnalysisResult<T, K> => {\n const isSingle = !Array.isArray(args);\n let normal = array.toArray(args);\n const first = normal[0];\n const t = typeof first;\n let variant: K[TypeName<T>];\n if (t === \"string\" && convertNumericStrings)\n if (!isNaN(parseInt(first as string, 10)) && \"number\" in variantMap) {\n variant = variantMap.number as K[TypeName<T>];\n normal = normal.map((n) => parseInt(n as string, 10));\n } else variant = variantMap[t as TypeName<T>];\n else variant = variantMap[t as TypeName<T>];\n return {\n single: isSingle,\n variant,\n normalized: normal,\n actual: args,\n } as ParamAnalysisResult<T, K>;\n};\n\nexport const checkForMultipleOrNoResults = <T, R>(\n name: string,\n params: T | T[],\n results: R[],\n isSingle: boolean,\n): void => {\n if (!isSingle) return;\n if (results.length === 0)\n throw new NotFoundError(`${name} not found matching ${JSON.stringify(params)}`);\n if (results.length > 1)\n throw new MultipleFoundError(\n `Expected one ${name} matching ${JSON.stringify(params)}, but found ${results.length}`,\n );\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, primitive } from \"@synnaxlabs/x\";\nimport z from \"zod\";\n\nimport { label } from \"@/label\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { DELETE_CHANNEL_NAME, ontologyID, SET_CHANNEL_NAME } from \"@/status/payload\";\nimport { type Key, keyZ, type New, type Status, statusZ } from \"@/status/types.gen\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nconst setReqZ = <DetailsSchema extends z.ZodType = z.ZodNever>(\n detailsSchema?: DetailsSchema,\n) =>\n z.object({\n parent: ontology.idZ.optional(),\n statuses: statusZ({ details: detailsSchema }).array(),\n });\nconst setResZ = <DetailsSchema extends z.ZodType = z.ZodNever>(\n detailsSchema?: DetailsSchema,\n) => z.object({ statuses: statusZ({ details: detailsSchema }).array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst emptyResZ = z.object({});\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n includeLabels: z.boolean().optional(),\n hasLabels: label.keyZ.array().optional(),\n variants: z.string().array().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ, includeLabels: z.boolean().optional() })\n .transform(({ key, includeLabels }) => ({ keys: [key], includeLabels }));\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveRequestZ]);\n\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\nexport type SingleRetrieveParams = z.input<typeof singleRetrieveParamsZ>;\nexport type MultiRetrieveParams = z.input<typeof retrieveRequestZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst retrieveResponseZ = <DetailsSchema extends z.ZodType = z.ZodNever>(\n detailsSchema?: DetailsSchema,\n) =>\n z.object({\n statuses: statusZ({ details: detailsSchema })\n .array()\n .default(() => []),\n });\n\nexport interface SetOptions extends query.WriteOptions {\n parent?: ontology.ID;\n}\n\nconst BASE_REQUEST: Partial<RetrieveRequest> = { includeLabels: true };\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n labels: label.Client;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Status,\n Status,\n SingleRetrieveParams\n> {\n readonly type: string = \"status\";\n readonly store: query.Table<Key, Status>;\n private readonly cfg: ClientConfig;\n\n constructor(cfg: ClientConfig) {\n const { cache, ontology: ontologyClient, labels } = cfg;\n const { relationships } = ontologyClient.cache;\n const store = cache.createTable<Key, Status>({\n name: \"statuses\",\n fetch: async (keys) => await this.fetchThrough({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, statusZ(), {\n value: (changed, prev) => {\n const next = { ...prev, ...changed };\n const id = ontologyID(changed.key);\n next.labels = label.cachedLabelsOf(relationships, labels.store, id);\n return next;\n },\n }),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n const composed = cache.derive<Key, Status, Status>({\n name: \"status.composed\",\n source: store,\n compose: (record) => this.compose(record),\n watch: [\n query.deriveWatch(relationships, (event) => this.affectedKeys(event)),\n query.deriveWatch(labels.store, (event) => this.statusesLabeledBy(event.key)),\n ],\n });\n const single = cache.queries<Key, Status, Key, Status>({\n name: \"status\",\n table: composed,\n fetch: async (key) => [(await this.fetchSingle(key)).key],\n compose: (records) => records[0],\n keyOf: (key) => key,\n single: true,\n });\n super(cache, {\n name: \"status\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.fetchThrough(req),\n matches: (status, req) => this.requestFilter(req)(status),\n watch: [\n query.watch(relationships, (event, _: RetrieveRequest) =>\n this.affectedKeys(event),\n ),\n query.watch(labels.store, (event) => this.statusesLabeledBy(event.key)),\n ],\n },\n compose: (record) => this.compose(record),\n single: {\n schema: z\n .union([\n z.strictObject({ key: keyZ, includeLabels: z.boolean().optional() }),\n keyZ.transform((key) => ({ key })),\n ])\n .transform(({ key }) => key),\n space: single,\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async retrieve<DetailsSchema extends z.ZodType>(\n params: SingleRetrieveParams & { detailsSchema?: DetailsSchema },\n ): Promise<Status<DetailsSchema>>;\n async retrieve(params: Key | SingleRetrieveParams): Promise<Status>;\n async retrieve(params: MultiRetrieveParams): Promise<Status[]>;\n async retrieve<DetailsSchema extends z.ZodType = z.ZodNever>(\n rawParams: Key | (RetrieveParams & { detailsSchema?: DetailsSchema }),\n ): Promise<Status<DetailsSchema> | Status<DetailsSchema>[]> {\n const params = typeof rawParams === \"string\" ? { key: rawParams } : rawParams;\n const { detailsSchema, ...rest } = params;\n const isSingle = \"key\" in rest;\n // Schema-parametrized retrieves validate details for one caller; their\n // results are not shared through the cache.\n if (detailsSchema != null) {\n const statuses = await this.execRetrieve<DetailsSchema>(params);\n checkForMultipleOrNoResults(\"Status\", params, statuses, isSingle);\n return isSingle ? statuses[0] : statuses;\n }\n if (isSingle) return (await super.retrieve(rest)) as Status<DetailsSchema>;\n return (await super.retrieve(rest)) as Status<DetailsSchema>[];\n }\n\n async set<DetailsSchema extends z.ZodType>(\n status: New<DetailsSchema>,\n opts?: SetOptions & { detailsSchema?: DetailsSchema },\n ): Promise<Status<DetailsSchema>>;\n async set(status: New, opts?: SetOptions): Promise<Status>;\n async set(statuses: New[], opts?: SetOptions): Promise<Status[]>;\n async set(statuses: New | New[], opts?: SetOptions): Promise<Status | Status[]>;\n async set<DetailsSchema extends z.ZodType = z.ZodNever>(\n statuses: New<DetailsSchema> | New<DetailsSchema>[],\n opts: SetOptions & { detailsSchema?: DetailsSchema } = {},\n ): Promise<Status<DetailsSchema> | Status<DetailsSchema>[]> {\n const isMany = Array.isArray(statuses);\n // Filling the schema defaults up front gives every status a key, so the cache can\n // hold it before the Core answers.\n const schema = statusZ<DetailsSchema>({ details: opts.detailsSchema });\n const normalized = array\n .toArray(statuses)\n .map((status) => schema.parse(status)) as Status<DetailsSchema>[];\n const apply = () => [this.store.set(normalized)];\n const res = await query.optimistic({\n rollbacks: apply(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/status/set\",\n {\n statuses: normalized as z.input<\n ReturnType<typeof setReqZ<DetailsSchema>>\n >[\"statuses\"],\n parent: opts.parent,\n },\n setReqZ(opts.detailsSchema),\n setResZ(opts.detailsSchema),\n ),\n });\n const created = res.statuses as Status<DetailsSchema>[];\n this.store.set(created);\n return isMany ? created : created[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const stat = await this.retrieve(key);\n const renamed = { ...stat, name };\n await query.optimistic({\n rollbacks: [\n this.store.set(renamed),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ],\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.set(renamed),\n });\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.store.delete(keysArr),\n this.cfg.ontology.cache.relationships.delete((r) =>\n keysArr.some((key) => label.matchLabeledBy(r, ontologyID(key))),\n ),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/status/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every status set delivered to the cache. */\n onSet(handler: (status: Status) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every status delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private async execRetrieve<DetailsSchema extends z.ZodType = z.ZodNever>(\n params: RetrieveParams & { detailsSchema?: DetailsSchema },\n ): Promise<Status<DetailsSchema>[]> {\n const res = await this.cfg.unary.send(\n \"/status/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResponseZ<DetailsSchema>(params.detailsSchema),\n );\n return res.statuses as Status<DetailsSchema>[];\n }\n\n /** Rebuilds a cached status with its cached labels attached. */\n private compose(cached: Status): Status {\n const labels = label.cachedLabelsOf(\n this.cfg.ontology.cache.relationships,\n this.cfg.labels.store,\n ontologyID(cached.key),\n );\n return { ...cached, labels };\n }\n\n /** Writes a fetched status and its included label relationships. */\n private writeThrough(status: Status): void {\n this.store.set(status);\n if (status.labels == null) return;\n this.cfg.labels.store.set(status.labels);\n const id = ontologyID(status.key);\n status.labels.forEach((l) => {\n const rel: ontology.Relationship = {\n from: id,\n type: label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n to: label.ontologyID(l.key),\n };\n this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n );\n });\n }\n\n /** Fetches statuses and writes their included labels through the caches. */\n private async fetchThrough(req: RetrieveRequest): Promise<Status[]> {\n const statuses = await this.execRetrieve({ ...BASE_REQUEST, ...req });\n statuses.forEach((s) => this.writeThrough(s));\n return statuses;\n }\n\n private async fetchSingle(key: Key): Promise<Status> {\n const cached = this.store.get(key);\n if (cached != null) return cached;\n const statuses = await this.fetchThrough({ keys: [key] });\n checkForMultipleOrNoResults(\"Status\", key, statuses, true);\n return statuses[0];\n }\n\n /**\n * Fetches a labeled-by target the cache is missing so composition sees it.\n * The fetched label lands in the label table, which recomposes answers.\n */\n private ensureLabel(rel: ontology.Relationship): void {\n if (rel.to.type !== \"label\" || this.cfg.labels.store.has(rel.to.key)) return;\n this.cfg.labels\n .retrieve(rel.to.key)\n .catch((exc: unknown) =>\n this.cfg.cache.onError(\n new Error(\"failed to fetch status label\", { cause: exc }),\n ),\n );\n }\n\n /** Reports whether the status is labeled by the given label. */\n private isLabeledBy(status: Key, labelKey: label.Key): boolean {\n return this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString({\n from: ontologyID(status),\n type: label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n to: label.ontologyID(labelKey),\n }),\n );\n }\n\n /** Statuses whose labels the relationship event changes; backfills the label. */\n private affectedKeys(\n event: query.TableEvent<string, ontology.Relationship>,\n ): Key[] | null {\n const rel =\n event.variant === \"set\" ? event.value : ontology.relationshipZ.parse(event.key);\n if (\n rel.type !== label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE ||\n rel.from.type !== \"status\"\n )\n return null;\n if (event.variant === \"set\") this.ensureLabel(rel);\n return [rel.from.key];\n }\n\n /** Returns the keys of cached statuses labeled by the given label. */\n private statusesLabeledBy(labelKey: label.Key): Key[] {\n return this.cfg.ontology.cache.relationships\n .get(\n (r) =>\n r.type === label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE &&\n r.from.type === \"status\" &&\n r.to.type === \"label\" &&\n r.to.key === labelKey,\n )\n .map((r) => r.from.key);\n }\n\n /**\n * Client-side matching for a request: key sets, variants, and label\n * membership via the relationship table. Server-computed shapes (search,\n * limit/offset) never reach this filter; they refetch instead.\n */\n private requestFilter(req: RetrieveRequest): (s: Status) => boolean {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const variantSet = primitive.isNonZero(req.variants)\n ? new Set(req.variants)\n : undefined;\n return (s) => {\n if (keySet != null && !keySet.has(s.key)) return false;\n if (variantSet != null && !variantSet.has(s.variant)) return false;\n if (\n primitive.isNonZero(req.hasLabels) &&\n !req.hasLabels.some((key) => this.isLabeledBy(s.key, key))\n )\n return false;\n return true;\n };\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n errors,\n id,\n narrow,\n type optional,\n primitive,\n record,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type Status, type Variant } from \"@/status/types.gen\";\n\n// Input type for creating statuses - uses conditional typing for optional details\ntype Base<V extends Variant> = {\n key: string;\n name: string;\n variant: V;\n message: string;\n description?: string;\n time: TimeStamp;\n};\n\n/** A status before it is stamped with a key, a time, and a name. */\nexport type Crude<\n DetailsSchema extends z.ZodType = z.ZodNever,\n V extends Variant = Variant,\n> = optional.Optional<Base<V>, \"key\" | \"time\" | \"name\"> &\n ([DetailsSchema] extends [z.ZodNever] ? {} : { details: z.output<DetailsSchema> });\n\n/**\n * Interface that errors may optionally implement to provide richer rendering when\n * passed to {@link fromException}. Implementers return a partial {@link Crude} spec\n * whose fields override the defaults derived from the underlying `Error`. This is a\n * duck-typed contract: `fromException` checks for the presence of a `toStatus` method\n * via the `in` operator, so there is no need to import this interface to use it.\n */\nexport interface Custom {\n toStatus(): Partial<Crude<z.ZodRecord, \"error\">>;\n}\n\nconst customReturnZ = z.object({\n message: z.string().optional(),\n description: z.string().optional(),\n details: record.unknownZ().optional(),\n});\n\nconst safeToStatus = (exc: unknown): z.infer<typeof customReturnZ> | undefined => {\n if (\n exc == null ||\n typeof exc !== \"object\" ||\n !(\"toStatus\" in exc) ||\n typeof exc.toStatus !== \"function\"\n )\n return undefined;\n let raw: unknown;\n try {\n raw = exc.toStatus();\n } catch {\n return undefined;\n }\n const parsed = customReturnZ.safeParse(raw);\n return parsed.success ? parsed.data : undefined;\n};\n\n/** Details a status built by {@link fromException} carries. */\nexport const exceptionDetailsSchema = z\n .object({\n stack: z.string(),\n error: z.instanceof(Error),\n })\n .and(record.unknownZ());\n\n/** Flattens an error's cause chain into one readable line. */\nconst causeChain = (err: Error): string | undefined => {\n const parts: string[] = [];\n let cause: unknown = err.cause;\n for (let i = 0; i < 8 && cause instanceof Error; i++) {\n if (cause.message.length > 0) parts.push(cause.message);\n cause = cause.cause;\n }\n if (parts.length === 0) return undefined;\n return parts.join(\": \");\n};\n\n/**\n * Turns any thrown value into an error status, flattening its cause chain into the\n * description and keeping the error and its stack in the details.\n */\nexport const fromException = (\n exc: unknown,\n message?: string,\n): Status<typeof exceptionDetailsSchema, z.ZodLiteral<\"error\">> => {\n const err = errors.fromUnknown(exc);\n const detail = causeChain(err);\n const crude: Crude<typeof exceptionDetailsSchema, \"error\"> = {\n variant: \"error\",\n message: message ?? err.message,\n description:\n message != null\n ? [err.message, detail].filter((part) => part != null).join(\": \")\n : detail,\n details: { stack: err.stack ?? \"\", error: err },\n };\n // Probe the original (pre-coercion) value so a non-Error throwable with a custom\n // `toStatus()` method still contributes its status fields.\n const custom = safeToStatus(exc);\n if (custom != null) {\n if (message != null && custom.message != null)\n crude.message = `${message}: ${custom.message}`;\n else if (custom.message != null) crude.message = custom.message;\n if (custom.description != null) crude.description = custom.description;\n if (custom.details != null && crude.details != null)\n crude.details = { ...crude.details, ...custom.details };\n }\n return create<typeof exceptionDetailsSchema, \"error\">(crude);\n};\n\n/**\n * Converts an exception-shaped status (one built via {@link fromException}) back into a\n * thrown-shaped {@link Error}. The returned error carries the status's wrapped message,\n * copies `name` and `stack` from the inner error preserved on `details.error`, and\n * stashes the full status on `cause` for callers that need the rich shape. Use this\n * when bridging the status pipeline back into a context that expects a real Error —\n * typically before `throw`-ing across an error boundary.\n */\nexport const toError = (\n s: Status<typeof exceptionDetailsSchema, z.ZodLiteral<\"error\">>,\n): Error => {\n const inner = s.details.error;\n const err = new Error(s.message, { cause: s });\n err.name = inner.name;\n err.stack = inner.stack;\n return err;\n};\n\n/** Stamps a {@link Crude} status with a fresh key and the current time. */\nexport const create = <\n DetailsSchema extends z.ZodType = z.ZodNever,\n V extends Variant = Variant,\n>(\n spec: Crude<DetailsSchema, V>,\n): Status<DetailsSchema, z.ZodType<V>> =>\n ({\n key: id.create(),\n time: TimeStamp.now(),\n name: \"\",\n ...spec,\n description: spec.description ?? \"\",\n }) as Status<DetailsSchema, z.ZodType<V>>;\n\n/**\n * Reads the details of a status whose schema is not statically known, as when\n * scanning the generically-typed status table for rows belonging to a domain.\n * @returns The details, or undefined when the status carries none.\n */\nexport const detailsOf = (status: Status): record.Unknown | undefined =>\n (status as { details?: record.Unknown }).details;\n\n/** @returns the variant when it is one of the kept ones, else undefined. */\nexport const keepVariants = (\n variant?: Variant,\n keep: Variant | Variant[] = [],\n): Variant | undefined => {\n if (variant == null) return undefined;\n if (Array.isArray(keep)) {\n if (keep.includes(variant)) return variant;\n return undefined;\n }\n return keep === variant ? variant : undefined;\n};\n\n/** @returns the variant unless it is one of the removed ones. */\nexport const removeVariants = (\n variant?: Variant,\n remove: Variant | Variant[] = [],\n): Variant | undefined => {\n if (variant == null) return undefined;\n if (Array.isArray(remove)) {\n if (remove.includes(variant)) return undefined;\n return variant;\n }\n return remove === variant ? undefined : variant;\n};\n\n/** Options for {@link toString}. */\nexport interface ToStringOptions {\n includeTimestamp?: boolean;\n includeName?: boolean;\n}\n\nconst DEFAULT_TO_STRING_OPTIONS: ToStringOptions = {\n includeTimestamp: false,\n includeName: true,\n};\n\nconst renderDescription = (description: string): string => {\n if (description.includes(\"\\n\")) return `Description:\\n${description}`;\n try {\n const parsed = JSON.parse(description);\n return `Description:\\n${JSON.stringify(parsed, null, 2)}`;\n } catch {\n return `Description: ${description}`;\n }\n};\n\n/** Renders a status as readable text, pretty-printing a JSON description. */\nexport const toString = <Details extends z.ZodType = z.ZodNever>(\n stat: Status<Details>,\n options: ToStringOptions = {},\n): string => {\n const opts = { ...DEFAULT_TO_STRING_OPTIONS, ...options };\n const parts: string[] = [];\n let header = stat.variant.toUpperCase();\n if (opts.includeName && primitive.isNonZero(stat.name)) header += ` [${stat.name}]`;\n header += `: ${stat.message}`;\n if (opts.includeTimestamp) header += ` (${stat.time.toString(\"dateTime\", \"local\")})`;\n parts.push(header);\n if (primitive.isNonZero(stat.description))\n parts.push(renderDescription(stat.description));\n if (\"details\" in stat && narrow.isObject(stat.details)) {\n const details = stat.details as Record<string, unknown>;\n if (\"stack\" in details && typeof details.stack === \"string\" && details.stack !== \"\")\n parts.push(`Stack Trace:\\n${details.stack}`);\n const extraDetails = Object.fromEntries(\n Object.entries(details).filter(([k]) => k !== \"stack\" && k !== \"error\"),\n );\n if (Object.keys(extraDetails).length > 0)\n parts.push(`Details:\\n${JSON.stringify(extraDetails, null, 2)}`);\n }\n return parts.join(\"\\n\\n\");\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/status/client\";\nexport * from \"@/status/payload\";\nexport * from \"@/status/status\";\nexport * from \"@/status/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\nimport { status } from \"@/status\";\n\nexport const keyZ = z.uint32();\nexport type Key = z.infer<typeof keyZ>;\n\n/** StatusDetails contains rack-specific status details. */\nexport const statusDetailsZ = z.object({\n /** rack is the key of the rack this status pertains to. */\n rack: keyZ,\n});\nexport interface StatusDetails extends z.infer<typeof statusDetailsZ> {}\n\nexport const statusZ = status.statusZ({ details: statusDetailsZ });\nexport type Status = z.infer<typeof statusZ>;\n\n/**\n * Payload is a collection container for hardware devices and tasks running on a\n * specific Core. Racks are the integration point between the Core and physical hardware\n * through the Driver.\n */\nexport const payloadZ = z.object({\n /** key is the composite identifier for this rack. */\n key: keyZ.refine((v) => v !== 0, \"key is required\"),\n /** name is a human-readable name for the rack. */\n name: z.string().min(1, \"name is required\"),\n /** embedded is true if this rack is embedded within the Synnax server process. */\n embedded: z.boolean().default(false),\n /** status is the current operational status of the rack. */\n status: statusZ.optional(),\n /**\n * integrations is the list of hardware integrations this rack supports (e.g., \"ni\",\n * \"opc\", \"labjack\"). An empty or nil list means the rack supports no integrations.\n */\n integrations: z\n .string()\n .array()\n .default(() => []),\n});\nexport interface Payload extends z.infer<typeof payloadZ> {}\n\nexport const newZ = payloadZ.omit({ embedded: true, key: true }).extend({\n key: keyZ.refine((v) => v !== 0, \"key is required\").default(0),\n});\nexport interface New extends z.input<typeof newZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"rack\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(0);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, deep, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport {\n type Key,\n keyZ,\n type New,\n newZ,\n ontologyID,\n type Payload,\n payloadZ,\n type Status,\n statusZ,\n} from \"@/rack/types.gen\";\nimport { type status } from \"@/status\";\nimport { type task } from \"@/task\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport const SET_CHANNEL_NAME = \"sy_rack_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_rack_delete\";\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n integration: z.string().optional(),\n searchTerm: z.string().optional(),\n embedded: z.boolean().optional(),\n hostIsNode: z.boolean().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n includeStatus: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst retrieveResZ = z.object({ racks: payloadZ.array().default(() => []) });\nexport const rackZ = payloadZ;\n\nconst singleRetrieveParamsZ = z.union([\n z\n .object({\n key: keyZ,\n includeStatus: z.boolean().optional(),\n })\n .transform(({ key, includeStatus }) => ({ keys: [key], includeStatus })),\n z\n .object({\n name: z.string(),\n includeStatus: z.boolean().optional(),\n })\n .transform(({ name, includeStatus }) => ({ names: [name], includeStatus })),\n]);\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\n\nconst multiRetrieveParamsZ = retrieveReqZ;\n\nexport type RetrieveMultipleParams = z.input<typeof multiRetrieveParamsZ>;\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, multiRetrieveParamsZ]);\n\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\ntype SingleQuery =\n { key: Key; includeStatus?: boolean } | { name: string; includeStatus?: boolean };\n\nconst createReqZ = z.object({ racks: newZ.array() });\nconst createResZ = z.object({ racks: payloadZ.array() });\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\n\n/** Query fields only the server can evaluate. */\nconst SERVER_FIELDS = [\"searchTerm\", \"limit\", \"offset\", \"hostIsNode\"] as const;\n\n/** Drops includeStatus when unset so equivalent queries hash identically. */\nconst normalizeSingle = (params: RetrieveSingleParams): SingleQuery => {\n const base = \"key\" in params ? { key: params.key } : { name: params.name };\n return params.includeStatus === true ? { ...base, includeStatus: true } : base;\n};\n\nconst singleQueryZ = z\n .union([\n z.strictObject({ key: keyZ, includeStatus: z.boolean().optional() }),\n z.strictObject({ name: z.string(), includeStatus: z.boolean().optional() }),\n keyZ.transform((key) => ({ key })),\n ])\n .transform(normalizeSingle);\n\n/** The table never holds statuses; the status table is their single home. */\nconst stripStatus = ({ status: _, ...rack }: Payload): Omit<Payload, \"status\"> => rack;\n\n/**\n * Client-side matching for a request: key and name sets and payload-held\n * flags. Server-computed shapes (search, pagination, host resolution) never\n * reach this filter; they refetch instead.\n */\nconst requestFilter = (\n req: RetrieveRequest,\n): ((r: Omit<Payload, \"status\">) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameSet = primitive.isNonZero(req.names) ? new Set(req.names) : undefined;\n return (r) => {\n if (keySet != null && !keySet.has(r.key)) return false;\n if (nameSet != null && !nameSet.has(r.name)) return false;\n if (req.integration != null && !r.integrations.includes(req.integration))\n return false;\n if (req.embedded != null && r.embedded !== req.embedded) return false;\n return true;\n };\n};\n\n// Rack statuses live in the status table under the \"rack:<key>\" status key.\nconst affectedRackKeys = (\n event: query.TableEvent<status.Key, status.Status>,\n): Key[] | null => {\n const [type, key] = event.key.split(\":\");\n if (type !== \"rack\") return null;\n const parsed = keyZ.safeParse(Number(key));\n return parsed.success ? [parsed.data] : null;\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n tasks: task.Client;\n cache: query.Cache;\n statusStore: query.Table<status.Key, status.Status>;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Omit<Payload, \"status\">,\n Rack,\n RetrieveSingleParams,\n SingleQuery\n> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Omit<Payload, \"status\">>;\n\n constructor(cfg: ClientConfig) {\n const { cache, statusStore } = cfg;\n const store = cache.createTable<Key, Omit<Payload, \"status\">>({\n name: \"racks\",\n fetch: async (keys) => (await this.fetchThrough({ keys })).map(stripStatus),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, payloadZ, {\n value: ({ status: _, ...rack }) => rack,\n }),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n // Composed rows always carry status; includeStatus only gates fetch flags.\n const composed = cache.derive<Key, Omit<Payload, \"status\">, Rack>({\n name: \"rack.composed\",\n source: store,\n compose: (record) => this.compose(record, true),\n equal: (a, b) => deep.equal(a.payload, b.payload),\n watch: [query.deriveWatch(statusStore, (event) => affectedRackKeys(event))],\n });\n const single = cache.queries<SingleQuery, Rack, Key, Rack>({\n name: \"rack\",\n table: composed,\n fetch: async (q) => [(await this.fetchSingle(q)).key],\n compose: (records) => records[0],\n keyOf: (q) => (\"key\" in q ? q.key : null),\n matches: (r, q) => (\"key\" in q ? r.key === q.key : r.name === q.name),\n single: true,\n });\n super(cache, {\n name: \"rack\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => (await this.fetchThrough(req)).map(stripStatus),\n matches: (r, req) => requestFilter(req)(r),\n serverFields: SERVER_FIELDS,\n watch: [\n query.watch(statusStore, (event, q: RetrieveRequest) => {\n if (q.includeStatus !== true) return null;\n return affectedRackKeys(event);\n }),\n ],\n },\n compose: (record, q) =>\n this.compose(record, (q as { includeStatus?: boolean }).includeStatus === true),\n single: { schema: singleQueryZ, space: single },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/rack/delete\",\n { keys: keysArr },\n deleteReqZ,\n deleteResZ,\n ),\n });\n drop();\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n const r = await this.retrieve(key);\n await this.create({ ...r.payload, name });\n },\n });\n rename();\n }\n\n async create(rack: New): Promise<Rack>;\n async create(racks: New[]): Promise<Rack[]>;\n async create(rack: New | New[]): Promise<Rack | Rack[]> {\n const isSingle = !Array.isArray(rack);\n const res = await this.cfg.unary.send(\n \"/rack/create\",\n { racks: array.toArray(rack) },\n createReqZ,\n createResZ,\n );\n this.store.set(res.racks.map(stripStatus));\n const sugared = this.sugar(res.racks);\n return isSingle ? sugared[0] : sugared;\n }\n\n sugar(payload: Payload): Rack;\n sugar(payloads: Payload[]): Rack[];\n sugar(payloads: Payload | Payload[]): Rack | Rack[] {\n const isSingle = !Array.isArray(payloads);\n const sugared = array\n .toArray(payloads)\n .map(\n ({ key, name, status, integrations, embedded }) =>\n new Rack(key, name, this.cfg.tasks, status, integrations, embedded),\n );\n return isSingle ? sugared[0] : sugared;\n }\n\n /** Rebuilds a cached rack, attaching its cached status when requested. */\n private compose(cached: Omit<Payload, \"status\">, includeStatus: boolean): Rack {\n if (!includeStatus) return this.sugar(cached);\n const st = this.statusOf(cached.key);\n if (st == null) return this.sugar(cached);\n return this.sugar({ ...cached, status: st });\n }\n\n // Only the \"rack:<key>\" row is the rack's status. Task statuses name their rack in\n // their details, and matching on that would let them take the rack's status over.\n private statusOf(key: Key): Status | undefined {\n const parsed = statusZ.safeParse(this.cfg.statusStore.get(statusKey(key)));\n return parsed.success ? parsed.data : undefined;\n }\n\n /** Writes fetched racks and their included statuses. */\n private writeThrough(racks: Payload[]): void {\n this.store.set(racks.map(stripStatus));\n racks.forEach(({ status: st }) => {\n if (st != null) this.cfg.statusStore.set(st);\n });\n }\n\n private async execRetrieve(params: RetrieveParams): Promise<Payload[]> {\n const res = await this.cfg.unary.send(\n \"/rack/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ,\n );\n return res.racks;\n }\n\n /** Fetches racks and writes their included statuses through the caches. */\n private async fetchThrough(req: RetrieveRequest): Promise<Payload[]> {\n const racks = await this.execRetrieve(req);\n this.writeThrough(racks);\n return racks;\n }\n\n private async fetchSingle(q: SingleQuery): Promise<Rack> {\n // Names are not unique, so only key queries can be served from the table.\n // A status-bearing hit needs both the record and its status cached.\n if (\"key\" in q && q.includeStatus !== true) {\n const cached = this.store.get(q.key);\n if (cached != null) return this.sugar(cached);\n }\n const racks = await this.execRetrieve(q);\n checkForMultipleOrNoResults(\"Rack\", q, racks, true);\n this.writeThrough(racks);\n return this.sugar(racks[0]);\n }\n}\n\nexport class Rack {\n key: Key;\n name: string;\n status?: Status;\n integrations: string[];\n embedded: boolean;\n private readonly tasks: task.Client;\n\n constructor(\n key: Key,\n name: string,\n taskClient: task.Client,\n status?: Status,\n integrations: string[] = [],\n embedded: boolean = false,\n ) {\n this.key = key;\n this.name = name;\n this.tasks = taskClient;\n this.status = status;\n this.integrations = integrations;\n this.embedded = embedded;\n }\n\n async listTasks(): Promise<task.Task[]> {\n return await this.tasks.retrieve({ rack: this.key });\n }\n\n async createTask(task: task.New): Promise<task.Task>;\n async createTask<Schemas extends task.Schemas = task.Schemas>(\n task: task.New<Schemas>,\n schemas: Schemas,\n ): Promise<task.Task<Schemas>>;\n\n async createTask<Schemas extends task.Schemas = task.Schemas>(\n task: task.New<Schemas>,\n schemas?: Schemas,\n ): Promise<task.Task<Schemas>> {\n task.rack = this.key;\n return await this.tasks.create(task, schemas as Required<Schemas>);\n }\n\n async deleteTask(task: task.Key): Promise<void> {\n await this.tasks.delete([task]);\n }\n\n get payload(): Payload {\n return {\n key: this.key,\n name: this.name,\n status: this.status,\n integrations: this.integrations,\n embedded: this.embedded,\n };\n }\n}\n\nexport const statusKey = (key: Key): string => ontology.idToString(ontologyID(key));\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/rack/client\";\nexport * from \"@/rack/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { type optional, record } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\nimport { rack } from \"@/rack\";\nimport { status } from \"@/status\";\n\nexport const keyZ = z.string();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * StatusDetails contains device-specific status details identifying the device and its\n * associated rack.\n */\nexport const statusDetailsZ = z.object({\n /** rack is the key of the rack this device belongs to. */\n rack: rack.keyZ,\n /** device is the device identifier. */\n device: keyZ,\n});\nexport interface StatusDetails extends z.infer<typeof statusDetailsZ> {}\n\nexport const statusZ = status.statusZ({ details: statusDetailsZ });\nexport type Status = z.infer<typeof statusZ>;\n\nexport interface DeviceSchemas<\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodType<string>,\n Model extends z.ZodType<string> = z.ZodType<string>,\n> {\n properties: Properties;\n make: Make;\n model: Model;\n}\n\nexport const deviceZ = <\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n>({ properties, make, model }: Partial<DeviceSchemas<Properties, Make, Model>> = {}) =>\n z.object({\n key: keyZ,\n rack: rack.keyZ.refine((v) => v !== 0, \"rack is required\"),\n location: z.string().min(1, \"location is required\"),\n make: make ?? z.string().min(1, \"make is required\"),\n model: model ?? z.string().min(1, \"model is required\"),\n name: z.string().min(1, \"name is required\"),\n configured: z.boolean().default(false),\n properties: properties ?? record.unknownZ().default(() => ({})),\n status: statusZ.optional(),\n parent: ontology.idZ.optional(),\n });\nexport interface Device<\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n> {\n key: Key;\n rack: rack.Key;\n location: string;\n make: z.infer<Make>;\n model: z.infer<Model>;\n name: string;\n configured: boolean;\n properties: z.infer<Properties>;\n status?: Status;\n parent?: ontology.ID;\n}\nexport type New<\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n> = optional.Optional<Omit<Device<Properties, Make, Model>, \"status\">, \"configured\"> & {\n status?: status.New<typeof statusDetailsZ>;\n};\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"device\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, primitive, type record, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n type Device,\n type DeviceSchemas,\n deviceZ,\n type Key,\n keyZ,\n type New,\n ontologyID,\n statusZ,\n} from \"@/device/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { keyZ as rackKeyZ } from \"@/rack/types.gen\";\nimport { type status } from \"@/status\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport const SET_CHANNEL_NAME = \"sy_device_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_device_delete\";\n\nconst genericDeviceZ = deviceZ();\n\nconst createReqZ = <\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n>(\n schemas?: DeviceSchemas<Properties, Make, Model>,\n) => z.object({ devices: zod.toArray(deviceZ(schemas)) });\n\nconst createResZ = <\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n>(\n schemas?: DeviceSchemas<Properties, Make, Model>,\n) => z.object({ devices: deviceZ(schemas).array() });\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n makes: z.string().array().optional(),\n models: z.string().array().optional(),\n locations: z.string().array().optional(),\n racks: rackKeyZ.array().optional(),\n searchTerm: z.string().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n includeStatus: z.boolean().optional(),\n includeParent: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nconst retrieveResZ = <\n Properties extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n Make extends z.ZodType<string> = z.ZodString,\n Model extends z.ZodType<string> = z.ZodString,\n>(\n schemas?: DeviceSchemas<Properties, Make, Model>,\n) =>\n z.object({\n devices: deviceZ(schemas)\n .array()\n .default(() => []),\n });\n\nconst singleRetrieveParamsZ = z\n .object({\n key: keyZ,\n includeStatus: z.boolean().optional(),\n })\n .transform(({ key, includeStatus }) => ({\n keys: [key],\n includeStatus,\n }));\n\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveRequestZ>;\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveRequestZ]);\n\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\ntype SingleQuery = { key: Key; includeStatus?: boolean };\n\ntype RetrieveSchemas<\n Properties extends z.ZodType<record.Unknown>,\n Make extends z.ZodType<string>,\n Model extends z.ZodType<string>,\n> = { schemas: DeviceSchemas<Properties, Make, Model> };\n\n/** Query fields only the server can evaluate. */\nconst SERVER_FIELDS = [\"searchTerm\", \"limit\", \"offset\", \"includeParent\"] as const;\n\n/** Drops includeStatus when unset so equivalent queries hash identically. */\nconst normalizeSingle = ({ key, includeStatus }: RetrieveSingleParams): SingleQuery =>\n includeStatus === true ? { key, includeStatus: true } : { key };\n\nconst singleQueryZ = z\n .union([\n z.strictObject({ key: keyZ, includeStatus: z.boolean().optional() }),\n keyZ.transform((key) => ({ key })),\n ])\n .transform(normalizeSingle);\n\n/** The table never holds statuses; the status table is their single home. */\nconst stripStatus = ({ status: _, ...device }: Device): Omit<Device, \"status\"> =>\n device;\n\n/**\n * Client-side matching for a request: key, name, make, model, location, and\n * rack sets. Server-computed shapes (search, pagination, parent resolution)\n * never reach this filter; they refetch instead.\n */\nconst requestFilter = (\n req: RetrieveRequest,\n): ((d: Omit<Device, \"status\">) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameSet = primitive.isNonZero(req.names) ? new Set(req.names) : undefined;\n const makeSet = primitive.isNonZero(req.makes) ? new Set(req.makes) : undefined;\n const modelSet = primitive.isNonZero(req.models) ? new Set(req.models) : undefined;\n const locationSet = primitive.isNonZero(req.locations)\n ? new Set(req.locations)\n : undefined;\n const rackSet = primitive.isNonZero(req.racks) ? new Set(req.racks) : undefined;\n return (d) => {\n if (keySet != null && !keySet.has(d.key)) return false;\n if (nameSet != null && !nameSet.has(d.name)) return false;\n if (makeSet != null && !makeSet.has(d.make)) return false;\n if (modelSet != null && !modelSet.has(d.model)) return false;\n if (locationSet != null && !locationSet.has(d.location)) return false;\n if (rackSet != null && !rackSet.has(d.rack)) return false;\n return true;\n };\n};\n\n// Device statuses live in the status table under the \"device:<key>\" status\n// key, carrying the device key in their details.\nconst affectedDeviceKeys = (\n event: query.TableEvent<status.Key, status.Status>,\n): Key[] | null => {\n if (event.variant === \"set\") {\n const parsed = statusZ.safeParse(event.value);\n return parsed.success ? [parsed.data.details.device] : null;\n }\n const [type, key] = event.key.split(\":\");\n if (type !== \"device\" || !primitive.isNonZero(key)) return null;\n return [key];\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n statusStore: query.Table<status.Key, status.Status>;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Omit<Device, \"status\">,\n Device,\n RetrieveSingleParams,\n SingleQuery\n> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Omit<Device, \"status\">>;\n\n constructor(cfg: ClientConfig) {\n const { cache, statusStore } = cfg;\n // Explicitly omit 'status' from the device type to make sure we aren't\n // storing two copies of the statuses in the store.\n const store = cache.createTable<Key, Omit<Device, \"status\">>({\n name: \"devices\",\n fetch: async (keys) => await this.fetchThrough({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, genericDeviceZ, {\n value: ({ status: _, ...device }) => device,\n }),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n // Composed rows always carry status; includeStatus only gates fetch flags.\n const composed = cache.derive<Key, Omit<Device, \"status\">, Device>({\n name: \"device.composed\",\n source: store,\n compose: (record) => this.compose(record, true),\n watch: [query.deriveWatch(statusStore, (event) => affectedDeviceKeys(event))],\n });\n const single = cache.queries<SingleQuery, Device, Key, Device>({\n name: \"device\",\n table: composed,\n fetch: async (q) => [(await this.fetchSingle(q)).key],\n // The composed row always carries status; the query gates whether the\n // answer keeps it, mirroring the request space.\n compose: (records, q) =>\n q.includeStatus === true ? records[0] : stripStatus(records[0]),\n keyOf: (q) => q.key,\n single: true,\n });\n super(cache, {\n name: \"device\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => (await this.fetchThrough(req)).map(stripStatus),\n matches: (d, req) => requestFilter(req)(d),\n serverFields: SERVER_FIELDS,\n watch: [\n query.watch(statusStore, (event, q: RetrieveRequest) => {\n if (q.includeStatus !== true) return null;\n return affectedDeviceKeys(event);\n }),\n ],\n },\n compose: (record, q) =>\n this.compose(record, (q as { includeStatus?: boolean }).includeStatus === true),\n single: { schema: singleQueryZ, space: single },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async retrieve<\n Properties extends z.ZodType<record.Unknown>,\n Make extends z.ZodType<string>,\n Model extends z.ZodType<string>,\n >(\n params: RetrieveSingleParams & RetrieveSchemas<Properties, Make, Model>,\n ): Promise<Device<Properties, Make, Model>>;\n\n async retrieve(params: Key | RetrieveSingleParams): Promise<Device>;\n\n async retrieve<\n Properties extends z.ZodType<record.Unknown>,\n Make extends z.ZodType<string>,\n Model extends z.ZodType<string>,\n >(\n params: RetrieveMultipleParams & RetrieveSchemas<Properties, Make, Model>,\n ): Promise<Array<Device<Properties, Make, Model>>>;\n\n async retrieve(params: RetrieveMultipleParams): Promise<Array<Device>>;\n\n async retrieve(\n rawParams: Key | (RetrieveParams & { schemas?: DeviceSchemas }),\n ): Promise<Device | Array<Device>> {\n const params = typeof rawParams === \"string\" ? { key: rawParams } : rawParams;\n const { schemas, ...rest } = params;\n const isSingle = \"key\" in rest;\n // Schemas are not hashable, so schema-typed retrieves bypass the query\n // cache and hit the network, still writing records through.\n if (schemas != null) {\n const devices = await this.execRetrieve(rest, schemas);\n checkForMultipleOrNoResults(\"Device\", rest, devices, isSingle);\n this.writeThrough(devices);\n return isSingle ? devices[0] : devices;\n }\n if (isSingle) return await super.retrieve(rest);\n return await super.retrieve(rest);\n }\n\n async create(device: New): Promise<Device>;\n\n async create(devices: New[]): Promise<Device[]>;\n\n async create<\n Properties extends z.ZodType<record.Unknown>,\n Make extends z.ZodType<string>,\n Model extends z.ZodType<string>,\n >(\n device: New<Properties, Make, Model>,\n schemas: DeviceSchemas<Properties, Make, Model>,\n opts?: query.WriteOptions,\n ): Promise<Device<Properties, Make, Model>>;\n\n async create(\n device: New,\n schemas?: DeviceSchemas,\n opts?: query.WriteOptions,\n ): Promise<Device>;\n\n async create<\n Properties extends z.ZodType<record.Unknown>,\n Make extends z.ZodType<string>,\n Model extends z.ZodType<string>,\n >(\n devices: New<Properties, Make, Model>[],\n schemas: DeviceSchemas<Properties, Make, Model>,\n opts?: query.WriteOptions,\n ): Promise<Device<Properties, Make, Model>[]>;\n\n async create(\n devices: New[],\n schemas?: DeviceSchemas,\n opts?: query.WriteOptions,\n ): Promise<Device[]>;\n\n async create(\n devices: New | New[],\n schemas?: DeviceSchemas,\n opts: query.WriteOptions = {},\n ): Promise<Device | Device[]> {\n const isSingle = !Array.isArray(devices);\n // Filling the schema defaults up front hands the cache the same records the request\n // carries. It is the schema createReqZ already applies.\n const normalized = array\n .toArray(devices)\n .map((device) => deviceZ(schemas).parse(device) as Device);\n const apply = () => [this.store.set(normalized.map(stripStatus))];\n const res = await query.optimistic({\n rollbacks: apply(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/device/create\",\n { devices: normalized },\n createReqZ(schemas),\n createResZ(schemas),\n ),\n });\n this.store.set(res.devices.map(stripStatus));\n return isSingle ? res.devices[0] : res.devices;\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/device/delete\",\n { keys: keysArr },\n deleteReqZ,\n deleteResZ,\n ),\n });\n drop();\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const dev = await this.retrieve(key);\n const renamed = { ...dev, name };\n await query.optimistic({\n rollbacks: [this.store.set(renamed.key, stripStatus(renamed))],\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n await this.create(renamed);\n },\n });\n }\n\n /** Subscribes to every device set delivered to the cache. Statuses excluded. */\n onSet(handler: (device: Omit<Device, \"status\">) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every device delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n /** Rebuilds a cached device, attaching its cached status when requested. */\n private compose(cached: Omit<Device, \"status\">, includeStatus: boolean): Device {\n if (!includeStatus) return cached;\n const st = this.cfg.statusStore.get(statusKey(cached.key));\n if (st == null) return cached;\n const parsed = statusZ.safeParse(st);\n if (!parsed.success) return cached;\n return { ...cached, status: parsed.data };\n }\n\n /** Writes fetched devices and their included statuses. */\n private writeThrough(devices: Device[]): void {\n this.store.set(devices.map(stripStatus));\n devices.forEach(({ status: st }) => {\n if (st != null) this.cfg.statusStore.set(st);\n });\n }\n\n private async execRetrieve(\n params: RetrieveParams,\n schemas?: DeviceSchemas,\n ): Promise<Device[]> {\n const res = await this.cfg.unary.send(\n \"/device/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ(schemas),\n );\n return res.devices;\n }\n\n /** Fetches devices and writes their included statuses through the caches. */\n private async fetchThrough(req: RetrieveRequest): Promise<Device[]> {\n const devices = await this.execRetrieve(req);\n this.writeThrough(devices);\n return devices;\n }\n\n private async fetchSingle(q: SingleQuery): Promise<Device> {\n // A status-bearing hit needs both the record and its status cached.\n if (q.includeStatus !== true) {\n const cached = this.store.get(q.key);\n if (cached != null) return cached;\n }\n const devices = await this.execRetrieve(q);\n checkForMultipleOrNoResults(\"Device\", q, devices, true);\n this.writeThrough(devices);\n return devices[0];\n }\n}\n\nexport const statusKey = (key: Key): string => ontology.idToString(ontologyID(key));\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/device/client\";\nexport * from \"@/device/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, type optional, record, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { device } from \"@/device\";\nimport { ontology } from \"@/ontology\";\nimport { rack } from \"@/rack\";\nimport { status } from \"@/status\";\n\n/** KeyedConfig is the base for every stored task configuration record. */\nexport const keyedConfigZ = z.object({\n /** key is the unique identifier for the stored configuration record. */\n key: z.uuid().default(uuid.create),\n});\nexport interface KeyedConfig extends z.infer<typeof keyedConfigZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\nexport const startConfigZ = keyedConfigZ.extend({\n autoStart: z.boolean().default(false),\n});\nexport interface StartConfig extends z.infer<typeof startConfigZ> {}\n\nexport const scanConfigZ = keyedConfigZ.extend({\n rate: z.number().default(0.2),\n disabled: z.boolean().default(false),\n});\nexport interface ScanConfig extends z.infer<typeof scanConfigZ> {}\n\nexport type StatusDetailsZodObject<Data extends z.ZodType = z.ZodNever> = z.ZodObject<{\n task: typeof keyZ;\n running: z.ZodBoolean;\n cmd: z.ZodDefault<z.ZodString>;\n configHash: z.ZodDefault<z.ZodString>;\n rack: z.ZodDefault<typeof rack.keyZ>;\n data: [Data] extends [z.ZodNever] ? z.ZodOptional<z.ZodUnknown> : z.ZodOptional<Data>;\n}>;\n\nexport interface StatusDetailsZFunction {\n <Data extends z.ZodType>(data: Data): StatusDetailsZodObject<Data>;\n <Data extends z.ZodType = z.ZodNever>(data?: Data): StatusDetailsZodObject<Data>;\n}\n\nexport const statusDetailsZ: StatusDetailsZFunction = <Data extends z.ZodType>(\n data?: Data,\n) =>\n z.object({\n task: keyZ,\n running: z.boolean(),\n cmd: z.string().default(\"\"),\n configHash: z.string().default(\"\"),\n rack: rack.keyZ.default(0),\n data: (data ?? z.unknown()).optional(),\n });\nexport type StatusDetails<Data extends z.ZodType = z.ZodNever> = {\n task: Key;\n running: boolean;\n cmd: string;\n configHash: string;\n rack: rack.Key;\n} & ([Data] extends [z.ZodNever] ? {} : { data?: z.infer<Data> });\n\n/** Command is a command to execute on a task in the Driver system. */\nexport const commandZ = z.object({\n /** task is the key of the target task. */\n task: keyZ,\n /** type is the command type (e.g., 'start', 'stop', 'configure'). */\n type: z.string(),\n /** key is a unique identifier for this command instance. */\n key: z.string(),\n /**\n * configHash is the config hash the sender wants running. Empty when the sender does\n * not know it. The Driver reuses its live instance when the hash matches and\n * redeploys when it differs.\n */\n configHash: z.string().default(\"\"),\n /** args contains optional arguments for the command. */\n args: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\nexport interface Command extends z.infer<typeof commandZ> {}\n\nexport const persistConfigZ = startConfigZ.extend({\n dataSavingDisabled: z.boolean().default(false),\n});\nexport interface PersistConfig extends z.infer<typeof persistConfigZ> {}\n\nexport const statusZ = <Data extends z.ZodType = z.ZodNever>(data?: Data) =>\n status.statusZ({ details: statusDetailsZ(data) });\nexport type Status<Data extends z.ZodType = z.ZodNever> = z.infer<\n ReturnType<typeof statusZ<Data>>\n>;\n\nexport const readConfigZ = persistConfigZ.extend({\n sampleRate: z.number().default(10),\n streamRate: z.number().default(5),\n});\nexport interface ReadConfig extends z.infer<typeof readConfigZ> {}\n\nexport const writeConfigZ = persistConfigZ.extend({\n device: device.keyZ.default(\"\"),\n});\nexport interface WriteConfig extends z.infer<typeof writeConfigZ> {}\n\nexport interface PayloadSchemas<\n Type extends z.ZodType<string> = z.ZodType<string>,\n Config extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n StatusData extends z.ZodType = z.ZodType,\n> {\n type: Type;\n config: Config;\n statusData: StatusData;\n}\n\nexport const payloadZ = <\n Type extends z.ZodType<string> = z.ZodString,\n Config extends z.ZodType<record.Unknown> = z.ZodType<record.Unknown>,\n StatusData extends z.ZodType = z.ZodNever,\n>({\n type,\n config,\n statusData,\n}: Partial<PayloadSchemas<Type, Config, StatusData>> = {}) =>\n z.object({\n key: keyZ.default(uuid.create),\n rack: rack.keyZ.default(0),\n name: z.string(),\n type: type ?? z.string(),\n config: config ?? record.unknownZ().default(() => ({})),\n configHash: z.string().default(\"\"),\n internal: z.boolean().default(false),\n snapshot: z.boolean().default(false),\n status: status.statusZ({ details: statusDetailsZ(statusData) }).optional(),\n });\nexport interface Payload<S extends PayloadSchemas = PayloadSchemas> {\n key: Key;\n rack: rack.Key;\n name: string;\n type: z.infer<S[\"type\"]>;\n config: z.infer<S[\"config\"]>;\n configHash: string;\n internal: boolean;\n snapshot: boolean;\n status?: Status<S[\"statusData\"]>;\n}\nexport type New<S extends PayloadSchemas = PayloadSchemas> = optional.Optional<\n Omit<Payload<S>, \"status\">,\n \"key\" | \"rack\" | \"configHash\" | \"internal\" | \"snapshot\"\n> & {\n status?: status.New<ReturnType<typeof statusDetailsZ>>;\n};\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"task\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport {\n array,\n binary,\n caseconv,\n type CrudeTimeSpan,\n deep,\n type destructor,\n id,\n primitive,\n type record,\n strings,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type framer } from \"@/framer\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport {\n type Key as RackKey,\n keyZ as rackKeyZ,\n ontologyID as rackOntologyID,\n} from \"@/rack/types.gen\";\nimport { type ranger } from \"@/ranger\";\nimport { status } from \"@/status\";\nimport {\n type Command,\n commandZ,\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Payload,\n type PayloadSchemas as Schemas,\n payloadZ,\n type Status,\n type StatusDetailsZodObject,\n statusZ,\n} from \"@/task/types.gen\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport type { PayloadSchemas as Schemas } from \"@/task/types.gen\";\n\nexport const COMMAND_CHANNEL_NAME = \"sy_task_cmd\";\nexport const SET_CHANNEL_NAME = \"sy_task_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_task_delete\";\n\nexport const setSignalZ = payloadZ().omit({ config: true, status: true });\nexport interface SetSignal extends z.infer<typeof setSignalZ> {}\n\nexport interface DriftedParams extends Pick<\n Payload,\n \"configHash\" | \"rack\" | \"status\"\n> {}\n\n/**\n * Reports whether a task's live instance has drifted from its stored task: the task is\n * running and the stored config or rack differs from what the instance was deployed\n * with. Tasks that are not running never drift. Both hashes are server-assigned, so\n * this compares two given values and never hashes a config. A status with an empty\n * deployed hash never drifts: the deployed config is unknown, not different.\n * @returns True when a redeploy (start) would change the running instance.\n */\nexport const drifted = (task: DriftedParams): boolean => {\n const details = task.status?.details;\n if (details == null || !details.running || details.configHash === \"\") return false;\n return details.configHash !== task.configHash || details.rack !== task.rack;\n};\n\n// Temporary hack that filters the set of commands that should change the\n// status of a task to loading.\n// Issue: https://linear.app/synnax/issue/SY-2723/fix-handling-of-non-startstop-commands-loading-indicators-in-tasks\nconst LOADING_COMMANDS = [\"start\", \"stop\"];\n\n// The rack monitor marks a rack whose Driver is alive with one of these.\nconst HEALTHY_RACK_VARIANTS: status.Variant[] = [\"success\", \"info\"];\n\n/** How long a command waits for the Driver before the wait is called off. */\nconst COMMAND_DEADLINE = TimeSpan.seconds(10);\n\nconst STATUS_NAME = \"Task Status\";\n\nconst retrieveSnapshottedTo = async (taskKey: Key, ontologyClient: ontology.Client) => {\n const parents = await ontologyClient.parents.retrieve({ ids: ontologyID(taskKey) });\n if (parents.length === 0) return null;\n return parents[0];\n};\n\n/** One command sent to a task, as issued from the task itself. */\nexport interface TaskExecuteCommandParams {\n type: string;\n args?: record.Unknown;\n}\n\n/** One command sent to a task, as issued from the client. */\nexport interface ExecuteCommandParams extends TaskExecuteCommandParams {\n task: Key;\n}\n\n/** Several commands sent in one round trip. */\nexport interface ExecuteCommandsParams {\n commands: NewCommand[];\n}\n\n/** A command awaited to completion, as issued from the task itself. */\nexport interface TaskExecuteCommandSyncParams extends TaskExecuteCommandParams {\n /** How long to wait for the status before giving up. */\n timeout?: CrudeTimeSpan;\n}\n\nexport interface ExecuteCommandsSyncParams<StatusData extends z.ZodType> extends Omit<\n ExecuteCommandsSyncInternalParams<StatusData>,\n \"frameClient\" | \"name\"\n> {}\n\nexport interface ExecuteCommandSyncParams<StatusData extends z.ZodType> extends Omit<\n ExecuteCommandSyncInternalParams<StatusData>,\n \"frameClient\" | \"name\"\n> {}\n\n/**\n * A unit of work a rack runs against hardware: its config, its running status, and the\n * commands it accepts. Get one from `client.hardware.tasks` rather than building it.\n */\nexport class Task<S extends Schemas = Schemas> {\n readonly key: Key;\n readonly rack: RackKey;\n name: string;\n internal: boolean;\n type: z.infer<S[\"type\"]>;\n snapshot: boolean;\n config: z.infer<S[\"config\"]>;\n readonly configHash: string;\n status?: Status<S[\"statusData\"]>;\n\n readonly schemas: S;\n private readonly clients?: {\n frame: framer.Client;\n ontology: ontology.Client;\n range: ranger.Client;\n };\n\n get frameClient(): framer.Client {\n if (this.clients == null) throw new Error(\"Task not created\");\n return this.clients.frame;\n }\n\n get ontologyClient(): ontology.Client {\n if (this.clients == null) throw new Error(\"Task not created\");\n return this.clients.ontology;\n }\n\n get rangeClient(): ranger.Client {\n if (this.clients == null) throw new Error(\"Task not created\");\n return this.clients.range;\n }\n\n constructor(\n {\n key,\n rack,\n type,\n name,\n config,\n configHash = \"\",\n internal = false,\n snapshot = false,\n status,\n }: Payload<S>,\n schemas?: S,\n frameClient?: framer.Client,\n ontologyClient?: ontology.Client,\n rangeClient?: ranger.Client,\n ) {\n this.key = key;\n this.rack = rack;\n this.name = name;\n this.type = type;\n this.config = config;\n this.configHash = configHash;\n this.schemas =\n schemas ??\n ({\n type: z.string(),\n config: z.unknown(),\n statusData: z.unknown().optional(),\n } as unknown as S);\n this.internal = internal;\n this.snapshot = snapshot;\n this.status = status;\n if (frameClient != null && ontologyClient != null && rangeClient != null)\n this.clients = {\n frame: frameClient,\n ontology: ontologyClient,\n range: rangeClient,\n };\n }\n\n get payload(): Payload<S> {\n return {\n key: this.key,\n rack: this.rack,\n name: this.name,\n type: this.type,\n config: this.config,\n configHash: this.configHash,\n status: this.status,\n internal: this.internal,\n snapshot: this.snapshot,\n };\n }\n\n get ontologyID(): ontology.ID {\n return ontologyID(this.key);\n }\n\n async executeCommand(params: TaskExecuteCommandParams): Promise<string> {\n return await executeCommand({\n ...params,\n frameClient: this.frameClient,\n task: this.key,\n configHash: this.configHash,\n });\n }\n\n async executeCommandSync(\n params: TaskExecuteCommandSyncParams,\n ): Promise<Status<S[\"statusData\"]>> {\n return await executeCommandSync<S[\"statusData\"]>({\n ...params,\n frameClient: this.frameClient,\n task: this.key,\n configHash: this.configHash,\n name: this.name,\n statusDataZ: this.schemas.statusData,\n });\n }\n\n async start(): Promise<void> {\n await this.executeCommand({ type: \"start\" });\n }\n\n async stop(): Promise<void> {\n await this.executeCommand({ type: \"stop\" });\n }\n\n async run<T>(fn: () => Promise<T>): Promise<T> {\n await this.start();\n try {\n return await fn();\n } finally {\n await this.stop();\n }\n }\n\n async snapshottedTo(): Promise<ontology.Resource | null> {\n if (this.ontologyClient == null || this.rangeClient == null)\n throw new Error(\"Task not created\");\n if (!this.snapshot) return null;\n return await retrieveSnapshottedTo(this.key, this.ontologyClient);\n }\n}\n\nconst retrieveReqZ = z.object({\n rack: rackKeyZ.optional(),\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n types: z.string().array().optional(),\n includeStatus: z.boolean().optional(),\n internal: z.boolean().optional(),\n snapshot: z.boolean().optional(),\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n});\n\nconst singleRetrieveParamsZ = z.union([\n z\n .object({ key: keyZ, includeStatus: z.boolean().optional() })\n .transform(({ key, includeStatus }) => ({ keys: [key], includeStatus })),\n z\n .object({ name: z.string(), includeStatus: z.boolean().optional() })\n .transform(({ name, includeStatus }) => ({ names: [name], includeStatus })),\n z\n .object({ type: z.string(), rack: rackKeyZ.optional() })\n .transform(({ type, rack }) => ({ types: [type], rack })),\n]);\n/** Names one task: by key, by name, or by type and rack. */\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\n\nconst multiRetrieveParamsZ = retrieveReqZ;\n/** Everything a multi-task retrieval can filter on. */\nexport type RetrieveMultipleParams = z.input<typeof multiRetrieveParamsZ>;\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, multiRetrieveParamsZ]);\n/** Params for a task retrieval, single or multiple. */\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\ntype SingleRequest = Partial<\n Pick<z.infer<typeof retrieveReqZ>, \"keys\" | \"names\" | \"types\" | \"rack\">\n>;\n\n// includeStatus does not change a query's identity: cached fetches always\n// request it, so it is stripped before hashing.\nconst normalizeSingle = (params: RetrieveSingleParams): SingleRequest => {\n const parsed = singleRetrieveParamsZ.parse(params);\n if (!(\"includeStatus\" in parsed)) return parsed;\n const { includeStatus: _, ...rest } = parsed;\n return rest;\n};\n\nconst singleQueryZ = z\n .union([\n z.strictObject({ key: keyZ, includeStatus: z.boolean().optional() }),\n z.strictObject({ name: z.string(), includeStatus: z.boolean().optional() }),\n z.strictObject({ type: z.string(), rack: rackKeyZ.optional() }),\n keyZ.transform((key) => ({ key })),\n ])\n .transform(normalizeSingle);\n\n// includeStatus does not change a request's identity either: cached fetches\n// always request it, so the schema strips it before hashing.\nconst cacheRetrieveReqZ = retrieveReqZ.transform(\n ({ includeStatus: _, ...rest }) => rest,\n);\nconst retrieveMultiParamsZ = cacheRetrieveReqZ.or(query.keyListZ(keyZ));\n\n/**\n * Client-side matching for a request: key, name, type, rack, and flag\n * filters. Server-computed shapes (search, pagination) never reach this\n * filter; they refetch instead.\n */\nconst requestFilter = (\n req: RetrieveRequest,\n): ((t: Omit<Task, \"status\">) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameSet = primitive.isNonZero(req.names) ? new Set(req.names) : undefined;\n const typeSet = primitive.isNonZero(req.types) ? new Set(req.types) : undefined;\n return (t) => {\n if (keySet != null && !keySet.has(t.key)) return false;\n if (nameSet != null && !nameSet.has(t.name)) return false;\n if (typeSet != null && !typeSet.has(t.type)) return false;\n if (req.rack != null && t.rack !== req.rack) return false;\n if (req.internal != null && t.internal !== req.internal) return false;\n if (req.snapshot != null && t.snapshot !== req.snapshot) return false;\n return true;\n };\n};\n\ninterface RetrieveSchemas<S extends Schemas = Schemas> {\n schemas?: S;\n}\n\nconst retrieveResZ = <S extends Schemas = Schemas>(schemas?: S) =>\n z.object({\n tasks: payloadZ(schemas)\n .array()\n .default(() => []),\n });\n\n/** A task retrieval on the wire. */\nexport interface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\nconst createReqZ = <S extends Schemas = Schemas>(schemas?: S) =>\n z.object({ tasks: payloadZ(schemas).array() });\nconst createResZ = <S extends Schemas = Schemas>(schemas?: S) =>\n z.object({ tasks: payloadZ(schemas).array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\nconst copyReqZ = z.object({ key: keyZ, name: z.string(), snapshot: z.boolean() });\nconst copyResZ = <S extends Schemas = Schemas>(schemas?: S) =>\n z.object({ task: payloadZ(schemas) });\n\nconst matchesSingle = (t: Omit<Task, \"status\">, query: SingleRequest): boolean => {\n if (primitive.isNonZero(query.keys)) return t.key === query.keys[0];\n if (primitive.isNonZero(query.names)) return t.name === query.names[0];\n if (primitive.isNonZero(query.types))\n return t.type === query.types[0] && (query.rack == null || t.rack === query.rack);\n return false;\n};\n\n/** Config for {@link Client}. */\nexport interface ClientConfig {\n unary: UnaryClient;\n framer: framer.Client;\n ontology: ontology.Client;\n ranges: ranger.Client;\n cache: query.Cache;\n statusStore: query.Table<status.Key, status.Status>;\n}\n\n/**\n * Creates, reads, deletes, and commands tasks on a Core. Reach it through\n * `client.hardware.tasks`. Reads are served from a cache a change stream keeps current.\n */\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Omit<Task, \"status\">,\n Task,\n RetrieveSingleParams,\n SingleRequest\n> {\n /** The task record table; injected into sibling clients at wiring. */\n readonly store: query.Table<Key, Omit<Task, \"status\">>;\n private readonly cfg: ClientConfig;\n private readonly commandDeadlines = new Map<Key, ReturnType<typeof setTimeout>>();\n\n constructor(cfg: ClientConfig) {\n const { cache, statusStore } = cfg;\n const store = cache.createTable<Key, Omit<Task, \"status\">>({\n name: \"tasks\",\n equal: (a, b) => deep.equal(a.payload, b.payload),\n fetch: async (keys) => await this.fetchThrough({ keys }),\n listen: [\n {\n bind: (table) => ({\n channel: SET_CHANNEL_NAME,\n schema: setSignalZ,\n // The set signal omits config: a changed hash makes the cached one stale.\n onChange: async (changed: SetSignal[]) => {\n const stale: Key[] = [];\n table.batch(() =>\n changed.forEach((sig) => {\n const cached = table.get(sig.key);\n if (cached == null || cached.configHash !== sig.configHash) {\n stale.push(sig.key);\n return;\n }\n table.set(sig.key, (prev) =>\n prev == null ? undefined : this.sugar({ ...prev.payload, ...sig }),\n );\n }),\n );\n if (stale.length > 0) await table.retrieve(stale, { refresh: true });\n },\n }),\n },\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n cache.listen({\n channel: COMMAND_CHANNEL_NAME,\n schema: commandZ,\n onChange: (commands) =>\n statusStore.batch(() =>\n commands.forEach((changed) => {\n if (!LOADING_COMMANDS.includes(changed.type)) return;\n const key = statusKey(changed.task);\n if (statusStore.get(key) == null) return;\n const optimistic = this.optimisticStatus(changed);\n statusStore.set(key, optimistic);\n if (optimistic.variant === \"loading\")\n this.armCommandDeadline(changed, optimistic);\n }),\n ),\n });\n const composed = cache.derive<Key, Omit<Task, \"status\">, Task>({\n name: \"task.composed\",\n source: store,\n compose: (record) => this.compose(record),\n equal: (a, b) => deep.equal(a.payload, b.payload),\n watch: [query.deriveWatch(statusStore, (event) => affectedTaskKeys(event))],\n });\n const single = cache.queries<SingleRequest, Task, Key, Task>({\n name: \"task\",\n table: composed,\n fetch: async (q) => [(await this.fetchSingle(q)).key],\n compose: (records) => records[0],\n keyOf: (q) => (primitive.isNonZero(q.keys) ? q.keys[0] : null),\n matches: matchesSingle,\n single: true,\n });\n super(cache, {\n name: \"task\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.fetchThrough(req),\n matches: (t, req) => requestFilter(req)(t),\n watch: [query.watch(statusStore, (event) => affectedTaskKeys(event))],\n },\n compose: (record) => this.compose(record),\n single: { schema: singleQueryZ, space: single },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(task: New): Promise<Task>;\n async create(tasks: New[]): Promise<Task[]>;\n\n async create<S extends Schemas>(task: New<S>, schemas: S): Promise<Task<S>>;\n async create<S extends Schemas>(tasks: New<S>[], schemas: S): Promise<Task<S>[]>;\n\n async create<S extends Schemas>(\n task: New<S> | New<S>[],\n schemas?: S,\n ): Promise<Task<S> | Task<S>[]> {\n const isSingle = !Array.isArray(task);\n const createReq = createReqZ(schemas);\n const createRes = createResZ(schemas);\n const res = await this.cfg.unary.send(\n \"/task/create\",\n { tasks: array.toArray(task) },\n createReq,\n createRes,\n );\n const sugared = this.sugar<S>(res.tasks as Payload<S>[], schemas);\n sugared.forEach((t) => this.writeThrough(t));\n return isSingle ? sugared[0] : sugared;\n }\n\n /**\n * Forgets the tasks locally without deleting them on the cluster, for callers\n * whose own endpoint already deleted them. Keeps a later retrieve from serving\n * a deleted task while the delete signal is still in flight.\n */\n dropCached(keys: Key | Key[]): void {\n this.dropLocal(array.toArray(keys));\n }\n\n private dropLocal(keys: Key[]): destructor.Destructor[] {\n return [\n this.cfg.ontology.cache.deleteResources(ontologyID(keys)),\n this.store.delete(keys),\n this.cfg.statusStore.delete(keys.map((k) => statusKey(k))),\n ];\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => this.dropLocal(keysArr);\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/task/delete\",\n { keys: keysArr },\n deleteReqZ,\n deleteResZ,\n ),\n });\n drop();\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n this.store.set(key, (p) =>\n p == null ? undefined : this.sugar({ ...p.payload, name }),\n ),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n const t = await this.retrieve(key);\n await this.create({ ...t.payload, name });\n },\n });\n rename();\n }\n\n async retrieve<S extends Schemas = Schemas>(\n params: RetrieveSingleParams & RetrieveSchemas<S>,\n ): Promise<Task<S>>;\n async retrieve(params: Key | RetrieveSingleParams): Promise<Task>;\n async retrieve<S extends Schemas = Schemas>(\n params: RetrieveMultipleParams & RetrieveSchemas<S>,\n ): Promise<Task<S>[]>;\n async retrieve(params: RetrieveMultipleParams): Promise<Task[]>;\n async retrieve<S extends Schemas = Schemas>(\n rawParams: Key | (RetrieveParams & RetrieveSchemas<S>),\n ): Promise<Task<S> | Task<S>[]> {\n const { schemas, ...params } =\n typeof rawParams === \"string\" ? { key: rawParams } : rawParams;\n const isSingle = singleRetrieveParamsZ.safeParse(params).success;\n // Schema-parametrized retrieves validate config/status for one caller;\n // their results are not shared through the cache.\n if (schemas != null) {\n const sugared = await this.execRetrieve<S>(params, schemas);\n checkForMultipleOrNoResults(\"Task\", params, sugared, isSingle);\n return isSingle ? sugared[0] : sugared;\n }\n if (isSingle)\n return (await super.retrieve(params as RetrieveSingleParams)) as Task<S>;\n return (await super.retrieve(\n params as RetrieveMultipleParams,\n )) as unknown as Task<S>[];\n }\n\n async copy(key: Key, name: string, snapshot: boolean): Promise<Task> {\n const copyRes = copyResZ();\n const response = await this.cfg.unary.send(\n \"/task/copy\",\n { key, name, snapshot },\n copyReqZ,\n copyRes,\n );\n const sugared = this.sugar(response.task);\n this.writeThrough(sugared);\n return sugared;\n }\n\n async list(rack?: number): Promise<Task[]> {\n const params: RetrieveMultipleParams = { internal: false };\n if (rack !== undefined) params.rack = rack;\n return await this.retrieve(params);\n }\n\n async retrieveSnapshottedTo(taskKey: Key): Promise<ontology.Resource | null> {\n if (this.cfg.ontology == null) throw new Error(\"Task not created\");\n return await retrieveSnapshottedTo(taskKey, this.cfg.ontology);\n }\n\n private async execRetrieve<S extends Schemas = Schemas>(\n params: RetrieveParams,\n schemas?: S,\n ): Promise<Task<S>[]> {\n const res = await this.cfg.unary.send(\n \"/task/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ(schemas),\n );\n return this.sugar(res.tasks as Payload<S>[], schemas);\n }\n\n /** Rebuilds a cached task with its cached status attached. */\n private compose(cached: Omit<Task, \"status\">): Task {\n const st = this.latestStatusOf(cached.key);\n const payload = cached.payload;\n if (st == null) return this.sugar(payload);\n return this.sugar({ ...payload, status: st });\n }\n\n // Every domain's statuses share one store, so a rack's status sits beside its\n // tasks' under the rack's ontology ID.\n private downRackStatus(rack: RackKey | undefined): status.Status | undefined {\n if (rack == null || primitive.isZero(rack)) return undefined;\n const stat = this.cfg.statusStore.get(ontology.idToString(rackOntologyID(rack)));\n if (stat == null || HEALTHY_RACK_VARIANTS.includes(stat.variant)) return undefined;\n return stat;\n }\n\n /**\n * Builds the status shown while a command is in flight. A rack whose Driver is down\n * answers nothing, so its warning stands in for a wait that would never end.\n */\n private optimisticStatus(cmd: Command): Status {\n // Carry the last known deploy info forward: zeroing it would make this\n // optimistic status claim the task deployed with an empty config/rack.\n const latest = this.latestStatusOf(cmd.task);\n const key = statusKey(cmd.task);\n const details = {\n task: cmd.task,\n cmd: \"\",\n configHash: latest?.details.configHash ?? \"\",\n rack: latest?.details.rack ?? 0,\n data: {},\n };\n const down = this.downRackStatus(this.store.get(cmd.task)?.rack);\n if (down == null)\n return status.create<StatusDetailsZodObject>({\n key,\n name: STATUS_NAME,\n variant: \"loading\",\n message: `Running ${cmd.type} command...`,\n details: { ...details, running: true },\n });\n return status.create<StatusDetailsZodObject>({\n key,\n name: STATUS_NAME,\n variant: \"warning\",\n message: down.message,\n description: down.description,\n details: { ...details, running: false },\n });\n }\n\n // Nothing else retires the loading status: a task on a silent rack waits on the\n // Core's next dead-rack alert, which dampens to once a minute.\n private armCommandDeadline(cmd: Command, optimistic: Status): void {\n const { statusStore } = this.cfg;\n const key = statusKey(cmd.task);\n clearTimeout(this.commandDeadlines.get(cmd.task));\n this.commandDeadlines.set(\n cmd.task,\n setTimeout(() => {\n this.commandDeadlines.delete(cmd.task);\n // Any later write replaced the exact object this deadline was armed for.\n if (statusStore.get(key) !== optimistic) return;\n statusStore.set(\n key,\n status.create<StatusDetailsZodObject>({\n key,\n name: STATUS_NAME,\n variant: \"warning\",\n message: `No response to the ${cmd.type} command`,\n description: `The Driver did not respond within ${COMMAND_DEADLINE.toString()}.`,\n // Nothing answered, so the command is taken to have had no effect.\n details: { ...optimistic.details, running: cmd.type === \"stop\" },\n }),\n );\n }, COMMAND_DEADLINE.milliseconds),\n );\n }\n\n // A task's status may live under the \"task:<key>\" row or under any status\n // whose details reference the task; the freshest wins. Rows are parsed\n // because the status table holds every domain's statuses generically.\n private latestStatusOf(key: Key): Status | undefined {\n const taskKey = statusKey(key);\n const candidates = this.cfg.statusStore\n .get((s) => s.key === taskKey || status.detailsOf(s)?.task === key)\n .map((s) => statusZ().safeParse(s))\n .filter((p) => p.success)\n .map((p) => p.data);\n if (candidates.length === 0) return undefined;\n return candidates.reduce((latest, s) =>\n new TimeStamp(s.time).afterEq(new TimeStamp(latest.time)) ? s : latest,\n );\n }\n\n /** Writes a fetched task and its included status. */\n private writeThrough(task: Task): void {\n this.store.set(task);\n if (task.status != null) this.cfg.statusStore.set(task.status);\n }\n\n /** Fetches tasks with statuses and writes the statuses through. */\n private async fetchThrough(req: RetrieveRequest): Promise<Task[]> {\n const tasks = await this.execRetrieve({ ...req, includeStatus: true });\n tasks.forEach((t) => {\n if (t.status != null) this.cfg.statusStore.set(t.status);\n });\n return tasks;\n }\n\n private async fetchSingle(q: SingleRequest): Promise<Task> {\n let cached: Omit<Task, \"status\"> | undefined;\n if (primitive.isNonZero(q.keys)) cached = this.store.get(q.keys[0]);\n else if (primitive.isNonZero(q.names))\n [cached] = this.store.get((t) => t.name === q.names?.[0]);\n // A cached task without a cached status is ambiguous: the task may have\n // no status or the status may not have synced. Only both count as a hit.\n if (cached != null && this.cfg.statusStore.has(statusKey(cached.key)))\n return this.compose(cached);\n const tasks = await this.execRetrieve({ ...q, includeStatus: true });\n checkForMultipleOrNoResults(\"Task\", q, tasks, true);\n this.writeThrough(tasks[0]);\n return tasks[0];\n }\n\n sugar<S extends Schemas = Schemas>(payloads: Payload<S>[], schemas?: S): Task<S>[];\n\n sugar<S extends Schemas = Schemas>(payload: Payload<S>, schemas?: S): Task<S>;\n\n sugar<S extends Schemas = Schemas>(\n payloads: Payload<S> | Payload<S>[],\n schemas?: S,\n ): Task<S>[] | Task<S> {\n const isSingle = !Array.isArray(payloads);\n const res = array.toArray(payloads).map(\n ({ key, rack, name, type, config, configHash, status, internal, snapshot }) =>\n new Task(\n {\n key,\n rack,\n name,\n type,\n config,\n configHash,\n internal,\n snapshot,\n status,\n },\n schemas,\n this.cfg.framer,\n this.cfg.ontology,\n this.cfg.ranges,\n ),\n );\n return isSingle ? res[0] : res;\n }\n\n /**\n * Fills a command's config hash from the cached task row. A command that carries\n * the hash lets the Driver reuse its live instance instead of redeploying.\n */\n private stampConfigHash(cmd: NewCommand): NewCommand {\n if (cmd.configHash != null) return cmd;\n return { ...cmd, configHash: this.store.get(cmd.task)?.configHash };\n }\n\n async executeCommand(params: ExecuteCommandParams): Promise<string>;\n\n async executeCommand(params: ExecuteCommandsParams): Promise<string[]>;\n\n async executeCommand(\n params: ExecuteCommandParams | ExecuteCommandsParams,\n ): Promise<string | string[]> {\n if (\"commands\" in params)\n return await executeCommands({\n commands: params.commands.map((c) => this.stampConfigHash(c)),\n frameClient: this.cfg.framer,\n });\n return await executeCommand({\n ...this.stampConfigHash(params),\n frameClient: this.cfg.framer,\n });\n }\n\n async executeCommandSync<StatusData extends z.ZodType = z.ZodNever>(\n params: ExecuteCommandsSyncParams<StatusData>,\n ): Promise<Status<StatusData>[]>;\n\n async executeCommandSync<StatusData extends z.ZodType = z.ZodNever>(\n params: ExecuteCommandSyncParams<StatusData>,\n ): Promise<Status<StatusData>>;\n\n async executeCommandSync<StatusData extends z.ZodType = z.ZodNever>(\n params:\n ExecuteCommandsSyncParams<StatusData> | ExecuteCommandSyncParams<StatusData>,\n ): Promise<Status<StatusData> | Status<StatusData>[]> {\n if (\"commands\" in params) {\n const retrieveNames = async () => {\n const { commands } = params;\n const ts = await this.retrieve({ keys: commands.map((t) => t.task) });\n return ts.map((t) => t.name);\n };\n return await executeCommandsSync({\n ...params,\n commands: params.commands.map((c) => this.stampConfigHash(c)),\n frameClient: this.cfg.framer,\n name: retrieveNames,\n });\n }\n const retrieveName = async () => {\n const { task } = params;\n const t = await this.retrieve(task);\n return t.name;\n };\n return await executeCommandSync({\n frameClient: this.cfg.framer,\n name: retrieveName,\n ...params,\n configHash: params.configHash ?? this.store.get(params.task)?.configHash,\n });\n }\n}\n\n/** @returns the key of the status that reports on the given task. */\nexport const statusKey = (key: Key): string => ontology.idToString(ontologyID(key));\n\nconst taskStatusZ = z.object({ details: z.object({ task: keyZ }) });\n\n// Task statuses may arrive under any status key; the referenced task lives in\n// the details, with the \"task:<key>\" status key as a fallback.\nconst affectedTaskKeys = (\n event: query.TableEvent<status.Key, status.Status>,\n): Key[] | null => {\n const keys: Key[] = [];\n if (event.variant === \"set\") {\n const parsed = taskStatusZ.safeParse(event.value);\n if (parsed.success) keys.push(parsed.data.details.task);\n }\n const [type, key] = event.key.split(\":\");\n if (type === \"task\" && primitive.isNonZero(key) && !keys.includes(key))\n keys.push(key);\n return keys.length === 0 ? null : keys;\n};\n\ninterface ExecuteCommandInternalParams {\n frameClient: framer.Client | null;\n task: Key;\n type: string;\n args?: {};\n configHash?: string;\n}\n\nconst executeCommand = async ({\n frameClient,\n task,\n type,\n args,\n configHash,\n}: ExecuteCommandInternalParams): Promise<string> =>\n (\n await executeCommands({\n frameClient,\n commands: [{ args, task, type, configHash }],\n })\n )[0];\n\n/** A command queued for a task. */\nexport interface NewCommand {\n task: Key;\n type: string;\n args?: {};\n /**\n * The config hash the sender wants running. Left unset, the client fills it from\n * its cached task row.\n */\n configHash?: string;\n}\n\ninterface ExecuteCommandsInternalParams {\n frameClient: framer.Client | null;\n commands: NewCommand[];\n}\n\nconst executeCommands = async ({\n frameClient,\n commands,\n}: ExecuteCommandsInternalParams): Promise<string[]> => {\n if (frameClient == null) throw new Error(\"Task not created\");\n const w = await frameClient.openWriter(COMMAND_CHANNEL_NAME);\n const cmds = commands.map((c) => ({\n ...c,\n configHash: c.configHash ?? \"\",\n key: id.create(),\n }));\n await w.write(COMMAND_CHANNEL_NAME, cmds);\n await w.close();\n return cmds.map((c) => c.key);\n};\n\ninterface ExecuteCommandSyncInternalParams<StatusData extends z.ZodType = z.ZodNever>\n extends\n Omit<ExecuteCommandsSyncInternalParams<StatusData>, \"commands\">,\n TaskExecuteCommandSyncParams {\n task: Key;\n configHash?: string;\n}\n\nconst executeCommandSync = async <StatusData extends z.ZodType = z.ZodNever>({\n frameClient,\n task,\n type,\n timeout,\n name: taskName,\n statusDataZ,\n args,\n configHash,\n}: ExecuteCommandSyncInternalParams<StatusData>): Promise<Status<StatusData>> =>\n (\n await executeCommandsSync({\n frameClient,\n commands: [{ args, task, type, configHash }],\n timeout,\n statusDataZ,\n name: taskName,\n })\n )[0];\n\ninterface ExecuteCommandsSyncInternalParams<StatusData extends z.ZodType = z.ZodNever> {\n frameClient: framer.Client | null;\n commands: NewCommand[];\n timeout?: CrudeTimeSpan;\n statusDataZ: StatusData;\n name: string | string[] | (() => Promise<string | string[]>);\n}\n\nconst executeCommandsSync = async <StatusData extends z.ZodType = z.ZodNever>({\n frameClient,\n commands,\n timeout = COMMAND_DEADLINE,\n statusDataZ,\n name: taskName,\n}: ExecuteCommandsSyncInternalParams<StatusData>): Promise<Status<StatusData>[]> => {\n if (frameClient == null) throw new Error(\"Task not created\");\n const streamer = await frameClient.openStreamer(status.SET_CHANNEL_NAME);\n const cmdKeys = await executeCommands({ frameClient, commands });\n const parsedTimeout = new TimeSpan(timeout);\n let states: Status<StatusData>[] = [];\n let timeoutID: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutID = setTimeout(() => {\n const taskKeys = commands.map((c) => c.task);\n formatTimeoutError(\"command\", taskName, parsedTimeout, taskKeys).then(\n reject,\n reject,\n );\n }, parsedTimeout.milliseconds);\n });\n try {\n while (true) {\n const frame = await Promise.race([streamer.read(), timeoutPromise]);\n // A frame can hold statuses for other tasks and racks, which have a different\n // shape and fail to parse.\n for (const str of frame.get(status.SET_CHANNEL_NAME).toStrings()) {\n const res = statusZ(statusDataZ).safeParse(binary.JSON_CODEC.decodeString(str));\n if (!res.success) continue;\n const state = res.data;\n if (state.details.cmd == null || !cmdKeys.includes(state.details.cmd)) continue;\n states = [...states.filter((s) => s.key !== state.key), state];\n if (states.length === cmdKeys.length) return states;\n }\n }\n } finally {\n clearTimeout(timeoutID);\n streamer.close();\n }\n};\n\nconst formatTimeoutError = async (\n type: string,\n name: string | string[] | (() => Promise<string | string[]>),\n timeout: TimeSpan,\n key: Key | Key[],\n): Promise<Error> => {\n const formattedType = caseconv.capitalize(type);\n const formattedTimeout = timeout.toString();\n try {\n let names: string[];\n if (typeof name === \"string\") names = [name];\n else if (Array.isArray(name)) names = name;\n else names = array.toArray(await name());\n const formattedName = strings.naturalLanguageJoin(names);\n return new Error(\n `${formattedType} command to ${formattedName} timed out after ${formattedTimeout}`,\n );\n } catch (e) {\n console.error(\"Failed to retrieve task name for timeout error:\", e);\n return new Error(\n `${formattedType} command to task with key ${strings.naturalLanguageJoin(array.toArray(key).map((k) => k.toString()))} timed out after ${formattedTimeout}`,\n );\n }\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/task/client\";\nexport * from \"@/task/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { graph } from \"@/arc/graph\";\nimport { program } from \"@/arc/program\";\nimport { text } from \"@/arc/text\";\nimport { ontology } from \"@/ontology\";\nimport { status } from \"@/status\";\nimport { task } from \"@/task\";\n\nexport const MODES = [\"text\", \"graph\"] as const;\nexport const modeZ = z.enum(MODES);\nexport type Mode = z.infer<typeof modeZ>;\n\nexport const EXECUTION_MODES = [\n \"AUTO\",\n \"BUSY_WAIT\",\n \"HIGH_RATE\",\n \"RT_EVENT\",\n \"HYBRID\",\n \"EVENT_DRIVEN\",\n] as const;\nexport const executionModeZ = z.enum(EXECUTION_MODES);\nexport type ExecutionMode = z.infer<typeof executionModeZ>;\n\n/** StatusDetails contains Arc-specific status details for execution state. */\nexport const statusDetailsZ = z.object({\n /** running indicates whether the Arc module is currently executing. */\n running: z.boolean(),\n});\nexport interface StatusDetails extends z.infer<typeof statusDetailsZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\nexport const statusZ = status.statusZ({ details: statusDetailsZ });\nexport type Status = z.infer<typeof statusZ>;\n\nexport const taskConfigZ = task.persistConfigZ.extend({\n arcKey: keyZ,\n hash: z.string().default(\"\"),\n executionMode: executionModeZ.default(\"AUTO\"),\n rtPriority: z.int32().default(47),\n cpuAffinity: z.int32().default(-1),\n memoryLocked: z.boolean().default(false),\n});\nexport interface TaskConfig extends z.infer<typeof taskConfigZ> {}\n\n/**\n * Arc is an Arc module combining visual graph representation and text-based source code\n * for reactive control systems. Compiles to WebAssembly for sandboxed execution.\n */\nexport const arcZ = z.object({\n /** key is the unique identifier for this module. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the module. */\n name: z.string().min(1, \"name is required\"),\n /**\n * mode specifies the representation mode for this module. Either \"text\" for\n * text-based Arc code or \"graph\" for visual dataflow.\n */\n mode: modeZ,\n /** graph is the visual dataflow graph representation of the module. */\n graph: graph.graphZ.prefault({}),\n /** text is the text-based Arc source code. */\n text: text.textZ.prefault({}),\n /** program is the compiled module output including IR and WebAssembly bytecode. */\n program: program.programZ.optional(),\n /** status is the current execution status of the module. */\n status: statusZ.optional(),\n});\nexport interface Arc extends z.infer<typeof arcZ> {}\nexport interface New extends z.input<typeof arcZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"arc\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { caseconv, crdt, record, spatial, zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { graph } from \"@/arc/graph\";\nimport { ir } from \"@/arc/ir\";\nimport { type Arc, arcZ, keyZ } from \"@/arc/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n arc: arcZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the Arc module. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/**\n * SetNode inserts the node if no node with the same key exists, otherwise replaces the\n * existing node in place. Operates only on the node's position; the node's function\n * type and inputs are set separately via SetNodeInputs.\n */\nexport const setNodePayloadZ = z.object({\n node: graph.nodeZ,\n});\n\nexport type SetNodePayload = z.infer<typeof setNodePayloadZ>;\n\n/** SetNodePosition moves a graph node to a new canvas position. */\nexport const setNodePositionPayloadZ = z.object({\n key: z.string(),\n position: spatial.xyZ,\n});\n\nexport type SetNodePositionPayload = z.infer<typeof setNodePositionPayloadZ>;\n\n/**\n * SetNodeInputs merges the given inputs into the entry for the given key in the graph\n * inputs map. Top-level fields present in the payload overwrite existing fields; fields\n * absent from the payload are preserved. The node's function type is held under \"type\".\n */\nexport const setNodeInputsPayloadZ = z.object({\n key: z.string(),\n inputs: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\n\nexport type SetNodeInputsPayload = z.infer<typeof setNodeInputsPayloadZ>;\n\n/**\n * RemoveNode removes the node with the given key along with its inputs entry and any\n * edges connected to it.\n */\nexport const removeNodePayloadZ = z.object({\n key: z.string(),\n});\n\nexport type RemoveNodePayload = z.infer<typeof removeNodePayloadZ>;\n\n/**\n * AddEdge appends the edge to the graph. No-op when an edge with the same source and\n * target handles already exists, so concurrent additions of the same connection\n * converge regardless of differing keys.\n */\nexport const addEdgePayloadZ = z.object({\n edge: graph.edgeZ,\n});\n\nexport type AddEdgePayload = z.infer<typeof addEdgePayloadZ>;\n\n/** RemoveEdge removes the edge with the given key, if present. */\nexport const removeEdgePayloadZ = z.object({\n key: z.string(),\n});\n\nexport type RemoveEdgePayload = z.infer<typeof removeEdgePayloadZ>;\n\n/**\n * ReconnectEdge rewrites the endpoints of the edge with the given key, preserving its\n * key and kind. No-op when no edge with the key exists.\n */\nexport const reconnectEdgePayloadZ = z.object({\n key: z.string(),\n source: ir.handleZ,\n target: ir.handleZ,\n});\n\nexport type ReconnectEdgePayload = z.infer<typeof reconnectEdgePayloadZ>;\n\n/**\n * InsertChar carries a single collaborative-edit character insertion against the\n * module's text. The payload is a sequence CRDT operation; the server relays it to the\n * other editors of the module without interpreting it.\n */\nexport const insertCharPayloadZ = z.object({\n id: crdt.idZ,\n origin: crdt.idZ,\n side: spatial.xLocationZ,\n char: z.int32(),\n});\n\nexport type InsertCharPayload = z.infer<typeof insertCharPayloadZ>;\n\n/**\n * DeleteChar carries a single collaborative-edit character deletion against the\n * module's text. The payload is a sequence CRDT operation; the server relays it to the\n * other editors of the module without interpreting it.\n */\nexport const deleteCharPayloadZ = z.object({\n id: crdt.idZ,\n});\n\nexport type DeleteCharPayload = z.infer<typeof deleteCharPayloadZ>;\n\n/**\n * ForgetChars removes the given already-deleted characters from the module's text\n * document, dropping both their insert and delete operations from the replicated\n * op-log. The server emits it after a quiet editing period to reclaim the space held by\n * tombstoned characters. Because the characters are already deleted, and thus\n * invisible, applying it never changes the materialized text.\n */\nexport const forgetCharsPayloadZ = z.object({\n ids: crdt.idZ.array().default(() => []),\n});\n\nexport type ForgetCharsPayload = z.infer<typeof forgetCharsPayloadZ>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({ type: z.literal(\"set_node\"), setNode: setNodePayloadZ }),\n z.object({\n type: z.literal(\"set_node_position\"),\n setNodePosition: setNodePositionPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_node_inputs\"),\n setNodeInputs: setNodeInputsPayloadZ,\n }),\n z.object({ type: z.literal(\"remove_node\"), removeNode: removeNodePayloadZ }),\n z.object({ type: z.literal(\"add_edge\"), addEdge: addEdgePayloadZ }),\n z.object({ type: z.literal(\"remove_edge\"), removeEdge: removeEdgePayloadZ }),\n z.object({ type: z.literal(\"reconnect_edge\"), reconnectEdge: reconnectEdgePayloadZ }),\n z.object({ type: z.literal(\"insert_char\"), insertChar: insertCharPayloadZ }),\n z.object({ type: z.literal(\"delete_char\"), deleteChar: deleteCharPayloadZ }),\n z.object({ type: z.literal(\"forget_chars\"), forgetChars: forgetCharsPayloadZ }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"Arc create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"Arc rename action payload\",\n }),\n});\n\nexport const setNode = (payload: z.input<typeof setNodePayloadZ>): Action => ({\n type: \"set_node\",\n setNode: zod.parse(setNodePayloadZ, payload, {\n label: \"Arc set_node action payload\",\n }),\n});\n\nexport const setNodePosition = (\n payload: z.input<typeof setNodePositionPayloadZ>,\n): Action => ({\n type: \"set_node_position\",\n setNodePosition: zod.parse(setNodePositionPayloadZ, payload, {\n label: \"Arc set_node_position action payload\",\n }),\n});\n\nexport const setNodeInputs = (\n payload: z.input<typeof setNodeInputsPayloadZ>,\n): Action => ({\n type: \"set_node_inputs\",\n setNodeInputs: zod.parse(setNodeInputsPayloadZ, payload, {\n label: \"Arc set_node_inputs action payload\",\n }),\n});\n\nexport const removeNode = (payload: z.input<typeof removeNodePayloadZ>): Action => ({\n type: \"remove_node\",\n removeNode: zod.parse(removeNodePayloadZ, payload, {\n label: \"Arc remove_node action payload\",\n }),\n});\n\nexport const addEdge = (payload: z.input<typeof addEdgePayloadZ>): Action => ({\n type: \"add_edge\",\n addEdge: zod.parse(addEdgePayloadZ, payload, {\n label: \"Arc add_edge action payload\",\n }),\n});\n\nexport const removeEdge = (payload: z.input<typeof removeEdgePayloadZ>): Action => ({\n type: \"remove_edge\",\n removeEdge: zod.parse(removeEdgePayloadZ, payload, {\n label: \"Arc remove_edge action payload\",\n }),\n});\n\nexport const reconnectEdge = (\n payload: z.input<typeof reconnectEdgePayloadZ>,\n): Action => ({\n type: \"reconnect_edge\",\n reconnectEdge: zod.parse(reconnectEdgePayloadZ, payload, {\n label: \"Arc reconnect_edge action payload\",\n }),\n});\n\nexport const insertChar = (payload: z.input<typeof insertCharPayloadZ>): Action => ({\n type: \"insert_char\",\n insertChar: zod.parse(insertCharPayloadZ, payload, {\n label: \"Arc insert_char action payload\",\n }),\n});\n\nexport const deleteChar = (payload: z.input<typeof deleteCharPayloadZ>): Action => ({\n type: \"delete_char\",\n deleteChar: zod.parse(deleteCharPayloadZ, payload, {\n label: \"Arc delete_char action payload\",\n }),\n});\n\nexport const forgetChars = (payload: z.input<typeof forgetCharsPayloadZ>): Action => ({\n type: \"forget_chars\",\n forgetChars: zod.parse(forgetCharsPayloadZ, payload, {\n label: \"Arc forget_chars action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<Arc, Action>;\n\nexport interface Handlers {\n create: (state: Draft<Arc>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<Arc>, payload: RenamePayload) => HandlerResult;\n setNode: (state: Draft<Arc>, payload: SetNodePayload) => HandlerResult;\n setNodePosition: (\n state: Draft<Arc>,\n payload: SetNodePositionPayload,\n ) => HandlerResult;\n setNodeInputs: (state: Draft<Arc>, payload: SetNodeInputsPayload) => HandlerResult;\n removeNode: (state: Draft<Arc>, payload: RemoveNodePayload) => HandlerResult;\n addEdge: (state: Draft<Arc>, payload: AddEdgePayload) => HandlerResult;\n removeEdge: (state: Draft<Arc>, payload: RemoveEdgePayload) => HandlerResult;\n reconnectEdge: (state: Draft<Arc>, payload: ReconnectEdgePayload) => HandlerResult;\n insertChar: (state: Draft<Arc>, payload: InsertCharPayload) => HandlerResult;\n deleteChar: (state: Draft<Arc>, payload: DeleteCharPayload) => HandlerResult;\n forgetChars: (state: Draft<Arc>, payload: ForgetCharsPayload) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<Arc, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"set_node\":\n return handlers.setNode(state, action.setNode);\n case \"set_node_position\":\n return handlers.setNodePosition(state, action.setNodePosition);\n case \"set_node_inputs\":\n return handlers.setNodeInputs(state, action.setNodeInputs);\n case \"remove_node\":\n return handlers.removeNode(state, action.removeNode);\n case \"add_edge\":\n return handlers.addEdge(state, action.addEdge);\n case \"remove_edge\":\n return handlers.removeEdge(state, action.removeEdge);\n case \"reconnect_edge\":\n return handlers.reconnectEdge(state, action.reconnectEdge);\n case \"insert_char\":\n return handlers.insertChar(state, action.insertChar);\n case \"delete_char\":\n return handlers.deleteChar(state, action.deleteChar);\n case \"forget_chars\":\n return handlers.forgetChars(state, action.forgetChars);\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type crdt, type record } from \"@synnaxlabs/x\";\n\nimport { actions } from \"@/actions\";\nimport {\n type Action,\n addEdge,\n createReduceAll,\n type Handlers,\n reconnectEdge,\n removeEdge,\n removeNode,\n rename,\n setNode,\n setNodeInputs,\n setNodePosition,\n} from \"@/arc/actions.gen\";\nimport { type ir } from \"@/arc/ir\";\n\nconst idToString = (id: crdt.ID): string => `${id.replica}:${id.counter}`;\n\nconst sameEndpoints = (a: ir.Edge, source: ir.Handle, target: ir.Handle): boolean =>\n a.source.node === source.node &&\n a.source.param === source.param &&\n a.target.node === target.node &&\n a.target.param === target.param;\n\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.arc);\n return { inverse: [], targets: [payload.arc.key] };\n },\n\n rename: (state, payload) => {\n const oldName = state.name;\n state.name = payload.name;\n return { inverse: [rename({ name: oldName })], targets: [state.key] };\n },\n setNode: (state, payload) => {\n const idx = state.graph.nodes.findIndex((n) => n.key === payload.node.key);\n if (idx === -1) {\n state.graph.nodes.push(payload.node);\n return {\n inverse: [removeNode({ key: payload.node.key })],\n targets: [payload.node.key],\n };\n }\n const oldNode = actions.snapshotDraft(state.graph.nodes[idx]);\n state.graph.nodes[idx] = payload.node;\n return { inverse: [setNode({ node: oldNode })], targets: [payload.node.key] };\n },\n setNodePosition: (state, payload) => {\n const node = state.graph.nodes.find((n) => n.key === payload.key);\n if (node == null) return actions.NO_OP_RESULT;\n const oldPosition = { x: node.position.x, y: node.position.y };\n node.position = payload.position;\n return {\n inverse: [setNodePosition({ key: payload.key, position: oldPosition })],\n targets: [payload.key],\n };\n },\n // The inverse of SetNodeInputs is imperfect for keys the action newly introduces:\n // SetNodeInputs only merges, so it cannot remove keys that did not previously exist.\n // The inverse here restores values for keys that DID exist before the merge; keys\n // added by the action remain on undo as phantom fields. A future ReplaceNodeInputs\n // action can close the gap by enabling wholesale replacement.\n setNodeInputs: (state, payload) => {\n const existingRaw = state.graph.inputs[payload.key];\n if (existingRaw == null) {\n state.graph.inputs[payload.key] = payload.inputs;\n return { inverse: [], targets: [payload.key] };\n }\n const existing = actions.snapshotDraft(existingRaw);\n const restoreFields: record.Unknown = {};\n for (const k of Object.keys(payload.inputs))\n if (existing[k] !== undefined) restoreFields[k] = existing[k];\n state.graph.inputs[payload.key] = { ...existing, ...payload.inputs };\n if (Object.keys(restoreFields).length === 0)\n return { inverse: [], targets: [payload.key] };\n return {\n inverse: [setNodeInputs({ key: payload.key, inputs: restoreFields })],\n targets: [payload.key],\n };\n },\n removeNode: (state, payload) => {\n const idx = state.graph.nodes.findIndex((n) => n.key === payload.key);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldNode = actions.snapshotDraft(state.graph.nodes[idx]);\n const oldInputs = actions.snapshotDraft(state.graph.inputs[payload.key]);\n const removedEdges = state.graph.edges\n .filter((e) => e.source.node === payload.key || e.target.node === payload.key)\n .map((e) => actions.snapshotDraft(e));\n state.graph.nodes.splice(idx, 1);\n delete state.graph.inputs[payload.key];\n state.graph.edges = state.graph.edges.filter(\n (e) => e.source.node !== payload.key && e.target.node !== payload.key,\n );\n const inverse: Action[] = [setNode({ node: oldNode })];\n if (oldInputs != null)\n inverse.push(setNodeInputs({ key: payload.key, inputs: oldInputs }));\n inverse.push(...removedEdges.map((e) => addEdge({ edge: e })));\n return { inverse, targets: [payload.key] };\n },\n addEdge: (state, payload) => {\n const { edge } = payload;\n if (state.graph.edges.some((e) => sameEndpoints(e, edge.source, edge.target)))\n return actions.NO_OP_RESULT;\n state.graph.edges.push(edge);\n return { inverse: [removeEdge({ key: edge.key })], targets: [edge.key] };\n },\n removeEdge: (state, payload) => {\n const idx = state.graph.edges.findIndex((e) => e.key === payload.key);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldEdge = actions.snapshotDraft(state.graph.edges[idx]);\n state.graph.edges.splice(idx, 1);\n return { inverse: [addEdge({ edge: oldEdge })], targets: [payload.key] };\n },\n reconnectEdge: (state, payload) => {\n const edge = state.graph.edges.find((e) => e.key === payload.key);\n if (edge == null) return actions.NO_OP_RESULT;\n const oldSource = actions.snapshotDraft(edge.source);\n const oldTarget = actions.snapshotDraft(edge.target);\n edge.source = payload.source;\n edge.target = payload.target;\n return {\n inverse: [\n reconnectEdge({ key: payload.key, source: oldSource, target: oldTarget }),\n ],\n targets: [payload.key],\n };\n },\n // Undo/redo is handled the editor, which emits the corresponding\n // insertChar, deleteChar actions.\n insertChar: (state, payload) => {\n state.text.doc.inserts.push(payload);\n return { inverse: [], targets: [] };\n },\n deleteChar: (state, payload) => {\n state.text.doc.deletes.push(payload);\n return { inverse: [], targets: [] };\n },\n // Server-emitted maintenance: drop the insert and delete ops of already-deleted\n // characters. The characters are tombstoned and invisible, so removing their ops does\n // not change the materialized text.\n forgetChars: (state, payload) => {\n if (payload.ids.length === 0) return { inverse: [], targets: [] };\n const forget = new Set(payload.ids.map(idToString));\n state.text.doc.inserts = state.text.doc.inserts.filter(\n (i) => !forget.has(idToString(i.id)),\n );\n state.text.doc.deletes = state.text.doc.deletes.filter(\n (d) => !forget.has(idToString(d.id)),\n );\n return { inverse: [], targets: [] };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.arc : undefined;\n\n// isUndoable reports whether an action should push onto the undo stack. Graph mutations\n// are user-driven and undoable; collaborative text edits are not (they carry no inverse\n// and belong to the CRDT, not the graph undo stack), nor is the server's tombstone\n// reclamation.\nexport const isUndoable = (action: Action): boolean =>\n action.type !== \"insert_char\" &&\n action.type !== \"delete_char\" &&\n action.type !== \"forget_chars\";\n\n// kindOf classifies an action batch for the undo coalesce window. A\n// node drag dispatches a stream of set_node_position actions for a single\n// gesture; classifying them all as \"move\" collapses them into one undoable.\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n const hasMove = actions.some((a) => a.type === \"set_node_position\");\n const onlyMove = actions.every((a) => a.type === \"set_node_position\");\n if (hasMove && onlyMove) return \"move\";\n if (actions.length === 1) return actions[0].type;\n return \"transaction\";\n};\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([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})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[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])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[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])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type Stream,\n type StreamClient,\n type UnaryClient,\n} from \"@synnaxlabs/freighter\";\nimport {\n array,\n deep,\n type destructor,\n errors,\n id,\n primitive,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod/v4\";\n\nimport { actions } from \"@/actions\";\nimport { createOf, isUndoable, kindOf, reduceAll } from \"@/arc/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/arc/actions.gen\";\nimport { type Arc, arcZ, type Key, keyZ, type New, ontologyID } from \"@/arc/types.gen\";\nimport { NotFoundError } from \"@/errors\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { rack } from \"@/rack\";\nimport { type status } from \"@/status\";\nimport { task } from \"@/task\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport const SET_CHANNEL_NAME = \"sy_arc_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_arc_delete\";\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n searchTerm: z.string().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n includeStatus: z.boolean().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst createReqZ = z.object({ arcs: arcZ.array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst retrieveResZ = z.object({ arcs: arcZ.array().default(() => []) });\nconst createResZ = z.object({ arcs: arcZ.array() });\nconst emptyResZ = z.object({});\n\nexport const lspMessageZ = z.object({ content: z.string() });\nexport type LSPMessage = z.infer<typeof lspMessageZ>;\n\nexport type RetrieveRequest = z.input<typeof retrieveReqZ>;\n\nconst keyRetrieveRequestZ = z\n .object({\n key: keyZ,\n includeStatus: z.boolean().optional(),\n })\n .transform(({ key, includeStatus }) => ({ keys: [key], includeStatus }));\n\nconst nameRetrieveRequestZ = z\n .object({\n name: z.string(),\n includeStatus: z.boolean().optional(),\n })\n .transform(({ name, includeStatus }) => ({ names: [name], includeStatus }));\n\nexport const singleRetrieveParamsZ = z.union([\n keyRetrieveRequestZ,\n nameRetrieveRequestZ,\n]);\n\nexport type SingleRetrieveParams = z.input<typeof singleRetrieveParamsZ>;\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveReqZ]);\n\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\nconst singleQueryZ = z.union([\n z.strictObject({ key: keyZ, includeStatus: z.boolean().optional() }),\n z.strictObject({ name: z.string(), includeStatus: z.boolean().optional() }),\n keyZ.transform((key) => ({ key })),\n]);\n\nconst setRackReqZ = z.object({ key: keyZ, rack: rack.keyZ });\nconst setRackResZ = z.object({ task: task.payloadZ().nullish() });\n\n/**\n * Client-side matching for a request: key and name sets. Server-computed\n * shapes (search, pagination) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((a: Arc) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameSet = primitive.isNonZero(req.names) ? new Set(req.names) : undefined;\n return (a) => {\n if (keySet != null && !keySet.has(a.key)) return false;\n if (nameSet != null && !nameSet.has(a.name)) return false;\n return true;\n };\n};\n\nconst isTaskChild = (rel: ontology.Relationship, arcKey: Key): boolean =>\n ontology.matchRelationship(rel, {\n from: ontologyID(arcKey),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: { type: \"task\" },\n });\n\nconst taskStatusZ = z.object({ details: z.object({ task: task.keyZ }) });\n\n// Task statuses may arrive under any status key; the referenced task lives in\n// the details, with the \"task:<key>\" status key as a fallback.\nconst affectedTaskKeys = (\n event: query.TableEvent<status.Key, status.Status>,\n): task.Key[] | null => {\n const keys: task.Key[] = [];\n if (event.variant === \"set\") {\n const parsed = taskStatusZ.safeParse(event.value);\n if (parsed.success) keys.push(parsed.data.details.task);\n }\n const [type, key] = event.key.split(\":\");\n if (type === \"task\" && primitive.isNonZero(key) && !keys.includes(key))\n keys.push(key);\n return keys.length === 0 ? null : keys;\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n stream: StreamClient;\n ontology: ontology.Client;\n tasks: task.Client;\n cache: query.Cache;\n statusStore: query.Table<status.Key, status.Status>;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Arc,\n Arc,\n SingleRetrieveParams,\n SingleRetrieveParams\n> {\n private readonly cfg: ClientConfig;\n private readonly dispatcher: actions.Controller<Key, Arc, Action>;\n private readonly store: query.Table<Key, Arc>;\n private readonly taskAnswers: query.Retrieves<Key, task.Task | null>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n // Fetched copies never clobber a doc holding locally replayed edits: the\n // table hydrates if-absent, and hydrate() decides when a fresh network\n // doc replaces the cached one.\n const store = cache.createTable<Key, Arc>({\n name: \"Arcs\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, Arc, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n isUndoable,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n const single = cache.queries<SingleRetrieveParams, Arc, Key, Arc>({\n name: \"Arc\",\n table: store,\n fetch: async (q) => [(await this.fetchSingle(q)).key],\n compose: (records) => records[0],\n keyOf: (q) => (\"key\" in q ? q.key : null),\n matches: (a, q) => (\"key\" in q ? a.key === q.key : a.name === q.name),\n single: true,\n });\n super(cache, {\n name: \"Arc\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) =>\n (await this.execRetrieve(req)).map((a) => this.hydrate(a)),\n matches: (a, req) => requestFilter(req)(a),\n },\n single: { schema: singleQueryZ, space: single },\n });\n this.cfg = cfg;\n this.store = store;\n this.dispatcher = dispatcher;\n const composedTasks = cache.derive<task.Key, Omit<task.Task, \"status\">, task.Task>({\n name: \"arc.task.composed\",\n source: this.cfg.tasks.store,\n compose: (record) => this.composeTask(record),\n equal: (a, b) => deep.equal(a.payload, b.payload),\n watch: [\n query.deriveWatch(this.cfg.statusStore, (event) => affectedTaskKeys(event)),\n ],\n });\n this.taskAnswers = cache.queries<Key, task.Task | null, task.Key, task.Task>({\n name: \"Arc task\",\n table: composedTasks,\n fetch: async (q) => {\n const tsk = await this.fetchTask(q);\n return tsk == null ? [] : [tsk.key];\n },\n compose: (records) => records[0] ?? null,\n matches: (t, q) =>\n this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString({\n from: ontologyID(q),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: task.ontologyID(t.key),\n }),\n ),\n watch: [\n query.watch(this.cfg.ontology.cache.relationships, (event, q: Key) => {\n const rel =\n event.variant === \"set\"\n ? event.value\n : ontology.relationshipZ.parse(event.key);\n if (!isTaskChild(rel, q)) return null;\n return [rel.to.key];\n }),\n ],\n });\n }\n\n async create(arc: New, opts?: query.WriteOptions<Arc[]>): Promise<Arc>;\n async create(arcs: New[], opts?: query.WriteOptions<Arc[]>): Promise<Arc[]>;\n async create(\n arcs: New | New[],\n opts: query.WriteOptions<Arc[]> = {},\n ): Promise<Arc | Arc[]> {\n const isMany = Array.isArray(arcs);\n const optimistic = array\n .toArray(arcs)\n .map((a) => zod.parse(arcZ, a, { label: \"Arc\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/arc/create\",\n { arcs: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.arcs);\n return isMany ? res.arcs : res.arcs[0];\n }\n\n /**\n * Binds the arc to the given rack, creating its task there or moving the\n * existing one. A zero rack unbinds the arc, deleting its task. Returns the\n * task, or null after an unbind.\n * @throws {ValidationError} when unbinding while the task is running.\n */\n async setRack(key: Key, rackKey: rack.Key): Promise<task.Task | null> {\n if (rackKey === 0) {\n await this.clearRack(key);\n return null;\n }\n const res = await this.cfg.unary.send(\n \"/arc/set-rack\",\n { key, rack: rackKey },\n setRackReqZ,\n setRackResZ,\n );\n if (res.task == null) return null;\n const tsk = this.cfg.tasks.sugar(res.task);\n this.cfg.tasks.store.set(tsk);\n return tsk;\n }\n\n // clearRack drops the deleted task from the cache so it is not served until\n // the delete signal lands.\n private async clearRack(key: Key): Promise<void> {\n const tsk = await this.retrieveTask(key);\n await this.cfg.unary.send(\n \"/arc/set-rack\",\n { key, rack: 0 },\n setRackReqZ,\n setRackResZ,\n );\n if (tsk != null) this.cfg.tasks.dropCached(tsk.key);\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const tsk = await this.retrieveTask(key);\n if (tsk != null) await this.cfg.tasks.rename(tsk.key, name);\n const rename = () => query.partialUpdate(this.store, key, { name });\n await query.optimistic({\n rollbacks: [rename()],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.sendDispatch(key, id.create(), [renameAction({ name })]),\n });\n rename();\n }\n\n private async retrieveTask(key: Key): Promise<task.Task | null> {\n return await this.taskAnswers.retrieve(key);\n }\n\n /**\n * Cached queries for the task deployed for an arc, keyed by the arc's key.\n * Resolves null when the arc has no task.\n */\n get task(): query.Retrieves<Key, task.Task | null> {\n return this.taskAnswers;\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => this.store.delete(keysArr);\n await query.optimistic({\n rollbacks: [drop()],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/arc/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every arc delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n async openLSP(): Promise<Stream<typeof lspMessageZ, typeof lspMessageZ>> {\n return await this.cfg.stream.stream(\"/arc/lsp\", lspMessageZ, lspMessageZ);\n }\n\n /**\n * Applies actions to the cached arc and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the arc isn't cached. Rolls\n * back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<Arc, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the arc's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the arc's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the arc has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the arc has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the arc's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/arc/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n private async execRetrieve(params: RetrieveParams): Promise<Arc[]> {\n const res = await this.cfg.unary.send(\n \"/arc/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ,\n );\n return res.arcs;\n }\n\n // Dispatch mutates documents server-side (including materialized text), so\n // a cached copy is only as fresh as the streamer. Fetches always hit the\n // network; only the server materializes text.\n private async fetchSingle(q: SingleRetrieveParams): Promise<Arc> {\n const arcs = await this.execRetrieve(q);\n checkForMultipleOrNoResults(\"Arc\", q, arcs, true);\n return this.hydrate(arcs[0]);\n }\n\n // Answers reuse the identical store doc so selector references stay\n // stable; a fresher network doc replaces it and answers. While a locally\n // replayed dispatch awaits its echo the replayed doc stays, but the\n // network doc answers: it carries the server-materialized text.\n private hydrate(a: Arc): Arc {\n if (this.dispatcher.hasOutstanding(a.key) === true) {\n this.store.ingest(a);\n return a;\n }\n const prev = this.store.get(a.key);\n if (prev != null && deep.equal(prev, a)) return prev;\n this.store.set(a);\n return a;\n }\n\n /**\n * Rebuilds a cached task with its cached status attached. The status is\n * parsed because the status table holds every domain's statuses generically.\n */\n private composeTask(cached: Omit<task.Task, \"status\">): task.Task {\n const cachedStatus = this.cfg.statusStore.get(task.statusKey(cached.key));\n const payload = cached.payload;\n if (cachedStatus == null) return this.cfg.tasks.sugar(payload);\n const parsed = task.statusZ().safeParse(cachedStatus);\n if (!parsed.success) return this.cfg.tasks.sugar(payload);\n return this.cfg.tasks.sugar({ ...payload, status: parsed.data });\n }\n\n private async fetchTask(arcKey: Key): Promise<task.Task | null> {\n let children: ontology.Resource[];\n try {\n children = await this.cfg.ontology.children.retrieve({\n ids: ontologyID(arcKey),\n types: [\"task\"],\n });\n } catch (e) {\n // An arc that does not exist cannot have a task.\n if (NotFoundError.matches(e)) return null;\n throw errors.fromUnknown(e);\n }\n const child = children[0];\n if (child == null) return null;\n return await this.cfg.tasks.retrieve(child.id.key);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { type z } from \"zod\";\n\nimport { compiler } from \"@/arc/compiler\";\nimport { ir } from \"@/arc/ir\";\n\nexport const moduleZ = ir.irZ.extend(compiler.outputZ.shape);\nexport interface Module extends z.infer<typeof moduleZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/arc/actions\";\nexport * from \"@/arc/actions.gen\";\nexport * from \"@/arc/client\";\nexport * from \"@/arc/compiler\";\nexport * from \"@/arc/graph\";\nexport * from \"@/arc/ir\";\nexport * from \"@/arc/module\";\nexport * from \"@/arc/text\";\nexport * from \"@/arc/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { zod } from \"@synnaxlabs/x\";\nimport { type z } from \"zod\";\n\nexport const keyZ = zod.uint12;\nexport type Key = z.infer<typeof keyZ>;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { control, telem, TimeSpan, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { node } from \"@/node\";\nimport { ontology } from \"@/ontology\";\nimport { status } from \"@/status\";\n\nexport const keyZ = z.uint32().or(\n z\n .string()\n .refine((v) => !isNaN(Number(v)))\n .transform(Number),\n);\nexport type Key = z.infer<typeof keyZ>;\n\nexport const localKeyZ = zod.uint20;\nexport type LocalKey = z.infer<typeof localKeyZ>;\n\nexport const OPERATION_TYPES = [\"min\", \"max\", \"avg\", \"none\", \"derivative\"] as const;\nexport const operationTypeZ = z.enum(OPERATION_TYPES);\nexport type OperationType = z.infer<typeof operationTypeZ>;\n\n/**\n * Operation defines an aggregation operation applied to channel data. Operations\n * calculate min, max, average, or derivative values over a time duration or triggered\n * by a reset channel.\n */\nexport const operationZ = z.object({\n /** type is the aggregation operation type: min, max, avg, derivative, or none. */\n type: operationTypeZ,\n /**\n * resetChannel is the key of a channel that resets the aggregation when it receives a\n * sample. If 0, no reset channel is used.\n */\n resetChannel: keyZ.default(0),\n /**\n * duration is the interval at which the aggregation resets. If 0, the aggregation is\n * not reset on a timer.\n */\n duration: telem.timeSpanZ.default(TimeSpan.ZERO),\n});\nexport interface Operation extends z.infer<typeof operationZ> {}\n\nexport const nameZ = z.string().min(1, \"Name is required\");\nexport type Name = z.infer<typeof nameZ>;\n\nexport const statusZ = status.statusZ();\nexport type Status = z.infer<typeof statusZ>;\n\n/**\n * Payload is a logical collection of samples emitted by or representing values from a\n * single source. Channels are the fundamental unit of telemetry storage and streaming\n * in Synnax.\n */\nexport const payloadZ = z.object({\n /**\n * key is the unique identifier for this channel, automatically assigned by Synnax.\n */\n key: keyZ.default(0),\n /** name is the human-readable channel name. */\n name: nameZ,\n /**\n * leaseholder is the node that holds the lease for this channel. Mostly for internal\n * use.\n */\n leaseholder: node.keyZ.default(0),\n /**\n * dataType is the data type of samples stored in this channel (e.g., float64, int32,\n * timestamp).\n */\n dataType: telem.dataTypeZ,\n /**\n * isIndex is true if this is an index channel. Index channels must have int64 values\n * (TIMESTAMP data type) written in ascending order, and are most commonly Unix\n * nanosecond timestamps.\n */\n isIndex: z.boolean().default(false),\n /**\n * index is the channel used to index this channel's values, associating each value\n * with a timestamp.\n */\n index: keyZ.default(0),\n /** alias is an optional alternate name for the channel within a specific context. */\n alias: z.string().optional(),\n /**\n * virtual is true if this channel does not store data in the database but can still\n * be used for streaming purposes.\n */\n virtual: z.boolean().default(false),\n /** internal is true if this is a system channel hidden from normal user queries. */\n internal: z.boolean().default(false),\n /**\n * expression is an Arc expression for calculated channels. If set, the channel is\n * automatically configured as virtual.\n */\n expression: z.string().default(\"\"),\n /**\n * operations contains optional aggregation operations (min, max, avg, derivative)\n * applied to channel data over time or triggered by a reset channel.\n */\n operations: operationZ.array().default(() => []),\n /**\n * concurrency sets the policy for concurrent writes to the channel's data. Only\n * virtual channels can have a policy of shared concurrency.\n */\n concurrency: control.concurrencyZ.default(control.Concurrency.exclusive),\n /** status is the current operational status of the channel. */\n status: statusZ.optional(),\n});\nexport interface Payload extends z.infer<typeof payloadZ> {}\nexport interface New extends z.input<typeof payloadZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"channel\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(0);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n type Key,\n keyZ,\n type Name,\n nameZ,\n ontologyID,\n type Payload,\n payloadZ,\n} from \"@/channel/types.gen\";\nimport { idToString } from \"@/ontology/payload\";\nimport {\n analyzeParams as baseAnalyzeParams,\n type ParamAnalysisResult,\n} from \"@/util/retrieve\";\n\n/** One or many channels, named by key or by name. */\nexport type PrimitiveParams = Key | Name | Key[] | Name[];\n\n/** Zod schema for {@link Params}, resolving every form to a key array. */\nexport const paramsZ = z.union([\n zod.toArray(keyZ),\n zod.toArray(nameZ),\n zod.toArray(payloadZ).transform((p) => p.map((c) => c.key)),\n]);\n/** Anything that names one or many channels. */\nexport type Params = PrimitiveParams | Payload | Payload[];\n\nconst CHAR_REGEX = /[a-zA-Z0-9_]/;\n\nconst VALID_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Rewrites a channel name into a valid identifier, replacing every other character with\n * an underscore and prefixing a leading digit.\n */\nexport const escapeInvalidName = (name: string, changeEmptyToUnderscore = false) => {\n if (name === \"\") return changeEmptyToUnderscore ? \"_\" : \"\";\n if (name.match(VALID_NAME_PATTERN)) return name;\n // if it doesn't match, convert non-alphanumeric characters to underscores and prepend\n // an underscore if the first character is a digit\n let result = \"\";\n for (const char of name)\n if (char.match(CHAR_REGEX)) result += char;\n else result += \"_\";\n if (result[0].match(/^\\d/)) result = `_${result}`;\n return result;\n};\n\n/** @returns the key of the status that reports on the given channel. */\nexport const statusKey = (channel: Key): string => idToString(ontologyID(channel));\n\n/**\n * Resolves channel params into a normalized array, reporting whether the caller named\n * one channel or many, and whether by key or by name.\n */\nexport const analyzeParams = (\n channels: Params,\n): ParamAnalysisResult<Key | Name, { number: \"keys\"; string: \"names\" }> => {\n if (Array.isArray(channels) && channels.length > 0 && typeof channels[0] === \"object\")\n channels = (channels as Payload[]).map((c) => c.key);\n else if (typeof channels === \"object\" && \"key\" in channels) channels = [channels.key];\n return baseAnalyzeParams(channels as PrimitiveParams, {\n number: \"keys\",\n string: \"names\",\n });\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Group is a named collection container for organizing related resources. Groups\n * provide hierarchical organization through the ontology system.\n */\nexport const groupZ = z.object({\n /** key is the unique identifier for this group. */\n key: keyZ,\n /** name is a human-readable name for the group. */\n name: z.string(),\n});\nexport interface Group extends z.infer<typeof groupZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"group\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, zod } from \"@synnaxlabs/x\";\nimport z from \"zod\";\n\nimport { type Group, groupZ, type Key, keyZ, ontologyID } from \"@/group/types.gen\";\nimport { ontology } from \"@/ontology\";\nimport { idZ as ontologyIDZ } from \"@/ontology/payload\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_group_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_group_delete\";\n\nconst resZ = z.object({ group: groupZ });\n\nconst createReqZ = z.object({\n parent: ontologyIDZ,\n key: keyZ.optional(),\n name: z.string(),\n});\n\nconst renameReqZ = z.object({ key: keyZ, name: z.string() });\n\nconst deleteReqZ = z.object({ keys: z.array(keyZ) });\n\nexport interface CreateParams extends z.infer<typeof createReqZ> {}\n\nconst retrieveChildrenParamsZ = z.object({\n parent: ontologyIDZ,\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n});\n\nexport type RetrieveSingleParams = { key: Key };\nexport type RetrieveChildrenParams = z.input<typeof retrieveChildrenParamsZ>;\nexport type RetrieveParams = RetrieveSingleParams | RetrieveChildrenParams;\n\ninterface ChildrenRequest extends z.infer<typeof retrieveChildrenParamsZ> {}\n\nconst isChildOf = (rel: ontology.Relationship, parent: ontology.ID): boolean =>\n ontology.matchRelationship(rel, {\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: { type: \"group\" },\n });\n\nexport interface ClientConfig {\n unary: UnaryClient;\n ontology: ontology.Client;\n cache: query.Cache;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveChildrenParamsZ,\n Key,\n Group\n> {\n /** Public so a client that deletes a group through an endpoint of its own can drop\n * the group from the cache. */\n readonly store: query.Table<Key, Group>;\n private readonly cfg: ClientConfig;\n\n constructor(cfg: ClientConfig) {\n const { cache, ontology: ontologyClient } = cfg;\n const store = cache.createTable<Key, Group>({\n name: \"groups\",\n fetch: async (keys) => await this.execRetrieveKeys(keys),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, groupZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"group\",\n table: store,\n request: {\n schema: retrieveChildrenParamsZ,\n fetch: async (req) => await this.fetchChildren(req),\n matches: (g, req) => this.isCachedChild(req.parent, g.key),\n watch: [\n query.watch(\n ontologyClient.cache.relationships,\n (event, req: ChildrenRequest) => {\n const rel =\n event.variant === \"set\"\n ? event.value\n : ontology.relationshipZ.parse(event.key);\n if (!isChildOf(rel, req.parent)) return null;\n return [rel.to.key];\n },\n ),\n ],\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(params: CreateParams): Promise<Group> {\n const res = await this.cfg.unary.send(\n \"/ontology/create-group\",\n params,\n createReqZ,\n resZ,\n );\n this.store.set(res.group);\n const rel: ontology.Relationship = {\n from: params.parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(res.group.key),\n };\n this.cfg.ontology.cache.relationships.set(ontology.relationshipToString(rel), rel);\n return res.group;\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/ontology/rename-group\",\n { key, name },\n renameReqZ,\n z.object({}),\n ),\n });\n rename();\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => this.store.delete(keysArr);\n await query.optimistic({\n rollbacks: [drop()],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/ontology/delete-group\",\n { keys: keysArr },\n deleteReqZ,\n z.object({}),\n ),\n });\n drop();\n }\n\n private isCachedChild(parent: ontology.ID, key: Key): boolean {\n return this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString({\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(key),\n }),\n );\n }\n\n private requireOntology(): ontology.Client {\n if (this.cfg.ontology == null)\n throw new Error(\"ontology client is not available on this client\");\n return this.cfg.ontology;\n }\n\n private async execRetrieveKeys(keys: Key[]): Promise<Group[]> {\n const res = await this.requireOntology().retrieve({\n ids: keys.map((key) => ontologyID(key)),\n });\n return res.map((r) => zod.parse(groupZ, r.data, { label: \"group\" }));\n }\n\n private async fetchChildren(req: ChildrenRequest): Promise<Group[]> {\n const { parent, ...options } = req;\n const res = await this.requireOntology().children.retrieve({\n ids: parent,\n ...options,\n types: [\"group\"],\n });\n const groups = res.map((r) => zod.parse(groupZ, r.data, { label: \"group\" }));\n const rels = this.cfg.ontology.cache.relationships;\n groups.forEach((g) => {\n const rel: ontology.Relationship = {\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(g.key),\n };\n rels.set(ontology.relationshipToString(rel), rel);\n });\n return groups;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/group/client\";\nexport * from \"@/group/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type change } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { type ontology } from \"@/ontology\";\nimport { type Alias } from \"@/ranger/alias/types.gen\";\nimport { type Key } from \"@/ranger/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_range_alias_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_range_alias_delete\";\n\nexport type AliasChange = change.Change<string, Alias>;\n\nconst SEPARATOR = \"---\";\n\nexport const createKey = (alias: Pick<Alias, \"range\" | \"channel\">): string =>\n `${alias.range}${SEPARATOR}${alias.channel}`;\n\nexport const ontologyID = (rangeKey: Key, channelKey: channel.Key): ontology.ID => ({\n type: \"range-alias\",\n key: createKey({ range: rangeKey, channel: channelKey }),\n});\n\nexport const TYPE_ONTOLOGY_ID: ontology.ID = { type: \"range-alias\", key: \"\" };\n\nexport interface DecodedDeleteAliasChange {\n range: Key;\n channel: channel.Key;\n}\n\nexport const decodeDeleteChange = (deletedAlias: string): DecodedDeleteAliasChange => {\n const [range, channel] = deletedAlias.split(SEPARATOR);\n return { range, channel: Number(channel) };\n};\n\n/** @deprecated Use {@link SET_CHANNEL_NAME} instead. */\nexport const SET_ALIAS_CHANNEL_NAME = SET_CHANNEL_NAME;\n/** @deprecated Use {@link DELETE_CHANNEL_NAME} instead. */\nexport const DELETE_ALIAS_CHANNEL_NAME = DELETE_CHANNEL_NAME;\n/** @deprecated Use {@link createKey} instead. */\nexport const aliasKey = createKey;\n/** @deprecated Use {@link decodeDeleteChange} instead. */\nexport const decodeDeleteAliasChange = decodeDeleteChange;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { color, telem, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { label } from \"@/label\";\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Payload is a user-defined region of time in the Synnax cluster. Ranges act as a\n * method for labeling and categorizing telemetry data within specific time periods.\n */\nexport const payloadZ = z.object({\n /** key is the unique identifier for this range. */\n key: keyZ,\n /** name is a human-readable name for the range. */\n name: z.string().min(1),\n /**\n * timeRange is the temporal extent of the range, defining its start and end\n * timestamps.\n */\n timeRange: telem.timeRangeBoundedZ,\n /**\n * color is an optional display color for visual identification of the range in user\n * interfaces.\n */\n color: color.colorZ.optional(),\n /**\n * labels contains optional labels attached to this range for categorization and\n * filtering.\n */\n labels: zod.nullToUndefined(label.labelZ.array()),\n /**\n * parent is an optional parent range for hierarchical organization. Ranges can be\n * nested within other ranges.\n */\n get parent(): z.ZodOptional<typeof payloadZ> {\n return payloadZ.optional();\n },\n});\nexport interface Payload extends z.infer<typeof payloadZ> {}\n\nexport const newZ = payloadZ\n .omit({ labels: true, parent: true })\n .partial({ key: true })\n .extend({\n parent: payloadZ.pick({ key: true }).optional(),\n });\nexport interface New extends z.input<typeof newZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"range\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport {\n array,\n control,\n type CrudeTimeRange,\n type CrudeTimeStamp,\n DataType,\n deep,\n type destructor,\n errors,\n type MultiSeries,\n primitive,\n type TypedArray,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n analyzeParams,\n type Params,\n type PrimitiveParams,\n statusKey,\n} from \"@/channel/payload\";\nimport {\n type Key,\n keyZ,\n type Name,\n type New,\n ontologyID,\n type Operation,\n operationZ,\n type Payload,\n payloadZ,\n statusZ,\n} from \"@/channel/types.gen\";\nimport { type Writer } from \"@/channel/writer\";\nimport { NotFoundError, ValidationError } from \"@/errors\";\nimport { type framer } from \"@/framer\";\nimport { group } from \"@/group\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { type ranger } from \"@/ranger\";\nimport { createKey, decodeDeleteChange } from \"@/ranger/alias/payload\";\nimport { keyZ as rangerKeyZ } from \"@/ranger/types.gen\";\nimport { type status } from \"@/status\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport const SET_CHANNEL_NAME = \"sy_channel_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_channel_delete\";\n\ninterface CreateOptions {\n retrieveIfNameExists?: boolean;\n}\n\n/**\n * Represents a Channel in a Synnax database. Typically, channels should not be\n * instantiated directly, but instead created via the `.channels.create` or retrieved\n * via the `.channels.retrieve` method on a Synnax client. Please refer to the [Synnax\n * documentation](https://docs.synnaxlabs.com/reference/concepts/channels) for detailed\n * information on what channels are and how to use them.\n */\nexport class Channel {\n private readonly frameClient: framer.Client | null;\n /**\n * A unique key identifying the channel in the Synnax database. This key is\n * automatically assigned by Synnax.\n */\n readonly key: Key;\n /**\n * A human-readable name for the channel. This name is not guaranteed to be unique.\n */\n readonly name: string;\n /** The data type of the channel. */\n readonly dataType: DataType;\n /**\n * The key of the node in the Synnax cluster that holds the 'lease' over the channel\n * i.e. it's the only node in the cluster allowed to accept writes to the channel. This\n * property is mostly for internal use.\n */\n readonly leaseholder: number;\n /**\n * The key of the index channel that this channel is associated with i.e. the channel\n * that stores its timestamps.\n */\n readonly index: Key;\n /** This is set to true if the channel is an index channel, and false otherwise. */\n readonly isIndex: boolean;\n /** This is set to true if the channel is an internal channel, and false otherwise. */\n readonly internal: boolean;\n /**\n * An alias for the channel under a specific range. This parameter is unstable and\n * should not be relied upon in the current version of Synnax.\n */\n alias: string | undefined;\n /**\n * Whether the channel is virtual. Virtual channels do not store any data in the\n * database, but can still be used for streaming purposes.\n */\n readonly virtual: boolean;\n /**\n * Only used for calculated channels. Specifies the Arc expression used to evaluate\n * the calculated value\n */\n readonly expression: string;\n readonly operations: Operation[];\n readonly concurrency: control.Concurrency;\n /** The status of the channel. */\n readonly status?: status.Status;\n\n constructor({\n dataType,\n name,\n leaseholder = 0,\n key = 0,\n isIndex = false,\n index = 0,\n internal = false,\n virtual = false,\n frameClient,\n alias,\n status: argsStatus,\n expression = \"\",\n operations = [],\n concurrency = control.Concurrency.exclusive,\n }: New & { frameClient?: framer.Client }) {\n this.key = zod.parse(keyZ, key, { label: \"channel key\" });\n this.name = name;\n this.dataType = new DataType(dataType);\n this.leaseholder = leaseholder;\n this.index = zod.parse(keyZ, index, { label: \"channel index\" });\n this.isIndex = isIndex;\n this.internal = internal;\n this.alias = alias;\n this.virtual = virtual;\n this.expression = expression;\n this.operations = zod.parse(operationZ.array(), operations, {\n label: \"channel operations\",\n });\n this.concurrency = concurrency;\n if (argsStatus != null)\n this.status = zod.parse(statusZ, argsStatus, { label: \"channel status\" });\n this.frameClient = frameClient ?? null;\n }\n\n private get framer(): framer.Client {\n if (this.frameClient == null)\n throw new ValidationError(\"cannot read from a channel that has not been created\");\n return this.frameClient;\n }\n\n /**\n * Returns the payload representation of this channel i.e. a pure JS object with\n * all of the channel fields but without any methods. This is used internally for\n * network transportation, but also provided to you as a convenience.\n */\n get payload(): Payload {\n return zod.parse(\n payloadZ,\n {\n key: this.key,\n name: this.name,\n dataType: this.dataType.valueOf(),\n leaseholder: this.leaseholder,\n index: this.index,\n isIndex: this.isIndex,\n internal: this.internal,\n virtual: this.virtual,\n expression: this.expression,\n status: this.status,\n operations: this.operations,\n concurrency: this.concurrency,\n },\n { label: \"channel payload\" },\n );\n }\n\n get isCalculated(): boolean {\n return isCalculated(this.payload);\n }\n\n /** @returns the ontology ID of the channel */\n get ontologyID(): ontology.ID {\n return ontologyID(this.key);\n }\n\n /**\n * Reads telemetry from the channel between the two timestamps.\n * @returns A typed array containing the retrieved\n */\n async read(tr: CrudeTimeRange): Promise<MultiSeries> {\n return await this.framer.read(tr, this.key);\n }\n\n /**\n * Writes telemetry to the channel starting at the given timestamp.\n * @param start - The starting timestamp of the first sample in data.\n */\n async write(start: CrudeTimeStamp, data: TypedArray): Promise<void> {\n return await this.framer.write(start, this.key, data);\n }\n}\n\n/** Zod schema for {@link RetrieveRequest}. */\nexport const retrieveRequestZ = z.object({\n nodeKey: zod.uint12.optional(),\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n searchTerm: z.string().optional(),\n rangeKey: rangerKeyZ.optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n dataTypes: DataType.z.array().optional(),\n notDataTypes: DataType.z.array().optional(),\n virtual: z.boolean().optional(),\n isIndex: z.boolean().optional(),\n internal: z.boolean().optional(),\n legacyCalculated: z.boolean().optional(),\n});\n/** Everything a channel retrieval can filter on. */\nexport type RetrieveRequest = z.input<typeof retrieveRequestZ>;\n\n/** The filters a retrieval accepts alongside its keys or names. */\nexport type RetrieveOptions = Omit<RetrieveRequest, \"keys\" | \"names\" | \"search\">;\n\nconst retrieveResZ = z.object({ channels: payloadZ.array().default(() => []) });\n\nconst retrieveGroupReqZ = z.object({});\n\nconst retrieveGroupResZ = z.object({ group: group.groupZ });\n\n/** Names one channel. Give a `rangeKey` to resolve its alias in that range. */\nexport type RetrieveSingleParams = { key: Key; rangeKey?: ranger.Key };\n\ntype NormalizedRequest = z.infer<typeof retrieveRequestZ>;\n\n/** Aliases and statuses are composed from their stores on read. */\nconst stripComposed = ({ alias: _alias, status: _status, ...rest }: Payload): Payload =>\n rest;\n\nconst normalizeSingle = ({\n key,\n rangeKey,\n}: RetrieveSingleParams): RetrieveSingleParams =>\n rangeKey == null ? { key } : { key, rangeKey };\n\nconst singleParamsZ = z\n .union([\n z.strictObject({ key: z.uint32(), rangeKey: rangerKeyZ.optional() }),\n z.uint32().transform((key) => ({ key })),\n ])\n .transform(normalizeSingle);\n\nconst onlyRangeKey = (options?: RetrieveOptions): boolean =>\n options == null ||\n Object.entries(options).every(([k, v]) => v === undefined || k === \"rangeKey\");\n\nconst isKeysOnly = (\n req: NormalizedRequest,\n): req is NormalizedRequest & { keys: Key[] } =>\n primitive.isNonZero(req.keys) &&\n req.names == null &&\n req.searchTerm == null &&\n req.nodeKey == null &&\n req.limit == null &&\n req.offset == null &&\n req.dataTypes == null &&\n req.notDataTypes == null &&\n req.virtual == null &&\n req.isIndex == null &&\n req.internal == null &&\n req.legacyCalculated == null;\n\nconst isNamesOnly = (\n req: NormalizedRequest,\n): req is NormalizedRequest & { names: string[] } =>\n primitive.isNonZero(req.names) &&\n req.keys == null &&\n req.searchTerm == null &&\n req.nodeKey == null &&\n req.limit == null &&\n req.offset == null &&\n req.dataTypes == null &&\n req.notDataTypes == null &&\n req.virtual == null &&\n req.isIndex == null &&\n req.internal == null &&\n req.legacyCalculated == null;\n\nconst NAME_LITERAL_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Mirrors the server's name matching: literal names compare exactly, anything\n * else compiles as a regular expression, anchored when unanchored.\n */\nconst createNameMatcher = (pattern: string): ((name: string) => boolean) => {\n if (NAME_LITERAL_PATTERN.test(pattern)) return (name) => name === pattern;\n const anchored =\n pattern.startsWith(\"^\") || pattern.endsWith(\"$\") ? pattern : `^${pattern}$`;\n try {\n const rx = new RegExp(anchored);\n return (name) => rx.test(name);\n } catch {\n return (name) => name === pattern;\n }\n};\n\n/**\n * Client-side matching for a request over every locally evaluable field.\n * Server-computed shapes (search, pagination) never reach this filter; they\n * refetch instead.\n */\nconst requestFilter = (req: NormalizedRequest): ((ch: Channel) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const nameMatchers = primitive.isNonZero(req.names)\n ? req.names.map(createNameMatcher)\n : undefined;\n return (ch) => {\n if (keySet != null && !keySet.has(ch.key)) return false;\n if (nameMatchers != null && !nameMatchers.some((m) => m(ch.name))) return false;\n if (primitive.isNonZero(req.nodeKey) && ch.leaseholder !== req.nodeKey)\n return false;\n // The server's virtual bucket excludes calculated channels even though\n // they are stored with virtual=true.\n if (req.virtual != null && (ch.virtual && !ch.isCalculated) !== req.virtual)\n return false;\n if (req.isIndex != null && ch.isIndex !== req.isIndex) return false;\n if (req.internal != null && ch.internal !== req.internal) return false;\n if (\n primitive.isNonZero(req.dataTypes) &&\n !req.dataTypes.some((dt) => dt.equals(ch.dataType))\n )\n return false;\n if (\n primitive.isNonZero(req.notDataTypes) &&\n req.notDataTypes.some((dt) => dt.equals(ch.dataType))\n )\n return false;\n return true;\n };\n};\n\n// Channel statuses live in the status table under the \"channel:<key>\" status key.\nconst affectedChannelKeys = (\n event: query.TableEvent<status.Key, status.Status>,\n): Key[] | null => {\n const [type, key] = event.key.split(\":\");\n if (type !== \"channel\" || !primitive.isNonZero(key)) return null;\n const parsed = keyZ.safeParse(key);\n return parsed.success ? [parsed.data] : null;\n};\n\n/**\n * The main client class for executing channel operations against a Synnax Core. This\n * class should not be instantiated directly, and instead should be used through the\n * `channels` property of an {@link Synnax} client.\n */\nexport interface ClientConfig {\n framer: framer.Client;\n unary: UnaryClient;\n writer: Writer;\n statuses: status.Client;\n ranges: ranger.Client;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\n/**\n * Creates, reads, and deletes channels on a Core. Reach it through `client.channels`.\n * Retrievals are served from a cache that a change stream keeps current, so a repeated\n * read costs nothing.\n */\nexport class Client extends query.Retriever<\n typeof retrieveRequestZ,\n Key,\n Channel,\n Channel,\n RetrieveSingleParams,\n RetrieveSingleParams\n> {\n private readonly cfg: ClientConfig;\n readonly writer: Writer;\n readonly store: query.Table<Key, Channel>;\n\n constructor(cfg: ClientConfig) {\n const { writer, statuses, ranges, cache } = cfg;\n const statusStore = statuses.store;\n const aliasStore = ranges.aliases;\n const sugar = (payload: Payload): Channel => this.sugar(payload);\n const store = cache.createTable<Key, Channel>({\n name: \"channels\",\n equal: (a, b) => deep.equal(a.payload, b.payload),\n fetch: async (keys) =>\n (await this.execRetrieve(keys)).map((p) => sugar(stripComposed(p))),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, payloadZ, {\n value: (changed) => sugar(stripComposed(changed)),\n }),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n const composed = cache.derive<Key, Channel, Channel>({\n name: \"channel.composed\",\n source: store,\n compose: (record) => this.compose(record.payload),\n equal: (a, b) => deep.equal(a.payload, b.payload),\n watch: [query.deriveWatch(statusStore, (event) => affectedChannelKeys(event))],\n });\n const single = cache.queries<RetrieveSingleParams, Channel, Key, Channel>({\n name: \"channel\",\n table: composed,\n fetch: async (query) => [(await this.fetchSingle(query)).key],\n // Composed rows carry status; the read-time step only glues the alias.\n compose: (records, query) =>\n query.rangeKey == null\n ? records[0]\n : this.composeAlias(records[0].payload, query.rangeKey),\n keyOf: (query) => query.key,\n single: true,\n watch: [\n query.watch(aliasStore, (event, query: RetrieveSingleParams) => {\n if (query.rangeKey == null) return null;\n const aliasKey = createKey({ range: query.rangeKey, channel: query.key });\n return event.key === aliasKey ? [query.key] : null;\n }),\n ],\n });\n super(cache, {\n name: \"channel\",\n table: store,\n request: {\n schema: retrieveRequestZ,\n fetch: async (query) => await this.fetchRequest(query),\n matches: (ch, query) => requestFilter(query)(ch),\n watch: [\n query.watch(aliasStore, (event, query: NormalizedRequest) => {\n if (query.rangeKey == null) return null;\n if (event.variant === \"set\")\n return event.value.range === query.rangeKey\n ? [event.value.channel]\n : null;\n const decoded = decodeDeleteChange(event.key);\n return decoded.range === query.rangeKey ? [decoded.channel] : null;\n }),\n ],\n },\n compose: (ch, query) => {\n const { rangeKey } = query as NormalizedRequest;\n return rangeKey == null ? ch : this.composeAlias(ch.payload, rangeKey);\n },\n single: { schema: singleParamsZ, space: single },\n });\n this.cfg = cfg;\n this.writer = writer;\n this.store = store;\n }\n\n /**\n * Creates a single channel with the given properties.\n * @param name - A human-readable name for the channel.\n * @param rate - The rate of the channel. This only applies to fixed rate channels.\n * @param dataType - The data type for the samples stored in the channel.\n * @param index - The key of the index channel that this channel should be associated\n * with. An 'index' channel is a channel that stores timestamps for other channels.\n * Refer to the Synnax documentation\n * (https://docs.synnaxlabs.com/reference/concepts/channels) for more information. The\n * index channel must have already been created. This field does not need to be\n * specified if the channel is an index channel, or the channel is a fixed rate\n * channel. If this value is specified, the 'rate' parameter will be ignored.\n * @param isIndex - Set to true if the channel is an index channel, and false\n * otherwise. Index channels must have a data type of `DataType.TIMESTAMP`.\n * @returns the created channel. {@link Channel}\n * @throws {ValidationError} if any of the parameters for creating the channel are\n * invalid.\n *\n * @example\n * ```typescript\n * const indexChannel = await client.channels.create({\n * name: \"time\",\n * dataType: DataType.TIMESTAMP,\n * isIndex: true,\n * })\n *\n *\n * const dataChannel = await client.channels.create({\n * name: \"temperature\",\n * dataType: DataType.FLOAT,\n * index: indexChannel.key,\n * });\n * ```\n */\n async create(channel: New, options?: CreateOptions): Promise<Channel>;\n\n /**\n * Creates multiple channels with the given properties. The order of the channels\n * returned is guaranteed to match the order of the channels passed in.\n * @param channels - An array of channel properties to create. For each channel, the\n * following properties should be considered:\n * @param name - A human-readable name for the channel.\n * @param rate - The rate of the channel. This only applies to fixed rate channels. If\n * the 'index' parameter is specified or 'isIndex' is set to true, this parameter will\n * be ignored.\n * @param dataType - The data type for the samples stored in the channel.\n * @param index - The key of the index channel that this channel should be associated\n * with. An 'index' channel is a channel that stores timestamps for other channels.\n * Refer to the Synnax documentation (https://docs.synnaxlabs.com) for more\n * information. The index channel must have already been created. This field does not\n * need to be specified if the channel is an index channel, or the channel is a fixed\n * rate channel. If this value is specified, the 'rate' parameter will be ignored.\n * @param isIndex - Set to true if the channel is an index channel, and false\n * otherwise. Index channels must have a data type of `DataType.TIMESTAMP`.\n */\n async create(channels: New[], options?: CreateOptions): Promise<Channel[]>;\n\n async create(\n channels: New | New[],\n options: CreateOptions = {},\n ): Promise<Channel | Channel[]> {\n const { retrieveIfNameExists = false } = options;\n const single = !Array.isArray(channels);\n let toCreate = array.toArray(channels);\n let created: Channel[] = [];\n if (retrieveIfNameExists) {\n const res = await this.execRetrieve(toCreate.map((c) => c.name));\n const existingNames = new Set(res.map((c) => c.name));\n toCreate = toCreate.filter((c) => !existingNames.has(c.name));\n created = this.sugar(res);\n }\n created = created.concat(this.sugar(await this.writer.create(toCreate)));\n this.store.set(created.map((ch) => this.sugar(stripComposed(ch.payload))));\n return single ? created[0] : created;\n }\n\n /**\n * Retrieves a channel from the database using the given key or name.\n * @param options - Optional parameters to control the retrieval process.\n * @param options.dataTypes - Limits the query to only channels with the specified\n * data type.\n * @param options.notDataTypes - Limits the query to only channels without the\n * specified data type.\n * @returns The retrieved channel.\n * @throws {NotFoundError} if the channel does not exist in the cluster.\n * @throws {MultipleFoundError} is only thrown if the channel is retrieved by name,\n * and multiple channels with the same name exist in the cluster.\n *\n * @example\n *\n * ```typescript\n * const channel = await client.channels.retrieve(\"temperature\");\n * const channel = await client.channels.retrieve(1);\n * ```\n */\n async retrieve(params: Key | Name, options?: RetrieveOptions): Promise<Channel>;\n\n /**\n * Retrieves multiple channels from the database using the provided keys or the\n * provided names.\n * @param params - The keys or the names of the channels to retrieve. Note that this\n * method does not support mixing keys and names in the same call.\n * @param options - Optional parameters to control the retrieval process.\n * @param options.dataTypes - Limits the query to only channels with the specified\n * data type.\n * @param options.notDataTypes - Limits the query to only channels without the\n * specified\n */\n async retrieve(params: Key | string, options?: RetrieveOptions): Promise<Channel>;\n\n async retrieve(\n params: PrimitiveParams | Payload[],\n options?: RetrieveOptions,\n ): Promise<Channel[]>;\n\n async retrieve(params: RetrieveSingleParams): Promise<Channel>;\n\n async retrieve(params: RetrieveRequest): Promise<Channel[]>;\n\n /**\n * Retrieves a channel from the database using the given parameters.\n *\n * this will be ignored.\n * @returns The retrieved channel.\n * @raises {QueryError} If the channel does not exist or if multiple results are returned.\n */\n async retrieve(\n params: PrimitiveParams | Payload[] | RetrieveSingleParams | RetrieveRequest,\n options?: RetrieveOptions,\n ): Promise<Channel | Channel[]> {\n if (typeof params === \"object\" && !Array.isArray(params))\n return await super.retrieve(params);\n const isSingle = !Array.isArray(params);\n const { variant, normalized: rawNormalized } = analyzeParams(params);\n const normalized =\n variant === \"keys\" ? rawNormalized.filter((k) => k !== 0) : rawNormalized;\n if (normalized.length === 0) {\n checkForMultipleOrNoResults<Params, Channel>(\"channel\", params, [], isSingle);\n return [];\n }\n if (isSingle && variant === \"keys\" && onlyRangeKey(options))\n return await super.retrieve({\n key: normalized[0] as Key,\n rangeKey: options?.rangeKey,\n });\n const res = await super.retrieve(\n zod.parse(\n retrieveRequestZ,\n { [variant]: normalized, ...options },\n { label: \"channel retrieve request\" },\n ),\n );\n checkForMultipleOrNoResults<Params, Channel>(\"channel\", params, res, isSingle);\n return isSingle ? res[0] : res;\n }\n\n /** * Deletes channels from the database using the given keys or names. */\n async delete(params: Params, opts: query.WriteOptions = {}): Promise<void> {\n const { normalized, variant } = analyzeParams(params);\n if (variant === \"keys\") {\n const keys = normalized;\n const ids = ontologyID(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ids),\n this.store.delete(keys),\n this.cfg.ontology.cache.resources.delete(ontology.idToString(ids)),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.writer.delete({ keys }),\n });\n drop();\n return;\n }\n const names = normalized;\n await this.writer.delete({ names });\n const cached = this.store.get((ch) => names.includes(ch.name));\n if (cached.length > 0) this.store.delete(cached.map((ch) => ch.key));\n }\n\n async rename(key: Key, name: string, opts?: query.WriteOptions): Promise<void>;\n async rename(keys: Key[], names: string[], opts?: query.WriteOptions): Promise<void>;\n async rename(\n keys: Key | Key[],\n names: string | string[],\n opts: query.WriteOptions = {},\n ): Promise<void> {\n const keysArr = array.toArray(keys);\n const namesArr = array.toArray(names);\n const rename = () =>\n keysArr.flatMap((key, i) => {\n const name = namesArr[i];\n return [\n this.renameThrough(key, name),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n });\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.writer.rename(keysArr, namesArr),\n });\n rename();\n }\n\n /** Renames the cached channel, skipping when absent. Returns a rollback. */\n private renameThrough(key: Key, name: string): destructor.Destructor {\n return this.store.set(key, (p) =>\n p == null ? undefined : this.sugar({ ...p.payload, name }),\n );\n }\n\n sugar(payload: Payload): Channel;\n sugar(payloads: Payload[]): Channel[];\n sugar(payloads: Payload | Payload[]): Channel | Channel[] {\n const { framer: frameClient } = this.cfg;\n if (Array.isArray(payloads))\n return payloads.map((p) => new Channel({ ...p, frameClient }));\n return new Channel({ ...payloads, frameClient });\n }\n\n async retrieveGroup(): Promise<group.Group> {\n const res = await this.cfg.unary.send(\n \"/channel/retrieve-group\",\n {},\n retrieveGroupReqZ,\n retrieveGroupResZ,\n );\n return res.group;\n }\n\n /** Rebuilds a cached channel with its cached status attached. */\n private compose(payload: Payload): Channel {\n const next: Payload = { ...payload, status: undefined, alias: undefined };\n if (isCalculated(payload)) {\n const parsed = statusZ.safeParse(\n this.cfg.statuses.store.get(statusKey(payload.key)),\n );\n if (parsed.success) next.status = parsed.data;\n }\n return this.sugar(next);\n }\n\n private composeAlias(payload: Payload, rangeKey: ranger.Key): Channel {\n return this.sugar({\n ...payload,\n alias: this.cfg.ranges.aliases.get(\n createKey({ range: rangeKey, channel: payload.key }),\n )?.alias,\n });\n }\n\n /** Fetches aliases under the range for keys the alias store has no entry for. */\n private async ensureAliases(rangeKey: ranger.Key, keys: Key[]): Promise<void> {\n const missing = keys.filter(\n (key) =>\n !this.cfg.ranges.aliases.has(createKey({ range: rangeKey, channel: key })),\n );\n if (missing.length === 0) return;\n const fetched = await this.cfg.ranges.retrieveAliases(rangeKey, missing);\n Object.entries(fetched).forEach(([channel, alias]) => {\n const entry: ranger.alias.Alias = {\n range: rangeKey,\n channel: Number(channel),\n alias,\n };\n this.cfg.ranges.aliases.set(createKey(entry), entry);\n });\n }\n\n /** Fetches channel payloads. Missing channels are omitted, not thrown. */\n private async execRetrieve(\n channels: Params | RetrieveRequest,\n options?: RetrieveOptions,\n ): Promise<Payload[]> {\n let request: RetrieveRequest;\n if (\n !Array.isArray(channels) &&\n typeof channels === \"object\" &&\n !(\"key\" in channels)\n )\n request = channels;\n else {\n const { variant, normalized: raw } = analyzeParams(channels);\n const normalized = raw.filter((k) => k !== 0);\n if (normalized.length === 0) return [];\n request = { [variant]: normalized, ...options };\n }\n const res = await this.cfg.unary.send(\n \"/channel/retrieve\",\n request,\n retrieveRequestZ,\n retrieveResZ,\n );\n return res.channels;\n }\n\n private async fetchSingle(query: RetrieveSingleParams): Promise<Channel> {\n const { key, rangeKey } = query;\n let ch = this.store.get(key);\n if (ch == null) {\n const payloads = await this.execRetrieve([key]);\n checkForMultipleOrNoResults(\"channel\", key, payloads, true);\n ch = this.sugar(stripComposed(payloads[0]));\n this.store.set(key, ch);\n }\n // A cached calculated channel without a cached status is ambiguous: the\n // status may not exist, or may simply never have been fetched.\n if (ch.isCalculated && !this.cfg.statuses.store.has(statusKey(key)))\n try {\n await this.cfg.statuses.retrieve(statusKey(key));\n } catch (e) {\n if (!NotFoundError.matches(e)) throw errors.fromUnknown(e);\n }\n if (rangeKey != null) await this.ensureAliases(rangeKey, [key]);\n return ch;\n }\n\n /**\n * Resolves literal names against the record store, fetching only the names it\n * cannot resolve. A name matching two stored channels is ambiguous, which only\n * a cluster running without name validation can produce, so the whole request\n * falls through to the cluster. Returns null when the store cannot be trusted\n * to answer any part of the request.\n */\n private async resolveNames(names: string[]): Promise<Channel[] | null> {\n if (!names.every((name) => NAME_LITERAL_PATTERN.test(name))) return null;\n const resolved: Channel[] = [];\n const missing: string[] = [];\n for (const name of new Set(names)) {\n const matches = this.store.get((ch) => ch.name === name);\n if (matches.length > 1) return null;\n if (matches.length === 0) missing.push(name);\n else resolved.push(matches[0]);\n }\n if (missing.length === 0) return resolved;\n const fetched = (await this.execRetrieve({ names: missing })).map((p) =>\n this.sugar(stripComposed(p)),\n );\n return [...resolved, ...fetched];\n }\n\n private async fetchRequest(query: NormalizedRequest): Promise<Channel[]> {\n const { rangeKey } = query;\n let channels: Channel[] | null = null;\n if (isKeysOnly(query)) channels = await this.store.retrieve(query.keys);\n else if (isNamesOnly(query)) channels = await this.resolveNames(query.names);\n channels ??= (await this.execRetrieve(query)).map((p) =>\n this.sugar(stripComposed(p)),\n );\n if (rangeKey != null)\n await this.ensureAliases(\n rangeKey,\n channels.map((ch) => ch.key),\n );\n return channels;\n }\n}\n\n/** @returns whether the channel computes its samples from an expression. */\nexport const isCalculated = ({ virtual, expression }: Payload): boolean =>\n virtual && expression !== \"\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { type DataType } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport {\n type Key,\n keyZ,\n nameZ,\n type New,\n type Payload,\n payloadZ,\n} from \"@/channel/types.gen\";\n\nconst createReqZ = z.object({ channels: payloadZ.array() });\nconst createResZ = z.object({ channels: payloadZ.array() });\n\nconst deleteReqZ = z.object({\n keys: keyZ.array().optional(),\n names: nameZ.array().optional(),\n});\nconst deleteResZ = z.object({});\n\nconst renameReqZ = z.object({ keys: keyZ.array(), names: nameZ.array() });\nconst renameResZ = z.object({});\n\nexport interface DeleteProps extends z.input<typeof deleteReqZ> {}\nexport interface RenameProps extends z.input<typeof renameReqZ> {}\n\nexport class Writer {\n private readonly client: UnaryClient;\n\n constructor(client: UnaryClient) {\n this.client = client;\n }\n\n async create(channels: New[]): Promise<Payload[]> {\n const { channels: created } = await this.client.send(\n \"/channel/create\",\n {\n channels: channels.map((c) => ({\n ...c,\n dataType: c.dataType as DataType,\n })),\n },\n createReqZ,\n createResZ,\n );\n return created;\n }\n\n async delete(props: DeleteProps): Promise<void> {\n await this.client.send(\"/channel/delete\", props, deleteReqZ, deleteResZ);\n }\n\n async rename(keys: Key[], names: string[]): Promise<void> {\n await this.client.send(\"/channel/rename\", { keys, names }, renameReqZ, renameResZ);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/channel/client\";\nexport * from \"@/channel/payload\";\nexport * from \"@/channel/types.gen\";\nexport * from \"@/channel/writer\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Middleware, type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { errors, TimeStamp } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { AuthError, ExpiredTokenError, InvalidTokenError } from \"@/errors\";\nimport { user } from \"@/user\";\n\nconst credentialsZ = z.object({ username: z.string(), password: z.string() });\nexport interface Credentials extends z.infer<typeof credentialsZ> {}\n\nconst clusterInfoZ = z.object({\n clusterKey: z.string(),\n nodeVersion: z.string().optional(),\n nodeKey: z.number().optional(),\n nodeTime: TimeStamp.z,\n});\n\nconst tokenResponseZ = z.object({\n token: z.string(),\n user: user.userZ,\n clusterInfo: clusterInfoZ.optional(),\n});\n\nexport const LOGIN_ENDPOINT = \"/auth/login\";\n\nconst MAX_RETRIES = 3;\n\nconst changePasswordReqZ = z.object({\n username: z.string(),\n password: z.string(),\n newPassword: z.string().min(1),\n});\nconst changePasswordResZ = z.object({});\n\nconst RETRY_ON = [InvalidTokenError, ExpiredTokenError] as const;\n\ntype AuthState =\n { authenticated: false } | { authenticated: true; user: user.User; token: string };\n\n/** Login outcome hooks. The connection machine is the sole consumer. */\nexport interface Observer {\n /** Fires after every successful login. */\n onSuccess?: () => void;\n /** Fires on a definitive credential rejection, never on token self-heal. */\n onFailure?: (error: Error) => void;\n}\n\nexport class Client {\n private readonly client: UnaryClient;\n private readonly credentials: Credentials;\n private readonly observer: Observer;\n private authState: AuthState = { authenticated: false };\n authenticating: Promise<Error | null> | undefined;\n private retryCount: number;\n private generation = 0;\n\n constructor(client: UnaryClient, credentials: Credentials, observer: Observer = {}) {\n this.client = client;\n this.credentials = credentials;\n this.observer = observer;\n this.retryCount = 0;\n }\n\n /** Replaces the stored credentials and clears auth state for a fresh login. */\n setCredentials({ username, password }: Credentials): void {\n this.credentials.username = username;\n this.credentials.password = password;\n this.authState = { authenticated: false };\n this.authenticating = undefined;\n this.retryCount = 0;\n this.generation += 1;\n }\n\n get authenticated(): boolean {\n return this.authState.authenticated;\n }\n\n get user(): user.User | undefined {\n return this.authState.authenticated ? this.authState.user : undefined;\n }\n\n get token(): string | undefined {\n return this.authState.authenticated ? this.authState.token : undefined;\n }\n\n async retrieveUser(): Promise<user.User> {\n if (!this.authState.authenticated) await this.authenticating;\n const { authState } = this;\n if (!authState.authenticated)\n throw new Error(\"Authentication failed: user not available\");\n return authState.user;\n }\n\n async changePassword(newPassword: string): Promise<void> {\n if (!this.authenticated) throw new Error(\"Not authenticated\");\n await this.client.send(\n \"/auth/change-password\",\n {\n username: this.credentials.username,\n password: this.credentials.password,\n newPassword,\n },\n changePasswordReqZ,\n changePasswordResZ,\n );\n this.credentials.password = newPassword;\n }\n\n middleware(): Middleware {\n const mw: Middleware = async (reqCtx, next) => {\n if (!this.authenticated && !reqCtx.target.endsWith(LOGIN_ENDPOINT)) {\n this.authenticating ??= (async (): Promise<Error | null> => {\n // logins issued before a setCredentials are stale; their result must\n // not reach the observer\n const generation = this.generation;\n try {\n const res = await this.client.send(\n LOGIN_ENDPOINT,\n this.credentials,\n credentialsZ,\n tokenResponseZ,\n );\n if (generation !== this.generation) return null;\n this.authState = {\n authenticated: true,\n user: res.user,\n token: res.token,\n };\n this.observer.onSuccess?.();\n return null;\n } catch (err) {\n const parsed = errors.fromUnknown(err);\n if (generation === this.generation && AuthError.matches(parsed))\n this.observer.onFailure?.(parsed);\n return parsed;\n }\n })();\n const err = await this.authenticating;\n if (err != null) {\n // clear the memoized failure so the next request retries the login\n this.authenticating = undefined;\n throw err;\n }\n }\n reqCtx.params.Authorization = `Bearer ${this.token}`;\n try {\n const resCtx = await next(reqCtx);\n this.retryCount = 0;\n return resCtx;\n } catch (err) {\n if (RETRY_ON.some((e) => e.matches(err)) && this.retryCount < MAX_RETRIES) {\n this.authState = { authenticated: false };\n this.authenticating = undefined;\n this.retryCount += 1;\n return await mw(reqCtx, next);\n }\n this.retryCount = 0;\n throw errors.fromUnknown(err);\n }\n };\n return mw;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type CrudeTimeSpan,\n deep,\n type destructor,\n id,\n migrate,\n observe,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { AuthError, DisconnectedError } from \"@/errors\";\nimport { status } from \"@/status\";\n\nexport const REASONS = [\"unreachable\", \"auth\", \"incompatible\"] as const;\nexport const reasonZ = z.enum(REASONS);\n/** Why the connection is in the error variant. */\nexport type Reason = z.infer<typeof reasonZ>;\n\n/** The fact vector beneath the connection's status variant. */\nexport const statusDetailsZ = z.object({\n error: z.instanceof(Error).optional(),\n authenticated: z.boolean(),\n streamLive: z.boolean(),\n // The cluster refused the change stream. Unary calls the user is allowed to\n // make still work; live updates do not arrive.\n streamDenied: z.boolean(),\n epoch: z.number(),\n clusterKey: z.string(),\n clientVersion: z.string(),\n nodeVersion: z.string().optional(),\n clientServerCompatible: z.boolean(),\n clockSkew: TimeSpan.z,\n clockSkewExceeded: z.boolean(),\n retry: z.object({ attempt: z.number(), nextAt: TimeStamp.z }).nullable(),\n // A check is in flight right now. A process fact, not a judgment: the\n // variant holds its verdict while attempts run beneath it.\n checking: z.boolean(),\n});\nexport interface StatusDetails extends z.infer<typeof statusDetailsZ> {}\n\n/** Error-variant details: the same facts plus the reason the connection failed. */\nexport const errorStatusDetailsZ = statusDetailsZ.extend({ reason: reasonZ });\nexport interface ErrorStatusDetails extends z.infer<typeof errorStatusDetailsZ> {}\n\nexport const nonErrorVariantZ = z.enum([\n \"success\",\n \"info\",\n \"warning\",\n \"loading\",\n \"disabled\",\n]);\n\n/**\n * The connection status: a standard status whose details carry the connection's\n * facts. Renders anywhere a status does, with no translation. Discriminated on\n * variant: `reason` exists only on the error member.\n */\nexport const statusZ = z.discriminatedUnion(\"variant\", [\n status.statusZ({ v: status.errorVariantZ, details: errorStatusDetailsZ }),\n status.statusZ({ v: nonErrorVariantZ, details: statusDetailsZ }),\n]);\nexport type ErrorStatus = status.Status<\n typeof errorStatusDetailsZ,\n typeof status.errorVariantZ\n>;\nexport type NonErrorStatus = status.Status<\n typeof statusDetailsZ,\n typeof nonErrorVariantZ\n>;\nexport type Status = ErrorStatus | NonErrorStatus;\n\nconst DEFAULT_STATUS_DETAILS: StatusDetails = {\n authenticated: false,\n streamLive: false,\n streamDenied: false,\n epoch: 0,\n clusterKey: \"\",\n clientVersion: __VERSION__,\n clientServerCompatible: false,\n clockSkew: TimeSpan.ZERO,\n clockSkewExceeded: false,\n retry: null,\n checking: false,\n};\n\n/** The status of a client that does not exist. */\nexport const DEFAULT_STATUS: Status = {\n key: \"connection\",\n name: \"Connection\",\n variant: \"disabled\",\n message: \"Disconnected\",\n description: \"\",\n time: TimeStamp.ZERO,\n details: DEFAULT_STATUS_DETAILS,\n};\n\n/** Consecutive check failures before escalating to error(unreachable). */\nexport const DEFAULT_ESCALATE_AFTER = 4;\n\nexport interface Config {\n clientVersion: string;\n /** Human-readable cluster name for status messages. */\n name?: string;\n escalateAfter: number;\n clockSkewThreshold: TimeSpan;\n /** Whether success requires a live change stream. */\n requiresStream: boolean;\n}\n\n/**\n * The consumer-facing view of a client's connection. Read {@link Handle.status}\n * or subscribe via {@link Handle.onChange}; the client owns every transition.\n */\nexport interface Handle {\n /** The current connection status. */\n readonly status: Status;\n /** Subscribes to status changes. Returns a destructor that unsubscribes. */\n onChange: (callback: (status: Status) => void) => destructor.Destructor;\n /**\n * Resets the retry backoff and checks immediately. Auth and incompatibility\n * errors are not cleared: those rest until the user supplies something new.\n */\n retryNow: () => void;\n}\n\nconst isSettled = ({ variant }: Status): boolean =>\n variant === \"success\" ||\n variant === \"warning\" ||\n variant === \"error\" ||\n variant === \"disabled\";\n\n/**\n * Resolves once the connection is usable: success, or warning when the cluster\n * refuses live updates. Rejects with the stored failure when it settles on an\n * error variant or is closed. The current status is evaluated first, so an\n * already-connected handle resolves without waiting.\n * @throws {Error} if the timeout elapses first.\n */\nexport const awaitConnected = async (\n handle: Handle,\n timeout?: CrudeTimeSpan,\n): Promise<Status> => {\n const settled = await observe.until(handle, () => handle.status, isSettled, timeout);\n if (settled.variant !== \"success\" && settled.variant !== \"warning\")\n throw settled.details.error ?? new DisconnectedError(settled.message);\n return settled;\n};\n\n/** The facts a single connectivity check yields. */\nexport interface Info {\n clusterKey: string;\n nodeVersion: string;\n /** Skew measured across the check's round trip. */\n clockSkew: TimeSpan;\n}\n\n/**\n * Everything that can move the connection status. The client is the only\n * producer: check and retry events come from its own loop, the rest arrive as\n * outside facts through its notify inbox.\n */\nexport type Event =\n | { type: \"check.started\" }\n | { type: \"check.success\"; info: Info }\n | { type: \"check.failure\"; error: Error; attempt: number }\n | { type: \"stream.live\" }\n | { type: \"stream.drop\"; error?: Error }\n | { type: \"stream.denied\"; error?: Error }\n | { type: \"auth.success\" }\n | { type: \"auth.failure\"; error: Error }\n | { type: \"epoch.advanced\"; epoch: number }\n | { type: \"retry.scheduled\"; attempt: number; nextAt: TimeStamp }\n | { type: \"retry.exhausted\" }\n | { type: \"retry.requested\" }\n | { type: \"credentials.replaced\" }\n | { type: \"closed\" };\n\nconst CONNECTING = \"Connecting\";\nconst RECONNECTING = \"Reconnecting\";\nconst UNREACHABLE = \"Cannot reach cluster\";\nconst STREAM_DENIED =\n \"Live updates are unavailable. This user cannot read the change channels.\";\n\nconst connectedMessage = ({ name }: Config): string =>\n `Connected to ${name ?? \"cluster\"}`;\n\n/** The status a freshly constructed client starts in. */\nexport const createInitialStatus = (config: Config): Status => ({\n ...DEFAULT_STATUS,\n key: id.create(),\n name: config.name ?? DEFAULT_STATUS.name,\n time: TimeStamp.now(),\n variant: \"loading\",\n message: `Connecting to ${config.name ?? \"cluster\"}`,\n details: { ...DEFAULT_STATUS_DETAILS, clientVersion: config.clientVersion },\n});\n\n// Merges facts without touching variant or reason, so the union member holds.\nconst update = <S extends Status>(prev: S, details: Partial<StatusDetails>): S => ({\n ...prev,\n details: { ...prev.details, ...details },\n});\n\n/** Moves to a non-error variant, structurally dropping any parked reason. */\nconst enter = (\n prev: Status,\n variant: Exclude<status.Variant, \"error\">,\n message: string,\n details: Partial<StatusDetails> = {},\n description: string = \"\",\n): NonErrorStatus => {\n const { reason: _, ...merged }: StatusDetails & { reason?: Reason } = {\n ...prev.details,\n ...details,\n };\n return { ...prev, variant, message, description, details: merged };\n};\n\nconst enterError = (\n prev: Status,\n message: string,\n reason: Reason,\n details: Partial<StatusDetails> = {},\n): ErrorStatus => ({\n ...prev,\n variant: \"error\",\n message,\n description: \"\",\n details: { ...prev.details, ...details, reason },\n});\n\nconst isCompatible = (nodeVersion: string, clientVersion: string): boolean =>\n migrate.versionsEqual(clientVersion, nodeVersion, {\n checkMajor: true,\n checkMinor: true,\n checkPatch: false,\n });\n\nconst checkFacts = (info: Info, config: Config): Partial<StatusDetails> => ({\n clusterKey: info.clusterKey,\n nodeVersion: info.nodeVersion,\n // the check traverses the auth middleware, so a response is proof of auth\n authenticated: true,\n clockSkew: info.clockSkew,\n clockSkewExceeded: info.clockSkew.abs().greaterThan(config.clockSkewThreshold),\n clientServerCompatible: isCompatible(info.nodeVersion, config.clientVersion),\n});\n\n// Connected, with live updates refused. A settled outcome: only a policy\n// change lifts it, so the machine rests here instead of chasing the stream.\nconst enterStreamDenied = (\n prev: Status,\n config: Config,\n details: Partial<StatusDetails> = {},\n): Status =>\n enter(\n prev,\n \"warning\",\n connectedMessage(config),\n {\n ...details,\n streamDenied: true,\n streamLive: false,\n error: undefined,\n retry: null,\n },\n STREAM_DENIED,\n );\n\nconst reduceCheckSuccess = (prev: Status, info: Info, config: Config): Status => {\n const { clusterKey } = prev.details;\n if (clusterKey !== \"\" && info.clusterKey !== clusterKey)\n return reduceClusterReplaced(prev, info, config);\n const facts = checkFacts(info, config);\n // reachable but the stream is still dark: the client re-demands it and we\n // stay degraded until it reports live. A parked unreachable error must\n // lift out of error: the short circuit it drives would starve the very\n // stream reopen this state waits on.\n if (config.requiresStream && !prev.details.streamLive) {\n if (prev.details.streamDenied) return enterStreamDenied(prev, config, facts);\n if (prev.variant === \"error\" && prev.details.reason === \"unreachable\")\n return enter(prev, \"loading\", RECONNECTING, {\n ...facts,\n error: undefined,\n retry: null,\n });\n return update(prev, facts);\n }\n if (prev.variant === \"success\") return update(prev, { ...facts, retry: null });\n return enter(prev, \"success\", connectedMessage(config), {\n ...facts,\n error: undefined,\n retry: null,\n });\n};\n\n// The cluster answering the check is not the one previously contacted.\n// Everything learned from the old cluster is void, so the machine returns to\n// first contact: loading at epoch 0 with a dark stream.\nconst reduceClusterReplaced = (prev: Status, info: Info, config: Config): Status =>\n enter(prev, \"loading\", `Connecting to ${config.name ?? \"cluster\"}`, {\n ...checkFacts(info, config),\n streamLive: false,\n streamDenied: false,\n epoch: 0,\n error: undefined,\n retry: null,\n });\n\nconst reduceAuthFailure = (prev: Status, error: Error): Status =>\n enterError(prev, error.message, \"auth\", {\n error,\n authenticated: false,\n retry: null,\n });\n\nconst reduceCheckFailure = (\n prev: Status,\n error: Error,\n attempt: number,\n config: Config,\n): Status => {\n if (AuthError.matches(error)) return reduceAuthFailure(prev, error);\n const escalating = prev.variant === \"loading\";\n if (escalating && attempt >= config.escalateAfter)\n return enterError(prev, error.message ?? UNREACHABLE, \"unreachable\", { error });\n if (prev.variant === \"success\")\n return enter(prev, \"loading\", RECONNECTING, { error });\n return update(prev, { error });\n};\n\nconst reduceStreamLive = (prev: Status, config: Config): Status => {\n const parked = prev.variant === \"error\" && prev.details.reason !== \"unreachable\";\n if (parked) return update(prev, { streamLive: true, streamDenied: false });\n return enter(prev, \"success\", connectedMessage(config), {\n streamLive: true,\n streamDenied: false,\n error: undefined,\n retry: null,\n });\n};\n\nconst reduceStreamDrop = (prev: Status, error?: Error): Status => {\n if (prev.variant !== \"success\") return update(prev, { streamLive: false });\n return enter(prev, \"loading\", RECONNECTING, { streamLive: false, error });\n};\n\nconst reduceRetryExhausted = (prev: Status): Status => {\n if (prev.variant !== \"loading\") return update(prev, { retry: null });\n return enterError(prev, prev.details.error?.message ?? UNREACHABLE, \"unreachable\", {\n retry: null,\n });\n};\n\n/**\n * Folds an event into the connection status. Pure: every transition in the\n * lifecycle lives here and nowhere else. `disabled` is terminal.\n */\nexport const reduce = (prev: Status, event: Event, config: Config): Status => {\n if (prev.variant === \"disabled\") return prev;\n switch (event.type) {\n case \"check.started\":\n return update(prev, { checking: true });\n case \"check.success\":\n return update(reduceCheckSuccess(prev, event.info, config), { checking: false });\n case \"check.failure\":\n return update(reduceCheckFailure(prev, event.error, event.attempt, config), {\n checking: false,\n });\n case \"stream.live\":\n return reduceStreamLive(prev, config);\n case \"stream.drop\":\n return reduceStreamDrop(prev, event.error);\n case \"stream.denied\":\n return enterStreamDenied(prev, config);\n case \"auth.success\":\n return update(prev, { authenticated: true });\n case \"auth.failure\":\n return reduceAuthFailure(prev, event.error);\n case \"epoch.advanced\":\n return update(prev, { epoch: event.epoch });\n case \"retry.scheduled\":\n return update(prev, { retry: { attempt: event.attempt, nextAt: event.nextAt } });\n case \"retry.exhausted\":\n return reduceRetryExhausted(prev);\n case \"retry.requested\":\n // deliberately does not clear auth or incompatibility: those rest until\n // the user supplies something new\n if (prev.variant !== \"error\" || prev.details.reason !== \"unreachable\")\n return prev;\n return enter(prev, \"loading\", CONNECTING);\n case \"credentials.replaced\":\n // the new user may hold the permissions the old one lacked\n return enter(prev, \"loading\", CONNECTING, {\n error: undefined,\n streamDenied: false,\n });\n case \"closed\":\n return enter(prev, \"disabled\", \"Closed\", {\n streamLive: false,\n retry: null,\n checking: false,\n });\n }\n};\n\n// Fields that legitimately churn without meaning anything: the stamp moves on\n// every advance and raw skew jitters on every successful check. Everything\n// else is material, so new fields notify by default.\nconst comparable = ({ time: _, ...rest }: Status): unknown => ({\n ...rest,\n details: { ...rest.details, clockSkew: undefined },\n});\n\n/** Whether the change is worth notifying observers about. */\nexport const materialChange = (prev: Status, next: Status): boolean =>\n !deep.equal(comparable(prev), comparable(next));\n\n/**\n * Folds the event and stamps the status time when the result is worth publishing.\n * @returns the next status and whether observers should be notified.\n */\nexport const advance = (\n prev: Status,\n event: Event,\n config: Config,\n): [Status, boolean] => {\n const next = reduce(prev, event, config);\n if (!materialChange(prev, next)) return [next, false];\n return [{ ...next, time: TimeStamp.now() }, true];\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type FileTransport,\n HTTPClient,\n type Middleware,\n type UnaryClient,\n unaryWithBreaker,\n WebSocketClient,\n} from \"@synnaxlabs/freighter\";\nimport { binary, type breaker, type url } from \"@synnaxlabs/x\";\n\nexport class Transport {\n readonly url: url.URL;\n readonly unary: UnaryClient;\n /**\n * The unary client without the breaker's retry wrapper, for callers that own their\n * retry policy (the connection checker). Shares middleware with {@link unary}.\n */\n readonly unaryNoRetry: UnaryClient;\n readonly file: FileTransport;\n readonly stream: WebSocketClient;\n readonly secure: boolean;\n\n constructor(url: url.URL, breakerCfg: breaker.Config = {}, secure: boolean = false) {\n this.secure = secure;\n this.url = url.child(\"/api/v1/\");\n const codec = new binary.JSONCodec();\n // The streaming file client and the unary client share one HTTPClient, so\n // middleware (e.g. auth) registered through unary applies to file too. The file\n // client deliberately skips the breaker's retry wrapper: an upload body may be a\n // one-shot ReadableStream that cannot be re-sent on a retry.\n const http = new HTTPClient(this.url, codec, this.secure);\n this.unary = unaryWithBreaker(http, breakerCfg);\n this.unaryNoRetry = http;\n this.file = http;\n this.stream = new WebSocketClient(this.url, codec, this.secure);\n }\n\n use(...middleware: Middleware[]): void {\n this.unary.use(...middleware);\n this.stream.use(...middleware);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Middleware, type UnaryClient } from \"@synnaxlabs/freighter\";\nimport {\n breaker,\n ClockSkewCalculator,\n type CrudeTimeSpan,\n type destructor,\n errors,\n migrate,\n observe,\n sync,\n TimeSpan,\n TimeStamp,\n url,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { auth } from \"@/auth\";\nimport {\n advance,\n awaitConnected,\n type Config,\n createInitialStatus,\n DEFAULT_ESCALATE_AFTER,\n type Event,\n type Handle,\n type Info,\n reduce,\n type Status,\n} from \"@/connection/status\";\nimport { AccessDeniedError, DisconnectedError, errorsMiddleware } from \"@/errors\";\nimport { Transport } from \"@/transport\";\n\nconst CHECK_ENDPOINT = \"/connectivity/check\";\n\nconst checkResZ = z.object({\n clusterKey: z.string(),\n nodeVersion: z.string(),\n nodeTime: TimeStamp.z,\n});\n\n/**\n * Runs a single connectivity check, measuring clock skew across the round trip.\n * The transport must carry the full middleware chain, auth included, so that a\n * response proves authentication.\n * @throws {AuthError} if the cluster rejects the client's credentials.\n * @throws {Unreachable} if the cluster cannot be reached.\n */\nexport const sendCheck = async (unary: UnaryClient): Promise<Info> => {\n const skew = new ClockSkewCalculator();\n skew.start();\n const res = await unary.send(CHECK_ENDPOINT, undefined, z.void(), checkResZ);\n skew.end(res.nodeTime);\n return {\n clusterKey: res.clusterKey,\n nodeVersion: res.nodeVersion,\n clockSkew: skew.skew,\n };\n};\n\n/** Address parameters for a one-shot connectivity check. */\nexport interface CheckParams {\n host: string;\n port: number | string;\n secure?: boolean;\n /** Human-readable cluster name for status messages. */\n name?: string;\n}\n\n/**\n * Runs a one-shot connectivity check against the given cluster address and folds the\n * result into a status. Never throws: failures land in the returned status.\n */\nexport const check = async (params: CheckParams): Promise<Status> => {\n const { host, port, secure = false, name } = params;\n const endpoint = new url.URL({ host, port: Number(port) });\n const transport = new Transport(endpoint, {}, secure);\n transport.use(errorsMiddleware);\n const cfg: Config = {\n clientVersion: __VERSION__,\n escalateAfter: 1,\n clockSkewThreshold: TimeSpan.seconds(1),\n requiresStream: false,\n name,\n };\n const initial = createInitialStatus(cfg);\n try {\n const info = await sendCheck(transport.unaryNoRetry);\n return reduce(initial, { type: \"check.success\", info }, cfg);\n } catch (err) {\n const error = errors.fromUnknown(err);\n return reduce(initial, { type: \"check.failure\", error, attempt: 1 }, cfg);\n }\n};\n\n/** How hard the check loop is working. */\nexport type Mode = \"checking\" | \"heartbeat\" | \"idle\";\n\n/** The mode a given connection status calls for. */\nexport const modeFor = ({ variant, details }: Status): Mode => {\n switch (variant) {\n // warning is settled, not in progress: a denied stream checks on the\n // slow cadence like a healthy one\n case \"success\":\n case \"warning\":\n return \"heartbeat\";\n case \"disabled\":\n return \"idle\";\n case \"error\":\n // unreachable keeps checking beneath the error and self-heals; auth and\n // incompatibility rest until the user acts\n return details.reason === \"unreachable\" ? \"checking\" : \"idle\";\n default:\n return \"checking\";\n }\n};\n\nconst DEFAULT_RETRY: breaker.Config = {\n baseInterval: TimeSpan.seconds(1),\n // checks are one cheap request: a low cap keeps a returned cluster from\n // going unnoticed while backoff is escalated\n maxInterval: TimeSpan.seconds(5),\n maxRetries: Infinity,\n scale: 2,\n jitter: 0.25,\n};\n\n/**\n * The outside facts that can move the connection. Everything else that moves it\n * (check results, retry scheduling) the client observes itself.\n */\nexport type FactEvent = Extract<\n Event,\n {\n type:\n | \"auth.success\"\n | \"auth.failure\"\n | \"stream.live\"\n | \"stream.drop\"\n | \"stream.denied\"\n | \"credentials.replaced\"\n | \"epoch.advanced\";\n }\n>;\n\n/** Heartbeats between re-probes of a denied change stream. */\nconst DEFAULT_DENIED_STREAM_PROBE_AFTER = 10;\n\nconst STREAM_DENIED = \"cannot stream changes: live updates are unavailable\";\n\nexport interface ClientParams {\n /**\n * Check transport. Must carry the full middleware chain, auth included, so\n * that a check response proves authentication.\n */\n unary: UnaryClient;\n /** Cluster address, used in error messages. */\n address: string;\n /** Human-readable cluster name for status messages. */\n name?: string;\n /** Consecutive check failures before escalating to error(unreachable). */\n escalateAfter?: number;\n clockSkewThreshold?: TimeSpan;\n /** Whether success requires a live change stream. */\n requiresStream?: boolean;\n /**\n * Degraded-check policy. `maxRetries` defaults to Infinity (never give up);\n * a finite value parks the loop once exhausted, until {@link Client.retryNow}.\n */\n retry?: breaker.Config;\n /** Check cadence while connected. Defaults to 30 seconds. */\n heartbeatInterval?: CrudeTimeSpan;\n /**\n * Heartbeats between re-probes of a denied change stream. Only a policy\n * change lifts a denial, and the client cannot hear about one. Defaults to 10.\n */\n deniedStreamProbeAfter?: number;\n /** Levers on the change stream, pulled when transitions demand it. */\n stream?: {\n /** Tears down cached state after a cluster replacement. */\n reset: () => Promise<void>;\n /** (Re)demands a live change stream. */\n ensure: () => Promise<void>;\n };\n /** Receives errors with no caller to throw to. Defaults to console logging. */\n onInternalError?: (error: Error) => void;\n}\n\n/**\n * Owns a cluster connection's status: checks on a cadence, backs off while degraded,\n * folds outside facts ({@link Client.notify}) into the status, and notifies observers\n * on material changes. The check loop starts on construction, deferred one microtask so\n * callers can finish synchronous wiring (middleware installation) first.\n */\nexport class Client implements Handle {\n private readonly unary: UnaryClient;\n private readonly address: string;\n private readonly config: Config;\n private readonly retry: breaker.Config;\n private readonly heartbeatInterval: TimeSpan;\n private readonly deniedStreamProbeAfter: number;\n private readonly stream?: ClientParams[\"stream\"];\n private readonly onInternalError: (error: Error) => void;\n private readonly observer = new observe.Observer<Status>();\n private readonly notifier = new sync.Notifier();\n private readonly loop: Promise<void>;\n private current: Status;\n private mode: Mode = \"checking\";\n private closed = false;\n private attempts = 0;\n private generation = 0;\n private probeCountdown = 0;\n private brk: breaker.Breaker | null = null;\n private versionWarned = false;\n\n constructor({\n unary,\n address,\n name,\n escalateAfter = DEFAULT_ESCALATE_AFTER,\n clockSkewThreshold = TimeSpan.seconds(1),\n requiresStream = false,\n retry,\n heartbeatInterval = TimeSpan.seconds(30),\n deniedStreamProbeAfter = DEFAULT_DENIED_STREAM_PROBE_AFTER,\n stream,\n onInternalError = console.error,\n }: ClientParams) {\n this.unary = unary;\n this.address = address;\n this.config = {\n clientVersion: __VERSION__,\n name,\n escalateAfter,\n clockSkewThreshold,\n requiresStream,\n };\n this.retry = { ...DEFAULT_RETRY, ...retry };\n this.heartbeatInterval = new TimeSpan(heartbeatInterval);\n this.deniedStreamProbeAfter = deniedStreamProbeAfter;\n this.stream = stream;\n this.onInternalError = onInternalError;\n this.current = createInitialStatus(this.config);\n this.loop = this.run().catch((err: unknown) =>\n this.onInternalError(new Error(\"connection check loop failed\", { cause: err })),\n );\n }\n\n /** The current connection status. */\n get status(): Status {\n return this.current;\n }\n\n /** Subscribes to material status changes. Returns an unsubscribe destructor. */\n onChange(callback: (status: Status) => void): destructor.Destructor {\n return this.observer.onChange(callback);\n }\n\n /**\n * Resets the retry backoff and checks immediately. Auth and incompatibility\n * errors are not cleared: those rest until the user supplies something new.\n */\n retryNow(): void {\n this.dispatch({ type: \"retry.requested\" });\n this.wake();\n }\n\n /**\n * Resolves once the connection is usable: success, or warning when the cluster\n * refuses live updates. Rejects with the stored failure when it settles on an error\n * variant or is closed. An already-connected client resolves without waiting.\n * @throws {Error} if the timeout elapses first.\n */\n async connect(timeout?: CrudeTimeSpan): Promise<Status> {\n return await awaitConnected(this, timeout);\n }\n\n /** Folds an outside fact into the connection status. */\n notify(event: FactEvent): void {\n const wasDenied = this.current.details.streamDenied;\n this.dispatch(event);\n if (event.type === \"stream.denied\") {\n this.probeCountdown = this.deniedStreamProbeAfter;\n // every probe hits the same refusal; only the first is news\n if (!wasDenied)\n this.onInternalError(\n new AccessDeniedError(STREAM_DENIED, { cause: event.error }),\n );\n }\n // a reopened stream may lead to a replaced cluster, and new credentials\n // deserve an immediate verdict: both check right away\n if (event.type === \"stream.live\" || event.type === \"credentials.replaced\")\n this.wake();\n }\n\n /**\n * Rejects unary requests instantly while the cluster is known unreachable,\n * instead of burning the transport's retry budget per call. The check and\n * login targets are exempt so the connection can heal.\n */\n middleware(): Middleware {\n const EXEMPT = [CHECK_ENDPOINT, auth.LOGIN_ENDPOINT];\n return async (ctx, next) => {\n const { variant, details } = this.current;\n if (\n variant === \"error\" &&\n details.reason === \"unreachable\" &&\n !EXEMPT.some((target) => ctx.target.endsWith(target))\n )\n throw new DisconnectedError(`Cannot reach cluster at ${this.address}`);\n return await next(ctx);\n };\n }\n\n /** Stops the check loop and settles the status on disabled. Terminal. */\n async close(): Promise<void> {\n if (this.closed) return;\n this.dispatch({ type: \"closed\" });\n this.closed = true;\n this.notifier.notify();\n await this.loop;\n }\n\n /**\n * Folds the event into the status, notifies observers, and applies the\n * transition's side effects.\n */\n private dispatch(event: Event): void {\n if (this.closed) return;\n const prev = this.current;\n const [next, changed] = advance(prev, event, this.config);\n this.current = next;\n if (changed) this.observer.notify(next);\n // a new cluster at the connection's address voids everything learned from\n // the old one: drop cached state, then bring the stream back up\n if (\n prev.details.clusterKey !== \"\" &&\n next.details.clusterKey !== prev.details.clusterKey\n )\n this.resetStream().catch((err: unknown) =>\n this.onInternalError(\n new Error(\"failed to reset cache after cluster replacement\", { cause: err }),\n ),\n );\n this.setMode(modeFor(next));\n }\n\n /** Drops everything cached from the replaced cluster, then brings the stream up. */\n private async resetStream(): Promise<void> {\n await this.stream?.reset();\n await this.stream?.ensure();\n }\n\n /** Discards in-flight checks and wakes the loop for an immediate check. */\n private wake(): void {\n if (this.closed) return;\n this.generation += 1;\n this.attempts = 0;\n this.brk?.reset();\n this.notifier.notify();\n }\n\n private setMode(mode: Mode): void {\n if (this.closed || this.mode === mode) return;\n this.mode = mode;\n // in-flight checks were aimed at the state the old mode ran under; their\n // late results must not degrade the new one\n this.generation += 1;\n if (mode !== \"checking\") this.attempts = 0;\n this.brk?.reset();\n this.notifier.notify();\n }\n\n /**\n * Consumes this check's turn at re-demanding a dark stream, returning whether it gets\n * one. A denied stream probes on a slow cadence: every probe costs an open the\n * cluster refuses until an administrator changes the caller's policies.\n */\n private takeStreamProbe(): boolean {\n if (!this.current.details.streamDenied) return true;\n if (this.probeCountdown > 0) {\n this.probeCountdown -= 1;\n return false;\n }\n this.probeCountdown = this.deniedStreamProbeAfter;\n return true;\n }\n\n private async runCheck(): Promise<void> {\n const generation = this.generation;\n const prevKey = this.current.details.clusterKey;\n this.dispatch({ type: \"check.started\" });\n try {\n const info = await sendCheck(this.unary);\n if (generation !== this.generation || this.closed) return;\n this.attempts = 0;\n this.dispatch({ type: \"check.success\", info });\n this.warn(this.current.details);\n const replaced = prevKey !== \"\" && info.clusterKey !== prevKey;\n // reachable but the stream is still dark: re-demand it, in case its own\n // retry budget was exhausted. Replacement already brings it up.\n if (\n !replaced &&\n this.config.requiresStream &&\n !this.current.details.streamLive &&\n this.takeStreamProbe()\n )\n this.stream?.ensure().catch((err: unknown) => {\n // the transition into denied already reported it\n if (AccessDeniedError.matches(err)) return;\n this.onInternalError(\n new Error(\"failed to bring up change stream\", { cause: err }),\n );\n });\n } catch (err) {\n if (generation !== this.generation || this.closed) return;\n this.attempts += 1;\n this.dispatch({\n type: \"check.failure\",\n error: errors.fromUnknown(err),\n attempt: this.attempts,\n });\n }\n }\n\n private async run(): Promise<void> {\n // defer the first check so the caller can finish synchronous wiring\n // (middleware installation) after construction\n await Promise.resolve();\n const brk = new breaker.Breaker({\n ...this.retry,\n sleepFn: async (duration) => {\n this.dispatch({\n type: \"retry.scheduled\",\n attempt: this.attempts,\n nextAt: TimeStamp.now().add(duration),\n });\n await this.notifier.wait(duration);\n },\n });\n this.brk = brk;\n while (!this.closed)\n if (this.mode === \"checking\") {\n await this.runCheck();\n if (this.closed) return;\n if (this.mode !== \"checking\") continue;\n if (await brk.wait()) continue;\n // finite budget exhausted: park until retryNow or a mode change\n this.dispatch({ type: \"retry.exhausted\" });\n if (this.closed) return;\n await this.notifier.wait(null);\n brk.reset();\n } else if (this.mode === \"heartbeat\") {\n await this.notifier.wait(this.heartbeatInterval);\n if (this.closed) return;\n if (this.mode === \"heartbeat\") await this.runCheck();\n } else await this.notifier.wait(null);\n }\n\n private warn({\n clockSkew,\n clockSkewExceeded,\n clientServerCompatible,\n clientVersion,\n nodeVersion,\n }: Status[\"details\"]): void {\n if (clockSkewExceeded) {\n const direction = clockSkew.valueOf() > 0n ? \"ahead of\" : \"behind\";\n console.warn(\n `Measured excessive clock skew between this host and the Synnax Core. ` +\n `This host is ${direction} the Synnax Core by approximately ` +\n `${clockSkew.abs().toString()}.`,\n );\n }\n if (clientServerCompatible || this.versionWarned) return;\n this.versionWarned = true;\n const clientIsNewer =\n nodeVersion == null || migrate.semVerNewer(clientVersion, nodeVersion);\n const toUpgrade = clientIsNewer ? \"Core\" : \"client\";\n console.warn(\n `The Synnax Core version ${nodeVersion != null ? `${nodeVersion} ` : \"\"}is too ` +\n `${clientIsNewer ? \"old\" : \"new\"} for client version ${clientVersion}.\\n` +\n ` This may cause compatibility issues. We recommend updating the ${toUpgrade}. For more information, see\\n` +\n ` https://docs.synnaxlabs.com/reference/client/resources/troubleshooting#old-${toUpgrade.toLowerCase()}-version`,\n );\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport {\n check,\n type CheckParams,\n Client,\n type ClientParams,\n type FactEvent,\n} from \"@/connection/client\";\nexport {\n type Config,\n DEFAULT_STATUS,\n type ErrorStatus,\n type ErrorStatusDetails,\n errorStatusDetailsZ,\n type Handle,\n type Info,\n type NonErrorStatus,\n nonErrorVariantZ,\n type Reason,\n REASONS,\n reasonZ,\n type Status,\n type StatusDetails,\n statusDetailsZ,\n statusZ,\n} from \"@/connection/status\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { control } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { keyZ } from \"@/channel/types.gen\";\n\n/** How strongly a writer claims a channel. The highest authority holds control. */\nexport type Authority = control.Authority;\n/** The highest authority. A writer holding it cannot be displaced. */\nexport const ABSOLUTE_AUTHORITY = control.ABSOLUTE_AUTHORITY;\n/** The lowest authority. Any other writer displaces it. */\nexport const ZERO_AUTHORITY = control.ZERO_AUTHORITY;\n/** Control of one channel moving between writers, or being released. */\nexport type Transfer = control.Transfer<typeof channel.keyZ>;\n/** Who holds control of a channel, and at what authority. */\nexport interface State extends control.State<typeof channel.keyZ> {}\n/** A named party that can hold control. */\nexport interface Subject extends control.Subject {}\n/** Zod schema for {@link State}. */\nexport const stateZ = control.stateZ(z.number());\n\n/**\n * A control state stored under the channel it controls, which is how the client caches\n * it.\n */\nexport const keyedStateZ = stateZ.transform((s) => ({ key: s.resource, ...s }));\nexport interface KeyedState extends z.infer<typeof keyedStateZ> {}\n\n/** Renders a {@link Transfer} as readable text, for logs and status messages. */\nexport const transferString = (t: Transfer): string => {\n const fromResource = t.from?.resource;\n const toResource = t.to?.resource;\n if (t.to == null) return `${fromResource} - ${t.from?.subject.name} -> released`;\n if (t.from == null)\n return `${toResource} - released -> ${\n t.to.subject.name\n } (${t.to.authority.toString()})`;\n return `${toResource} - ${t.from.subject.name} -> ${\n t.to.subject.name\n } (${t.to.authority.toString()})`;\n};\n\nexport const updateZ = z.object({\n transfers: z.array(control.transferZ(keyZ)),\n});\n\nexport interface Update extends z.infer<typeof updateZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { keyZ } from \"@/channel/types.gen\";\nimport { type KeyedState, keyedStateZ, updateZ } from \"@/control/state\";\nimport { query } from \"@/query\";\n\n/** The free virtual channel carrying control updates for the entire cluster. */\nconst CHANNEL_NAME = \"sy_control\";\n\nconst RETRIEVE_ENDPOINT = \"/control/retrieve\";\n\nconst retrieveRequestZ = z.object({ keys: keyZ.array().optional() });\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\nconst retrieveResZ = z.object({ states: keyedStateZ.array().default(() => []) });\n\nexport type RetrieveMultipleParams = z.input<typeof retrieveRequestZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n}\n\n/**\n * Reads the control state of channels across the cluster. A channel is in the table\n * exactly while a subject holds it, so absence is the uncontrolled state: a release\n * deletes the entry instead of storing a sentinel.\n */\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n channel.Key,\n KeyedState\n> {\n readonly type: string = \"control\";\n /** The control state table, keyed by the channel under control. */\n readonly store: query.Table<channel.Key, KeyedState>;\n private readonly cfg: ClientConfig;\n\n constructor(cfg: ClientConfig) {\n const store = cfg.cache.createTable<channel.Key, KeyedState>({\n name: \"control\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [transferListener()],\n });\n super(cfg.cache, {\n name: \"control\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (state, req) => req.keys == null || req.keys.includes(state.key),\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n private async execRetrieve(req: RetrieveRequest): Promise<KeyedState[]> {\n // An empty key set reads the whole cluster, so it must not reach the Core here.\n if (req.keys != null && req.keys.length === 0) return [];\n const { states } = await this.cfg.unary.send(\n RETRIEVE_ENDPOINT,\n { keys: req.keys ?? [] },\n retrieveRequestZ,\n retrieveResZ,\n );\n return states;\n }\n}\n\n/**\n * Mirrors the cluster's control transfers into the table: the `to` end of a transfer\n * sets the channel's holder, and a transfer without one deletes the entry.\n */\nconst transferListener = (): query.ListenerSpec<channel.Key, KeyedState> => ({\n bind: (table): query.Listener<typeof updateZ> => ({\n channel: CHANNEL_NAME,\n schema: updateZ,\n onChange: (updates) =>\n table.batch(() =>\n updates\n .flatMap((u) => u.transfers)\n .forEach(({ from, to }) => {\n if (to == null) table.delete(from.resource);\n else table.set({ key: to.resource, ...to });\n }),\n ),\n }),\n});\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/control/client\";\nexport * from \"@/control/state\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type DataType, type math, type Series } from \"@synnaxlabs/x\";\n\n/**\n * Converts series into the representation the caller renders from before they enter\n * cache buffers. Injected at construction; the cache applies it to every write.\n */\nexport interface Transform {\n /** @returns the buffer data type used to hold series of the given type. */\n resolveDataType: (dt: DataType) => DataType;\n /**\n * Converts the series to the resolved data type.\n * @param offset - Subtracted from each sample before narrowing conversions to\n * preserve precision. Omitted when the buffer anchors off the first sample.\n */\n convert: (series: Series, offset?: math.Numeric) => Series;\n}\n\n/** A transform that stores every series exactly as it arrives. */\nexport const IDENTITY_TRANSFORM: Transform = {\n resolveDataType: (dt) => dt,\n convert: (series) => series,\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { TimeRange } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { keyZ, nameZ } from \"@/channel/types.gen\";\n\nconst reqZ = z.object({\n keys: keyZ.array().optional(),\n bounds: TimeRange.z,\n names: nameZ.array().optional(),\n});\ninterface Request extends z.infer<typeof reqZ> {}\n\nconst resZ = z.object({});\n\n/** Deletes a time range of telemetry from a Core. Reach it through `client.telem`. */\nexport class Deleter {\n private readonly client: UnaryClient;\n\n constructor(client: UnaryClient) {\n this.client = client;\n }\n\n async delete(props: Request): Promise<void> {\n await this.client.send(\"/frame/delete\", props, reqZ, resZ);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { alamos } from \"@synnaxlabs/alamos\";\nimport {\n bounds,\n MultiSeries,\n type Series,\n Size,\n TimeRange,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\n\nimport { IDENTITY_TRANSFORM, type Transform } from \"@/framer/cache/transform\";\n\nexport interface DirtyReadResult {\n series: MultiSeries;\n gaps: TimeRange[];\n}\n\nexport interface GCMetrics {\n purgedSeries: number;\n purgedBytes: Size;\n}\n\nexport const zeroGCMetrics = (): GCMetrics => ({\n purgedSeries: 0,\n purgedBytes: Size.bytes(0),\n});\n\n/** Props for the {@link Static} cache. */\nexport interface StaticProps {\n /** Used for logging */\n instrumentation?: alamos.Instrumentation;\n /** Applied to every series before it enters the cache. Defaults to identity. */\n transform?: Transform;\n /**\n * Sets the amount of time that a cache entry must be in the cache before it can\n * be marked as stale and subject to garbage collection.\n * @default TimeSpan.seconds(20) */\n staleEntryThreshold?: TimeSpan;\n}\n\nexport const DEFAULT_STATIC_PROPS: Required<StaticProps> = {\n instrumentation: alamos.NOOP,\n transform: IDENTITY_TRANSFORM,\n staleEntryThreshold: TimeSpan.seconds(20),\n};\n\ninterface CacheEntry {\n /** The cached samples, after the transform and any insertion trimming. */\n data: Series;\n /** When the entry entered the cache, for garbage collection staleness. */\n addedAt: TimeStamp;\n}\n\n/**\n * A cache for historical channel data that will not be modified after it is written.\n * Fetched and streamed entries are held apart because they measure position in\n * different spaces: a fetched sample carries its committed alignment, the same sample\n * streamed carries a provisional leading one. Insertion and gap computation both assume\n * a single space, so each kind gets its own list.\n */\nexport class Static {\n private fetched: CacheEntry[] = [];\n private streamed: CacheEntry[] = [];\n private readonly props: Required<StaticProps>;\n\n constructor(props: StaticProps) {\n const {\n instrumentation = DEFAULT_STATIC_PROPS.instrumentation,\n transform = DEFAULT_STATIC_PROPS.transform,\n staleEntryThreshold = DEFAULT_STATIC_PROPS.staleEntryThreshold,\n } = props;\n this.props = { instrumentation, transform, staleEntryThreshold };\n }\n\n /**\n * Writes the given series to the cache, merging written series with any existing\n * series in the cache.\n * @param streamed - Marks the series as live-streamed data. A fetched write evicts\n * every streamed entry whose time range it fully covers.\n */\n write(series: MultiSeries, streamed: boolean = false): void {\n if (series.length === 0) return;\n if (!streamed) this.evictStreamed(series);\n const entries = streamed ? this.streamed : this.fetched;\n series.series.forEach((s) =>\n this.writeOne(this.props.transform.convert(s), entries),\n );\n this.repairIntegrity(series, entries);\n }\n\n // Containment, not overlap: a fetch stamped wider than the data it returned\n // (an uncommitted tail) must not evict streamed samples it did not replace.\n private evictStreamed(written: MultiSeries): void {\n this.streamed = this.streamed.filter(\n (e) =>\n !written.series.some(\n (s) =>\n s.timeRange.start.beforeEq(e.data.timeRange.start) &&\n s.timeRange.end.afterEq(e.data.timeRange.end),\n ),\n );\n }\n\n /**\n * Executes a 'dirty' read of the cache, retrieving any series in the cache that\n * overlap with the given time range. The series may extend before or after the range.\n * Gaps are computed against fetched entries only. Streamed entries carry provisional\n * leading alignments that cannot pair with fetched data on another channel, so they\n * never claim coverage; the fetch they provoke evicts them.\n * @returns A list of series that overlap with the given time range and a list of\n * gaps, representing the regions of time the fetched series do not cover.\n */\n dirtyRead(tr: TimeRange): DirtyReadResult {\n const overlapping = (entries: CacheEntry[]): Series[] =>\n entries.filter((e) => e.data.timeRange.overlapsWith(tr)).map((e) => e.data);\n const fetched = overlapping(this.fetched);\n const series = [...fetched, ...overlapping(this.streamed)];\n if (fetched.length === 0) return { series: new MultiSeries(series), gaps: [tr] };\n const gaps: TimeRange[] = [];\n const pushGap = (start: TimeStamp, end: TimeStamp): void => {\n const gap = new TimeRange(start, end);\n if (gap.isValid && !gap.span.isZero) gaps.push(gap);\n };\n pushGap(tr.start, fetched[0].timeRange.start);\n for (let i = 1; i < fetched.length; i++)\n pushGap(fetched[i - 1].timeRange.end, fetched[i].timeRange.start);\n pushGap(fetched[fetched.length - 1].timeRange.end, tr.end);\n return { series: new MultiSeries(series), gaps };\n }\n\n /**\n * Garbage collects the cache, removing any stale entries.\n * @returns metrics about the garbage collection.\n */\n gc(): GCMetrics {\n const { staleEntryThreshold } = this.props;\n const res = zeroGCMetrics();\n const collect = (entries: CacheEntry[]): CacheEntry[] =>\n entries.filter((s) => {\n const shouldKeep =\n s.data.refCount > 0 ||\n TimeStamp.since(s.addedAt).lessThan(staleEntryThreshold);\n if (!shouldKeep) {\n res.purgedBytes = res.purgedBytes.add(s.data.byteCapacity);\n res.purgedSeries++;\n }\n return shouldKeep;\n });\n this.fetched = collect(this.fetched);\n this.streamed = collect(this.streamed);\n return res;\n }\n\n /** Closes the cache, freeing all of its resources. */\n close(): void {\n this.fetched = [];\n this.streamed = [];\n }\n\n private writeOne(series: Series, entries: CacheEntry[]): void {\n const {\n instrumentation: { L },\n } = this.props;\n if (series.length === 0) return;\n const insertionPlan = bounds.buildInsertionPlan(\n entries.map((s) => s.data.alignmentBounds),\n series.alignmentBounds,\n );\n if (insertionPlan === null)\n return L.debug(\"Found no viable insertion plan\", () => ({\n inserting: series.digest,\n cacheContents: entries.map((s) => s.data.digest),\n }));\n const { removeBefore, removeAfter, insertInto, deleteInBetween } = insertionPlan;\n series = series.slice(removeBefore, series.length - removeAfter);\n if (series.length === 0) return;\n entries.splice(insertInto, deleteInBetween, {\n data: series,\n addedAt: TimeStamp.now(),\n });\n }\n\n private repairIntegrity(write: MultiSeries, entries: CacheEntry[]): void {\n const {\n instrumentation: { L },\n } = this.props;\n // Entries are ordered and non-overlapping, so neighbor comparison suffices. An\n // overlap is an insertion bug: evict both entries and let a refetch heal the gap.\n for (let i = 1; i < entries.length; i++) {\n if (\n !bounds.overlapsWith(\n entries[i - 1].data.alignmentBounds,\n entries[i].data.alignmentBounds,\n )\n )\n continue;\n const [prev, curr] = entries.splice(i - 1, 2);\n L.error(\"cache integrity violation - evicting overlapping entries\", () => ({\n write: write.series.map((s) => s.digest),\n evicted: [prev.data.digest, curr.data.digest],\n }));\n i = 0;\n }\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { alamos } from \"@synnaxlabs/alamos\";\nimport {\n DataType,\n math,\n MultiSeries,\n Series,\n Size,\n TimeRange,\n type TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\n\nimport { IDENTITY_TRANSFORM, type Transform } from \"@/framer/cache/transform\";\n\n/** Response from a write to the {@link Dynamic} cache. */\nexport interface WriteResponse {\n /** Series flushed because the write did not fit in the current buffer. */\n flushed: MultiSeries;\n /** A list of series that were allocated during the write. */\n allocated: MultiSeries;\n}\n\n/** Props for the {@link Dynamic} cache. */\nexport interface DynamicProps {\n /**\n * Sets the maximum size of the buffer that the cache will maintain before flushing\n * data out to the caller.\n */\n dynamicBufferSize: number | TimeSpan;\n /** Applied to every series before it enters a buffer. Defaults to identity. */\n transform?: Transform;\n /** Used for logging. */\n instrumentation?: alamos.Instrumentation;\n /** Pulls the current time. */\n now?: () => TimeStamp;\n}\n\n// Bounds for dynamically calculated buffer sizes.\nconst MIN_SIZE = 100;\nconst MAX_SIZE = 1e6;\n// Size used until enough writes have arrived to estimate a rate.\nconst DEF_SIZE = 1e4;\nconst MAX_DEF_WRITES = 100;\n\n// Variable-rate types allocate bytes, not samples. Rough bytes-per-sample estimate.\nconst VARIABLE_DT_MULTIPLIER = 40;\n\n/**\n * @returns true when every byte of the series fits in the buffer's free space. Measured\n * in bytes because a variable-length buffer counts its capacity that way.\n */\nconst fits = (buffer: Series, series: Series): boolean =>\n series.byteLength.valueOf() <=\n buffer.byteCapacity.valueOf() - buffer.byteLength.valueOf();\n\n// Bounds on compacting a buffer that rotated early. Both have to trip: the fraction\n// spares a nearly full buffer, the floor one whose waste is not worth a copy.\nconst COMPACT_MAX_FILL = 0.25;\nconst COMPACT_MIN_WASTE = Size.kilobytes(256);\n\n/**\n * @returns true when copying the buffer's samples into a right-sized series is worth\n * the copy. A held buffer never qualifies: the holder keeps the original alive, so a\n * copy would only add a second allocation, and it would break the object identity a\n * consumer that both reads and streams deduplicates on.\n */\nconst shouldCompact = (buffer: Series): boolean => {\n if (buffer.refCount > 0 || buffer.length === 0) return false;\n const used = buffer.byteLength.valueOf();\n const capacity = buffer.byteCapacity.valueOf();\n return (\n capacity - used > COMPACT_MIN_WASTE.valueOf() && used < capacity * COMPACT_MAX_FILL\n );\n};\n\n/**\n * A cache for channel data that maintains a single, rolling Series as a buffer\n * for channel data. The buffer's data type is derived from the first written series,\n * so the cache needs no channel metadata.\n */\nexport class Dynamic {\n private readonly props: Required<Omit<DynamicProps, \"now\">>;\n\n private counter = 0;\n private curr: Series | null = null;\n /** End timestamp of the last fully written stamped series in the current buffer.\n * Null when the buffer holds unstamped or partially written data, in which case\n * the flush falls back to the wall clock. */\n private currDataEnd: TimeStamp | null = null;\n private avgRate: number = 0;\n private timeOfLastWrite: TimeStamp;\n private totalWrites: number = 0;\n private readonly now: () => TimeStamp;\n\n constructor(props: DynamicProps) {\n const {\n dynamicBufferSize,\n transform = IDENTITY_TRANSFORM,\n instrumentation = alamos.NOOP,\n now = () => TimeStamp.now(),\n } = props;\n this.props = { dynamicBufferSize, transform, instrumentation };\n this.now = now;\n this.timeOfLastWrite = this.now();\n }\n\n /** @returns the number of samples currently held in the cache. */\n get length(): number {\n return this.curr?.length ?? 0;\n }\n\n /**\n * @returns the current buffer being written to by the cache. Under no circumstances\n * should this be modified by the caller.\n */\n get leadingBuffer(): Series | null {\n return this.curr;\n }\n\n /**\n * @returns the time range the buffer's samples actually cover: its start to the last\n * stamped write, or the wall clock when the buffer holds unstamped data. Unlike the\n * buffer's provisional time range, the end never claims future time. Null when there\n * is no buffer.\n */\n get dataTimeRange(): TimeRange | null {\n if (this.curr == null) return null;\n return new TimeRange(this.curr.timeRange.start, this.currDataEnd ?? this.now());\n }\n\n /**\n * @returns a list of buffers that were filled by the cache during the write. If the\n * current buffer is able to fit all writes, no buffers will be returned.\n */\n write(series: MultiSeries): WriteResponse {\n const res: WriteResponse = {\n flushed: new MultiSeries([]),\n allocated: new MultiSeries([]),\n };\n const list = series.series;\n for (let i = 0; i < list.length; i++) this._write(list[i], res);\n return res;\n }\n\n private allocate(\n capacity: number,\n alignment: bigint,\n start: TimeStamp,\n source: Series,\n ): Series {\n this.counter++;\n const dt = this.props.transform.resolveDataType(source.dataType);\n // Bigint series narrowed to a non-bigint buffer store each value as a small delta\n // off a per-buffer anchor to avoid losing precision. For timestamps, now() is\n // close enough to the values being written. For int64 and uint64 the values can\n // be anything, so the first sample we see is used as the anchor.\n const narrowing = source.dataType.usesBigInt && !dt.usesBigInt;\n let sampleOffset: math.Numeric = 0;\n if (narrowing)\n if (source.dataType.equals(DataType.TIMESTAMP)) sampleOffset = start.valueOf();\n else if (source.length > 0) sampleOffset = BigInt(source.data[0].valueOf());\n return Series.alloc({\n capacity: dt.isVariable ? capacity * VARIABLE_DT_MULTIPLIER : capacity,\n dataType: dt,\n timeRange: start.range(TimeStamp.MAX),\n sampleOffset,\n glBufferUsage: \"dynamic\",\n alignment,\n key: `dynamic-${this.counter}`,\n });\n }\n\n /**\n * @returns the sample capacity for a buffer that must hold the given series whole:\n * the configured size, or the series' own size when that is larger.\n */\n private capacityFor(source: Series): number {\n const dt = this.props.transform.resolveDataType(source.dataType);\n const required = dt.isVariable\n ? Math.ceil(source.byteLength.valueOf() / VARIABLE_DT_MULTIPLIER)\n : source.length;\n return Math.max(this.nextBufferSize(), required);\n }\n\n // Unstamped series (virtual channels, writes without an in-frame index) fall back\n // to the wall clock.\n private allocStart(series: Series): TimeStamp {\n return series.timeRange.isZero ? this.now() : series.timeRange.start;\n }\n\n private allocCurr(\n res: WriteResponse,\n source: Series,\n start: TimeStamp | null,\n ): Series {\n this.curr = this.allocate(\n this.capacityFor(source),\n source.alignment,\n start ?? this.allocStart(source),\n source,\n );\n res.allocated.push(this.curr);\n return this.curr;\n }\n\n /** @returns the timestamp the flushed buffer's end was stamped with, or null when\n * there was no buffer. */\n private flushCurr(res: WriteResponse): TimeStamp | null {\n if (this.curr == null) return null;\n const end = this.currDataEnd ?? this.now();\n this.curr.timeRange.end = end;\n this.currDataEnd = null;\n res.flushed.push(this.compacted(this.curr, res));\n this.curr = null;\n return end;\n }\n\n /**\n * @returns a right-sized copy of a buffer that rotated with most of its space\n * unused, or the buffer itself. A rotated buffer holds its whole allocation until\n * it is collected, which is wasteful when an oversized series ended it early.\n */\n private compacted(buffer: Series, res: WriteResponse): Series {\n // A buffer allocated during this same write has not reached its subscribers yet,\n // so its reference count cannot yet report who is about to hold it.\n if (!shouldCompact(buffer) || res.allocated.series.includes(buffer)) return buffer;\n return buffer.compact();\n }\n\n private _write(series: Series, res: WriteResponse): void {\n const { transform, instrumentation: ins } = this.props;\n if (this.curr != null) {\n const resolved = transform.resolveDataType(series.dataType);\n if (!this.curr.dataType.equals(resolved)) {\n // The channel's data type changed (e.g. a calculated channel was reconfigured).\n ins.L.warn(\"buffer data type changed, resetting\", {\n prev: this.curr.dataType.toString(),\n next: resolved.toString(),\n });\n this.flushCurr(res);\n } else if (series.alignment < this.curr.alignment) {\n // The alignment counter rewound (e.g. the Core restarted and reset its\n // in-memory counter).\n ins.L.warn(\"alignment regressed, resetting buffer\", {\n buffer: this.curr.alignment.toString(),\n incoming: series.alignment.toString(),\n });\n this.flushCurr(res);\n }\n }\n let curr = this.curr;\n let trimmed = false;\n if (curr != null) {\n // overlap > 0: the incoming series steps back into samples the current buffer\n // already holds. overlap < 0: there is a gap between the buffer and the series.\n const overlap = Number(curr.alignment + BigInt(curr.length) - series.alignment);\n if (overlap > 0) {\n // Drop the re-sent leading samples; a fresh allocation here would fragment\n // the cache with overlapping series. sub() is zero-copy.\n if (overlap >= series.length) return;\n series = series.sub(overlap);\n trimmed = true;\n } else if (overlap < 0) {\n this.flushCurr(res);\n curr = null;\n }\n }\n const convert = (buffer: Series): Series =>\n transform.convert(series, buffer.sampleOffset);\n let rotationStart: TimeStamp | null = null;\n if (curr != null) {\n const converted = convert(curr);\n // A series never splits across two buffers. The timestamp where a split falls is\n // not in the data, so both sides would have to guess the boundary they share, and\n // a guess lands outside the data whenever samples are irregular.\n if (fits(curr, converted)) curr.write(converted);\n else {\n const end = this.flushCurr(res);\n // A trimmed series keeps the whole frame's start, which is earlier than the\n // samples it still holds. Those samples begin where the buffer they were\n // trimmed against ends, so the next buffer starts there.\n if (trimmed) rotationStart = end;\n curr = null;\n }\n }\n if (curr == null) {\n curr = this.allocCurr(res, series, rotationStart);\n curr.write(convert(curr));\n }\n this.currDataEnd = series.timeRange.isZero ? null : series.timeRange.end;\n this.updateAvgRate(series);\n }\n\n private updateAvgRate(series: Series): void {\n if (typeof this.props.dynamicBufferSize === \"number\") return;\n const now = this.now();\n const newRate = series.length / now.span(this.timeOfLastWrite).seconds;\n if (this.totalWrites > 0 && isFinite(newRate) && newRate > 0)\n this.avgRate =\n (this.avgRate * (this.totalWrites - 1) + newRate) / this.totalWrites;\n this.totalWrites++;\n this.timeOfLastWrite = now;\n }\n\n private nextBufferSize(): number {\n const { dynamicBufferSize } = this.props;\n if (typeof dynamicBufferSize === \"number\") return dynamicBufferSize;\n if (this.totalWrites < MAX_DEF_WRITES) return DEF_SIZE;\n const size = math.roundToNearestMagnitude(this.avgRate * dynamicBufferSize.seconds);\n return Math.round(Math.max(Math.min(size, MAX_SIZE), MIN_SIZE));\n }\n\n /**\n * Flushes the leading buffer, stamping its end with the last stamped write or\n * the wall clock.\n * @returns the flushed buffer, or null when there is none.\n */\n flush(): Series | null {\n const res: WriteResponse = {\n flushed: new MultiSeries([]),\n allocated: new MultiSeries([]),\n };\n this.flushCurr(res);\n return res.flushed.series[0] ?? null;\n }\n\n /** Closes the cache. It must not be used afterwards. */\n close(): void {\n this.curr = null;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { MultiSeries, type Series, type TimeRange } from \"@synnaxlabs/x\";\n\nimport { UnexpectedError } from \"@/errors\";\nimport { Dynamic, type DynamicProps } from \"@/framer/cache/dynamic\";\nimport {\n type DirtyReadResult,\n type GCMetrics,\n Static,\n type StaticProps,\n} from \"@/framer/cache/static\";\n\nexport interface UnaryProps\n extends StaticProps, Pick<DynamicProps, \"dynamicBufferSize\"> {}\n\n/**\n * Caches data for a single channel: a dynamic leading buffer for live writes backed\n * by a static cache for flushed and historical data.\n * @throws {UnexpectedError} from every method after close().\n */\nexport class Unary {\n private closed: boolean = false;\n private readonly static: Static;\n private readonly dynamic: Dynamic;\n\n constructor(props: UnaryProps) {\n this.static = new Static(props);\n this.dynamic = new Dynamic({\n dynamicBufferSize: props.dynamicBufferSize,\n transform: props.transform,\n instrumentation: props.instrumentation,\n });\n }\n\n writeDynamic(series: MultiSeries): MultiSeries {\n this.checkOpen(\"writeDynamic\");\n const { flushed, allocated } = this.dynamic.write(series);\n // Flushed buffers stay streamed until a fetch replaces them.\n if (flushed.length > 0) this.static.write(flushed, true);\n return allocated;\n }\n\n get leadingBuffer(): Series | null {\n this.checkOpen(\"leadingBuffer\");\n return this.dynamic.leadingBuffer;\n }\n\n /**\n * Flushes the live leading buffer into the static cache with its real end time,\n * so reads treat the span after it as a gap to fetch. Call when streaming for\n * the channel stops.\n */\n flushDynamic(): void {\n this.checkOpen(\"flushDynamic\");\n const flushed = this.dynamic.flush();\n if (flushed != null && flushed.length > 0)\n this.static.write(new MultiSeries([flushed]), true);\n }\n\n writeStatic(series: MultiSeries): void {\n this.checkOpen(\"writeStatic\");\n this.static.write(series);\n }\n\n /**\n * Reads cached data overlapping the given time range. The result includes the live\n * leading buffer when the data it actually holds overlaps the range, judged by the\n * last stamped write rather than the buffer's provisional MAX end, so the buffer\n * never leaks into reads of spans it has no samples for. It never claims coverage\n * either: its samples carry provisional leading alignments that cannot pair with\n * fetched data on another channel, so its span is still reported as a gap to fetch. A\n * span may therefore return in both its streamed and fetched representation.\n */\n read(tr: TimeRange): DirtyReadResult {\n this.checkOpen(\"read\");\n const res = this.static.dirtyRead(tr);\n const buf = this.dynamic.leadingBuffer;\n const dataTr = this.dynamic.dataTimeRange;\n if (buf == null || dataTr == null || buf.length === 0 || !dataTr.overlapsWith(tr))\n return res;\n res.series.push(buf);\n return res;\n }\n\n gc(): GCMetrics {\n this.checkOpen(\"gc\");\n return this.static.gc();\n }\n\n close(): void {\n this.closed = true;\n this.dynamic.close();\n this.static.close();\n }\n\n private checkOpen(op: string): void {\n if (this.closed)\n throw new UnexpectedError(`${op} called on a closed telemetry cache entry`);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { TimeSpan } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { UnexpectedError } from \"@/errors\";\nimport { type DynamicProps } from \"@/framer/cache/dynamic\";\nimport {\n DEFAULT_STATIC_PROPS,\n type StaticProps,\n zeroGCMetrics,\n} from \"@/framer/cache/static\";\nimport { Unary } from \"@/framer/cache/unary\";\n\nconst DEFAULT_DYNAMIC_BUFFER_SIZE: TimeSpan = TimeSpan.seconds(60);\n\n/** Props for instantiating a {@link Cache} */\nexport interface CacheProps\n extends StaticProps, Partial<Pick<DynamicProps, \"dynamicBufferSize\">> {\n /**\n * Sets the interval at which the cache will garbage collect, removing stale data\n * that is not in use by the rest of the program.\n * @default TimeSpan.seconds(30)\n */\n gcInterval?: TimeSpan;\n}\n\n/**\n * Maintains an in-memory cache of channel data. Entries are created on demand and\n * carry no channel metadata; buffer types derive from the data written to them.\n */\nexport class Cache {\n private readonly props: Required<CacheProps>;\n private readonly cache = new Map<channel.Key, Unary>();\n private readonly gcInterval: ReturnType<typeof setInterval>;\n private closed = false;\n\n constructor(props: CacheProps = {}) {\n const {\n dynamicBufferSize = DEFAULT_DYNAMIC_BUFFER_SIZE,\n gcInterval = TimeSpan.seconds(30),\n instrumentation = DEFAULT_STATIC_PROPS.instrumentation,\n transform = DEFAULT_STATIC_PROPS.transform,\n staleEntryThreshold = DEFAULT_STATIC_PROPS.staleEntryThreshold,\n } = props;\n this.props = {\n dynamicBufferSize,\n gcInterval,\n instrumentation,\n transform,\n staleEntryThreshold,\n };\n this.gcInterval = setInterval(() => this.gc(), gcInterval.milliseconds);\n }\n\n /**\n * Returns the cache entry for the given channel, creating an empty one if it does\n * not exist.\n * @throws {UnexpectedError} if the cache has been closed.\n */\n get(key: channel.Key): Unary {\n if (this.closed)\n throw new UnexpectedError(`get(${key}) called on a closed telemetry cache`);\n const existing = this.cache.get(key);\n if (existing != null) return existing;\n const { dynamicBufferSize, transform, staleEntryThreshold } = this.props;\n const unary = new Unary({\n dynamicBufferSize,\n transform,\n staleEntryThreshold,\n instrumentation: this.props.instrumentation.child(`cache-${key}`),\n });\n this.cache.set(key, unary);\n return unary;\n }\n\n private gc(): void {\n const {\n instrumentation: { L },\n } = this.props;\n L.info(\"starting garbage collection\");\n const total = zeroGCMetrics();\n this.cache.forEach((c) => {\n const res = c.gc();\n total.purgedSeries += res.purgedSeries;\n total.purgedBytes = total.purgedBytes.add(res.purgedBytes);\n });\n L.info(\n \"garbage collection complete\",\n {\n purgedSeries: total.purgedSeries,\n purgedBytes: total.purgedBytes.toString(),\n },\n true,\n );\n }\n\n /**\n * Closes the cache, clearing all entries and stopping garbage collection. All\n * methods throw after close.\n */\n close(): void {\n this.closed = true;\n clearInterval(this.gcInterval);\n this.cache.forEach((c) => c.close());\n this.cache.clear();\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { Unreachable } from \"@synnaxlabs/freighter\";\nimport {\n debounce,\n errors,\n MultiSeries,\n type Series,\n TimeRange,\n TimeSpan,\n} from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { UnexpectedError } from \"@/errors\";\nimport { type Cache } from \"@/framer/cache/cache\";\nimport { type Frame } from \"@/framer/frame\";\n\n/** A function that reads a telemetry frame from the Synnax cluster. */\nexport interface RemoteReader {\n (tr: TimeRange, keys: channel.Key[]): Promise<Frame>;\n}\n\ninterface ReadRequest {\n channel: channel.Key;\n gaps: TimeRange[];\n}\n\n// Tracks one read's outstanding fetches, so the read settles when its last fetch lands.\n// The first failure among them wins.\ninterface Tracker {\n entry: debounce.Entry<ReadRequest>;\n remaining: number;\n failure?: unknown;\n}\n\ninterface BatchFetch {\n gap: TimeRange;\n channels: Set<channel.Key>;\n trackers: Set<Tracker>;\n}\n\nexport interface ReaderProps {\n /** Function used to read remote data from the server. */\n readRemote: RemoteReader;\n /** Will read from and populate the given cache with fetched data. */\n cache: Cache;\n /**\n * Used to batch read requests to the server to minimize traffic. The window is not\n * extended by later reads, so it is also the maximum wait before a batch fires.\n * @default TimeSpan.milliseconds(50)\n */\n batchDebounce?: TimeSpan;\n /**\n * Reads whose gap time ranges are within this threshold merge into one request.\n * @default TimeSpan.milliseconds(5)\n */\n overlapThreshold?: TimeSpan;\n /**\n * Deadline for a single remote fetch. A fetch that does not settle within it rejects\n * the reads it serves with an Unreachable error.\n * @default TimeSpan.seconds(30)\n */\n fetchTimeout?: TimeSpan;\n}\n\n/**\n * Reads historical telemetry, serving from the cache and batch-filling gaps from the\n * server. A fetch failure rejects only the reads whose gaps were in the failed fetch.\n */\nexport class Reader {\n private readonly props: Required<Omit<ReaderProps, \"batchDebounce\">>;\n private readonly batcher: debounce.Batcher<ReadRequest>;\n private closed = false;\n // Reads whose fetches are in flight, so close can reject them without waiting on the\n // fetches themselves.\n private readonly inFlight = new Set<Tracker>();\n\n constructor(props: ReaderProps) {\n const {\n readRemote,\n cache,\n batchDebounce = TimeSpan.milliseconds(50),\n overlapThreshold = TimeSpan.milliseconds(5),\n fetchTimeout = TimeSpan.seconds(30),\n } = props;\n this.props = { readRemote, cache, overlapThreshold, fetchTimeout };\n this.batcher = new debounce.Batcher({\n interval: batchDebounce,\n exec: async (entries) => {\n if (this.closed) throw new UnexpectedError(\"telemetry reader is closed\");\n await this.batchRead(entries);\n },\n });\n }\n\n /**\n * Reads the given time range for the given channel.\n * @throws {UnexpectedError} if the reader is closed while the read is pending.\n * @throws {Unreachable} if a fetch serving the read exceeds the fetch timeout.\n */\n async read(tr: TimeRange, channel: channel.Key): Promise<MultiSeries> {\n const { cache } = this.props;\n const unary = cache.get(channel);\n const { series, gaps } = unary.read(tr);\n if (gaps.length === 0) return series;\n if (this.closed) throw new UnexpectedError(\"telemetry reader is closed\");\n await this.batcher.enqueue({ channel, gaps });\n return unary.read(tr).series;\n }\n\n private async batchRead(entries: Array<debounce.Entry<ReadRequest>>): Promise<void> {\n const { cache, overlapThreshold } = this.props;\n const batched: BatchFetch[] = [];\n const trackers = new Map<debounce.Entry<ReadRequest>, Tracker>();\n entries.forEach((entry) => {\n const unary = cache.get(entry.req.channel);\n entry.req.gaps.forEach((rawGap) => {\n // An earlier batch or a streaming write may have filled part of the gap while\n // this entry sat in the debounce window.\n unary.read(rawGap).gaps.forEach((gap) => {\n let tracker = trackers.get(entry);\n if (tracker == null) {\n tracker = { entry, remaining: 0 };\n trackers.set(entry, tracker);\n this.inFlight.add(tracker);\n }\n const g = batched.find((r) => r.gap.equals(gap, overlapThreshold));\n if (g == null) {\n batched.push({\n gap,\n channels: new Set([entry.req.channel]),\n trackers: new Set([tracker]),\n });\n tracker.remaining++;\n } else {\n g.channels.add(entry.req.channel);\n g.gap = TimeRange.max(g.gap, gap);\n if (!g.trackers.has(tracker)) {\n g.trackers.add(tracker);\n tracker.remaining++;\n }\n }\n });\n });\n });\n entries.forEach((entry) => {\n if (!trackers.has(entry)) entry.resolve();\n });\n await Promise.all(batched.map(async (b) => await this.fetchGap(b)));\n }\n\n // Never throws: every outcome, including a deadline expiry and a post-close arrival,\n // settles through the trackers.\n private async fetchGap({ gap, channels, trackers }: BatchFetch): Promise<void> {\n const { cache } = this.props;\n let failure: unknown;\n try {\n const frame = await this.fetchWithDeadline(gap, Array.from(channels));\n if (!this.closed) {\n // Group series by key in one pass; per-key get() scans the whole frame.\n const grouped = new Map<channel.Key, Series[]>();\n frame.forEach((k, s) => {\n const key = k as channel.Key;\n const existing = grouped.get(key);\n if (existing == null) grouped.set(key, [s]);\n else existing.push(s);\n });\n channels.forEach((key) =>\n cache.get(key).writeStatic(new MultiSeries(grouped.get(key) ?? [])),\n );\n }\n } catch (err) {\n failure = err;\n }\n trackers.forEach((tracker) => {\n // close() already settled it.\n if (!this.inFlight.has(tracker)) return;\n if (failure != null) tracker.failure ??= failure;\n tracker.remaining--;\n if (tracker.remaining > 0) return;\n this.inFlight.delete(tracker);\n if (tracker.failure == null) tracker.entry.resolve();\n else tracker.entry.reject(tracker.failure);\n });\n }\n\n private async fetchWithDeadline(\n gap: TimeRange,\n channels: channel.Key[],\n ): Promise<Frame> {\n const { readRemote, fetchTimeout } = this.props;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const timeout = fetchTimeout.toString();\n const message = `gap read for ${gap.toString()} timed out after ${timeout}`;\n reject(new Unreachable({ message }));\n }, fetchTimeout.milliseconds);\n });\n const fetched = readRemote(gap, channels);\n try {\n return await Promise.race([fetched, deadline]);\n } catch (err) {\n // The read already failed for its callers; a late settle of the losing fetch must\n // not surface as an unhandled rejection.\n fetched.catch(() => {});\n throw errors.fromUnknown(err);\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Closes the reader, rejecting every pending read with an UnexpectedError. In-flight\n * fetch results are discarded when they arrive.\n */\n async close(): Promise<void> {\n this.closed = true;\n const err = new UnexpectedError(\"telemetry reader is closed\");\n this.batcher.close(err);\n this.inFlight.forEach(({ entry }) => entry.reject(err));\n this.inFlight.clear();\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { alamos } from \"@synnaxlabs/alamos\";\nimport {\n array,\n breaker,\n type CrudeTimeSpan,\n type destructor,\n MultiSeries,\n Rate,\n type Series,\n sync,\n TimeSpan,\n} from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { UnexpectedError } from \"@/errors\";\nimport { type Cache } from \"@/framer/cache/cache\";\nimport { type Streamer, type StreamerConfig } from \"@/framer/streamer\";\nimport { status } from \"@/status\";\n\n/** Stream lifecycle hooks the streamer uses to track connection health. */\nexport interface StreamHooks {\n /** Called after every successful reconnect of the underlying stream. */\n onReopen: () => void;\n /** Called when the underlying stream fails and reconnection begins. */\n onDrop: (error: Error) => void;\n}\n\n/** Opens the underlying frame stream, hardened against connection loss. */\nexport interface HardenedOpener {\n (config: StreamerConfig, hooks: StreamHooks): Promise<Streamer>;\n}\n\n/**\n * Receives every channel that changed on the shared stream, which may include\n * keys the handler did not subscribe to.\n */\nexport type StreamHandler = (data: Map<channel.Key, MultiSeries>) => void;\n\n/** Receives per-key data-plane status transitions for subscribed channels. */\nexport type StatusHandler = (key: channel.Key, status: status.Status) => void;\n\n/**\n * A durable handle on streaming demand. Closing it releases the demand; until then\n * the streamer owns converging the underlying stream to it.\n */\nexport interface Subscription {\n /** Releases the subscription's demand. */\n close: () => void;\n /** @returns the current data-plane status for the given key. */\n status: (key: channel.Key) => status.Status;\n /** Registers a handler for status transitions on the subscription's keys. */\n onStatusChange: (handler: StatusHandler) => destructor.Destructor;\n}\n\ninterface Entry {\n handler: StreamHandler;\n keys: Set<channel.Key>;\n statusHandlers: Set<StatusHandler>;\n removed: boolean;\n}\n\nexport interface MultiplexedStreamerProps {\n cache: Cache;\n openStreamer: HardenedOpener;\n instrumentation?: alamos.Instrumentation;\n /**\n * How long a closed subscription's keys stay on the stream, damping churn from\n * rapid unsubscribe and resubscribe cycles.\n * @default TimeSpan.seconds(5)\n */\n removalDelay?: CrudeTimeSpan;\n /** Retry behavior for stream open and update failures. */\n breaker?: breaker.Config;\n}\n\n// Coalesces rapid demand changes into one stream update. The timer is not reset by\n// later calls, so sustained subscribing cannot starve the update.\nconst RECONCILE_DELAY = TimeSpan.milliseconds(100);\n\nconst THROTTLE_RATE = Rate.hz(60).valueOf();\n\nconst LOADING: status.Crude = { variant: \"loading\", message: \"subscribing\" };\nconst STREAMING: status.Crude = { variant: \"success\", message: \"streaming\" };\nconst RECONNECTING: status.Crude = { variant: \"warning\", message: \"reconnecting\" };\n\n/**\n * Multiplexes durable subscriptions onto one shared frame stream. Demand\n * registration is synchronous and cannot fail per key; all convergence work\n * surfaces as per-key statuses instead of thrown errors.\n */\nexport class MultiplexedStreamer {\n private readonly props: Required<\n Omit<MultiplexedStreamerProps, \"removalDelay\" | \"breaker\">\n > & {\n removalDelay: TimeSpan;\n };\n\n // Serializes stream open, update, and close against each other. Never held while\n // waiting on retry backoff so close() stays prompt.\n private readonly connMu = sync.newMutex({ closed: false });\n private readonly breaker: breaker.Breaker;\n private readonly entries = new Set<Entry>();\n private readonly statuses = new Map<channel.Key, status.Status>();\n private reconcileTimer: ReturnType<typeof setTimeout> | null = null;\n private readonly removalTimers = new Set<ReturnType<typeof setTimeout>>();\n private runLoop: Promise<void> | null = null;\n private streamer: Streamer | null = null;\n // The key set last accepted by the stream. Kept separately from the streamer so a\n // mid-reconnect streamer cannot be consulted for it.\n private sentKeys = new Set<channel.Key>();\n\n constructor(props: MultiplexedStreamerProps) {\n const {\n cache,\n openStreamer,\n instrumentation = alamos.NOOP,\n removalDelay = TimeSpan.seconds(5),\n } = props;\n this.props = {\n instrumentation,\n cache,\n openStreamer,\n removalDelay: new TimeSpan(removalDelay),\n };\n const {\n maxRetries = Infinity,\n baseInterval = TimeSpan.milliseconds(250),\n maxInterval = TimeSpan.seconds(5),\n scale = 2,\n jitter = 0.25,\n } = props.breaker ?? {};\n this.breaker = new breaker.Breaker({\n maxRetries,\n baseInterval,\n maxInterval,\n scale,\n jitter,\n });\n }\n\n /**\n * Registers demand for the given keys. Registration is synchronous: the handler\n * is called with any existing leading buffers, and the stream converges to the\n * new demand in the background.\n * @throws {UnexpectedError} if the streamer has been closed.\n */\n stream(handler: StreamHandler, keys: channel.Key[]): Subscription {\n if (this.connMu.closed)\n throw new UnexpectedError(\"stream() called on a closed telemetry streamer\");\n const { cache, instrumentation: ins } = this.props;\n ins.L.debug(\"adding stream handler\", { keys });\n // Deliver existing buffers before registration so a throwing handler leaves no\n // demand behind.\n const initial: Map<channel.Key, MultiSeries> = new Map(\n keys.map((key) => [\n key,\n new MultiSeries(array.toArray<Series>(cache.get(key).leadingBuffer)),\n ]),\n );\n handler(initial);\n const entry: Entry = {\n handler,\n keys: new Set(keys),\n statusHandlers: new Set(),\n removed: false,\n };\n this.entries.add(entry);\n keys.forEach((key) => {\n if (!this.statuses.has(key)) this.statuses.set(key, status.create(LOADING));\n });\n this.scheduleReconcile();\n return {\n close: () => this.remove(entry),\n status: (key) => this.statuses.get(key) ?? status.create(LOADING),\n onStatusChange: (statusHandler) => {\n entry.statusHandlers.add(statusHandler);\n return () => entry.statusHandlers.delete(statusHandler);\n },\n };\n }\n\n async close(): Promise<void> {\n const { instrumentation: ins } = this.props;\n if (this.reconcileTimer != null) clearTimeout(this.reconcileTimer);\n this.reconcileTimer = null;\n this.removalTimers.forEach(clearTimeout);\n this.removalTimers.clear();\n await this.connMu.runExclusive(async () => {\n this.connMu.closed = true;\n try {\n await this.releaseStream();\n } catch (e) {\n ins.L.error(\"failed to close streamer\", { error: e });\n }\n });\n }\n\n private async releaseStream(): Promise<void> {\n const prev = this.streamer;\n const prevLoop = this.runLoop;\n this.streamer = null;\n this.runLoop = null;\n prev?.close();\n if (prevLoop != null) await prevLoop;\n }\n\n private remove(entry: Entry): void {\n entry.removed = true;\n const timer = setTimeout(() => {\n this.removalTimers.delete(timer);\n this.entries.delete(entry);\n this.scheduleReconcile();\n }, this.props.removalDelay.milliseconds);\n this.removalTimers.add(timer);\n }\n\n private scheduleReconcile(delay: TimeSpan = RECONCILE_DELAY): void {\n if (this.connMu.closed || this.reconcileTimer != null) return;\n this.reconcileTimer = setTimeout(() => {\n this.reconcileTimer = null;\n void this.reconcile();\n }, delay.milliseconds);\n }\n\n /** @returns the union of keys across all entries, including those pending\n * removal, so the stream lags demand only by the removal delay. */\n private desiredKeys(): Set<channel.Key> {\n const keys = new Set<channel.Key>();\n this.entries.forEach((e) => e.keys.forEach((k) => keys.add(k)));\n return keys;\n }\n\n private setStatus(key: channel.Key, crude: status.Crude): void {\n const prev = this.statuses.get(key);\n if (prev?.variant === crude.variant && prev?.message === crude.message) return;\n const next = status.create(crude);\n this.statuses.set(key, next);\n this.entries.forEach((e) => {\n if (e.removed || !e.keys.has(key)) return;\n e.statusHandlers.forEach((handler) => {\n try {\n handler(key, next);\n } catch (err) {\n this.props.instrumentation.L.error(\n \"status handler failed\",\n { error: err },\n true,\n );\n }\n });\n });\n }\n\n // A flushed buffer stops claiming live coverage, so reads refetch the span the\n // stream will not deliver.\n private flushBuffers(keys: Iterable<channel.Key>): void {\n const { cache } = this.props;\n for (const key of keys) cache.get(key).flushDynamic();\n }\n\n private async reconcile(): Promise<void> {\n const { instrumentation: ins } = this.props;\n let retry = false;\n await this.connMu.runExclusive(async () => {\n if (this.connMu.closed) return;\n const desired = this.desiredKeys();\n try {\n if (desired.size === 0) {\n const removed = this.sentKeys;\n this.sentKeys = new Set();\n this.statuses.clear();\n await this.releaseStream();\n this.flushBuffers(removed);\n this.breaker.reset();\n ins.L.info(\"streamer closed, no keys to stream\");\n return;\n }\n if (\n this.streamer != null &&\n desired.size === this.sentKeys.size &&\n desired.isSubsetOf(this.sentKeys)\n )\n return;\n const arrKeys = Array.from(desired);\n const fresh = arrKeys.filter((k) => !this.sentKeys.has(k));\n const removed = Array.from(this.sentKeys).filter((k) => !desired.has(k));\n if (this.streamer == null) {\n ins.L.info(\"creating new streamer\", { keys: arrKeys });\n const streamer = await this.props.openStreamer(\n { channels: arrKeys, throttleRate: THROTTLE_RATE },\n {\n onReopen: () =>\n this.sentKeys.forEach((key) => this.setStatus(key, STREAMING)),\n // Frames may drop until the reopen, so the buffers' live-coverage\n // claims end here.\n onDrop: () => {\n this.flushBuffers(this.sentKeys);\n this.sentKeys.forEach((key) => this.setStatus(key, RECONNECTING));\n },\n },\n );\n this.streamer = streamer;\n this.runLoop = this.run(streamer);\n } else {\n ins.L.debug(\"updating streamer\", () => ({\n prev: Array.from(this.sentKeys),\n next: arrKeys,\n }));\n await this.streamer.update(arrKeys);\n }\n this.sentKeys = desired;\n this.flushBuffers(removed);\n // Existing keys keep their status so a demand change cannot clear a per-key\n // error.\n fresh.forEach((key) => this.setStatus(key, STREAMING));\n this.statuses.forEach((_, key) => {\n if (!desired.has(key)) this.statuses.delete(key);\n });\n this.breaker.reset();\n } catch (e) {\n ins.L.error(\"failed to update streamer\", { error: e });\n const failure = status.fromException(e, \"failed to stream channel\");\n desired.forEach((key) => {\n if (!this.sentKeys.has(key)) this.setStatus(key, failure);\n });\n retry = true;\n }\n });\n if (!retry || this.connMu.closed) return;\n if (await this.breaker.wait()) this.scheduleReconcile(TimeSpan.ZERO);\n }\n\n private async run(streamer: Streamer): Promise<void> {\n const { cache, instrumentation: ins } = this.props;\n try {\n for await (const frame of streamer) {\n // Group series by key in one pass; per-key get() scans the whole frame.\n const grouped: Map<channel.Key, Series[]> = new Map();\n frame.forEach((k, s) => {\n const key = k as channel.Key;\n const existing = grouped.get(key);\n if (existing == null) grouped.set(key, [s]);\n else existing.push(s);\n });\n const changed: Map<channel.Key, MultiSeries> = new Map();\n const demanded = this.desiredKeys();\n grouped.forEach((series, k) => {\n try {\n const unary = cache.get(k);\n changed.set(k, unary.writeDynamic(new MultiSeries(series)));\n // A frame for a key with no remaining demand arrived behind the\n // stream update; its buffer must not claim live coverage.\n if (!demanded.has(k)) unary.flushDynamic();\n this.setStatus(k, STREAMING);\n } catch (e) {\n this.setStatus(k, status.fromException(e, \"failed to buffer channel\"));\n }\n });\n if (changed.size !== 0)\n this.entries.forEach((e) => {\n if (e.removed) return;\n try {\n e.handler(changed);\n } catch (err) {\n ins.L.error(\"stream handler failed\", { error: err }, true);\n }\n });\n }\n } catch (e) {\n ins.L.error(\"streamer run loop failed\", { error: e }, true);\n } finally {\n // A loop that ends while demand remains is an outage, not a shutdown.\n if (!this.connMu.closed && this.streamer === streamer) {\n this.streamer = null;\n this.runLoop = null;\n this.flushBuffers(this.sentKeys);\n this.sentKeys = new Set();\n this.scheduleReconcile(TimeSpan.ZERO);\n }\n }\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type MultiSeries, type TimeRange } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { Cache, type CacheProps } from \"@/framer/cache/cache\";\nimport { Reader, type ReaderProps } from \"@/framer/cache/reader\";\nimport {\n MultiplexedStreamer,\n type MultiplexedStreamerProps,\n type StreamHandler,\n type Subscription,\n} from \"@/framer/cache/streamer\";\nimport { HardenedStreamer } from \"@/framer/hardened\";\nimport { type StreamOpener } from \"@/framer/streamer\";\n\n/** Props for {@link Feed}, including the transport it reads and streams through. */\nexport interface FeedProps\n extends\n CacheProps,\n Omit<ReaderProps, \"cache\">,\n Omit<MultiplexedStreamerProps, \"cache\" | \"openStreamer\"> {\n openStreamer: StreamOpener;\n}\n\n/** The part of {@link FeedProps} a caller sets. The client supplies the rest. */\nexport interface FeedOptions extends Omit<FeedProps, \"readRemote\" | \"openStreamer\"> {}\n\n/**\n * Cached, demand-managed access to channel telemetry: durable streaming\n * subscriptions multiplexed onto one frame stream, and batched historical reads\n * served through per-channel rolling buffers.\n */\nexport class Feed {\n private readonly cache: Cache;\n private readonly reader: Reader;\n private readonly streamer: MultiplexedStreamer;\n\n constructor(props: FeedProps) {\n const {\n readRemote,\n openStreamer,\n transform,\n instrumentation,\n dynamicBufferSize,\n gcInterval,\n staleEntryThreshold,\n removalDelay,\n breaker,\n batchDebounce,\n overlapThreshold,\n } = props;\n this.cache = new Cache({\n transform,\n dynamicBufferSize,\n gcInterval,\n staleEntryThreshold,\n instrumentation: instrumentation?.child(\"cache\"),\n });\n this.reader = new Reader({\n readRemote,\n cache: this.cache,\n batchDebounce,\n overlapThreshold,\n });\n this.streamer = new MultiplexedStreamer({\n cache: this.cache,\n openStreamer: async (config, { onReopen, onDrop }) =>\n await HardenedStreamer.open(openStreamer, config, breaker, onReopen, onDrop),\n removalDelay,\n breaker,\n instrumentation: instrumentation?.child(\"streamer\"),\n });\n }\n\n /**\n * Registers durable streaming demand for the given keys. Returns synchronously;\n * convergence failures surface as per-key statuses, never as rejections. The\n * handler's first call precedes registration, so a throw from it leaves no\n * subscription behind.\n * @throws {UnexpectedError} if the feed has been closed.\n */\n stream(handler: StreamHandler, keys: channel.Key[]): Subscription {\n return this.streamer.stream(handler, keys);\n }\n\n /**\n * Reads the given time range for the given channel, serving from the cache and\n * gap-filling from the cluster.\n */\n async read(tr: TimeRange, key: channel.Key): Promise<MultiSeries> {\n return await this.reader.read(tr, key);\n }\n\n /** Closes the feed, releasing the stream and all cached buffers. */\n async close(): Promise<void> {\n await this.streamer.close();\n await this.reader.close();\n this.cache.close();\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n array,\n MultiSeries,\n Series,\n type SeriesDigest,\n type SeriesPayload,\n Size,\n type TelemValue,\n TimeRange,\n TimeStamp,\n unique,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { UnexpectedError, ValidationError } from \"@/errors\";\n\ntype ColumnType = \"key\" | \"name\" | null;\n\n/** A frame's shape without its samples, for logging and debugging. */\nexport interface Digest extends Record<channel.Key | channel.Name, SeriesDigest[]> {}\n\nconst columnType = (columns: channel.PrimitiveParams): ColumnType => {\n const arrKeys = array.toArray(columns);\n if (arrKeys.length === 0) return null;\n if (typeof arrKeys[0] === \"number\") return \"key\";\n if (!isNaN(parseInt(arrKeys[0], 10))) return \"key\";\n return \"name\";\n};\n\nconst validateMatchedColsAndSeries = (\n columns: channel.PrimitiveParams,\n series: Series[],\n): void => {\n const colsArr = array.toArray(columns);\n if (colsArr.length === series.length) return;\n const colType = columnType(columns);\n if (colType === null)\n throw new ValidationError(\n \"[Frame] - channel keys or names must be provided when constructing a frame.\",\n );\n throw new ValidationError(\n `[Frame] - ${colType}s and series must be the same length.\n Got ${colsArr.length} ${colType}s and ${series.length} series.`,\n );\n};\n\n/** Anything {@link Frame}'s constructor accepts. */\nexport type CrudeFrame =\n | Frame\n | CrudePayload\n | Map<channel.Key | channel.Name, Series[] | Series>\n | Record<channel.Key | channel.Name, Series[] | Series>;\n\n/**\n * A frame is a collection of series mapped to a particular channel. Frames\n * can be keyed by channel name or channel key, but not both.\n *\n * Frames have two important characteristics: alignment and orientation.\n *\n * A frame's alignment defines how correlated the series for different channels in the\n * frame are:\n *\n * - A frame is weakly aligned if the time range occupied by all series of a\n * particular channel is the same for all channels in the frame. This means that the\n * series for a particular channel can have gaps between them.\n *\n * - A strongly aligned frame means that all channels share the same rate/index and\n * there are no gaps in time between series. Strongly aligned frames are natural\n * to interpret, as the values in a particular 'row' of the frame share the same\n * timestamp. All frames written to Synnax must be strongly aligned.\n *\n * - Unaligned frames don't meet the requirements for weakly or strongly aligned frames.\n * Unaligned frames are common when reading from channels that don't have the same\n * index/rate and are continuous in different periods of time.\n *\n * Frames also have an orientation: horizontal, vertical, or square.\n *\n * - Horizontal frames have a single channel, and are strongly aligned by default.\n * A horizontal frame typically has a single array (in which case, it's also 'square'),\n * although it can have multiple series if all the series are continuous in time.\n *\n * - Vertical frames are strongly aligned and have on or more channels, but ONLY a single\n * array per channel. Synnax requires that all frames written to the database are\n * vertical.\n *\n * - Square frames are both horizontal and vertical. Only a frame with a single channel\n * and array can be square.\n */\nexport class Frame {\n readonly columns: channel.Key[] | channel.Name[] = [];\n readonly series: Series[] = [];\n\n constructor(\n columnsOrData: channel.PrimitiveParams | CrudeFrame = [],\n series: Series | Series[] = [],\n ) {\n if (columnsOrData instanceof Frame) {\n this.columns = columnsOrData.columns;\n this.series = columnsOrData.series;\n return;\n }\n\n if (columnsOrData instanceof Map) {\n columnsOrData.forEach((v, k) => this.push(k, ...array.toArray(v)));\n return;\n }\n\n const isObject = typeof columnsOrData === \"object\" && !Array.isArray(columnsOrData);\n\n if (isObject) {\n if (\"keys\" in columnsOrData && \"series\" in columnsOrData) {\n const data_ = columnsOrData as Payload;\n data_.series ??= [];\n data_.keys ??= [];\n const series = data_.series.map((a) => seriesFromPayload(a));\n validateMatchedColsAndSeries(data_.keys, series);\n this.columns = data_.keys.slice();\n this.series = series;\n } else\n Object.entries(columnsOrData).forEach(([k, v]) => {\n const key = parseInt(k, 10);\n if (!isNaN(key)) return this.push(key, ...array.toArray(v));\n this.push(k, ...array.toArray(v));\n });\n return;\n }\n\n if (\n Array.isArray(columnsOrData) ||\n [\"string\", \"number\"].includes(typeof columnsOrData)\n ) {\n const data_ = array.toArray(series);\n const cols = array.toArray(columnsOrData) as channel.Key[] | channel.Name[];\n validateMatchedColsAndSeries(cols, data_);\n data_.forEach((d, i) => this.push(cols[i], d));\n return;\n }\n\n throw new ValidationError(\n `[Frame] - invalid frame construction parameters. data parameter ust be a frame\n payload, a list of lazy series, a lazy array, a map, or a record keyed by channel\n name. keys parameter must be a set of channel keys or channel names.`,\n );\n }\n\n /**\n * @returns \"key\" if the frame columns are channel keys, \"name\" if the columns are\n * channel names, and null if the frame has no columns.\n */\n get colType(): ColumnType {\n if (this.columns.length === 0) return null;\n const firstKey = this.columns[0];\n return typeof firstKey === \"string\" ? \"name\" : \"key\";\n }\n\n /**\n * @returns the channel keys if the frame is keyed by channel key, and throws an error\n * otherwise.\n */\n get keys(): channel.Key[] {\n if (this.colType === \"name\") throw new UnexpectedError(\"colType is not key\");\n return (this.columns as channel.Key[]) ?? [];\n }\n\n /**\n * @returns the unique channel keys if the frame is keyed by channel key, and throws an\n * error otherwise.\n */\n get uniqueKeys(): channel.Key[] {\n return unique.unique(this.keys);\n }\n\n /**\n * @returns the channel names if the frame is keyed by channel name, and throws an error\n * otherwise.\n */\n get names(): string[] {\n if (this.colType === \"key\") throw new UnexpectedError(\"colType is not name\");\n return (this.columns as string[]) ?? [];\n }\n\n /**\n * @returns the unique channel names if the frame is keyed by channel name, and throws an\n * otherwise.\n */\n get uniqueNames(): string[] {\n return unique.unique(this.names);\n }\n\n /** @returns the unique columns in the frame. */\n get uniqueColumns(): channel.Key[] | channel.Name[] {\n return this.colType === \"key\" ? this.uniqueKeys : this.uniqueNames;\n }\n\n toPayload(): Payload {\n return {\n series: this.series.map((a) => seriesToPayload(a)),\n keys: [...this.keys],\n };\n }\n\n /**\n * @returns true if the frame is vertical. Vertical frames are strongly aligned and\n * have on or more channels, but ONLY a single array per channel. Synnax requires\n * that all frames written to the database are vertical.\n */\n get isVertical(): boolean {\n return this.uniqueColumns.length === this.columns.length;\n }\n\n /**\n * @returns true if the frame is horizontal. Horizontal frames have a single channel,\n * and are strongly aligned by default. A horizontal frame typically has a single\n * array (in which case, it's also 'square'), although it can have multiple series if\n * all the series are continuous in time.\n */\n get isHorizontal(): boolean {\n return this.uniqueColumns.length === 1;\n }\n\n /**\n * @returns true if the frame is square. Square frames are both horizontal and vertical.\n * Only a frame with a single channel and array can be square.\n */\n get isSquare(): boolean {\n return this.isHorizontal && this.isVertical;\n }\n\n /**\n * @returns true if the frame is weakly aligned. A frame is weakly aligned if it meets\n * the time range occupied by all series of a particular channel is the same for all\n * channels in the frame. This means that the series for a particular channel can have\n * gaps between them.\n */\n get isWeaklyAligned(): boolean {\n if (this.columns.length <= 1) return true;\n const { timeRanges } = this;\n return timeRanges.every((tr) => tr.equals(timeRanges[0]));\n }\n\n timeRange(col?: channel.Key | channel.Name): TimeRange {\n if (col == null) {\n if (this.columns.length === 0) return TimeRange.ZERO;\n const start = TimeStamp.min(...this.series.map((a) => a.timeRange.start));\n const end = TimeStamp.max(...this.series.map((a) => a.timeRange.end));\n return new TimeRange(start, end);\n }\n const group = this.get(col);\n if (group == null) return TimeRange.ZERO;\n return group.timeRange;\n }\n\n latest(): Record<string, TelemValue | undefined> {\n return this.at(-1);\n }\n\n get timeRanges(): TimeRange[] {\n return this.uniqueColumns.map((col) => this.timeRange(col));\n }\n\n /**\n * @returns lazy series matching the given channel key or name.\n * @param key the channel key or name.\n */\n get(key: channel.Key | channel.Name): MultiSeries;\n\n /**\n * @returns a frame with the given channel keys or names.\n * @param keys the channel keys or names.\n */\n get(keys: channel.Key[] | channel.Name[]): Frame;\n\n get(key: channel.PrimitiveParams): MultiSeries | Frame {\n if (Array.isArray(key))\n return this.filter((k) => (key as channel.Key[]).includes(k as channel.Key));\n return new MultiSeries(this.series.filter((_, i) => this.columns[i] === key));\n }\n\n /** Pushes a set of series for the given channel onto the frame. */\n push(key: channel.Key | channel.Name, ...v: Series[]): void;\n\n /** Pushes the frame onto the current frame. */\n push(frame: Frame): void;\n\n push(keyOrFrame: channel.Key | channel.Name | Frame, ...v: Series[]): void {\n if (keyOrFrame instanceof Frame) {\n if (\n keyOrFrame.colType != null &&\n this.colType !== null &&\n keyOrFrame.colType !== this.colType\n )\n throw new ValidationError(\"keyVariant must match\");\n this.series.push(...keyOrFrame.series);\n (this.columns as channel.Key[]).push(...(keyOrFrame.columns as channel.Key[]));\n } else {\n this.series.push(...v);\n if (typeof keyOrFrame === \"string\" && this.colType === \"key\")\n throw new ValidationError(\"keyVariant must match\");\n else if (typeof keyOrFrame !== \"string\" && this.colType === \"name\")\n throw new ValidationError(\"keyVariant must match\");\n (this.columns as channel.Key[]).push(\n ...(Array.from({ length: v.length }, () => keyOrFrame) as channel.Key[]),\n );\n }\n }\n\n /**\n * @returns a shallow copy of this frame containing all series in the current frame and the\n * provided frame.\n */\n concat(frame: Frame): Frame {\n return new Frame([...this.columns, ...frame.columns] as channel.Key[], [\n ...this.series,\n ...frame.series,\n ]);\n }\n\n /**\n * @returns true if the frame contains the provided channel key or name.\n * @param channel the channel key or name to check.\n */\n has(channel: channel.Key | channel.Name): boolean {\n if (typeof channel === \"string\" && this.colType === \"key\") return false;\n if (typeof channel === \"number\" && this.colType === \"name\") return false;\n return (this.columns as channel.Key[]).includes(channel as channel.Key);\n }\n\n /**\n * @returns a new frame containing the mapped output of the provided function.\n * @param fn a function that takes a channel key and series and returns a boolean.\n */\n map(\n fn: (\n k: channel.Key | channel.Name,\n arr: Series,\n i: number,\n ) => [channel.Key | channel.Name, Series],\n ): Frame {\n const frame = new Frame();\n this.forEach((k, arr, i) => frame.push(...fn(k, arr, i)));\n return frame;\n }\n\n mapFilter(\n fn: (\n k: channel.Key | channel.Name,\n arr: Series,\n i: number,\n ) => [channel.Key | channel.Name, Series, boolean],\n ): Frame {\n const frame = new Frame();\n this.forEach((k, arr, i) => {\n const [newK, newArr, keep] = fn(k, arr, i);\n if (keep) frame.push(newK, newArr);\n });\n return frame;\n }\n\n /**\n * Iterates over all series in the current frame.\n * @param fn a function that takes a channel key and series.\n */\n forEach(fn: (k: channel.Key | channel.Name, arr: Series, i: number) => void): void {\n this.columns.forEach((k, i) => {\n const a = this.series[i];\n fn(k, a, i);\n });\n }\n\n /**\n * Iterates over all unique columns in the frame.\n * @param fn a function that takes a channel key, multi-series, and index.\n */\n forEachUnique(\n fn: (k: channel.Key | channel.Name, ms: MultiSeries, i: number) => void,\n ): void {\n this.uniqueColumns.forEach((k, i) => fn(k, this.get(k), i));\n }\n\n at(index: number, required: true): Record<channel.Key | channel.Name, TelemValue>;\n\n at(\n index: number,\n required?: false,\n ): Record<channel.Key | channel.Name, TelemValue | undefined>;\n\n at(\n index: number,\n required = false,\n ): Record<channel.Key | channel.Name, TelemValue | undefined> {\n const res: Record<channel.Key | channel.Name, TelemValue> = {};\n this.uniqueColumns.forEach((k) => {\n res[k] = this.get(k).at(index, required as true);\n });\n return res;\n }\n\n /**\n * @returns a new frame containing all series in the current frame that pass\n * the provided filter function.\n * @param fn a function that takes a channel key and series and returns a boolean.\n */\n filter(\n fn: (k: channel.Key | channel.Name, arr: Series, i: number) => boolean,\n ): Frame {\n const frame = new Frame();\n this.columns.forEach((k, i) => {\n const a = this.series[i];\n if (fn(k, a, i)) frame.push(k, a);\n });\n return frame;\n }\n\n /** @returns the total number of bytes in the frame. */\n get byteLength(): Size {\n return new Size(this.series.reduce((acc, v) => acc.add(v.byteLength), Size.ZERO));\n }\n\n /**\n * @returns a digest of information about the structure of the frame for debugging\n * purposes.\n */\n get digest(): Digest {\n const digest: Digest = {};\n this.keys.forEach((k, i) => {\n const sd = this.series[i].digest;\n if (k in digest) digest[k].push(sd);\n else digest[k] = [sd];\n });\n return digest;\n }\n\n /** @returns the total number of samples in the frame. */\n get length(): number {\n return this.series.reduce((acc, v) => acc + v.length, 0);\n }\n\n toString(): string {\n let str = `Frame{\\n`;\n this.uniqueColumns.forEach((c) => {\n str += ` ${c}: ${this.get(c)\n .series.map((s) => s.toString())\n .join(\",\")}\\n`;\n });\n str += \"}\";\n return str;\n }\n}\n\n/** Zod schema for a frame on the wire. */\nexport const frameZ = z.object({\n keys: z.union([\n z.null().transform<number[]>(() => []),\n z.number().array().default([]),\n ]),\n series: z.union([\n z.null().transform<z.infer<typeof Series.crudeZ>[]>(() => []),\n Series.crudeZ.array().default([]),\n ]),\n});\n\nexport interface Payload extends z.infer<typeof frameZ> {}\n\nexport interface CrudePayload extends z.input<typeof frameZ> {}\n\n/** Rebuilds a {@link Series} from its wire form. */\nexport const seriesFromPayload = (series: SeriesPayload): Series => {\n const { dataType, data, timeRange, alignment } = series;\n return new Series({ data, dataType, timeRange, glBufferUsage: \"static\", alignment });\n};\n\n/** Reduces a {@link Series} to its wire form. */\nexport const seriesToPayload = (series: Series): SeriesPayload => ({\n timeRange: series.timeRange,\n dataType: series.dataType,\n data: new Uint8Array(series.data.buffer),\n alignment: series.alignment,\n});\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nexport enum WriterCommand {\n Open = 0,\n Write = 1,\n Commit = 2,\n SetAuthority = 3,\n}\nexport const writerCommandZ = z.enum(WriterCommand);\n\nexport enum IteratorCommand {\n Open = 0,\n Next = 1,\n Prev = 2,\n SeekFirst = 3,\n SeekLast = 4,\n SeekLE = 5,\n SeekGE = 6,\n Valid = 7,\n Error = 8,\n}\nexport const iteratorCommandZ = z.enum(IteratorCommand);\n\nexport enum IteratorResponseVariant {\n None = 0,\n Ack = 1,\n Data = 2,\n}\nexport const iteratorResponseVariantZ = z.enum(IteratorResponseVariant);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type WebsocketMessage } from \"@synnaxlabs/freighter\";\nimport {\n binary,\n DataType,\n type SeriesPayload,\n TimeRange,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport { type z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { ValidationError } from \"@/errors\";\nimport { type Frame, type Payload } from \"@/framer/frame\";\nimport { type StreamerResponse } from \"@/framer/streamer\";\nimport { IteratorResponseVariant, WriterCommand } from \"@/framer/types.gen\";\nimport { type WriteRequest } from \"@/framer/writer\";\n\nconst BITS_PER_BYTE = 8;\n\nconst bitPackedByteCount = (nSamples: number): number =>\n Math.ceil(nSamples / BITS_PER_BYTE);\n\nconst seriesPldLength = (series: SeriesPayload): number =>\n series.data.byteLength / series.dataType.density.valueOf();\n\nconst seriesWireByteLength = (series: SeriesPayload): number => {\n if (series.dataType.equals(DataType.BOOLEAN))\n return bitPackedByteCount(seriesPldLength(series));\n return series.data.byteLength;\n};\n\nconst packBoolBits = (src: ArrayBuffer | Uint8Array): Uint8Array => {\n const srcBytes = src instanceof Uint8Array ? src : new Uint8Array(src);\n const dst = new Uint8Array(bitPackedByteCount(srcBytes.length));\n for (let i = 0; i < srcBytes.length; i++)\n if (srcBytes[i] !== 0)\n dst[Math.floor(i / BITS_PER_BYTE)] |= 1 << (i % BITS_PER_BYTE);\n return dst;\n};\n\nconst unpackBoolBits = (src: Uint8Array, sampleCount: number): ArrayBuffer => {\n const buf = new ArrayBuffer(sampleCount);\n const dst = new Uint8Array(buf);\n for (let i = 0; i < sampleCount; i++)\n dst[i] = (src[Math.floor(i / BITS_PER_BYTE)] >> (i % BITS_PER_BYTE)) & 1;\n return buf;\n};\n\n/** Orders channel keys the way the Core does. The default comparator sorts numbers as\n * strings and diverges as soon as two keys differ in decimal width. */\nconst compareKeys = (a: channel.Key, b: channel.Key): number => a - b;\n\nconst sortFramePayloadByKey = (framePayload: Payload): void => {\n const { keys, series } = framePayload;\n if (keys.every((k, i) => i === 0 || keys[i - 1] <= k)) return;\n const order = keys.map((_, i) => i).sort((a, b) => compareKeys(keys[a], keys[b]));\n const orderedKeys = order.map((i) => keys[i]);\n const orderedSeries = order.map((i) => series[i]);\n for (let i = 0; i < keys.length; i++) {\n keys[i] = orderedKeys[i];\n series[i] = orderedSeries[i];\n }\n};\n\nconst ZERO_ALIGNMENTS_FLAG_POS = 5;\nconst EQUAL_ALIGNMENTS_FLAG_POS = 4;\nconst EQUAL_LENGTHS_FLAG_POS = 3;\nconst EQUAL_TIME_RANGES_FLAG_POS = 2;\nconst TIME_RANGES_ZERO_FLAG_POS = 1;\nconst ALL_CHANNELS_PRESENT_FLAG_POS = 0;\n\nconst TIMESTAMP_SIZE = DataType.TIMESTAMP.density.valueOf();\nconst ALIGNMENT_SIZE = 8;\nconst DATA_LENGTH_SIZE = 4;\nconst KEY_SIZE = 4;\nconst SEQ_NUM_SIZE = 4;\nconst FLAGS_SIZE = 1;\n\ninterface CodecState {\n keys: channel.Key[];\n keyDataTypes: Map<channel.Key, DataType>;\n hasVariableDataTypes: boolean;\n}\n\nexport class Codec {\n contentType: string = CONTENT_TYPE;\n private states: Map<number, CodecState> = new Map();\n private currState: CodecState | undefined;\n private seqNum: number = 0;\n\n constructor(keys: channel.Key[] = [], dataTypes: DataType[] = []) {\n if (keys.length > 0 || dataTypes.length > 0) this.update(keys, dataTypes);\n }\n\n update(keys: channel.Key[], dataTypes: DataType[]): void {\n this.seqNum++;\n const state = {\n keys: [...keys],\n keyDataTypes: new Map(),\n hasVariableDataTypes: false,\n };\n keys.forEach((k, i) => {\n const dt = dataTypes[i];\n state.keyDataTypes.set(k, dt);\n if (dt.isVariable) state.hasVariableDataTypes = true;\n });\n // Encoder and decoder walk this order positionally when a frame carries every\n // channel, so it has to match the Core's.\n state.keys.sort(compareKeys);\n this.states.set(this.seqNum, state);\n this.currState = state;\n }\n\n private throwIfNotUpdated(op: string): void {\n if (this.seqNum < 1)\n throw new ValidationError(`\n The codec has not been updated with a list of channels and data types.\n Please call the update method before calling ${op}.\n `);\n }\n\n encode(payload: unknown, startOffset: number = 0): Uint8Array<ArrayBuffer> {\n this.throwIfNotUpdated(\"encode\");\n let src = payload as Payload;\n if (payload != null && typeof payload === \"object\" && \"toPayload\" in payload)\n src = (payload as Frame).toPayload();\n sortFramePayloadByKey(src);\n let currDataSize = -1;\n let startTime: TimeStamp | undefined;\n let endTime: TimeStamp | undefined;\n let currAlignment: bigint | undefined;\n let byteArraySize = startOffset + FLAGS_SIZE + SEQ_NUM_SIZE;\n let equalLengthsFlag = !this.currState?.hasVariableDataTypes;\n let equalTimeRangesFlag = true;\n let timeRangesZeroFlag = true;\n let channelFlag = true;\n let equalAlignmentsFlag = true;\n let zeroAlignmentsFlag = true;\n\n if (src.keys.length !== this.currState?.keys.length) {\n channelFlag = false;\n byteArraySize += src.keys.length * KEY_SIZE;\n }\n\n src.series.forEach((series, i) => {\n const pldLength = seriesPldLength(series);\n const key = src.keys[i];\n const dt = this.currState?.keyDataTypes.get(key);\n if (dt == null)\n throw new ValidationError(\n `Channel ${key} was not provided in the list of channels when opening the writer`,\n );\n if (!dt.equals(series.dataType))\n throw new ValidationError(\n `Series data type of ${series.dataType.toString()} does not match the data type of ${dt.toString()} for channel ${key}`,\n );\n\n byteArraySize += seriesWireByteLength(series);\n if (currDataSize === -1) {\n currDataSize = pldLength;\n startTime = series.timeRange?.start;\n endTime = series.timeRange?.end;\n currAlignment = BigInt(series.alignment ?? 0n);\n return;\n }\n if (currDataSize !== pldLength) equalLengthsFlag = false;\n if (\n startTime?.valueOf() !== series.timeRange?.start.valueOf() ||\n endTime?.valueOf() !== series.timeRange?.end.valueOf()\n )\n equalTimeRangesFlag = false;\n if (currAlignment !== BigInt(series.alignment ?? 0)) equalAlignmentsFlag = false;\n });\n\n timeRangesZeroFlag = equalTimeRangesFlag && startTime == null && endTime == null;\n\n zeroAlignmentsFlag =\n equalAlignmentsFlag && (currAlignment === undefined || currAlignment === 0n);\n\n if (equalLengthsFlag) byteArraySize += DATA_LENGTH_SIZE;\n else byteArraySize += src.keys.length * DATA_LENGTH_SIZE;\n\n if (!timeRangesZeroFlag)\n if (equalTimeRangesFlag) byteArraySize += TIMESTAMP_SIZE * 2;\n else byteArraySize += src.keys.length * TIMESTAMP_SIZE * 2;\n\n if (!zeroAlignmentsFlag)\n if (equalAlignmentsFlag) byteArraySize += ALIGNMENT_SIZE;\n else byteArraySize += src.keys.length * ALIGNMENT_SIZE;\n\n const buffer = new Uint8Array(byteArraySize);\n const view = new DataView(buffer.buffer);\n let offset = startOffset;\n buffer[offset] =\n (Number(zeroAlignmentsFlag) << ZERO_ALIGNMENTS_FLAG_POS) |\n (Number(equalAlignmentsFlag) << EQUAL_ALIGNMENTS_FLAG_POS) |\n (Number(equalLengthsFlag) << EQUAL_LENGTHS_FLAG_POS) |\n (Number(equalTimeRangesFlag) << EQUAL_TIME_RANGES_FLAG_POS) |\n (Number(timeRangesZeroFlag) << TIME_RANGES_ZERO_FLAG_POS) |\n (Number(channelFlag) << ALL_CHANNELS_PRESENT_FLAG_POS);\n offset++;\n view.setUint32(offset, this.seqNum, true);\n offset += SEQ_NUM_SIZE;\n\n if (equalLengthsFlag) {\n view.setUint32(offset, currDataSize, true);\n offset += DATA_LENGTH_SIZE;\n }\n\n if (equalTimeRangesFlag && !timeRangesZeroFlag) {\n view.setBigUint64(offset, startTime?.valueOf() ?? 0n, true);\n offset += TIMESTAMP_SIZE;\n view.setBigUint64(offset, endTime?.valueOf() ?? 0n, true);\n offset += TIMESTAMP_SIZE;\n }\n\n if (equalAlignmentsFlag && !zeroAlignmentsFlag) {\n view.setBigUint64(offset, currAlignment ?? 0n, true);\n offset += ALIGNMENT_SIZE;\n }\n\n src.series.forEach((series, i) => {\n if (!channelFlag) {\n view.setUint32(offset, src.keys[i], true);\n offset += KEY_SIZE;\n }\n if (!equalLengthsFlag) {\n let seriesLengthOrSize = series.data.byteLength;\n if (!series.dataType.isVariable) seriesLengthOrSize = seriesPldLength(series);\n view.setUint32(offset, seriesLengthOrSize, true);\n offset += DATA_LENGTH_SIZE;\n }\n const bytes = series.dataType.equals(DataType.BOOLEAN)\n ? packBoolBits(series.data)\n : new Uint8Array(series.data);\n buffer.set(bytes, offset);\n offset += bytes.byteLength;\n if (!equalTimeRangesFlag && !timeRangesZeroFlag) {\n view.setBigUint64(offset, series.timeRange?.start.valueOf() ?? 0n, true);\n offset += TIMESTAMP_SIZE;\n view.setBigUint64(offset, series.timeRange?.end.valueOf() ?? 0n, true);\n offset += TIMESTAMP_SIZE;\n }\n if (!equalAlignmentsFlag && !zeroAlignmentsFlag) {\n view.setBigUint64(offset, series.alignment ?? 0n, true);\n offset += ALIGNMENT_SIZE;\n }\n });\n return buffer;\n }\n\n decode(data: Uint8Array | ArrayBuffer, offset: number = 0): Payload {\n this.throwIfNotUpdated(\"decode\");\n const src = data instanceof Uint8Array ? data : new Uint8Array(data);\n const returnFrame: Payload = { keys: [], series: [] };\n let index = offset;\n let sizeRepresentation = 0;\n let currSize = 0;\n let startTime: TimeStamp | undefined;\n let endTime: TimeStamp | undefined;\n let currAlignment: bigint | undefined;\n\n const view = new DataView(src.buffer, src.byteOffset, src.byteLength);\n const zeroAlignmentsFlag = Boolean((src[index] >> ZERO_ALIGNMENTS_FLAG_POS) & 1);\n const equalAlignmentsFlag = Boolean((src[index] >> EQUAL_ALIGNMENTS_FLAG_POS) & 1);\n const sizeFlag = Boolean((src[index] >> EQUAL_LENGTHS_FLAG_POS) & 1);\n const equalTimeRangesFlag = Boolean((src[index] >> EQUAL_TIME_RANGES_FLAG_POS) & 1);\n const timeRangesZeroFlag = Boolean((src[index] >> TIME_RANGES_ZERO_FLAG_POS) & 1);\n const channelFlag = Boolean((src[index] >> ALL_CHANNELS_PRESENT_FLAG_POS) & 1);\n index++;\n\n const seqNum = view.getUint32(index, true);\n index += SEQ_NUM_SIZE;\n const state = this.states.get(seqNum);\n if (state == null) return returnFrame;\n\n if (sizeFlag) {\n if (index + DATA_LENGTH_SIZE > view.byteLength) return returnFrame;\n sizeRepresentation = view.getUint32(index, true);\n index += DATA_LENGTH_SIZE;\n }\n\n if (equalTimeRangesFlag && !timeRangesZeroFlag) {\n if (index + TIMESTAMP_SIZE > view.byteLength) return returnFrame;\n startTime = new TimeStamp(view.getBigUint64(index, true));\n index += TIMESTAMP_SIZE;\n endTime = new TimeStamp(view.getBigUint64(index, true));\n index += TIMESTAMP_SIZE;\n }\n\n if (equalAlignmentsFlag && !zeroAlignmentsFlag) {\n if (index + ALIGNMENT_SIZE > view.byteLength) return returnFrame;\n currAlignment = view.getBigUint64(index, true);\n index += ALIGNMENT_SIZE;\n }\n\n const decodeSeries = (k: channel.Key): boolean => {\n const dataType = state.keyDataTypes.get(k);\n if (dataType == null) return false;\n currSize = 0;\n if (!sizeFlag) {\n if (index + DATA_LENGTH_SIZE > view.byteLength) return false;\n currSize = view.getUint32(index, true);\n index += DATA_LENGTH_SIZE;\n } else currSize = sizeRepresentation;\n\n let dataByteLength = currSize;\n if (!dataType.isVariable) dataByteLength *= dataType.density.valueOf();\n const isBool = dataType.equals(DataType.BOOLEAN);\n const wireByteLength = isBool ? bitPackedByteCount(currSize) : dataByteLength;\n if (index + wireByteLength > view.byteLength) return false;\n const wireBytes = src.slice(index, index + wireByteLength);\n const currSeries: SeriesPayload = {\n dataType,\n data: isBool ? unpackBoolBits(wireBytes, currSize) : wireBytes.buffer,\n };\n index += wireByteLength;\n if (!equalTimeRangesFlag && !timeRangesZeroFlag) {\n if (index + TIMESTAMP_SIZE * 2 > view.byteLength) return false;\n const start = view.getBigUint64(index, true);\n index += TIMESTAMP_SIZE;\n const end = view.getBigUint64(index, true);\n index += TIMESTAMP_SIZE;\n currSeries.timeRange = new TimeRange({ start, end });\n } else if (!timeRangesZeroFlag)\n currSeries.timeRange = new TimeRange({\n start: startTime?.valueOf() ?? 0n,\n end: endTime?.valueOf() ?? 0n,\n });\n else currSeries.timeRange = new TimeRange({ start: 0n, end: 0n });\n\n if (!equalAlignmentsFlag && !zeroAlignmentsFlag) {\n if (index + ALIGNMENT_SIZE > view.byteLength) return false;\n currAlignment = view.getBigUint64(index, true);\n index += ALIGNMENT_SIZE;\n currSeries.alignment = currAlignment;\n } else if (!zeroAlignmentsFlag) currSeries.alignment = currAlignment;\n else currSeries.alignment = 0n;\n\n returnFrame.series.push(currSeries);\n returnFrame.keys.push(k);\n return true;\n };\n\n if (channelFlag) state.keys.forEach((k) => decodeSeries(k));\n else\n while (index < view.byteLength) {\n if (index + KEY_SIZE > view.byteLength) break;\n const frameKey = view.getUint32(index, true);\n index += KEY_SIZE;\n if (!decodeSeries(frameKey)) break;\n }\n return returnFrame;\n }\n}\n\nexport const LOW_PERF_SPECIAL_CHAR = 254;\nconst LOW_PERF_SPECIAL_CHAR_BUF = new Uint8Array([LOW_PERF_SPECIAL_CHAR]);\nexport const HIGH_PERF_SPECIAL_CHAR = 255;\nconst HIGH_PERF_SPECIAL_CHAR_BUF = new Uint8Array([HIGH_PERF_SPECIAL_CHAR]);\nconst CONTENT_TYPE = \"application/vnd.synnax.frame\";\n\nexport class WSWriterCodec implements binary.Codec {\n contentType = CONTENT_TYPE;\n private base: Codec;\n private lowPerfCodec: binary.Codec;\n\n constructor(base: Codec) {\n this.base = base;\n this.lowPerfCodec = binary.JSON_CODEC;\n }\n\n encode(payload: unknown): Uint8Array<ArrayBuffer> {\n const pld = payload as WebsocketMessage<WriteRequest>;\n if (pld.type == \"close\" || pld.payload?.command != WriterCommand.Write) {\n const data = this.lowPerfCodec.encode(pld);\n const b = new Uint8Array({ length: data.byteLength + 1 });\n b.set(LOW_PERF_SPECIAL_CHAR_BUF, 0);\n b.set(new Uint8Array(data), 1);\n return b;\n }\n const data = this.base.encode(pld.payload?.frame, 1);\n data.set(HIGH_PERF_SPECIAL_CHAR_BUF, 0);\n return data;\n }\n\n decode<P extends z.ZodType>(data: Uint8Array | ArrayBuffer, schema?: P): z.infer<P> {\n const dv = new DataView(data instanceof Uint8Array ? data.buffer : data);\n const codec = dv.getUint8(0);\n if (codec === LOW_PERF_SPECIAL_CHAR)\n return this.lowPerfCodec.decode(data.slice(1), schema);\n const v: WebsocketMessage<WriteRequest> = { type: \"data\" };\n const frame = this.base.decode(data, 1);\n v.payload = { command: WriterCommand.Write, frame };\n return v as z.infer<P>;\n }\n}\n\nexport class WSStreamerCodec implements binary.Codec {\n contentType = CONTENT_TYPE;\n private base: Codec;\n private lowPerfCodec: binary.Codec;\n\n constructor(base: Codec) {\n this.base = base;\n this.lowPerfCodec = binary.JSON_CODEC;\n }\n\n encode(payload: unknown): Uint8Array<ArrayBuffer> {\n return this.lowPerfCodec.encode(payload);\n }\n\n decode<P extends z.ZodType>(data: Uint8Array | ArrayBuffer, schema?: P): z.infer<P> {\n const dv = new DataView(data instanceof Uint8Array ? data.buffer : data);\n const codec = dv.getUint8(0);\n if (codec === LOW_PERF_SPECIAL_CHAR)\n return this.lowPerfCodec.decode(data.slice(1), schema);\n const v: WebsocketMessage<StreamerResponse> = {\n type: \"data\",\n payload: { frame: this.base.decode(data, 1) },\n };\n return v as z.infer<P>;\n }\n}\n\nexport class WSIteratorCodec implements binary.Codec {\n contentType = CONTENT_TYPE;\n private base: Codec;\n private lowPerfCodec: binary.Codec;\n\n constructor(base: Codec) {\n this.base = base;\n this.lowPerfCodec = binary.JSON_CODEC;\n }\n\n encode(payload: unknown): Uint8Array<ArrayBuffer> {\n return this.lowPerfCodec.encode(payload);\n }\n\n decode<P extends z.ZodType>(data: Uint8Array | ArrayBuffer, schema?: P): z.infer<P> {\n const dv = new DataView(data instanceof Uint8Array ? data.buffer : data);\n const codec = dv.getUint8(0);\n if (codec === LOW_PERF_SPECIAL_CHAR)\n return this.lowPerfCodec.decode(data.slice(1), schema);\n const v: WebsocketMessage<unknown> = {\n type: \"data\",\n payload: {\n variant: IteratorResponseVariant.Data,\n ack: false,\n command: 0,\n frame: this.base.decode(data, 1),\n },\n };\n return v as z.infer<P>;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type CrudeSeries, Series } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { analyzeParams, paramsZ } from \"@/channel/payload\";\nimport { QueryError, ValidationError } from \"@/errors\";\nimport { Codec } from \"@/framer/codec\";\nimport { type CrudeFrame, Frame } from \"@/framer/frame\";\n\n/** Fetches channel payloads. Missing channels are omitted, not thrown. */\nexport type ChannelRetriever = (channels: channel.Params) => Promise<channel.Payload[]>;\n\n/** Fetches channel payloads, throwing a {@link QueryError} when any is missing. */\nconst retrieveRequired = async (\n retrieve: ChannelRetriever,\n channels: channel.Params,\n): Promise<channel.Payload[]> => {\n const { normalized } = analyzeParams(channels);\n const results = await retrieve(normalized);\n const notFound: (channel.Key | channel.Name)[] = [];\n normalized.forEach((v) => {\n if (results.find((c) => c.name === v || c.key === v) == null) notFound.push(v);\n });\n if (notFound.length > 0)\n throw new QueryError(`Could not find channels: ${JSON.stringify(notFound)}`);\n return results;\n};\n\nexport class ReadAdapter {\n private adapter: Map<channel.Key, string> | null;\n private readonly retrieveChannels: ChannelRetriever;\n keys: Set<channel.Key>;\n codec: Codec;\n\n private constructor(retrieveChannels: ChannelRetriever) {\n this.retrieveChannels = retrieveChannels;\n this.adapter = null;\n this.keys = new Set();\n this.codec = new Codec();\n }\n\n static async open(\n retrieveChannels: ChannelRetriever,\n channels: channel.Params,\n ): Promise<ReadAdapter> {\n const adapter = new ReadAdapter(retrieveChannels);\n await adapter.update(channels);\n return adapter;\n }\n\n async update(channels: channel.Params): Promise<boolean> {\n const { variant, normalized } = analyzeParams(channels);\n const fetched = await this.retrieveChannels(normalized);\n const newKeys = fetched.map((c) => c.key);\n const newKeySet = new Set(newKeys);\n if (newKeySet.size === this.keys.size && newKeySet.isSubsetOf(this.keys))\n return false;\n this.codec.update(\n newKeys,\n fetched.map((c) => c.dataType),\n );\n if (variant === \"keys\") {\n this.adapter = null;\n this.keys = new Set(normalized);\n return true;\n }\n const a = new Map<channel.Key, string>();\n this.adapter = a;\n normalized.forEach((name) => {\n const channel = fetched.find((channel) => channel.name === name);\n if (channel == null) throw new Error(`Channel ${name} not found`);\n a.set(channel.key, channel.name);\n });\n this.keys = new Set(this.adapter.keys());\n return true;\n }\n\n adapt(frm: Frame): Frame {\n if (this.adapter == null) {\n let shouldFilter = false;\n frm.forEach((k) => {\n if (!this.keys.has(k as channel.Key)) shouldFilter = true;\n });\n if (shouldFilter) return frm.filter((k) => this.keys.has(k as channel.Key));\n return frm;\n }\n const { adapter } = this;\n return frm.mapFilter((col, arr) => {\n if (typeof col === \"number\") {\n const name = adapter.get(col);\n if (name == null) return [col, arr, false];\n return [name, arr, true];\n }\n return [col, arr, true];\n });\n }\n}\n\nexport class WriteAdapter {\n private byName: Map<channel.Name, channel.Payload> | null;\n private byKey: Map<channel.Key, channel.Payload>;\n private readonly retrieveChannels: ChannelRetriever;\n keys: channel.Key[];\n codec: Codec;\n\n private constructor(retrieveChannels: ChannelRetriever) {\n this.retrieveChannels = retrieveChannels;\n this.byName = null;\n this.byKey = new Map();\n this.keys = [];\n this.codec = new Codec();\n }\n\n static async open(\n retrieveChannels: ChannelRetriever,\n channels: channel.Params,\n ): Promise<WriteAdapter> {\n const adapter = new WriteAdapter(retrieveChannels);\n await adapter.update(channels);\n return adapter;\n }\n\n async adaptParams(data: channel.Params): Promise<channel.Key[]> {\n const arrParams = paramsZ.parse(data);\n const keys = await Promise.all(\n arrParams.map(async (p) => await this.adaptToKey(p)),\n );\n return keys;\n }\n\n async update(channels: channel.Params): Promise<boolean> {\n const results = await retrieveRequired(this.retrieveChannels, channels);\n const newKeys = results.map((c) => c.key);\n const previousKeySet = new Set(this.keys);\n const newKeySet = new Set(newKeys);\n if (newKeySet.size === previousKeySet.size && newKeySet.isSubsetOf(previousKeySet))\n return false;\n this.byName = new Map(results.map((c) => [c.name, c]));\n this.byKey = new Map(results.map((c) => [c.key, c]));\n this.keys = newKeys;\n this.codec.update(\n this.keys,\n results.map((c) => c.dataType),\n );\n return true;\n }\n\n private async fetchChannel(\n ch: channel.Key | channel.Name | channel.Payload,\n ): Promise<channel.Payload> {\n // The channel set is fixed between updates, so cached payloads cannot go stale.\n let cached: channel.Payload | undefined;\n if (typeof ch === \"number\") cached = this.byKey.get(ch);\n else if (typeof ch === \"string\") cached = this.byName?.get(ch);\n else cached = this.byKey.get(ch.key);\n if (cached != null) return cached;\n const res = await this.retrieveChannels(ch);\n if (res.length === 0) throw new Error(`Channel ${JSON.stringify(ch)} not found`);\n return res[0];\n }\n\n private async adaptToKey(k: channel.Key | channel.Name): Promise<channel.Key> {\n if (typeof k === \"number\") return k;\n const res = await this.fetchChannel(k);\n return res.key;\n }\n\n encode(frame: Frame): Uint8Array {\n return this.codec.encode(frame.toPayload());\n }\n\n async adapt(\n columnsOrData:\n channel.Params | Record<channel.Key | channel.Name, CrudeSeries> | CrudeFrame,\n series?: CrudeSeries | CrudeSeries[],\n ): Promise<Frame> {\n if (typeof columnsOrData === \"string\" || typeof columnsOrData === \"number\") {\n if (series == null)\n throw new ValidationError(`\n Received a single channel name or key but no series.\n `);\n if (Array.isArray(series))\n if (series.some((s) => s instanceof Series || Array.isArray(s)))\n throw new ValidationError(`\n Received a single channel name or key but multiple series.\n `);\n\n const pld = await this.fetchChannel(columnsOrData);\n const s = new Series({ data: series, dataType: pld.dataType });\n return new Frame(pld.key, s);\n }\n\n if (Array.isArray(columnsOrData)) {\n if (series == null)\n throw new ValidationError(`\n Received an array of channel names or keys but no series.\n `);\n if (!Array.isArray(series))\n throw new ValidationError(`\n Received an array of channel names or keys but no array of series.\n `);\n const cols = [];\n const data = [];\n for (let i = 0; i < columnsOrData.length; i++) {\n const pld = await this.fetchChannel(columnsOrData[i]);\n if (i >= series.length)\n throw new ValidationError(`\n Received an array of channel names or keys but not enough series.\n `);\n\n const s = new Series({\n data: series[i] as CrudeSeries,\n dataType: pld.dataType,\n });\n cols.push(pld.key);\n data.push(s);\n }\n return new Frame(cols, data);\n }\n\n if (columnsOrData instanceof Frame || columnsOrData instanceof Map) {\n const fr = new Frame(columnsOrData);\n if (this.byName == null) return fr;\n const cols = fr.columns.map((col_) => {\n const col = typeof col_ === \"string\" ? this.byName?.get(col_)?.key : col_;\n if (col == null)\n throw new ValidationError(`\n Channel ${col_} was not provided in the list of channels when opening the writer\n `);\n return col;\n });\n return new Frame(cols, fr.series);\n }\n\n const cols = [];\n const data = [];\n const kvs = Object.entries(columnsOrData);\n for (let i = 0; i < kvs.length; i++) {\n const [k, v] = kvs[i];\n const pld = await this.fetchChannel(k);\n const s = new Series({ data: v, dataType: pld.dataType });\n cols.push(pld.key);\n data.push(s);\n }\n\n return new Frame(cols, data);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { EOF, type Stream } from \"@synnaxlabs/freighter\";\nimport { errors } from \"@synnaxlabs/x\";\nimport { type z } from \"zod\";\n\nimport { UnexpectedError } from \"@/errors\";\n\nexport class StreamProxy<RQ extends z.ZodType, RS extends z.ZodType> {\n readonly name: string;\n private readonly stream: Stream<RQ, RS>;\n\n constructor(name: string, stream: Stream<RQ, RS>) {\n this.stream = stream;\n this.name = name;\n }\n\n async receive(): Promise<z.infer<RS>> {\n return await this.stream.receive();\n }\n\n received(): boolean {\n return this.stream.received();\n }\n\n async closeAndAck(): Promise<void> {\n this.stream.closeSend();\n while (true) {\n let res: z.infer<RS>;\n try {\n res = await this.stream.receive();\n } catch (err) {\n if (EOF.matches(err)) return;\n throw errors.fromUnknown(err);\n }\n throw new UnexpectedError(\n `${this.name} received unexpected response ${JSON.stringify(res)} on closure.`,\n );\n }\n }\n\n closeSend(): void {\n this.stream.closeSend();\n }\n\n send(req: z.input<RQ>): void {\n this.stream.send(req);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Stream, type WebSocketClient } from \"@synnaxlabs/freighter\";\nimport {\n type CrudeTimeRange,\n type CrudeTimeSpan,\n type CrudeTimeStamp,\n errors,\n TimeRange,\n TimeSpan,\n TimeStamp,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { keyZ } from \"@/channel/types.gen\";\nimport { type ChannelRetriever, ReadAdapter } from \"@/framer/adapter\";\nimport { WSIteratorCodec } from \"@/framer/codec\";\nimport { Frame, frameZ } from \"@/framer/frame\";\nimport { StreamProxy } from \"@/framer/streamProxy\";\nimport { IteratorCommand, IteratorResponseVariant } from \"@/framer/types.gen\";\n\n/** Span that makes an iterator step by its chunk size instead of a fixed duration. */\nexport const AUTO_SPAN = new TimeSpan(-1);\n\nexport const iteratorReqZ = z.object({\n command: z.enum(IteratorCommand),\n span: TimeSpan.z.optional(),\n bounds: TimeRange.z.optional(),\n stamp: TimeStamp.z.optional(),\n keys: keyZ.array().optional(),\n chunkSize: z.number().optional(),\n downsampleFactor: z.int().optional(),\n});\n\nexport interface IteratorRequest extends z.infer<typeof iteratorReqZ> {}\n\nexport const iteratorResZ = z.object({\n variant: z.enum(IteratorResponseVariant),\n ack: z.boolean(),\n command: z.enum(IteratorCommand),\n error: errors.payloadZ.optional().nullable(),\n frame: frameZ.optional(),\n});\n\nexport interface IteratorResponse extends z.infer<typeof iteratorResZ> {}\n\n/** Config for an iterator. Pass it to `client.telem.openIterator`. */\nexport interface IteratorConfig {\n /** chunkSize is the maximum number of samples contained per channel in the frame\n * resulting from a call to next with {@link AUTO_SPAN}.\n */\n chunkSize?: number;\n /**\n * downsampleFactor is the factor to downsample the data by. If downsampleFactor is\n * less than or equal to 1, no downsampling will be performed.\n */\n downsampleFactor?: number;\n}\n\n/**\n * Iterates over a cluster's telemetry in time order. Open one through the segment\n * client, never directly. Suited to large ranges; to read between two timestamps, use\n * the segment client's read method instead.\n */\nexport class Iterator {\n private readonly stream: StreamProxy<typeof iteratorReqZ, typeof iteratorResZ>;\n private readonly adapter: ReadAdapter;\n value: Frame;\n\n private constructor(\n stream: Stream<typeof iteratorReqZ, typeof iteratorResZ>,\n adapter: ReadAdapter,\n ) {\n this.stream = new StreamProxy(\"Iterator\", stream);\n this.value = new Frame();\n this.adapter = adapter;\n }\n\n /**\n * Opens the iterator, configuring it to iterate over the telemetry in the channels\n * with the given keys within the provided time range.\n * @param retrieveChannels - Resolves channel names to keys and data types.\n * @param client - The stream client allowing streaming of iterated data.\n * @param opts - See {@link IteratorConfig}.\n */\n static async _open(\n tr: CrudeTimeRange,\n channels: channel.Params,\n retrieveChannels: ChannelRetriever,\n client: WebSocketClient,\n opts: IteratorConfig = {},\n ): Promise<Iterator> {\n const adapter = await ReadAdapter.open(retrieveChannels, channels);\n client = client.withCodec(new WSIteratorCodec(adapter.codec));\n const stream = await client.stream(\"/frame/iterate\", iteratorReqZ, iteratorResZ);\n const iter = new Iterator(stream, adapter);\n await iter.execute({\n command: IteratorCommand.Open,\n keys: Array.from(adapter.keys),\n bounds: new TimeRange(tr),\n chunkSize: opts.chunkSize ?? 1e5,\n downsampleFactor: opts.downsampleFactor ?? 1,\n });\n return iter;\n }\n\n /**\n * Reads the next time span of telemetry for each channel in the iterator.\n * @param span - The time span to read. A negative span is equivalent to calling prev\n * with the absolute value of the span. If the span is AUTO_SPAN, the iterator will\n * automatically determine the span to read. This is useful for iterating over an\n * entire range efficiently.\n * @returns false if a segment satisfying the request can't be found for a particular\n * channel or the iterator has accumulated an error.\n */\n async next(span: CrudeTimeSpan = AUTO_SPAN): Promise<boolean> {\n return await this.execute({\n command: IteratorCommand.Next,\n span: new TimeSpan(span),\n });\n }\n\n /**\n * Reads the previous time span of telemetry for each channel in the iterator.\n * @param span - The time span to read. A negative span is equivalent to calling next\n * with the absolute value of the span. If the span is AUTO_SPAN, the iterator will\n * automatically determine the span to read. This is useful for iterating over an\n * entire range efficiently.\n * @returns false if a segment satisfying the request can't be found for a particular\n * channel or the iterator has accumulated an error.\n */\n async prev(span: CrudeTimeSpan = AUTO_SPAN): Promise<boolean> {\n return await this.execute({\n command: IteratorCommand.Prev,\n span: new TimeSpan(span),\n });\n }\n\n /**\n * Seeks the iterator to the first segment in the time range, but does not read it.\n * Also invalidates the iterator. The iterator will not be considered valid until a\n * call to next or prev.\n * @returns false if the iterator is not pointing to a valid segment for a particular\n * channel or has accumulated an error.\n */\n async seekFirst(): Promise<boolean> {\n return await this.execute({ command: IteratorCommand.SeekFirst });\n }\n\n /** Seeks the iterator to the last segment in the time range, but does not read it.\n * Also invalidates the iterator. The iterator will not be considered valid\n * until a call to next or prev.\n *\n * @returns false if the iterator is not pointing to a valid segment for a particular\n * channel or has accumulated an error.\n */\n async seekLast(): Promise<boolean> {\n return await this.execute({ command: IteratorCommand.SeekLast });\n }\n\n /**\n * Seeks the iterator to the first segment whose start is less than or equal to the\n * provided timestamp. Also invalidates the iterator. The iterator will not be\n * considered valid until a call to next or prev.\n * @returns false if the iterator is not pointing to a valid segment for a particular\n * channel or has accumulated an error.\n */\n async seekLE(stamp: CrudeTimeStamp): Promise<boolean> {\n return await this.execute({\n command: IteratorCommand.SeekLE,\n stamp: new TimeStamp(stamp),\n });\n }\n\n /**\n * Seeks the iterator to the first segment whose start is greater than or equal to the\n * provided timestamp. Also invalidates the iterator. The iterator will not be\n * considered valid until a call to next or prev.\n * @returns false if the iterator is not pointing to a valid segment for a particular\n * channel or has accumulated an error.\n */\n async seekGE(stamp: CrudeTimeStamp): Promise<boolean> {\n return await this.execute({\n command: IteratorCommand.SeekGE,\n stamp: new TimeStamp(stamp),\n });\n }\n\n /**\n * @returns true if the iterator value contains a valid segment, and false otherwise.\n * valid most commonly returns false when the iterator is exhausted or has accumulated\n * an error.\n */\n async valid(): Promise<boolean> {\n return await this.execute({ command: IteratorCommand.Valid });\n }\n\n /**\n * Closes the iterator. An iterator MUST be closed after use, and this method\n * should probably be placed in a 'finally' block. If the iterator is not closed,\n * it may leak resources.\n */\n async close(): Promise<void> {\n await this.stream.closeAndAck();\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Frame, any, undefined> {\n return new IteratorIterator(this);\n }\n\n private async execute(request: IteratorRequest): Promise<boolean> {\n this.stream.send(request);\n this.value = new Frame();\n while (true) {\n const res = await this.stream.receive();\n if (res.variant === IteratorResponseVariant.Ack) return res.ack;\n this.value.push(this.adapter.adapt(new Frame(res.frame)));\n }\n }\n}\n\nclass IteratorIterator implements AsyncIterator<Frame> {\n private readonly iter: Iterator;\n private open: boolean = false;\n\n constructor(iter: Iterator) {\n this.iter = iter;\n }\n\n async next(): Promise<IteratorResult<Frame, any>> {\n try {\n let ok = true;\n if (!this.open) {\n if (!(await this.iter.seekFirst())) ok = false;\n this.open = true;\n }\n if (!(await this.iter.next())) ok = false;\n if (!ok) await this.iter.close();\n return { done: !ok, value: this.iter.value };\n } catch (e) {\n await this.iter.close();\n throw errors.fromUnknown(e);\n }\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type WebSocketClient } from \"@synnaxlabs/freighter\";\nimport { type CrudeTimeRange, csv, runtime } from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { UnexpectedError } from \"@/errors\";\nimport { type ChannelRetriever } from \"@/framer/adapter\";\nimport { type Frame } from \"@/framer/frame\";\nimport { Iterator, type IteratorConfig } from \"@/framer/iterator\";\n\nexport interface ReadRequest {\n channels: channel.Params;\n timeRange: CrudeTimeRange;\n channelNames?: Record<channel.Key | channel.Name, string>;\n responseType: \"csv\";\n iteratorConfig?: IteratorConfig;\n}\n\nexport class Reader {\n private readonly retrieveChannels: ChannelRetriever;\n private readonly streamClient: WebSocketClient;\n\n constructor(retrieveChannels: ChannelRetriever, streamClient: WebSocketClient) {\n this.retrieveChannels = retrieveChannels;\n this.streamClient = streamClient;\n }\n\n async read(request: ReadRequest): Promise<ReadableStream<Uint8Array>> {\n const {\n channels: channelParams,\n timeRange,\n channelNames,\n iteratorConfig,\n } = request;\n const channelPayloads = await this.retrieveChannels(channelParams);\n const allKeys = new Set<channel.Key>();\n const payloadKeys = new Set<channel.Key>();\n channelPayloads.forEach((ch) => {\n allKeys.add(ch.key);\n payloadKeys.add(ch.key);\n if (ch.index !== 0) allKeys.add(ch.index);\n });\n const missingIndexKeys = allKeys.difference(payloadKeys);\n if (missingIndexKeys.size > 0) {\n const indexChannels = await this.retrieveChannels(Array.from(missingIndexKeys));\n channelPayloads.push(...indexChannels);\n }\n const iterator = await Iterator._open(\n timeRange,\n Array.from(allKeys),\n this.retrieveChannels,\n this.streamClient,\n iteratorConfig,\n );\n return createCSVReadableStream({\n iterator,\n channelPayloads,\n headers: channelNames,\n });\n }\n}\n\ninterface CreateCSVExportStreamParams {\n iterator: Iterator;\n channelPayloads: channel.Payload[];\n headers?: Record<channel.Key | channel.Name, string>;\n}\n\nconst createCSVReadableStream = ({\n iterator,\n channelPayloads,\n headers,\n}: CreateCSVExportStreamParams): ReadableStream<Uint8Array> => {\n const delimiter = runtime.getOS() === \"Windows\" ? \"\\r\\n\" : \"\\n\";\n const encoder = new TextEncoder();\n let headerWritten = false;\n let seekDone = false;\n const groups = groupChannelsByIndex(channelPayloads);\n const { columns, columnsByIndexKey, emptyGroupStrings } = buildColumnMeta(\n channelPayloads,\n groups,\n headers,\n );\n // Use a cursor-based approach instead of having to call .shift() for O(1) access\n let pendingRecords: RecordEntry[] = [];\n let pendingCursor = 0;\n let stagedRecords: RecordEntry[] = [];\n\n const extractRecordsFromFrame = (frame: Frame): void => {\n for (const [indexKey] of groups) {\n const indexSeries = frame.get(indexKey);\n if (indexSeries.length === 0) continue;\n const groupColumns = columnsByIndexKey.get(indexKey) ?? [];\n // Pre-fetch all series for this group to avoid repeated lookups\n const seriesData = groupColumns.map((col) => frame.get(col.key));\n for (let i = 0; i < indexSeries.length; i++) {\n const time = indexSeries.at(i, true) as bigint;\n const values = seriesData.map((series) => csv.formatValue(series.at(i, true)));\n stagedRecords.push({ time, values, indexKey });\n }\n }\n };\n\n const buildCSVRows = (maxRows: number, flush: boolean = false): string[] => {\n if (stagedRecords.length > 0) {\n stagedRecords.sort((a, b) => Number(a.time - b.time));\n if (pendingCursor > 0) {\n pendingRecords = pendingRecords.slice(pendingCursor);\n pendingCursor = 0;\n }\n pendingRecords = mergeSortedRecords(pendingRecords, stagedRecords);\n stagedRecords = [];\n }\n const rows: string[] = [];\n const pendingLen = pendingRecords.length;\n while (pendingCursor < pendingLen && rows.length < maxRows) {\n const minTime = pendingRecords[pendingCursor].time;\n // Don't output the last timestamp unless flushing - more data might arrive\n // Optimization: only check if last record has same time (since array is sorted)\n if (!flush && pendingRecords[pendingLen - 1].time === minTime) break;\n // Collect all records at this timestamp using cursor (O(1) per record)\n // Use Map keyed by indexKey for O(1) lookup instead of find()\n const recordsByGroup = new Map<channel.Key, RecordEntry>();\n while (\n pendingCursor < pendingLen &&\n pendingRecords[pendingCursor].time === minTime\n ) {\n const record = pendingRecords[pendingCursor++];\n recordsByGroup.set(record.indexKey, record);\n }\n const rowParts: string[] = [];\n for (const [indexKey] of groups) {\n const record = recordsByGroup.get(indexKey);\n rowParts.push(\n record?.values.join(\",\") ?? emptyGroupStrings.get(indexKey) ?? \"\",\n );\n }\n rows.push(rowParts.join(\",\"));\n }\n return rows;\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller): Promise<void> {\n try {\n if (!seekDone) {\n await iterator.seekFirst();\n seekDone = true;\n }\n if (!headerWritten) {\n const headerRow = columns.map((c) => csv.formatValue(c.header)).join(\",\");\n controller.enqueue(encoder.encode(`${headerRow}${delimiter}`));\n headerWritten = true;\n }\n const bufferedCount =\n pendingRecords.length - pendingCursor + stagedRecords.length;\n if (bufferedCount < BUFFER_SIZE) {\n const hasMore = await iterator.next();\n if (hasMore) extractRecordsFromFrame(iterator.value);\n }\n const rows = buildCSVRows(BUFFER_SIZE);\n if (rows.length > 0)\n controller.enqueue(encoder.encode(`${rows.join(delimiter)}${delimiter}`));\n const remainingPending = pendingRecords.length - pendingCursor;\n if (remainingPending === 0 || stagedRecords.length === 0) {\n const hasMore = await iterator.next();\n if (!hasMore) {\n const finalRows = buildCSVRows(Infinity, true);\n if (finalRows.length > 0)\n controller.enqueue(\n encoder.encode(`${finalRows.join(delimiter)}${delimiter}`),\n );\n await iterator.close();\n controller.close();\n return;\n }\n extractRecordsFromFrame(iterator.value);\n }\n } catch (error) {\n await iterator.close();\n controller.error(error);\n }\n },\n\n async cancel(): Promise<void> {\n await iterator.close();\n },\n });\n};\n\nconst groupChannelsByIndex = (\n channels: channel.Payload[],\n): Map<channel.Key, channel.Key[]> => {\n const groupMap = new Map<channel.Key, channel.Key[]>();\n for (const ch of channels) {\n if (ch.index === 0) continue;\n let group = groupMap.get(ch.index);\n if (group == null) {\n group = [ch.index];\n groupMap.set(ch.index, group);\n }\n if (!ch.isIndex && !group.includes(ch.key)) group.push(ch.key);\n }\n return groupMap;\n};\n\ninterface ColumnMeta {\n key: channel.Key;\n header: string;\n}\n\ninterface ColumnMetaResult {\n columns: ColumnMeta[];\n columnsByIndexKey: Map<channel.Key, ColumnMeta[]>;\n emptyGroupStrings: Map<channel.Key, string>;\n}\n\nconst buildColumnMeta = (\n channels: channel.Payload[],\n groups: Map<channel.Key, channel.Key[]>,\n headers?: Record<channel.Key | channel.Name, string>,\n): ColumnMetaResult => {\n const channelMap = new Map(channels.map((ch) => [ch.key, ch]));\n const columns: ColumnMeta[] = [];\n const columnsByIndexKey = new Map<channel.Key, ColumnMeta[]>();\n const emptyGroupStrings = new Map<channel.Key, string>();\n\n for (const [indexKey, channelKeys] of groups) {\n const groupColumns: ColumnMeta[] = [];\n for (const key of channelKeys) {\n const ch = channelMap.get(key);\n if (ch == null) throw new UnexpectedError(`Channel ${key} not found`);\n const meta: ColumnMeta = {\n key,\n header: headers?.[key] ?? headers?.[ch.name] ?? ch.name,\n };\n columns.push(meta);\n groupColumns.push(meta);\n }\n columnsByIndexKey.set(indexKey, groupColumns);\n // Pre-compute empty group string for fast row building\n emptyGroupStrings.set(indexKey, \",\".repeat(groupColumns.length - 1));\n }\n\n return { columns, columnsByIndexKey, emptyGroupStrings };\n};\ninterface RecordEntry {\n time: bigint;\n values: string[];\n indexKey: channel.Key;\n}\n\nconst mergeSortedRecords = (a: RecordEntry[], b: RecordEntry[]): RecordEntry[] => {\n const result: RecordEntry[] = [];\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length)\n if (a[i].time <= b[j].time) result.push(a[i++]);\n else result.push(b[j++]);\n result.push(...a.slice(i), ...b.slice(j));\n return result;\n};\n\nconst BUFFER_SIZE = 1000;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { EOF, type Stream, type WebSocketClient } from \"@synnaxlabs/freighter\";\nimport { errors, Rate, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { paramsZ } from \"@/channel/payload\";\nimport { type ChannelRetriever, ReadAdapter } from \"@/framer/adapter\";\nimport { WSStreamerCodec } from \"@/framer/codec\";\nimport { Frame, frameZ } from \"@/framer/frame\";\nimport { StreamProxy } from \"@/framer/streamProxy\";\n\nconst reqZ = z.object({\n keys: z.number().array(),\n downsampleFactor: z.int(),\n throttleRate: Rate.z.optional(),\n excludeGroups: z.uint32().array().optional(),\n});\n\n/**\n * Request interface for streaming frames from a Synnax cluster.\n * Contains the keys of channels to stream from and a downsample factor.\n */\nexport interface StreamerRequest extends z.infer<typeof reqZ> {}\n\nconst resZ = z.object({ frame: frameZ });\n\n/**\n * Response interface for streaming frames from a Synnax cluster.\n * Contains a frame of telemetry data.\n */\nexport interface StreamerResponse extends z.infer<typeof resZ> {}\n\nconst intermediateStreamerConfigZ = z.object({\n /** The channels to stream data from. Can be channel keys, names, or payloads. */\n channels: paramsZ,\n /** Optional factor to downsample the data by. Defaults to 1 (no downsampling). */\n downsampleFactor: z.int().default(1),\n /** Optional throttle rate in Hz to limit the rate of frames sent to the client. Defaults to 0 (no throttling). */\n throttleRate: Rate.z.default(new Rate(0)),\n /** excludeGroups sets writer group IDs whose frames should be filtered out by the\n Core. Used for telemetry bypass deduplication. */\n excludeGroups: z.uint32().array().default([]),\n});\n\n/** Zod schema for {@link StreamerConfig}. A bare channel list parses as a config. */\nexport const streamerConfigZ = intermediateStreamerConfigZ.or(\n paramsZ.transform((channels) => intermediateStreamerConfigZ.parse({ channels })),\n);\n\n/** Config for a streamer. Pass it to `client.telem.openStreamer`. */\nexport type StreamerConfig = z.input<typeof streamerConfigZ>;\n\n/**\n * Streams frames of telemetry from a Synnax cluster in real time. Open one with the\n * client's openStreamer method, never directly. Read frames with `read` or by\n * iterating the streamer. Close it in a `finally` block to free its resources.\n *\n * @see https://docs.synnaxlabs.com/reference/client/working-with-data/streaming-data\n */\nexport interface Streamer extends AsyncIterator<Frame>, AsyncIterable<Frame> {\n /** The keys of the channels currently being streamed from. */\n keys: channel.Key[];\n /** Replaces the list of channels being streamed from. */\n update: (channels: channel.Params) => Promise<void>;\n /** Close the streamer and free all associated resources. */\n close: () => void;\n /** Read the next frame of telemetry. */\n read: () => Promise<Frame>;\n}\n\n/** A function that opens a streamer. */\nexport interface StreamOpener {\n (config: StreamerConfig): Promise<Streamer>;\n}\n\n/**\n * Creates a function that opens streamers with the given channel resolver and client.\n * @param retrieveChannels - Resolves channel params to payloads for the codec\n * @param client - The WebSocket client to use for streaming\n * @returns A function that opens streamers with the given configuration\n */\nexport const createStreamOpener =\n (retrieveChannels: ChannelRetriever, client: WebSocketClient): StreamOpener =>\n async (config) => {\n const cfg = zod.parse(streamerConfigZ, config, { label: \"streamer config\" });\n const adapter = await ReadAdapter.open(retrieveChannels, cfg.channels);\n client = client.withCodec(new WSStreamerCodec(adapter.codec));\n const stream = await client.stream(\"/frame/stream\", reqZ, resZ);\n const streamer = new BaseStreamer(\n stream,\n adapter,\n cfg.downsampleFactor,\n cfg.throttleRate,\n cfg.excludeGroups,\n );\n stream.send({\n keys: Array.from(adapter.keys),\n downsampleFactor: cfg.downsampleFactor,\n throttleRate: cfg.throttleRate,\n excludeGroups: cfg.excludeGroups,\n });\n await stream.receive();\n return streamer;\n };\n\n/**\n * Opens a new streamer with the given configuration.\n * @param retrieveChannels - Resolves channel params to payloads for the codec\n * @param client - The WebSocket client to use for streaming\n * @returns A promise that resolves to a new streamer\n */\nexport const openStreamer = async (\n retrieveChannels: ChannelRetriever,\n client: WebSocketClient,\n config: StreamerConfig,\n): Promise<Streamer> => await createStreamOpener(retrieveChannels, client)(config);\n\nclass BaseStreamer implements Streamer {\n private readonly stream: StreamProxy<typeof reqZ, typeof resZ>;\n private readonly adapter: ReadAdapter;\n private readonly downsampleFactor: number;\n private readonly throttleRate: Rate;\n private readonly excludeGroups: number[];\n\n constructor(\n stream: Stream<typeof reqZ, typeof resZ>,\n adapter: ReadAdapter,\n downsampleFactor: number = 1,\n throttleRate: Rate = new Rate(0),\n excludeGroups: number[] = [],\n ) {\n this.stream = new StreamProxy(\"Streamer\", stream);\n this.adapter = adapter;\n this.downsampleFactor = downsampleFactor;\n this.throttleRate = throttleRate;\n this.excludeGroups = excludeGroups;\n }\n\n get keys(): channel.Key[] {\n return Array.from(this.adapter.keys);\n }\n\n async next(): Promise<IteratorResult<Frame, any>> {\n try {\n const frame = await this.read();\n return { done: false, value: frame };\n } catch (err) {\n if (EOF.matches(err)) return { done: true, value: undefined };\n throw errors.fromUnknown(err);\n }\n }\n\n async read(): Promise<Frame> {\n return this.adapter.adapt(new Frame((await this.stream.receive()).frame));\n }\n\n async update(channels: channel.Params): Promise<void> {\n const hasChanged = await this.adapter.update(channels);\n if (!hasChanged) return;\n this.stream.send({\n keys: Array.from(this.adapter.keys),\n downsampleFactor: this.downsampleFactor,\n throttleRate: this.throttleRate,\n excludeGroups: this.excludeGroups,\n });\n }\n\n close(): void {\n this.stream.closeSend();\n }\n\n [Symbol.asyncIterator](): AsyncIterator<Frame, any, undefined> {\n return this;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { EOF, type Stream, type WebSocketClient } from \"@synnaxlabs/freighter\";\nimport {\n control,\n type CrudeSeries,\n errors,\n TimeSpan,\n TimeStamp,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { paramsZ } from \"@/channel/payload\";\nimport { keyZ, nameZ } from \"@/channel/types.gen\";\nimport { SynnaxError } from \"@/errors\";\nimport { type ChannelRetriever, WriteAdapter } from \"@/framer/adapter\";\nimport { WSWriterCodec } from \"@/framer/codec\";\nimport { type CrudeFrame, frameZ } from \"@/framer/frame\";\nimport { WriterCommand } from \"@/framer/types.gen\";\n\n/** Whether a writer persists its samples, streams them to subscribers, or both. */\nexport enum WriterMode {\n PersistStream = 1,\n Persist = 2,\n Stream = 3,\n}\n\n/** `autoIndexPersistInterval` that flushes the index on every auto commit. */\nexport const ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT: TimeSpan = new TimeSpan(-1);\n\nexport class WriterClosedError extends SynnaxError.sub(\"writer_closed\") {\n constructor() {\n super(\"WriterClosed\");\n }\n}\n\nconst writerModeZ = z.enum(WriterMode).or(\n z.enum([\"persist\", \"stream\", \"persistStream\"]).transform((mode) => {\n switch (mode) {\n case \"persist\":\n return WriterMode.Persist;\n case \"stream\":\n return WriterMode.Stream;\n case \"persistStream\":\n return WriterMode.PersistStream;\n }\n }),\n);\n\n/** A {@link WriterMode}, or its name as a string. */\nexport type CrudeWriterMode = z.input<typeof writerModeZ>;\n\nconst baseWriterConfigZ = z.object({\n /** start sets the starting timestamp for the first sample in the writer. */\n start: TimeStamp.z.optional(),\n /** controlSubject sets the control subject of the writer. */\n controlSubject: control.subjectZ.optional(),\n /** authorities set the control authority to set for each channel on the writer.\n * Defaults to absolute authority. If not working with concurrent control, it's best\n * to leave this as the default.\n */\n authorities: z\n .union([control.authorityZ.transform((a) => [a]), control.authorityZ.array()])\n .default([control.ABSOLUTE_AUTHORITY]),\n /** mode sets the persistence and streaming mode of the writer. The default mode is\n * WriterModePersistStream.\n */\n mode: writerModeZ.default(WriterMode.PersistStream),\n /**\n * errOnUnauthorized sets whether the writer raises an error when it attempts to write\n * to a channel without permission.\n */\n errOnUnauthorized: z.boolean().default(false),\n /**\n * enableAutoCommit determines whether the writer will automatically commit. If\n * enableAutoCommit is true, then the writer will commit after each write, and will\n * flush that commit to index after the specified autoIndexPersistInterval.\n */\n enableAutoCommit: z.boolean().default(true),\n /** autoIndexPersistInterval sets the interval at which commits will be flushed to\n * disk. */\n autoIndexPersistInterval: TimeSpan.z.default(TimeSpan.SECOND),\n /**\n * autoIndex causes Synnax to automatically generate timestamps for any index channel\n * that is not included in a write call. The first sample in each write is stamped at\n * the time the write is received, and subsequent samples are spaced 1 nanosecond\n * apart. Generated timestamps are guaranteed to be strictly monotonic across all\n * writes on the writer. If the writer is opened with data channels whose index\n * channels are not included, those index channels are added implicitly.\n */\n autoIndex: z.boolean().default(false),\n});\n\nconst netWriterConfigZ = baseWriterConfigZ.extend({\n keys: keyZ.array().optional(),\n});\n\nexport type NetWriterConfig = z.input<typeof netWriterConfigZ>;\n\n// Intermediate utility type to allow for the use of paramsZ in the writer config.\nconst intermediateWriterConfigZ = baseWriterConfigZ.extend({\n channels: paramsZ,\n});\n\n/** Zod schema for {@link WriterConfig}. A bare channel list parses as a config. */\nexport const writerConfigZ = intermediateWriterConfigZ.or(\n paramsZ.transform((channels) =>\n intermediateWriterConfigZ.parse({ channels, start: TimeStamp.now() }),\n ),\n);\n\n/** Config for a writer. Pass it to `client.telem.openWriter`. */\nexport type WriterConfig = z.input<typeof writerConfigZ>;\n\nconst reqZ = z.object({\n command: z.enum(WriterCommand),\n config: netWriterConfigZ.optional(),\n frame: frameZ.optional(),\n buffer: z.instanceof(Uint8Array).optional(),\n});\n\nexport interface WriteRequest extends z.input<typeof reqZ> {}\n\nconst resZ = z.object({\n command: z.enum(WriterCommand),\n end: TimeStamp.z,\n err: errors.payloadZ.optional(),\n});\n\nconst authorityParamsZ = z\n .tuple([\n z.union([\n z.record(keyZ.or(nameZ), control.authorityZ),\n keyZ.or(nameZ),\n control.authorityZ,\n ]),\n control.authorityZ.optional(),\n ])\n .transform(([value, authority]) => {\n if (control.authorityZ.safeParse(value).success)\n return { keys: [], authorities: [value as control.Authority] };\n if (keyZ.or(nameZ).safeParse(value).success) {\n if (authority == null)\n throw new Error(\n \"authority is required when setting authority for a single channel\",\n );\n return {\n keys: [value] as channel.Key[] | channel.Name[],\n authorities: [authority],\n };\n }\n const oValue = value as Record<channel.Key | channel.Name, control.Authority>;\n return { keys: Object.keys(oValue), authorities: Object.values(oValue) };\n });\n\n/**\n * Arguments to `Writer.setAuthority`: one authority for every channel, one channel and\n * its authority, or a record of channel to authority.\n */\nexport type AuthorityParams = z.input<typeof authorityParamsZ>;\n\ninterface Response extends z.infer<typeof resZ> {}\n\n/**\n * Writes telemetry to a set of channels in time order. Open one with\n * {@link FrameClient#openWriter}, never directly. Prefer the frame client's write\n * method unless the volume warrants the streaming protocol.\n *\n * Opening fails when the start timestamp overlaps existing telemetry on any of the\n * channels. `write` is asynchronous, so a failure surfaces on a later call: once the\n * writer accumulates an error, every write and commit returns false until `error`\n * reads and clears it. `commit` blocks until the cluster has the frames written since\n * the last commit, and may be called repeatedly. Close in a `finally` block to release\n * resources; close throws any accumulated error.\n */\nexport class Writer {\n private readonly stream: Stream<typeof reqZ, typeof resZ>;\n private readonly adapter: WriteAdapter;\n private closeErr: Error | null = null;\n\n private constructor(stream: Stream<typeof reqZ, typeof resZ>, adapter: WriteAdapter) {\n this.stream = stream;\n this.adapter = adapter;\n }\n\n static async _open(\n retrieveChannels: ChannelRetriever,\n client: WebSocketClient,\n config: WriterConfig,\n ): Promise<Writer> {\n const cfg = zod.parse(writerConfigZ, config);\n const adapter = await WriteAdapter.open(retrieveChannels, cfg.channels);\n client = client.withCodec(new WSWriterCodec(adapter.codec));\n const stream = await client.stream(\"/frame/write\", reqZ, resZ);\n const writer = new Writer(stream, adapter);\n await writer.execute({\n command: WriterCommand.Open,\n config: { ...cfg, keys: adapter.keys },\n });\n return writer;\n }\n\n async write(channel: channel.Key | channel.Name, data: CrudeSeries): Promise<void>;\n async write(\n channel: channel.Key[] | channel.Name[],\n data: CrudeSeries[],\n ): Promise<void>;\n async write(\n frame: CrudeFrame | Record<channel.Key | channel.Name, CrudeSeries>,\n ): Promise<void>;\n async write(\n channelsOrData:\n channel.Params | Record<channel.Key | channel.Name, CrudeSeries> | CrudeFrame,\n series?: CrudeSeries | CrudeSeries[],\n ): Promise<void>;\n\n /**\n * Writes the given frame to the database.\n *\n * @param frame - The frame to write to the database. The frame must:\n *\n * 1. Have exactly one array for each key in the list of keys provided to the\n * writer's open method.\n * 2. Have equal length arrays for each key.\n * 3. When writing to an index (i.e. TimeStamp) channel, the values must be\n * monotonically increasing.\n *\n * @throws if the writer has accumulated an error. Once write throws, all subsequent\n * calls to write and commit will also throw, and the writer must be closed and\n * re-opened to continue writing.\n */\n async write(\n channelsOrData:\n channel.Params | Record<channel.Key | channel.Name, CrudeSeries> | CrudeFrame,\n series?: CrudeSeries | CrudeSeries[],\n ): Promise<void> {\n if (this.closeErr != null) throw this.closeErr;\n if (this.stream.received()) return await this.close();\n const frame = await this.adapter.adapt(channelsOrData, series);\n try {\n this.stream.send({ command: WriterCommand.Write, frame: frame.toPayload() });\n } catch (err) {\n if (!EOF.matches(err)) throw errors.fromUnknown(err);\n }\n }\n\n async setAuthority(\n value: AuthorityParams[0],\n authority?: AuthorityParams[1],\n ): Promise<void> {\n if (this.closeErr != null) throw this.closeErr;\n const parsed = zod.parse(authorityParamsZ, [value, authority], {\n label: \"authority params\",\n });\n const config = {\n keys: await this.adapter.adaptParams(parsed.keys),\n authorities: parsed.authorities,\n };\n await this.execute({ command: WriterCommand.SetAuthority, config });\n }\n\n /**\n * Commits the written frames to the database. Commit is synchronous, meaning that it\n * will not return until all frames have been committed to the database.\n * @returns the timestamp of the last sample written to the writer.\n * @throws if the commit fails or any previous writer method has thrown. Once commit\n * throws, the writer must be closed and re-opened to continue use.\n */\n async commit(): Promise<TimeStamp> {\n if (this.closeErr != null) throw this.closeErr;\n if (this.stream.received()) {\n await this.closeInternal(null);\n return TimeStamp.ZERO;\n }\n const res = await this.execute({ command: WriterCommand.Commit });\n return res.end;\n }\n\n /**\n * Closes the writer, raising any accumulated error encountered during operation.\n * A writer MUST be closed after use, and this method should probably be placed\n * in a 'finally' block.\n */\n async close(): Promise<void> {\n await this.closeInternal(null);\n }\n\n private async closeInternal(err: Error | null): Promise<null> {\n if (this.closeErr != null) throw this.closeErr;\n this.closeErr = err;\n this.stream.closeSend();\n while (true) {\n if (this.closeErr != null) {\n if (WriterClosedError.matches(this.closeErr)) return null;\n throw this.closeErr;\n }\n try {\n const res = await this.stream.receive();\n this.closeErr = errors.decode(res?.err);\n } catch (err) {\n const e = errors.fromUnknown(err);\n this.closeErr = EOF.matches(e) ? new WriterClosedError() : e;\n }\n }\n }\n\n private async execute(req: WriteRequest): Promise<Response> {\n try {\n this.stream.send(req);\n } catch (err) {\n // A send failure is always EOF or StreamClosed, never WriterClosedError, so\n // closeInternal re-throws here and the receive loop below is reached only when\n // the send succeeds.\n await this.closeInternal(errors.fromUnknown(err));\n }\n while (true) {\n let res: Response;\n try {\n res = await this.stream.receive();\n } catch (err) {\n await this.closeInternal(errors.fromUnknown(err));\n continue;\n }\n const resErr = errors.decode(res?.err);\n if (resErr != null) await this.closeInternal(resErr);\n if (res?.command == req.command) return res;\n }\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient, type WebSocketClient } from \"@synnaxlabs/freighter\";\nimport {\n type CrudeSeries,\n type CrudeTimeRange,\n type CrudeTimeStamp,\n type MultiSeries,\n TimeRange,\n TimeSpan,\n} from \"@synnaxlabs/x\";\n\nimport { type channel } from \"@/channel\";\nimport { analyzeParams } from \"@/channel/payload\";\nimport { type ChannelRetriever } from \"@/framer/adapter\";\nimport { Deleter } from \"@/framer/deleter\";\nimport { Feed, type FeedOptions } from \"@/framer/feed\";\nimport { Frame } from \"@/framer/frame\";\nimport { AUTO_SPAN, Iterator, type IteratorConfig } from \"@/framer/iterator\";\nimport { Reader, type ReadRequest } from \"@/framer/reader\";\nimport { openStreamer, type Streamer, type StreamerConfig } from \"@/framer/streamer\";\nimport { Writer, type WriterConfig, WriterMode } from \"@/framer/writer\";\nimport { ontology } from \"@/ontology\";\n\nexport const ontologyID = ontology.createIDFactory<string>(\"framer\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n\n/** Config for {@link Client}. */\nexport interface ClientConfig {\n stream: WebSocketClient;\n unary: UnaryClient;\n retrieveChannels: ChannelRetriever;\n}\n\n/**\n * Reads and writes telemetry on a Core. Reach it through `client.telem` rather than\n * building one: `read` and `write` cover one-shot access, and the `open*` methods hand\n * back a long-lived stream the caller must close.\n */\nexport class Client {\n private readonly cfg: ClientConfig;\n private readonly deleter: Deleter;\n private readonly reader: Reader;\n\n constructor(cfg: ClientConfig) {\n const { stream, unary, retrieveChannels } = cfg;\n this.cfg = cfg;\n this.deleter = new Deleter(unary);\n this.reader = new Reader(retrieveChannels, stream);\n }\n\n /**\n * Opens a new iterator over the given channels within the provided time range.\n * @param channels - A list of channels (by name or key) to iterate over.\n * @param opts - see {@link IteratorConfig}\n * @returns a new {@link Iterator}.\n */\n async openIterator(\n tr: CrudeTimeRange,\n channels: channel.Params,\n opts?: IteratorConfig,\n ): Promise<Iterator> {\n return await Iterator._open(\n tr,\n channels,\n this.cfg.retrieveChannels,\n this.cfg.stream,\n opts,\n );\n }\n\n /**\n * Opens a new writer on the given channels.\n * @param config - The configuration for the created writer, see documentation for\n * writerConfig for more detail.\n * @returns a new {@link Writer}.\n */\n async openWriter(config: WriterConfig): Promise<Writer> {\n return await Writer._open(this.cfg.retrieveChannels, this.cfg.stream, config);\n }\n\n /**\n * Opens a new streamer with the provided configuration.\n * @param config.channels - The channels to stream values from. Can be a key, name,\n * list of keys, or list of names.\n * @param config.from - If this parameter is set and is before the current time, the\n * streamer will first read and receive historical data from before this point and\n * then will start reading new values.\n */\n async openStreamer(config: StreamerConfig): Promise<Streamer> {\n return await openStreamer(this.cfg.retrieveChannels, this.cfg.stream, config);\n }\n\n /**\n * Opens a feed over this client. The underlying stream opens on first demand;\n * the caller must close the feed.\n */\n openFeed(options: FeedOptions = {}): Feed {\n return new Feed({\n ...options,\n readRemote: async (tr, keys) => await this.read(tr, keys),\n openStreamer: async (config) => await this.openStreamer(config),\n });\n }\n\n async write(\n start: CrudeTimeStamp,\n channel: channel.Key | channel.Name,\n data: CrudeSeries,\n ): Promise<void>;\n\n async write(\n start: CrudeTimeStamp,\n channels: channel.Key[] | channel.Name[],\n data: CrudeSeries[],\n ): Promise<void>;\n\n async write(\n start: CrudeTimeStamp,\n data: Record<channel.Key | channel.Name, CrudeSeries>,\n ): Promise<void>;\n\n /**\n * Writes telemetry to the given channels, starting at the given timestamp. It commits\n * and closes before it returns, so the samples land on disk.\n *\n * @param start - The timestamp of the first sample.\n * @throws {NotFoundError} if a channel does not exist.\n * @throws {UnauthorizedError} if another writer holds control of a channel.\n * @throws {ValidationError} if the data type does not match the channel's.\n */\n async write(\n start: CrudeTimeStamp,\n channels: channel.Params | Record<channel.Key | channel.Name, CrudeSeries>,\n data?: CrudeSeries | CrudeSeries[],\n ): Promise<void> {\n if (data == null) {\n const data_ = channels as Record<channel.Key | channel.Name, CrudeSeries>;\n const w = await this.openWriter({\n start,\n channels: Object.keys(data_),\n mode: WriterMode.Persist,\n errOnUnauthorized: true,\n autoIndexPersistInterval: TimeSpan.MAX,\n });\n await w.write(data_);\n return await w.close();\n }\n const w = await this.openWriter({\n start,\n channels: channels as channel.Params,\n mode: WriterMode.Persist,\n errOnUnauthorized: true,\n autoIndexPersistInterval: TimeSpan.MAX,\n });\n await w.write(channels as channel.Params, data);\n await w.close();\n }\n\n /**\n * Reads every sample in the time range from the given channels.\n *\n * @returns a {@link MultiSeries} for one channel, or a {@link Frame} for several.\n * @throws {NotFoundError} if a channel does not exist.\n */\n async read(\n tr: CrudeTimeRange,\n channel: channel.Key | channel.Name,\n ): Promise<MultiSeries>;\n async read(tr: CrudeTimeRange, channels: channel.Params): Promise<Frame>;\n async read(request: ReadRequest): Promise<ReadableStream<Uint8Array>>;\n async read(\n tr: CrudeTimeRange | ReadRequest,\n channels?: channel.Params,\n ): Promise<MultiSeries | Frame | ReadableStream<Uint8Array>> {\n if (!(\"start\" in tr)) return await this.reader.read(tr);\n const { single } = analyzeParams(channels!);\n const fr = await this.readFrame(tr, channels!);\n if (single) return fr.get(channels as channel.Key | channel.Name);\n return fr;\n }\n\n private async readFrame(\n tr: CrudeTimeRange,\n channels: channel.Params,\n ): Promise<Frame> {\n const i = await this.openIterator(tr, channels);\n const frame = new Frame();\n try {\n for await (const f of i) frame.push(f);\n } finally {\n await i.close();\n }\n return frame;\n }\n\n async readLatest(\n channel: channel.Key | channel.Name,\n n: number,\n ): Promise<MultiSeries>;\n\n async readLatest(channels: channel.Params, n: number): Promise<Frame>;\n\n /**\n * Reads the latest n samples from the given channel(s). If fewer than n samples are\n * available, returns only the samples that exist.\n * @param channels - A single channel key/name or an array of channel keys/names.\n * @param n - The maximum number of samples to read. Defaults to 1.\n * @returns A MultiSeries when a single channel is provided, or a Frame when multiple\n * channels are provided.\n */\n async readLatest(\n channels: channel.Params,\n n: number = 1,\n ): Promise<MultiSeries | Frame> {\n const { single } = analyzeParams(channels);\n const fr = await this.readLatestNFrame(channels, n);\n if (single) return fr.get(channels as channel.Key | channel.Name);\n return fr;\n }\n\n private async readLatestNFrame(channels: channel.Params, n: number): Promise<Frame> {\n const i = await this.openIterator(TimeRange.MAX, channels, { chunkSize: n });\n const frame = new Frame();\n if (n > 0)\n try {\n await i.seekLast();\n await i.prev(AUTO_SPAN);\n frame.push(i.value);\n } finally {\n await i.close();\n }\n return frame;\n }\n\n /**\n * Deletes every sample in the time range from the given channels. Deletion is\n * permanent.\n */\n async delete(channels: channel.Params, timeRange: CrudeTimeRange): Promise<void> {\n const { normalized, variant } = analyzeParams(channels);\n const bounds = new TimeRange(timeRange);\n if (variant === \"keys\")\n return await this.deleter.delete({ keys: normalized, bounds });\n return await this.deleter.delete({ names: normalized, bounds });\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport { type ChannelRetriever } from \"@/framer/adapter\";\nexport { type RemoteReader } from \"@/framer/cache/reader\";\nexport {\n type StatusHandler,\n type StreamHandler,\n type Subscription,\n} from \"@/framer/cache/streamer\";\nexport { IDENTITY_TRANSFORM, type Transform } from \"@/framer/cache/transform\";\nexport * from \"@/framer/client\";\nexport * from \"@/framer/feed\";\nexport * from \"@/framer/frame\";\nexport * from \"@/framer/hardened\";\nexport * from \"@/framer/iterator\";\nexport * from \"@/framer/reader\";\nexport * from \"@/framer/streamer\";\nexport * from \"@/framer/types.gen\";\nexport * from \"@/framer/writer\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type FileTransport, type UploadBody } from \"@synnaxlabs/freighter\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\n/**\n * The serialized wire formats a resource can be imported from or exported to. Today\n * only \"JSON\" is supported.\n */\nexport const encodingZ = z.enum([\"JSON\"]);\n\n/** The serialized wire format of an imported or exported resource. */\nexport type Encoding = z.infer<typeof encodingZ>;\n\n/**\n * Options shared by import and export. Carries the wire format of the resource and is\n * the extension point for any future per-call settings.\n */\nexport interface Options {\n /** The serialized format of the resource. */\n encoding: Encoding;\n}\n\n/** The standard options for a JSON import or export. */\nexport const JSON_OPTIONS: Options = { encoding: \"JSON\" };\n\n/** The wire shape of the per-import request params. Both fields are required. */\nconst importParamsZ = z.object({\n fileName: z.string().min(1),\n parent: ontology.idZ.transform((id) => ontology.idToString(id)),\n});\n\n/** Options for a single import call. */\nexport interface ImportOptions extends Options {\n /**\n * The name of the file the resource was read from. When the file's contents carry no\n * top-level `name` field, the Core names the imported resource after the file, with\n * any trailing extension stripped. A `name` in the file always wins.\n */\n fileName: string;\n /**\n * The ontology resource to create the imported resource under — a project for project\n * items, a group for symbols. The Core creates the resource and its parent\n * relationship in a single transaction, so a parenting failure rolls back the import.\n */\n parent: ontology.ID;\n}\n\n/**\n * Imports and exports resources to and from a Synnax cluster as serialized bytes — the\n * same on-disk representation a user reads from or writes to a file. The bytes are\n * opaque to the client: nothing is parsed or transformed on the way through, so the\n * wire format is exactly the file's contents.\n *\n * Each call moves exactly one resource. When source is a Blob, the client never holds\n * the payload in its own memory; bytes are sent as-is (already in memory). Exports\n * always stream back without buffering. The Core, however, currently materializes each\n * payload, so a single import or export is bounded by its available memory.\n *\n * The client is environment-agnostic — the byte streams are standard Web Streams that\n * work in browsers, Node 18+, and Tauri webviews. Callers bridge the filesystem with\n * their own runtime's primitives:\n *\n * - Node: `import(Readable.toWeb(createReadStream(path)), opts)` and `(await export(id,\n * opts)).pipeTo(Writable.toWeb(createWriteStream(path)))`.\n * - Browser: `import(fileInput.files[0], opts)` and pipe the export into a\n * showSaveFilePicker writable (or buffer it with `new Response(stream).blob()`).\n * - Tauri/Console: read the picked file into a Blob to import, and hand the export\n * stream to the Console's download hook.\n */\nexport interface ClientConfig {\n file: FileTransport;\n}\n\nexport class Client {\n private readonly cfg: ClientConfig;\n\n constructor(cfg: ClientConfig) {\n this.cfg = cfg;\n }\n\n /**\n * Imports a resource from the given serialized source and returns its new ontology\n * ID.\n * @param source - the serialized resource (e.g. a file's contents). A Blob is sent\n * from wherever the engine holds it, so a file never enters client memory; bytes are\n * sent as-is.\n * @param options - the import options, including the wire format of source, the\n * source file's name (used to name the resource when the file carries no name), and\n * the parent resource to create the resource under.\n * @returns the new resource's ontology ID as stamped by the Core.\n */\n async import(\n source: UploadBody,\n { encoding, ...params }: ImportOptions,\n ): Promise<ontology.ID> {\n return await this.cfg.file.upload(\n \"/imex/import\",\n source,\n { encoding, params, paramsSchema: importParamsZ },\n ontology.idZ,\n );\n }\n\n /**\n * Exports the resource identified by id as a byte stream. The caller pipes the stream\n * wherever it likes — a file on disk, a browser download, or an in-memory buffer via\n * `new Response(stream).json()` — without the client ever buffering the whole\n * payload.\n * @param options - the export options, including the desired wire format.\n * @returns the serialized resource as a stream of bytes.\n */\n async export(id: ontology.ID, options: Options): Promise<ReadableStream<Uint8Array>> {\n return await this.cfg.file.download(\"/imex/export\", id, ontology.idZ, options);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { color, spatial, text, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { channel } from \"@/channel\";\nimport { ontology } from \"@/ontology\";\n\nexport const AXIS_KEYS = [\"x1\", \"x2\", \"y1\", \"y2\", \"y3\", \"y4\"] as const;\nexport const axisKeyZ = z.enum(AXIS_KEYS);\nexport type AxisKey = z.infer<typeof axisKeyZ>;\n\nexport const TICK_TYPES = [\"linear\", \"time\"] as const;\nexport const tickTypeZ = z.enum(TICK_TYPES);\nexport type TickType = z.infer<typeof tickTypeZ>;\n\nexport const DOWNSAMPLE_MODES = [\"average\", \"decimate\"] as const;\nexport const downsampleModeZ = z.enum(DOWNSAMPLE_MODES);\nexport type DownsampleMode = z.infer<typeof downsampleModeZ>;\n\nexport const X_AXIS_KEYS = [\"x1\", \"x2\"] as const;\nexport const xAxisKeyZ = z.enum(X_AXIS_KEYS);\nexport type XAxisKey = z.infer<typeof xAxisKeyZ>;\n\nexport const Y_AXIS_KEYS = [\"y1\", \"y2\", \"y3\", \"y4\"] as const;\nexport const yAxisKeyZ = z.enum(Y_AXIS_KEYS);\nexport type YAxisKey = z.infer<typeof yAxisKeyZ>;\n\n/** Title is the plot title configuration. */\nexport const titleZ = z.object({\n /** level is the typography level of the title text. */\n level: text.levelZ.default(\"h4\"),\n /** visible is whether the title is shown above the plot. */\n visible: z.boolean().default(false),\n});\nexport interface Title extends z.infer<typeof titleZ> {}\n\n/** Legend is the plot legend configuration. */\nexport const legendZ = z.object({\n /**\n * hidden is whether the legend is hidden. When false (the default), the legend is\n * shown.\n */\n hidden: z.boolean().default(false),\n /** position is the anchor position of the legend within the plot container. */\n position: spatial.stickyXYZ.prefault({\n x: 50,\n y: 50,\n root: { x: \"left\", y: \"top\" },\n units: { x: \"px\", y: \"px\" },\n }),\n});\nexport interface Legend extends z.infer<typeof legendZ> {}\n\n/**\n * Channels binds channel keys to each axis. x1 and x2 are single-channel; y1 through y4\n * carry zero or more channels each.\n */\nexport const channelsZ = z.object({\n /** x1 is the channel rendered on the x1 axis. */\n x1: channel.keyZ.default(0),\n /** x2 is the channel rendered on the x2 axis. */\n x2: channel.keyZ.default(0),\n /** y1 are the channels rendered on the y1 axis. */\n y1: channel.keyZ.array().default(() => []),\n /** y2 are the channels rendered on the y2 axis. */\n y2: channel.keyZ.array().default(() => []),\n /** y3 are the channels rendered on the y3 axis. */\n y3: channel.keyZ.array().default(() => []),\n /** y4 are the channels rendered on the y4 axis. */\n y4: channel.keyZ.array().default(() => []),\n});\nexport interface Channels extends z.infer<typeof channelsZ> {}\n\n/** Ranges binds range keys to each x-axis. */\nexport const rangesZ = z.object({\n /**\n * x1 are the range keys plotted against the x1 axis. Range keys are opaque strings\n * rather than UUIDs because the console layers synthetic rolling-window ranges (e.g.\n * \"recent\", \"rolling1m\") alongside persisted ranges; the server stores whatever the\n * client sends.\n */\n x1: z\n .string()\n .array()\n .default(() => []),\n /** x2 are the range keys plotted against the x2 axis. */\n x2: z\n .string()\n .array()\n .default(() => []),\n});\nexport interface Ranges extends z.infer<typeof rangesZ> {}\n\n/**\n * ManualBounds controls whether an axis uses a manually-set bound on each side\n * independently. When a side is false (the default), the corresponding entry in\n * Axis.bounds is recomputed locally from the rendered data window and never broadcast\n * to the server; when true, Axis.bounds holds the user-set value.\n */\nexport const manualBoundsZ = z.object({\n /**\n * lower is whether the lower bound is set manually rather than computed from data.\n */\n lower: z.boolean().default(false),\n /**\n * upper is whether the upper bound is set manually rather than computed from data.\n */\n upper: z.boolean().default(false),\n});\nexport interface ManualBounds extends z.infer<typeof manualBoundsZ> {}\n\n/** Line is the per-line styling and downsampling configuration. */\nexport const lineZ = z.object({\n /**\n * key is the line identifier derived from its channel and range assignment. Format is\n * internal to the client and stable across re-renders so styling overrides persist.\n */\n key: z.string(),\n /**\n * label is the user-specified line label. Null means derive from the channel name at\n * render time; non-null is an override.\n */\n label: z.string().optional(),\n /**\n * color is the line color. When null, the Console assigns one from the visualization\n * palette at render time.\n */\n color: color.colorZ.optional(),\n /** strokeWidth is the line stroke width in pixels. */\n strokeWidth: z.number().default(2),\n /**\n * downsample is the downsample factor applied before rendering. 1 means render every\n * sample; higher values render every Nth sample.\n */\n downsample: z.uint32().default(1),\n /** downsampleMode selects how the downsample factor is applied. */\n downsampleMode: downsampleModeZ.default(\"decimate\"),\n});\nexport interface Line extends z.infer<typeof lineZ> {}\n\n/** Rule is a horizontal or vertical annotation line drawn over the plot. */\nexport const ruleZ = z.object({\n /** key is the unique rule identifier within the line plot. */\n key: z.string(),\n /** label is the human-readable label rendered alongside the rule. */\n label: z.string(),\n /**\n * color is the display color of the rule. When null, the Console assigns a default at\n * render time.\n */\n color: color.colorZ.optional(),\n /** axis is the axis the rule is anchored to. */\n axis: axisKeyZ,\n /** lineWidth is the rule line width in pixels. */\n lineWidth: z.number().default(1),\n /** lineDash is the dash length in pixels; 0 renders a solid line. */\n lineDash: z.number().default(0),\n /** units is the unit label displayed next to the position value. */\n units: z.string().default(\"\"),\n /** position is the value-space position of the rule along its anchored axis. */\n position: z.number(),\n});\nexport interface Rule extends z.infer<typeof ruleZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/** Axis is the configuration for a single plot axis. */\nexport const axisZ = z.object({\n /** key identifies which of the six axes this configuration applies to. */\n key: axisKeyZ,\n /** label is the human-readable label rendered along the axis. */\n label: z.string().default(\"\"),\n /** labelDirection is the orientation in which the label text is laid out. */\n labelDirection: spatial.directionZ.default(\"x\"),\n /** labelLevel is the typography level of the label. */\n labelLevel: text.levelZ.default(\"small\"),\n /**\n * bounds is the value-space window of the axis. When the matching entry in\n * manual_bounds is false the field is overwritten locally on every render; otherwise\n * it is the user-set fixed bound.\n */\n bounds: spatial.boundsZ().prefault({ lower: 0, upper: 0 }),\n /** manualBounds controls per-edge manual bound override. */\n manualBounds: manualBoundsZ.prefault({}),\n /** tickSpacing is the target pixel distance between adjacent tick marks. */\n tickSpacing: z.number().default(75),\n /**\n * type selects the tick label style. Null means default (linear). X-axes typically\n * carry \"time\" when bound to a timestamp channel.\n */\n type: tickTypeZ.optional(),\n});\nexport interface Axis extends z.infer<typeof axisZ> {}\n\n/** Axes bundles configuration for all six fixed plot axes. */\nexport const axesZ = z.object({\n /** x1 is the x1 axis configuration. */\n x1: axisZ.prefault({ key: \"x1\" }),\n /** x2 is the x2 axis configuration. */\n x2: axisZ.prefault({ key: \"x2\" }),\n /** y1 is the y1 axis configuration. */\n y1: axisZ.prefault({ key: \"y1\", labelDirection: \"y\" }),\n /** y2 is the y2 axis configuration. */\n y2: axisZ.prefault({ key: \"y2\", labelDirection: \"y\" }),\n /** y3 is the y3 axis configuration. */\n y3: axisZ.prefault({ key: \"y3\", labelDirection: \"y\" }),\n /** y4 is the y4 axis configuration. */\n y4: axisZ.prefault({ key: \"y4\", labelDirection: \"y\" }),\n});\nexport interface Axes extends z.infer<typeof axesZ> {}\n\n/**\n * LinePlot is a time-series visualization component for plotting telemetry data. Line\n * plots support multiple channels, real-time streaming, and historical data display\n * with zoom and pan capabilities.\n */\nexport const linePlotZ = z.object({\n /** key is the unique identifier for this line plot. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the line plot. */\n name: z.string().min(1, \"name is required\"),\n /** title is the plot title configuration. */\n title: titleZ.prefault({}),\n /** legend is the plot legend configuration. */\n legend: legendZ.prefault({}),\n /** channels binds channel keys to each axis. */\n channels: channelsZ.prefault({}),\n /** ranges binds range keys to each x-axis. */\n ranges: rangesZ.prefault({}),\n /** axes bundles per-axis configuration. */\n axes: axesZ.prefault({}),\n /**\n * lines holds per-line styling and downsampling configuration. Each entry corresponds\n * to one channel and range combination produced by the channels and ranges bindings.\n */\n lines: lineZ.array().default(() => []),\n /** rules holds annotation rules drawn over the plot. */\n rules: ruleZ.array().default(() => []),\n});\nexport interface LinePlot extends z.infer<typeof linePlotZ> {}\nexport interface New extends z.input<typeof linePlotZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"lineplot\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { color, spatial, text, zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { channel } from \"@/channel\";\nimport {\n axisKeyZ,\n downsampleModeZ,\n keyZ,\n type LinePlot,\n linePlotZ,\n lineZ,\n manualBoundsZ,\n ruleZ,\n tickTypeZ,\n xAxisKeyZ,\n yAxisKeyZ,\n} from \"@/lineplot/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n linePlot: linePlotZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the line plot. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/** SetTitleVisible sets whether the plot title is shown above the plot. */\nexport const setTitleVisiblePayloadZ = z.object({\n visible: z.boolean(),\n});\n\nexport type SetTitleVisiblePayload = z.infer<typeof setTitleVisiblePayloadZ>;\n\n/** SetTitleLevel sets the typography level of the plot title. */\nexport const setTitleLevelPayloadZ = z.object({\n level: text.levelZ,\n});\n\nexport type SetTitleLevelPayload = z.infer<typeof setTitleLevelPayloadZ>;\n\n/** SetLegendHidden sets whether the plot legend is hidden. */\nexport const setLegendHiddenPayloadZ = z.object({\n hidden: z.boolean(),\n});\n\nexport type SetLegendHiddenPayload = z.infer<typeof setLegendHiddenPayloadZ>;\n\n/**\n * SetLegendPosition sets the anchor position of the plot legend within the container.\n */\nexport const setLegendPositionPayloadZ = z.object({\n position: spatial.stickyXYZ,\n});\n\nexport type SetLegendPositionPayload = z.infer<typeof setLegendPositionPayloadZ>;\n\n/**\n * AddChannel appends the channel to the channels array bound to the y-axis named by\n * axis_key. No-op when the channel is already present.\n */\nexport const addChannelPayloadZ = z.object({\n axisKey: yAxisKeyZ,\n channel: channel.keyZ,\n});\n\nexport type AddChannelPayload = z.infer<typeof addChannelPayloadZ>;\n\n/**\n * RemoveChannel removes the channel from the y-axis named by axis_key. No-op when the\n * channel is not present.\n */\nexport const removeChannelPayloadZ = z.object({\n axisKey: yAxisKeyZ,\n channel: channel.keyZ,\n});\n\nexport type RemoveChannelPayload = z.infer<typeof removeChannelPayloadZ>;\n\n/**\n * SetChannels replaces the entire set of channels bound to the y-axis named by axis_key\n * with channels. Channels absent from the new set are removed and their lines dropped;\n * channels not previously present are added. Existing channels keep their line styling.\n */\nexport const setChannelsPayloadZ = z.object({\n axisKey: yAxisKeyZ,\n channels: channel.keyZ.array().default(() => []),\n});\n\nexport type SetChannelsPayload = z.infer<typeof setChannelsPayloadZ>;\n\n/** SetXChannel replaces the single channel bound to the x-axis named by axis_key. */\nexport const setXChannelPayloadZ = z.object({\n axisKey: xAxisKeyZ,\n channel: channel.keyZ,\n});\n\nexport type SetXChannelPayload = z.infer<typeof setXChannelPayloadZ>;\n\n/**\n * AddRange appends the range key to the ranges array bound to the x-axis named by\n * axis_key. No-op when the range is already present.\n */\nexport const addRangePayloadZ = z.object({\n axisKey: xAxisKeyZ,\n range: z.string(),\n});\n\nexport type AddRangePayload = z.infer<typeof addRangePayloadZ>;\n\n/**\n * RemoveRange removes the range key from the x-axis named by axis_key. No-op when the\n * range is not present.\n */\nexport const removeRangePayloadZ = z.object({\n axisKey: xAxisKeyZ,\n range: z.string(),\n});\n\nexport type RemoveRangePayload = z.infer<typeof removeRangePayloadZ>;\n\n/**\n * SetRanges replaces the entire set of range keys bound to the x-axis named by axis_key\n * with ranges. Ranges absent from the new set are removed and their lines dropped;\n * ranges not previously present are added. Existing ranges keep their line styling.\n */\nexport const setRangesPayloadZ = z.object({\n axisKey: xAxisKeyZ,\n ranges: z\n .string()\n .array()\n .default(() => []),\n});\n\nexport type SetRangesPayload = z.infer<typeof setRangesPayloadZ>;\n\n/** SetAxisLabel sets the label rendered along the axis identified by key. */\nexport const setAxisLabelPayloadZ = z.object({\n key: axisKeyZ,\n label: z.string(),\n});\n\nexport type SetAxisLabelPayload = z.infer<typeof setAxisLabelPayloadZ>;\n\n/** SetAxisLabelDirection sets the orientation in which the axis label is laid out. */\nexport const setAxisLabelDirectionPayloadZ = z.object({\n key: axisKeyZ,\n labelDirection: spatial.directionZ,\n});\n\nexport type SetAxisLabelDirectionPayload = z.infer<\n typeof setAxisLabelDirectionPayloadZ\n>;\n\n/** SetAxisLabelLevel sets the typography level of the axis label. */\nexport const setAxisLabelLevelPayloadZ = z.object({\n key: axisKeyZ,\n labelLevel: text.levelZ,\n});\n\nexport type SetAxisLabelLevelPayload = z.infer<typeof setAxisLabelLevelPayloadZ>;\n\n/**\n * SetAxisBounds sets the axis value-space window together with its per-edge manual\n * override flags. The two travel together: fixing a bound enables the manual override\n * for that edge, so callers set both at once.\n */\nexport const setAxisBoundsPayloadZ = z.object({\n key: axisKeyZ,\n bounds: spatial.boundsZ(),\n manualBounds: manualBoundsZ,\n});\n\nexport type SetAxisBoundsPayload = z.infer<typeof setAxisBoundsPayloadZ>;\n\n/** SetAxisTickSpacing sets the target pixel distance between adjacent tick marks. */\nexport const setAxisTickSpacingPayloadZ = z.object({\n key: axisKeyZ,\n tickSpacing: z.number(),\n});\n\nexport type SetAxisTickSpacingPayload = z.infer<typeof setAxisTickSpacingPayloadZ>;\n\n/**\n * SetAxisType sets the axis tick label style. Null resets it to the default, which the\n * Console derives (linear, or time for a timestamp-bound x-axis) at render time.\n */\nexport const setAxisTypePayloadZ = z.object({\n key: axisKeyZ,\n type: tickTypeZ.optional(),\n});\n\nexport type SetAxisTypePayload = z.infer<typeof setAxisTypePayloadZ>;\n\n/**\n * SetLineLabel sets the label of the line identified by key. Null resets it to derive\n * from the channel name at render time.\n */\nexport const setLineLabelPayloadZ = z.object({\n key: z.string(),\n label: z.string().optional(),\n});\n\nexport type SetLineLabelPayload = z.infer<typeof setLineLabelPayloadZ>;\n\n/**\n * SetLineColor sets the color of the line identified by key. Null resets it to a\n * palette color assigned at render time.\n */\nexport const setLineColorPayloadZ = z.object({\n key: z.string(),\n color: color.colorZ.optional(),\n});\n\nexport type SetLineColorPayload = z.infer<typeof setLineColorPayloadZ>;\n\n/**\n * SetLineStrokeWidth sets the stroke width, in pixels, of the line identified by key.\n */\nexport const setLineStrokeWidthPayloadZ = z.object({\n key: z.string(),\n strokeWidth: z.number(),\n});\n\nexport type SetLineStrokeWidthPayload = z.infer<typeof setLineStrokeWidthPayloadZ>;\n\n/** SetLineDownsample sets the downsample factor of the line identified by key. */\nexport const setLineDownsamplePayloadZ = z.object({\n key: z.string(),\n downsample: z.uint32(),\n});\n\nexport type SetLineDownsamplePayload = z.infer<typeof setLineDownsamplePayloadZ>;\n\n/**\n * SetLineDownsampleMode sets how the downsample factor is applied for the line\n * identified by key.\n */\nexport const setLineDownsampleModePayloadZ = z.object({\n key: z.string(),\n downsampleMode: downsampleModeZ,\n});\n\nexport type SetLineDownsampleModePayload = z.infer<\n typeof setLineDownsampleModePayloadZ\n>;\n\n/**\n * SetLine replaces the line with line.key in place, inserting it when no such line\n * exists. The fine-grained setLine* actions cover per-field edits; this full-object\n * form restores a line dropped by reconciliation.\n */\nexport const setLinePayloadZ = z.object({\n line: lineZ,\n});\n\nexport type SetLinePayload = z.infer<typeof setLinePayloadZ>;\n\n/**\n * SetRule inserts the rule if no rule with rule.key exists, otherwise replaces the\n * existing entry in place. The fine-grained setRule* actions cover per-field edits;\n * this full-object form creates a rule or restores one removed by another action's\n * inverse.\n */\nexport const setRulePayloadZ = z.object({\n rule: ruleZ,\n});\n\nexport type SetRulePayload = z.infer<typeof setRulePayloadZ>;\n\n/** SetRuleLabel sets the label of the rule identified by key. */\nexport const setRuleLabelPayloadZ = z.object({\n key: z.string(),\n label: z.string(),\n});\n\nexport type SetRuleLabelPayload = z.infer<typeof setRuleLabelPayloadZ>;\n\n/**\n * SetRuleColor sets the color of the rule identified by key. Null resets it to a\n * default color assigned at render time.\n */\nexport const setRuleColorPayloadZ = z.object({\n key: z.string(),\n color: color.colorZ.optional(),\n});\n\nexport type SetRuleColorPayload = z.infer<typeof setRuleColorPayloadZ>;\n\n/** SetRuleAxis sets the axis the rule identified by key is anchored to. */\nexport const setRuleAxisPayloadZ = z.object({\n key: z.string(),\n axis: axisKeyZ,\n});\n\nexport type SetRuleAxisPayload = z.infer<typeof setRuleAxisPayloadZ>;\n\n/** SetRuleLineWidth sets the line width, in pixels, of the rule identified by key. */\nexport const setRuleLineWidthPayloadZ = z.object({\n key: z.string(),\n lineWidth: z.number(),\n});\n\nexport type SetRuleLineWidthPayload = z.infer<typeof setRuleLineWidthPayloadZ>;\n\n/** SetRuleLineDash sets the dash length, in pixels, of the rule identified by key. */\nexport const setRuleLineDashPayloadZ = z.object({\n key: z.string(),\n lineDash: z.number(),\n});\n\nexport type SetRuleLineDashPayload = z.infer<typeof setRuleLineDashPayloadZ>;\n\n/** SetRuleUnits sets the unit label of the rule identified by key. */\nexport const setRuleUnitsPayloadZ = z.object({\n key: z.string(),\n units: z.string(),\n});\n\nexport type SetRuleUnitsPayload = z.infer<typeof setRuleUnitsPayloadZ>;\n\n/** SetRulePosition sets the value-space position of the rule identified by key. */\nexport const setRulePositionPayloadZ = z.object({\n key: z.string(),\n position: z.number(),\n});\n\nexport type SetRulePositionPayload = z.infer<typeof setRulePositionPayloadZ>;\n\n/** RemoveRule removes the rule with the given key, if present. */\nexport const removeRulePayloadZ = z.object({\n key: z.string(),\n});\n\nexport type RemoveRulePayload = z.infer<typeof removeRulePayloadZ>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({\n type: z.literal(\"set_title_visible\"),\n setTitleVisible: setTitleVisiblePayloadZ,\n }),\n z.object({\n type: z.literal(\"set_title_level\"),\n setTitleLevel: setTitleLevelPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_legend_hidden\"),\n setLegendHidden: setLegendHiddenPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_legend_position\"),\n setLegendPosition: setLegendPositionPayloadZ,\n }),\n z.object({ type: z.literal(\"add_channel\"), addChannel: addChannelPayloadZ }),\n z.object({ type: z.literal(\"remove_channel\"), removeChannel: removeChannelPayloadZ }),\n z.object({ type: z.literal(\"set_channels\"), setChannels: setChannelsPayloadZ }),\n z.object({ type: z.literal(\"set_x_channel\"), setXChannel: setXChannelPayloadZ }),\n z.object({ type: z.literal(\"add_range\"), addRange: addRangePayloadZ }),\n z.object({ type: z.literal(\"remove_range\"), removeRange: removeRangePayloadZ }),\n z.object({ type: z.literal(\"set_ranges\"), setRanges: setRangesPayloadZ }),\n z.object({ type: z.literal(\"set_axis_label\"), setAxisLabel: setAxisLabelPayloadZ }),\n z.object({\n type: z.literal(\"set_axis_label_direction\"),\n setAxisLabelDirection: setAxisLabelDirectionPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_axis_label_level\"),\n setAxisLabelLevel: setAxisLabelLevelPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_axis_bounds\"),\n setAxisBounds: setAxisBoundsPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_axis_tick_spacing\"),\n setAxisTickSpacing: setAxisTickSpacingPayloadZ,\n }),\n z.object({ type: z.literal(\"set_axis_type\"), setAxisType: setAxisTypePayloadZ }),\n z.object({ type: z.literal(\"set_line_label\"), setLineLabel: setLineLabelPayloadZ }),\n z.object({ type: z.literal(\"set_line_color\"), setLineColor: setLineColorPayloadZ }),\n z.object({\n type: z.literal(\"set_line_stroke_width\"),\n setLineStrokeWidth: setLineStrokeWidthPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_line_downsample\"),\n setLineDownsample: setLineDownsamplePayloadZ,\n }),\n z.object({\n type: z.literal(\"set_line_downsample_mode\"),\n setLineDownsampleMode: setLineDownsampleModePayloadZ,\n }),\n z.object({ type: z.literal(\"set_line\"), setLine: setLinePayloadZ }),\n z.object({ type: z.literal(\"set_rule\"), setRule: setRulePayloadZ }),\n z.object({ type: z.literal(\"set_rule_label\"), setRuleLabel: setRuleLabelPayloadZ }),\n z.object({ type: z.literal(\"set_rule_color\"), setRuleColor: setRuleColorPayloadZ }),\n z.object({ type: z.literal(\"set_rule_axis\"), setRuleAxis: setRuleAxisPayloadZ }),\n z.object({\n type: z.literal(\"set_rule_line_width\"),\n setRuleLineWidth: setRuleLineWidthPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_rule_line_dash\"),\n setRuleLineDash: setRuleLineDashPayloadZ,\n }),\n z.object({ type: z.literal(\"set_rule_units\"), setRuleUnits: setRuleUnitsPayloadZ }),\n z.object({\n type: z.literal(\"set_rule_position\"),\n setRulePosition: setRulePositionPayloadZ,\n }),\n z.object({ type: z.literal(\"remove_rule\"), removeRule: removeRulePayloadZ }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"line plot create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"line plot rename action payload\",\n }),\n});\n\nexport const setTitleVisible = (\n payload: z.input<typeof setTitleVisiblePayloadZ>,\n): Action => ({\n type: \"set_title_visible\",\n setTitleVisible: zod.parse(setTitleVisiblePayloadZ, payload, {\n label: \"line plot set_title_visible action payload\",\n }),\n});\n\nexport const setTitleLevel = (\n payload: z.input<typeof setTitleLevelPayloadZ>,\n): Action => ({\n type: \"set_title_level\",\n setTitleLevel: zod.parse(setTitleLevelPayloadZ, payload, {\n label: \"line plot set_title_level action payload\",\n }),\n});\n\nexport const setLegendHidden = (\n payload: z.input<typeof setLegendHiddenPayloadZ>,\n): Action => ({\n type: \"set_legend_hidden\",\n setLegendHidden: zod.parse(setLegendHiddenPayloadZ, payload, {\n label: \"line plot set_legend_hidden action payload\",\n }),\n});\n\nexport const setLegendPosition = (\n payload: z.input<typeof setLegendPositionPayloadZ>,\n): Action => ({\n type: \"set_legend_position\",\n setLegendPosition: zod.parse(setLegendPositionPayloadZ, payload, {\n label: \"line plot set_legend_position action payload\",\n }),\n});\n\nexport const addChannel = (payload: z.input<typeof addChannelPayloadZ>): Action => ({\n type: \"add_channel\",\n addChannel: zod.parse(addChannelPayloadZ, payload, {\n label: \"line plot add_channel action payload\",\n }),\n});\n\nexport const removeChannel = (\n payload: z.input<typeof removeChannelPayloadZ>,\n): Action => ({\n type: \"remove_channel\",\n removeChannel: zod.parse(removeChannelPayloadZ, payload, {\n label: \"line plot remove_channel action payload\",\n }),\n});\n\nexport const setChannels = (payload: z.input<typeof setChannelsPayloadZ>): Action => ({\n type: \"set_channels\",\n setChannels: zod.parse(setChannelsPayloadZ, payload, {\n label: \"line plot set_channels action payload\",\n }),\n});\n\nexport const setXChannel = (payload: z.input<typeof setXChannelPayloadZ>): Action => ({\n type: \"set_x_channel\",\n setXChannel: zod.parse(setXChannelPayloadZ, payload, {\n label: \"line plot set_x_channel action payload\",\n }),\n});\n\nexport const addRange = (payload: z.input<typeof addRangePayloadZ>): Action => ({\n type: \"add_range\",\n addRange: zod.parse(addRangePayloadZ, payload, {\n label: \"line plot add_range action payload\",\n }),\n});\n\nexport const removeRange = (payload: z.input<typeof removeRangePayloadZ>): Action => ({\n type: \"remove_range\",\n removeRange: zod.parse(removeRangePayloadZ, payload, {\n label: \"line plot remove_range action payload\",\n }),\n});\n\nexport const setRanges = (payload: z.input<typeof setRangesPayloadZ>): Action => ({\n type: \"set_ranges\",\n setRanges: zod.parse(setRangesPayloadZ, payload, {\n label: \"line plot set_ranges action payload\",\n }),\n});\n\nexport const setAxisLabel = (\n payload: z.input<typeof setAxisLabelPayloadZ>,\n): Action => ({\n type: \"set_axis_label\",\n setAxisLabel: zod.parse(setAxisLabelPayloadZ, payload, {\n label: \"line plot set_axis_label action payload\",\n }),\n});\n\nexport const setAxisLabelDirection = (\n payload: z.input<typeof setAxisLabelDirectionPayloadZ>,\n): Action => ({\n type: \"set_axis_label_direction\",\n setAxisLabelDirection: zod.parse(setAxisLabelDirectionPayloadZ, payload, {\n label: \"line plot set_axis_label_direction action payload\",\n }),\n});\n\nexport const setAxisLabelLevel = (\n payload: z.input<typeof setAxisLabelLevelPayloadZ>,\n): Action => ({\n type: \"set_axis_label_level\",\n setAxisLabelLevel: zod.parse(setAxisLabelLevelPayloadZ, payload, {\n label: \"line plot set_axis_label_level action payload\",\n }),\n});\n\nexport const setAxisBounds = (\n payload: z.input<typeof setAxisBoundsPayloadZ>,\n): Action => ({\n type: \"set_axis_bounds\",\n setAxisBounds: zod.parse(setAxisBoundsPayloadZ, payload, {\n label: \"line plot set_axis_bounds action payload\",\n }),\n});\n\nexport const setAxisTickSpacing = (\n payload: z.input<typeof setAxisTickSpacingPayloadZ>,\n): Action => ({\n type: \"set_axis_tick_spacing\",\n setAxisTickSpacing: zod.parse(setAxisTickSpacingPayloadZ, payload, {\n label: \"line plot set_axis_tick_spacing action payload\",\n }),\n});\n\nexport const setAxisType = (payload: z.input<typeof setAxisTypePayloadZ>): Action => ({\n type: \"set_axis_type\",\n setAxisType: zod.parse(setAxisTypePayloadZ, payload, {\n label: \"line plot set_axis_type action payload\",\n }),\n});\n\nexport const setLineLabel = (\n payload: z.input<typeof setLineLabelPayloadZ>,\n): Action => ({\n type: \"set_line_label\",\n setLineLabel: zod.parse(setLineLabelPayloadZ, payload, {\n label: \"line plot set_line_label action payload\",\n }),\n});\n\nexport const setLineColor = (\n payload: z.input<typeof setLineColorPayloadZ>,\n): Action => ({\n type: \"set_line_color\",\n setLineColor: zod.parse(setLineColorPayloadZ, payload, {\n label: \"line plot set_line_color action payload\",\n }),\n});\n\nexport const setLineStrokeWidth = (\n payload: z.input<typeof setLineStrokeWidthPayloadZ>,\n): Action => ({\n type: \"set_line_stroke_width\",\n setLineStrokeWidth: zod.parse(setLineStrokeWidthPayloadZ, payload, {\n label: \"line plot set_line_stroke_width action payload\",\n }),\n});\n\nexport const setLineDownsample = (\n payload: z.input<typeof setLineDownsamplePayloadZ>,\n): Action => ({\n type: \"set_line_downsample\",\n setLineDownsample: zod.parse(setLineDownsamplePayloadZ, payload, {\n label: \"line plot set_line_downsample action payload\",\n }),\n});\n\nexport const setLineDownsampleMode = (\n payload: z.input<typeof setLineDownsampleModePayloadZ>,\n): Action => ({\n type: \"set_line_downsample_mode\",\n setLineDownsampleMode: zod.parse(setLineDownsampleModePayloadZ, payload, {\n label: \"line plot set_line_downsample_mode action payload\",\n }),\n});\n\nexport const setLine = (payload: z.input<typeof setLinePayloadZ>): Action => ({\n type: \"set_line\",\n setLine: zod.parse(setLinePayloadZ, payload, {\n label: \"line plot set_line action payload\",\n }),\n});\n\nexport const setRule = (payload: z.input<typeof setRulePayloadZ>): Action => ({\n type: \"set_rule\",\n setRule: zod.parse(setRulePayloadZ, payload, {\n label: \"line plot set_rule action payload\",\n }),\n});\n\nexport const setRuleLabel = (\n payload: z.input<typeof setRuleLabelPayloadZ>,\n): Action => ({\n type: \"set_rule_label\",\n setRuleLabel: zod.parse(setRuleLabelPayloadZ, payload, {\n label: \"line plot set_rule_label action payload\",\n }),\n});\n\nexport const setRuleColor = (\n payload: z.input<typeof setRuleColorPayloadZ>,\n): Action => ({\n type: \"set_rule_color\",\n setRuleColor: zod.parse(setRuleColorPayloadZ, payload, {\n label: \"line plot set_rule_color action payload\",\n }),\n});\n\nexport const setRuleAxis = (payload: z.input<typeof setRuleAxisPayloadZ>): Action => ({\n type: \"set_rule_axis\",\n setRuleAxis: zod.parse(setRuleAxisPayloadZ, payload, {\n label: \"line plot set_rule_axis action payload\",\n }),\n});\n\nexport const setRuleLineWidth = (\n payload: z.input<typeof setRuleLineWidthPayloadZ>,\n): Action => ({\n type: \"set_rule_line_width\",\n setRuleLineWidth: zod.parse(setRuleLineWidthPayloadZ, payload, {\n label: \"line plot set_rule_line_width action payload\",\n }),\n});\n\nexport const setRuleLineDash = (\n payload: z.input<typeof setRuleLineDashPayloadZ>,\n): Action => ({\n type: \"set_rule_line_dash\",\n setRuleLineDash: zod.parse(setRuleLineDashPayloadZ, payload, {\n label: \"line plot set_rule_line_dash action payload\",\n }),\n});\n\nexport const setRuleUnits = (\n payload: z.input<typeof setRuleUnitsPayloadZ>,\n): Action => ({\n type: \"set_rule_units\",\n setRuleUnits: zod.parse(setRuleUnitsPayloadZ, payload, {\n label: \"line plot set_rule_units action payload\",\n }),\n});\n\nexport const setRulePosition = (\n payload: z.input<typeof setRulePositionPayloadZ>,\n): Action => ({\n type: \"set_rule_position\",\n setRulePosition: zod.parse(setRulePositionPayloadZ, payload, {\n label: \"line plot set_rule_position action payload\",\n }),\n});\n\nexport const removeRule = (payload: z.input<typeof removeRulePayloadZ>): Action => ({\n type: \"remove_rule\",\n removeRule: zod.parse(removeRulePayloadZ, payload, {\n label: \"line plot remove_rule action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<LinePlot, Action>;\n\nexport interface Handlers {\n create: (state: Draft<LinePlot>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<LinePlot>, payload: RenamePayload) => HandlerResult;\n setTitleVisible: (\n state: Draft<LinePlot>,\n payload: SetTitleVisiblePayload,\n ) => HandlerResult;\n setTitleLevel: (\n state: Draft<LinePlot>,\n payload: SetTitleLevelPayload,\n ) => HandlerResult;\n setLegendHidden: (\n state: Draft<LinePlot>,\n payload: SetLegendHiddenPayload,\n ) => HandlerResult;\n setLegendPosition: (\n state: Draft<LinePlot>,\n payload: SetLegendPositionPayload,\n ) => HandlerResult;\n addChannel: (state: Draft<LinePlot>, payload: AddChannelPayload) => HandlerResult;\n removeChannel: (\n state: Draft<LinePlot>,\n payload: RemoveChannelPayload,\n ) => HandlerResult;\n setChannels: (state: Draft<LinePlot>, payload: SetChannelsPayload) => HandlerResult;\n setXChannel: (state: Draft<LinePlot>, payload: SetXChannelPayload) => HandlerResult;\n addRange: (state: Draft<LinePlot>, payload: AddRangePayload) => HandlerResult;\n removeRange: (state: Draft<LinePlot>, payload: RemoveRangePayload) => HandlerResult;\n setRanges: (state: Draft<LinePlot>, payload: SetRangesPayload) => HandlerResult;\n setAxisLabel: (state: Draft<LinePlot>, payload: SetAxisLabelPayload) => HandlerResult;\n setAxisLabelDirection: (\n state: Draft<LinePlot>,\n payload: SetAxisLabelDirectionPayload,\n ) => HandlerResult;\n setAxisLabelLevel: (\n state: Draft<LinePlot>,\n payload: SetAxisLabelLevelPayload,\n ) => HandlerResult;\n setAxisBounds: (\n state: Draft<LinePlot>,\n payload: SetAxisBoundsPayload,\n ) => HandlerResult;\n setAxisTickSpacing: (\n state: Draft<LinePlot>,\n payload: SetAxisTickSpacingPayload,\n ) => HandlerResult;\n setAxisType: (state: Draft<LinePlot>, payload: SetAxisTypePayload) => HandlerResult;\n setLineLabel: (state: Draft<LinePlot>, payload: SetLineLabelPayload) => HandlerResult;\n setLineColor: (state: Draft<LinePlot>, payload: SetLineColorPayload) => HandlerResult;\n setLineStrokeWidth: (\n state: Draft<LinePlot>,\n payload: SetLineStrokeWidthPayload,\n ) => HandlerResult;\n setLineDownsample: (\n state: Draft<LinePlot>,\n payload: SetLineDownsamplePayload,\n ) => HandlerResult;\n setLineDownsampleMode: (\n state: Draft<LinePlot>,\n payload: SetLineDownsampleModePayload,\n ) => HandlerResult;\n setLine: (state: Draft<LinePlot>, payload: SetLinePayload) => HandlerResult;\n setRule: (state: Draft<LinePlot>, payload: SetRulePayload) => HandlerResult;\n setRuleLabel: (state: Draft<LinePlot>, payload: SetRuleLabelPayload) => HandlerResult;\n setRuleColor: (state: Draft<LinePlot>, payload: SetRuleColorPayload) => HandlerResult;\n setRuleAxis: (state: Draft<LinePlot>, payload: SetRuleAxisPayload) => HandlerResult;\n setRuleLineWidth: (\n state: Draft<LinePlot>,\n payload: SetRuleLineWidthPayload,\n ) => HandlerResult;\n setRuleLineDash: (\n state: Draft<LinePlot>,\n payload: SetRuleLineDashPayload,\n ) => HandlerResult;\n setRuleUnits: (state: Draft<LinePlot>, payload: SetRuleUnitsPayload) => HandlerResult;\n setRulePosition: (\n state: Draft<LinePlot>,\n payload: SetRulePositionPayload,\n ) => HandlerResult;\n removeRule: (state: Draft<LinePlot>, payload: RemoveRulePayload) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<LinePlot, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"set_title_visible\":\n return handlers.setTitleVisible(state, action.setTitleVisible);\n case \"set_title_level\":\n return handlers.setTitleLevel(state, action.setTitleLevel);\n case \"set_legend_hidden\":\n return handlers.setLegendHidden(state, action.setLegendHidden);\n case \"set_legend_position\":\n return handlers.setLegendPosition(state, action.setLegendPosition);\n case \"add_channel\":\n return handlers.addChannel(state, action.addChannel);\n case \"remove_channel\":\n return handlers.removeChannel(state, action.removeChannel);\n case \"set_channels\":\n return handlers.setChannels(state, action.setChannels);\n case \"set_x_channel\":\n return handlers.setXChannel(state, action.setXChannel);\n case \"add_range\":\n return handlers.addRange(state, action.addRange);\n case \"remove_range\":\n return handlers.removeRange(state, action.removeRange);\n case \"set_ranges\":\n return handlers.setRanges(state, action.setRanges);\n case \"set_axis_label\":\n return handlers.setAxisLabel(state, action.setAxisLabel);\n case \"set_axis_label_direction\":\n return handlers.setAxisLabelDirection(state, action.setAxisLabelDirection);\n case \"set_axis_label_level\":\n return handlers.setAxisLabelLevel(state, action.setAxisLabelLevel);\n case \"set_axis_bounds\":\n return handlers.setAxisBounds(state, action.setAxisBounds);\n case \"set_axis_tick_spacing\":\n return handlers.setAxisTickSpacing(state, action.setAxisTickSpacing);\n case \"set_axis_type\":\n return handlers.setAxisType(state, action.setAxisType);\n case \"set_line_label\":\n return handlers.setLineLabel(state, action.setLineLabel);\n case \"set_line_color\":\n return handlers.setLineColor(state, action.setLineColor);\n case \"set_line_stroke_width\":\n return handlers.setLineStrokeWidth(state, action.setLineStrokeWidth);\n case \"set_line_downsample\":\n return handlers.setLineDownsample(state, action.setLineDownsample);\n case \"set_line_downsample_mode\":\n return handlers.setLineDownsampleMode(state, action.setLineDownsampleMode);\n case \"set_line\":\n return handlers.setLine(state, action.setLine);\n case \"set_rule\":\n return handlers.setRule(state, action.setRule);\n case \"set_rule_label\":\n return handlers.setRuleLabel(state, action.setRuleLabel);\n case \"set_rule_color\":\n return handlers.setRuleColor(state, action.setRuleColor);\n case \"set_rule_axis\":\n return handlers.setRuleAxis(state, action.setRuleAxis);\n case \"set_rule_line_width\":\n return handlers.setRuleLineWidth(state, action.setRuleLineWidth);\n case \"set_rule_line_dash\":\n return handlers.setRuleLineDash(state, action.setRuleLineDash);\n case \"set_rule_units\":\n return handlers.setRuleUnits(state, action.setRuleUnits);\n case \"set_rule_position\":\n return handlers.setRulePosition(state, action.setRulePosition);\n case \"remove_rule\":\n return handlers.removeRule(state, action.removeRule);\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type channel } from \"@/channel\";\nimport {\n type Channels,\n type Line,\n lineZ,\n type Ranges,\n X_AXIS_KEYS,\n type XAxisKey,\n Y_AXIS_KEYS,\n type YAxisKey,\n} from \"@/lineplot/types.gen\";\n\n// LineKeyParts is the structured identity of a plotted line: a y-channel on a y-axis\n// plotted against an x-channel/x-axis over a range. It is the decoded form of Line.key.\nexport interface LineKeyParts {\n yAxis: YAxisKey;\n xAxis: XAxisKey;\n range: string;\n xChannel: channel.Key;\n yChannel: channel.Key;\n}\n\nconst SEPARATOR = \"---\";\n\n// lineKey encodes the identity of a line into the stable string stored as\n// Line.key. This is the only place the key format is defined.\nexport const lineKey = (parts: LineKeyParts): string =>\n [parts.yAxis, parts.xAxis, parts.range, parts.xChannel, parts.yChannel].join(\n SEPARATOR,\n );\n\nexport const parseLineKey = (key: string): LineKeyParts => {\n const [yAxis, xAxis, range, xChannel, yChannel] = key.split(SEPARATOR);\n return {\n yAxis: yAxis as YAxisKey,\n xAxis: xAxis as XAxisKey,\n range,\n xChannel: Number(xChannel),\n yChannel: Number(yChannel),\n };\n};\n\n// reconcileLines rebuilds the complete set of lines implied by the channel and\n// range bindings: one line per (x-axis, range, y-axis, y-channel) combination.\n// Existing lines are preserved by key so user styling survives, missing ones\n// are created with default styling, and lines whose combination no longer\n// exists are returned in `dropped` (so callers can restore them on undo).\nexport const reconcileLines = (\n channels: Channels,\n ranges: Ranges,\n existing: Line[],\n): { lines: Line[]; dropped: Line[] } => {\n const byKey = new Map(existing.map((l) => [l.key, l]));\n const kept = new Set<string>();\n const lines: Line[] = [];\n for (const xAxis of X_AXIS_KEYS) {\n const xChannel = channels[xAxis];\n for (const range of ranges[xAxis])\n for (const yAxis of Y_AXIS_KEYS)\n for (const yChannel of channels[yAxis]) {\n const key = lineKey({ yAxis, xAxis, range, xChannel, yChannel });\n if (kept.has(key)) continue;\n kept.add(key);\n // A new line takes Oracle schema defaults (stroke width, downsample);\n // label and color stay unset so they resolve at render time.\n lines.push(byKey.get(key) ?? lineZ.parse({ key }));\n }\n }\n const dropped = existing.filter((l) => !kept.has(l.key));\n return { lines, dropped };\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { actions } from \"@/actions\";\nimport {\n type Action,\n addChannel,\n addRange,\n createReduceAll,\n type Handlers,\n removeChannel,\n removeRange,\n removeRule,\n rename,\n setAxisBounds,\n setAxisLabel,\n setAxisLabelDirection,\n setAxisLabelLevel,\n setAxisTickSpacing,\n setAxisType,\n setChannels,\n setLegendHidden,\n setLegendPosition,\n setLine,\n setLineColor,\n setLineDownsample,\n setLineDownsampleMode,\n setLineLabel,\n setLineStrokeWidth,\n setRanges,\n setRule,\n setRuleAxis,\n setRuleColor,\n setRuleLabel,\n setRuleLineDash,\n setRuleLineWidth,\n setRulePosition,\n setRuleUnits,\n setTitleLevel,\n setTitleVisible,\n setXChannel,\n} from \"@/lineplot/actions.gen\";\nimport { reconcileLines } from \"@/lineplot/line\";\n\n// Handlers report the narrowest resource each action touches as its target,\n// type-prefixed to keep the key spaces (numeric channels, \"y1\" axes, uuid\n// lines/rules) from colliding within a plot's undo state. Plot-level config\n// (name, title, legend) targets the plot key itself; everything else targets\n// the specific channel/range/axis/line/rule so concurrent edits to distinct\n// resources neither coalesce nor invalidate each other's undoables.\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.linePlot);\n return { inverse: [], targets: [payload.linePlot.key] };\n },\n\n rename: (state, payload) => {\n const oldName = state.name;\n state.name = payload.name;\n return { inverse: [rename({ name: oldName })], targets: [state.key] };\n },\n\n setTitleVisible: (state, payload) => {\n const oldVisible = state.title.visible;\n state.title.visible = payload.visible;\n return {\n inverse: [setTitleVisible({ visible: oldVisible })],\n targets: [state.key],\n };\n },\n\n setTitleLevel: (state, payload) => {\n const oldLevel = state.title.level;\n state.title.level = payload.level;\n return {\n inverse: [setTitleLevel({ level: oldLevel })],\n targets: [state.key],\n };\n },\n\n setLegendHidden: (state, payload) => {\n const oldHidden = state.legend.hidden;\n state.legend.hidden = payload.hidden;\n return {\n inverse: [setLegendHidden({ hidden: oldHidden })],\n targets: [state.key],\n };\n },\n\n setLegendPosition: (state, payload) => {\n const oldPosition = actions.snapshotDraft(state.legend.position);\n state.legend.position = payload.position;\n return {\n inverse: [setLegendPosition({ position: oldPosition })],\n targets: [state.key],\n };\n },\n\n // addChannel appends the y-channel and reconciles the line set, materializing\n // a line for every (x-axis, range) combination it now participates in.\n // removeChannel is its inverse and tears those lines back down.\n addChannel: (state, payload) => {\n const axis = payload.axisKey;\n const slice = state.channels[axis];\n if (slice.includes(payload.channel)) return actions.NO_OP_RESULT;\n slice.push(payload.channel);\n state.lines = reconcileLines(state.channels, state.ranges, state.lines).lines;\n return {\n inverse: [removeChannel({ axisKey: axis, channel: payload.channel })],\n targets: [`channel:${payload.channel}`],\n };\n },\n\n // removeChannel drops the y-channel and reconciles the line set; every line it\n // produced is dropped. Dropped lines are restored verbatim on undo so user\n // styling survives a remove/add cycle.\n removeChannel: (state, payload) => {\n const axis = payload.axisKey;\n const slice = state.channels[axis];\n const idx = slice.indexOf(payload.channel);\n if (idx === -1) return actions.NO_OP_RESULT;\n slice.splice(idx, 1);\n const { lines, dropped } = reconcileLines(\n state.channels,\n state.ranges,\n state.lines,\n );\n state.lines = lines;\n return {\n inverse: [\n addChannel({ axisKey: axis, channel: payload.channel }),\n ...dropped.map((l) => setLine({ line: actions.snapshotDraft(l) })),\n ],\n targets: [`channel:${payload.channel}`],\n };\n },\n\n // setChannels replaces a y-axis's whole channel set in one edit, reconciling\n // the line set once. It is the bulk form of addChannel/removeChannel for the\n // multi-select toolbar: channels new to the set add lines, channels dropped\n // from it tear theirs down. Dropped lines are restored verbatim on undo so\n // styling survives, and targets name only the channels that actually changed\n // so the undoable invalidation stays per-channel.\n setChannels: (state, payload) => {\n const axis = payload.axisKey;\n const current = state.channels[axis];\n const nextSet = new Set(payload.channels);\n const currentSet = new Set(current);\n const removed = current.filter((channel) => !nextSet.has(channel));\n const added = payload.channels.filter((channel) => !currentSet.has(channel));\n if (added.length === 0 && removed.length === 0) return actions.NO_OP_RESULT;\n const oldChannels = actions.snapshotDraft(current);\n state.channels[axis] = [...payload.channels];\n const { lines, dropped } = reconcileLines(\n state.channels,\n state.ranges,\n state.lines,\n );\n state.lines = lines;\n return {\n inverse: [\n setChannels({ axisKey: axis, channels: oldChannels }),\n ...dropped.map((l) => setLine({ line: actions.snapshotDraft(l) })),\n ],\n targets: [...removed, ...added].map((channel) => `channel:${channel}`),\n };\n },\n\n // setXChannel swaps the single channel on an x-axis. Reconciliation rekeys every line\n // on that axis: the old lines are dropped and fresh ones materialized. Undo restores\n // both the previous channel and the previous line styling.\n setXChannel: (state, payload) => {\n const axis = payload.axisKey;\n const oldChannel = state.channels[axis];\n if (oldChannel === payload.channel) return actions.NO_OP_RESULT;\n state.channels[axis] = payload.channel;\n const { lines, dropped } = reconcileLines(\n state.channels,\n state.ranges,\n state.lines,\n );\n state.lines = lines;\n return {\n inverse: [\n setXChannel({ axisKey: axis, channel: oldChannel }),\n ...dropped.map((l) => setLine({ line: actions.snapshotDraft(l) })),\n ],\n targets: [`axis:${axis}`],\n };\n },\n\n // addRange appends the range to an x-axis and reconciles the line set, materializing\n // a line for every y-channel plotted against it. removeRange is its inverse.\n addRange: (state, payload) => {\n const axis = payload.axisKey;\n const slice = state.ranges[axis];\n if (slice.includes(payload.range)) return actions.NO_OP_RESULT;\n slice.push(payload.range);\n state.lines = reconcileLines(state.channels, state.ranges, state.lines).lines;\n return {\n inverse: [removeRange({ axisKey: axis, range: payload.range })],\n targets: [`range:${payload.range}`],\n };\n },\n\n // removeRange drops the range and reconciles the line set, dropping every line\n // it produced and restoring their styling on undo.\n removeRange: (state, payload) => {\n const axis = payload.axisKey;\n const slice = state.ranges[axis];\n const idx = slice.indexOf(payload.range);\n if (idx === -1) return actions.NO_OP_RESULT;\n slice.splice(idx, 1);\n const { lines, dropped } = reconcileLines(\n state.channels,\n state.ranges,\n state.lines,\n );\n state.lines = lines;\n return {\n inverse: [\n addRange({ axisKey: axis, range: payload.range }),\n ...dropped.map((l) => setLine({ line: actions.snapshotDraft(l) })),\n ],\n targets: [`range:${payload.range}`],\n };\n },\n\n // setRanges replaces an x-axis's whole range set in one edit, reconciling the\n // line set once. It is the bulk form of addRange/removeRange for the\n // multi-select toolbar; dropped lines are restored verbatim on undo and\n // targets name only the ranges that actually changed.\n setRanges: (state, payload) => {\n const axis = payload.axisKey;\n const current = state.ranges[axis];\n const nextSet = new Set(payload.ranges);\n const currentSet = new Set(current);\n const removed = current.filter((range) => !nextSet.has(range));\n const added = payload.ranges.filter((range) => !currentSet.has(range));\n if (added.length === 0 && removed.length === 0) return actions.NO_OP_RESULT;\n const oldRanges = actions.snapshotDraft(current);\n state.ranges[axis] = [...payload.ranges];\n const { lines, dropped } = reconcileLines(\n state.channels,\n state.ranges,\n state.lines,\n );\n state.lines = lines;\n return {\n inverse: [\n setRanges({ axisKey: axis, ranges: oldRanges }),\n ...dropped.map((l) => setLine({ line: actions.snapshotDraft(l) })),\n ],\n targets: [...removed, ...added].map((range) => `range:${range}`),\n };\n },\n\n setAxisLabel: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [setAxisLabel({ key: payload.key, label: axis.label })];\n axis.label = payload.label;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setAxisLabelDirection: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [\n setAxisLabelDirection({ key: payload.key, labelDirection: axis.labelDirection }),\n ];\n axis.labelDirection = payload.labelDirection;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setAxisLabelLevel: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [\n setAxisLabelLevel({ key: payload.key, labelLevel: axis.labelLevel }),\n ];\n axis.labelLevel = payload.labelLevel;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setAxisBounds: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [\n setAxisBounds({\n key: payload.key,\n bounds: actions.snapshotDraft(axis.bounds),\n manualBounds: actions.snapshotDraft(axis.manualBounds),\n }),\n ];\n axis.bounds = payload.bounds;\n axis.manualBounds = payload.manualBounds;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setAxisTickSpacing: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [\n setAxisTickSpacing({ key: payload.key, tickSpacing: axis.tickSpacing }),\n ];\n axis.tickSpacing = payload.tickSpacing;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setAxisType: (state, payload) => {\n const axis = state.axes[payload.key];\n const inverse = [setAxisType({ key: payload.key, type: axis.type })];\n axis.type = payload.type;\n return { inverse, targets: [`axis:${payload.key}`] };\n },\n\n setLineLabel: (state, payload) => {\n const line = state.lines.find((l) => l.key === payload.key);\n if (line == null) return actions.NO_OP_RESULT;\n const inverse = [setLineLabel({ key: payload.key, label: line.label })];\n line.label = payload.label;\n return { inverse, targets: [`line:${payload.key}`] };\n },\n\n setLineColor: (state, payload) => {\n const line = state.lines.find((l) => l.key === payload.key);\n if (line == null) return actions.NO_OP_RESULT;\n const inverse = [\n setLineColor({\n key: payload.key,\n color: line.color === undefined ? undefined : actions.snapshotDraft(line.color),\n }),\n ];\n line.color = payload.color;\n return { inverse, targets: [`line:${payload.key}`] };\n },\n\n setLineStrokeWidth: (state, payload) => {\n const line = state.lines.find((l) => l.key === payload.key);\n if (line == null) return actions.NO_OP_RESULT;\n const inverse = [\n setLineStrokeWidth({ key: payload.key, strokeWidth: line.strokeWidth }),\n ];\n line.strokeWidth = payload.strokeWidth;\n return { inverse, targets: [`line:${payload.key}`] };\n },\n\n setLineDownsample: (state, payload) => {\n const line = state.lines.find((l) => l.key === payload.key);\n if (line == null) return actions.NO_OP_RESULT;\n const inverse = [\n setLineDownsample({ key: payload.key, downsample: line.downsample }),\n ];\n line.downsample = payload.downsample;\n return { inverse, targets: [`line:${payload.key}`] };\n },\n\n setLineDownsampleMode: (state, payload) => {\n const line = state.lines.find((l) => l.key === payload.key);\n if (line == null) return actions.NO_OP_RESULT;\n const inverse = [\n setLineDownsampleMode({ key: payload.key, downsampleMode: line.downsampleMode }),\n ];\n line.downsampleMode = payload.downsampleMode;\n return { inverse, targets: [`line:${payload.key}`] };\n },\n\n // setLine replaces a line's full configuration in place, or inserts it when its\n // key is new. The fine-grained setLine* actions cover per-field toolbar edits;\n // this full-object form restores a line dropped by reconciliation, so a fresh\n // insert is not independently undoable (it only re-materializes a dropped line).\n setLine: (state, payload) => {\n const idx = state.lines.findIndex((l) => l.key === payload.line.key);\n if (idx === -1) {\n state.lines.push(payload.line);\n return { inverse: [], targets: [] };\n }\n const oldLine = actions.snapshotDraft(state.lines[idx]);\n state.lines[idx] = payload.line;\n return {\n inverse: [setLine({ line: oldLine })],\n targets: [`line:${payload.line.key}`],\n };\n },\n\n setRule: (state, payload) => {\n const idx = state.rules.findIndex((r) => r.key === payload.rule.key);\n if (idx === -1) {\n state.rules.push(payload.rule);\n return {\n inverse: [removeRule({ key: payload.rule.key })],\n targets: [`rule:${payload.rule.key}`],\n };\n }\n const oldRule = actions.snapshotDraft(state.rules[idx]);\n state.rules[idx] = payload.rule;\n return {\n inverse: [setRule({ rule: oldRule })],\n targets: [`rule:${payload.rule.key}`],\n };\n },\n\n removeRule: (state, payload) => {\n const idx = state.rules.findIndex((r) => r.key === payload.key);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldRule = actions.snapshotDraft(state.rules[idx]);\n state.rules.splice(idx, 1);\n return { inverse: [setRule({ rule: oldRule })], targets: [`rule:${payload.key}`] };\n },\n\n setRuleLabel: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRuleLabel({ key: payload.key, label: rule.label })];\n rule.label = payload.label;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRuleColor: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [\n setRuleColor({\n key: payload.key,\n color: rule.color === undefined ? undefined : actions.snapshotDraft(rule.color),\n }),\n ];\n rule.color = payload.color;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRuleAxis: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRuleAxis({ key: payload.key, axis: rule.axis })];\n rule.axis = payload.axis;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRuleLineWidth: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRuleLineWidth({ key: payload.key, lineWidth: rule.lineWidth })];\n rule.lineWidth = payload.lineWidth;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRuleLineDash: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRuleLineDash({ key: payload.key, lineDash: rule.lineDash })];\n rule.lineDash = payload.lineDash;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRuleUnits: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRuleUnits({ key: payload.key, units: rule.units })];\n rule.units = payload.units;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n\n setRulePosition: (state, payload) => {\n const rule = state.rules.find((r) => r.key === payload.key);\n if (rule == null) return actions.NO_OP_RESULT;\n const inverse = [setRulePosition({ key: payload.key, position: rule.position })];\n rule.position = payload.position;\n return { inverse, targets: [`rule:${payload.key}`] };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.linePlot : undefined;\n\n// Drag streams (axis bounds, rule position, line style, legend) coalesce into one undo\n// entry within the coalesce window. Single-target actions key by their axis/line/rule\n// so gestures on different targets don't merge; dragging axis x1 then axis x2 is two\n// undo steps. Edits to distinct fields of the same target (e.g. an x1 label then its\n// bounds) deliberately share a key, matching the previous single-setAxis coalescing.\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n if (actions.length > 1) return \"transaction\";\n const a = actions[0];\n switch (a.type) {\n case \"set_axis_label\":\n return `axis:${a.setAxisLabel.key}`;\n case \"set_axis_label_direction\":\n return `axis:${a.setAxisLabelDirection.key}`;\n case \"set_axis_label_level\":\n return `axis:${a.setAxisLabelLevel.key}`;\n case \"set_axis_bounds\":\n return `axis:${a.setAxisBounds.key}`;\n case \"set_axis_tick_spacing\":\n return `axis:${a.setAxisTickSpacing.key}`;\n case \"set_axis_type\":\n return `axis:${a.setAxisType.key}`;\n case \"set_line_label\":\n return `line:${a.setLineLabel.key}`;\n case \"set_line_color\":\n return `line:${a.setLineColor.key}`;\n case \"set_line_stroke_width\":\n return `line:${a.setLineStrokeWidth.key}`;\n case \"set_line_downsample\":\n return `line:${a.setLineDownsample.key}`;\n case \"set_line_downsample_mode\":\n return `line:${a.setLineDownsampleMode.key}`;\n case \"set_line\":\n return `line:${a.setLine.line.key}`;\n case \"set_rule\":\n return `rule:${a.setRule.rule.key}`;\n case \"set_rule_label\":\n return `rule:${a.setRuleLabel.key}`;\n case \"set_rule_color\":\n return `rule:${a.setRuleColor.key}`;\n case \"set_rule_axis\":\n return `rule:${a.setRuleAxis.key}`;\n case \"set_rule_line_width\":\n return `rule:${a.setRuleLineWidth.key}`;\n case \"set_rule_line_dash\":\n return `rule:${a.setRuleLineDash.key}`;\n case \"set_rule_units\":\n return `rule:${a.setRuleUnits.key}`;\n case \"set_rule_position\":\n return `rule:${a.setRulePosition.key}`;\n default:\n return a.type;\n }\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, record, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * Project is a named, persistable container that stores the layout and organization of\n * the Console application. Projects allow users to save and restore custom arrangements\n * of visualizations, tabs, and window configurations.\n */\nexport const projectZ = z.object({\n /** key is the unique identifier for this project. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the project. */\n name: z.string().min(1, \"name is required\"),\n /**\n * layout is the mosaic tree structure that defines how visualizations are arranged.\n * Contains tab layout, split configurations, and window positions.\n */\n layout: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\nexport interface Project extends z.infer<typeof projectZ> {}\nexport interface New extends z.input<typeof projectZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"project\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type FileTransport,\n type UnaryClient,\n type UploadBody,\n} from \"@synnaxlabs/freighter\";\nimport {\n array,\n caseconv,\n type destructor,\n primitive,\n record,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { imex } from \"@/imex\";\nimport { type ontology } from \"@/ontology\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Project,\n projectZ,\n} from \"@/project/types.gen\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_project_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_project_delete\";\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array().optional(),\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nexport interface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\nconst createReqZ = z.object({ projects: projectZ.array() });\nconst renameReqZ = z.object({ key: keyZ, name: z.string() });\nconst setLayoutReqZ = z.object({\n key: keyZ,\n layout: caseconv.preserveCase(record.unknownZ()),\n});\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst exportReqZ = z.object({ key: keyZ, encoding: imex.encodingZ });\n\nconst importParamsZ = z.object({ fileName: z.string().min(1) });\n\nconst retrieveResZ = z.object({ projects: projectZ.array().default(() => []) });\nconst createResZ = z.object({ projects: projectZ.array() });\nconst importResZ = z.object({ project: projectZ });\nconst emptyResZ = z.object({});\n\n/** Options for a project import call. */\nexport interface ImportOptions {\n /**\n * The name of the uploaded archive or picked directory. Its extension-stripped form\n * names the project when the bundle carries no name.\n */\n fileName: string;\n}\n\nexport interface SetLayoutParams extends z.input<typeof setLayoutReqZ> {}\n\n/**\n * Client-side matching for a request: key sets. Server-computed shapes\n * (search, limit/offset) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((p: Project) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (p) => keySet == null || keySet.has(p.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n file: FileTransport;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Project> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Project>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n const store = cache.createTable<Key, Project>({\n name: \"projects\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, projectZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"project\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (project, req) => requestFilter(req)(project),\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(project: New, opts?: query.WriteOptions<Project[]>): Promise<Project>;\n async create(\n projects: New[],\n opts?: query.WriteOptions<Project[]>,\n ): Promise<Project[]>;\n async create(\n projects: New | New[],\n opts: query.WriteOptions<Project[]> = {},\n ): Promise<Project | Project[]> {\n const isMany = Array.isArray(projects);\n const optimistic = array\n .toArray(projects)\n .map((p) => zod.parse(projectZ, p, { label: \"project\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/project/create\",\n { projects: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.projects);\n return isMany ? res.projects : res.projects[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/project/rename\",\n { key, name },\n renameReqZ,\n emptyResZ,\n ),\n });\n rename();\n }\n\n async setLayout(\n key: Key,\n layout: record.Unknown,\n opts: query.WriteOptions = {},\n ): Promise<void> {\n await query.optimistic({\n rollbacks: [query.partialUpdate(this.store, key, { layout })],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/project/set-layout\",\n { key, layout },\n setLayoutReqZ,\n emptyResZ,\n ),\n });\n this.mergeThrough(key, { layout });\n }\n\n async delete(key: Key, opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key[], opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/project/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /**\n * Exports the project and its contents as a bundle: a zip archive holding one JSON\n * file per document and panel, group children as directories, and a manifest.json\n * naming the project. Two members of one directory that take the same file name keep\n * distinct names through a numeric suffix. The caller pipes the stream wherever it\n * likes without the client buffering the whole archive.\n * @param options - the export options, including the serialization member files are\n * written in.\n * @returns the bundle as a stream of zip bytes.\n */\n async export(key: Key, options: imex.Options): Promise<ReadableStream<Uint8Array>> {\n return await this.cfg.file.download(\n \"/project/export\",\n { key, encoding: options.encoding },\n exportReqZ,\n { encoding: \"ZIP\" },\n );\n }\n\n /**\n * Imports a project bundle: a zip archive holding one JSON envelope per document and\n * panel, group children as directories, and a manifest.json naming the project. The\n * Core creates a fresh project and imports every member in a single transaction, so a\n * failure leaves nothing behind. Legacy project directories (a root LAYOUT.json with\n * no manifest) import through the same call.\n *\n * @param data - the bundle as zip bytes.\n * @param options - the import options, including the source file's name.\n * @returns the created project.\n * @throws {ValidationError} if the manifest is missing, malformed, or of another\n * bundle kind, if two member names collide, or if a member cannot be imported.\n */\n async import(data: UploadBody, options: ImportOptions): Promise<Project> {\n const res = await this.cfg.file.upload(\n \"/project/import\",\n data,\n { encoding: \"ZIP\", params: options, paramsSchema: importParamsZ },\n importResZ,\n );\n this.store.set(res.project);\n return res.project;\n }\n\n /** Subscribes to every project delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n // Undefined fields are dropped: the server keeps prior values for them.\n private mergeThrough(key: Key, changes: Partial<Project>): void {\n const prev = this.store.get(key);\n if (prev != null)\n this.store.set(key, { ...prev, ...record.purgeUndefined(changes) });\n }\n\n private async execRetrieve(req: RetrieveRequest): Promise<Project[]> {\n const res = await this.cfg.unary.send(\n \"/project/retrieve\",\n req,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.projects;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/project/client\";\nexport * from \"@/project/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { createOf, kindOf, reduceAll } from \"@/lineplot/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/lineplot/actions.gen\";\nimport {\n type Key,\n keyZ,\n type LinePlot,\n linePlotZ,\n type New,\n ontologyID,\n} from \"@/lineplot/types.gen\";\nimport { type ontology } from \"@/ontology\";\nimport { project } from \"@/project\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_lineplot_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_lineplot_delete\";\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nexport const retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveReqZ]);\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveReqZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\nconst retrieveResZ = z.object({ linePlots: linePlotZ.array().default(() => []) });\n\nconst createReqZ = z.object({ project: project.keyZ, linePlots: linePlotZ.array() });\nconst createResZ = z.object({ linePlots: linePlotZ.array() });\n\nconst emptyResZ = z.object({});\n\n/**\n * Client-side matching for a request: exact for the requested key set, the\n * only field a request carries.\n */\nconst requestFilter = (req: RetrieveRequest): ((p: LinePlot) => boolean) => {\n const keySet = new Set(req.keys);\n return (p) => keySet.has(p.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n LinePlot\n> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, LinePlot>;\n private readonly dispatcher: actions.Controller<Key, LinePlot, Action>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n // Dispatch mutates documents server-side, so fetched copies never clobber\n // a doc holding locally replayed edits: the table hydrates if-absent.\n const store = cache.createTable<Key, LinePlot>({\n name: \"line plots\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, LinePlot, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n super(cache, {\n name: \"line plot\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (plot, req) => requestFilter(req)(plot),\n },\n });\n this.cfg = cfg;\n this.store = store;\n this.dispatcher = dispatcher;\n }\n\n async create(\n project: project.Key,\n linePlot: New,\n opts?: query.WriteOptions<LinePlot[]>,\n ): Promise<LinePlot>;\n async create(\n project: project.Key,\n linePlots: New[],\n opts?: query.WriteOptions<LinePlot[]>,\n ): Promise<LinePlot[]>;\n async create(\n project: project.Key,\n linePlots: New | New[],\n opts: query.WriteOptions<LinePlot[]> = {},\n ): Promise<LinePlot | LinePlot[]> {\n const isMany = Array.isArray(linePlots);\n const optimistic = array\n .toArray(linePlots)\n .map((p) => zod.parse(linePlotZ, p, { label: \"line plot\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/lineplot/create\",\n { project, linePlots: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.linePlots);\n return isMany ? res.linePlots : res.linePlots[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.sendDispatch(key, \"\", [renameAction({ name })]),\n });\n rename();\n }\n\n /**\n * Applies actions to the cached line plot and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the line plot isn't cached.\n * Rolls back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<LinePlot, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the line plot's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the line plot's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the line plot has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the line plot has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the line plot's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/lineplot/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/lineplot/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every line plot delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<LinePlot[]> {\n const res = await this.cfg.unary.send(\n \"/lineplot/retrieve\",\n params,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.linePlots;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/lineplot/actions\";\nexport * from \"@/lineplot/actions.gen\";\nexport * from \"@/lineplot/client\";\nexport * from \"@/lineplot/line\";\nexport * from \"@/lineplot/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { color, notation, telem, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { channel } from \"@/channel\";\nimport { ontology } from \"@/ontology\";\n\n/** TimestampConfig is per-channel timestamp display configuration. */\nexport const timestampConfigZ = z.object({\n /** format controls how channel timestamps are rendered. */\n format: telem.timestampFormatZ,\n /** tz is the time zone used when rendering timestamps. */\n tz: telem.timeZoneZ,\n});\nexport interface TimestampConfig extends z.infer<typeof timestampConfigZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/** ChannelEntry is a per-channel display configuration entry within a log. */\nexport const channelEntryZ = z.object({\n /** channel is the channel this entry references. */\n channel: channel.keyZ,\n /** color is the display color for the channel. */\n color: color.colorZ,\n /** notation is the numeric notation used to render samples. */\n notation: notation.notationZ.default(\"standard\"),\n /**\n * precision is the number of decimal digits to display. -1 means \"use the log-level\n * precision\"; 17 is the maximum significant digits for a float64.\n */\n precision: z.int32().min(-1).max(17).default(-1),\n /** alias is a human-readable alias displayed in place of the channel name. */\n alias: z.string().default(\"\"),\n /** timestamp is the per-channel timestamp display configuration. */\n timestamp: timestampConfigZ.prefault({ format: \"preciseDate\", tz: \"local\" }),\n});\nexport interface ChannelEntry extends z.infer<typeof channelEntryZ> {}\n\n/**\n * Log is a timestamped event and message logging component. Logs display chronological\n * records of events, system messages, and audit trails with filtering and formatting\n * capabilities.\n */\nexport const logZ = z.object({\n /** key is the unique identifier for this log. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the log. */\n name: z.string().min(1, \"name is required\"),\n /** channels are the channels displayed in this log, in order. */\n channels: channelEntryZ.array().default(() => []),\n /** timestampPrecision is the precision of displayed timestamps (0-3). */\n timestampPrecision: z.int32().min(0).max(3).default(0),\n /** channelNamesHidden is true when channel names are hidden. */\n channelNamesHidden: z.boolean().default(false),\n /** receiptTimestampHidden is true when the receipt timestamp column is hidden. */\n receiptTimestampHidden: z.boolean().default(false),\n});\nexport interface Log extends z.infer<typeof logZ> {}\nexport interface New extends z.input<typeof logZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"log\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { color, notation, telem, zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { channel } from \"@/channel\";\nimport { channelEntryZ, keyZ, type Log, logZ } from \"@/log/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n log: logZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the log. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/**\n * AddChannel appends a default channel entry for the given channel. No-op when the\n * channel is already present.\n */\nexport const addChannelPayloadZ = z.object({\n channel: channel.keyZ,\n});\n\nexport type AddChannelPayload = z.infer<typeof addChannelPayloadZ>;\n\n/**\n * RemoveChannel removes the channel entry for the given channel. No-op when the channel\n * is not present.\n */\nexport const removeChannelPayloadZ = z.object({\n channel: channel.keyZ,\n});\n\nexport type RemoveChannelPayload = z.infer<typeof removeChannelPayloadZ>;\n\n/**\n * SetChannelEntry inserts the channel entry if no entry with the same channel exists,\n * otherwise replaces the existing entry in place. The fine-grained setChannel* actions\n * cover per-field edits; this full-object form inserts new entries and restores an\n * entry dropped by reconciliation.\n */\nexport const setChannelEntryPayloadZ = z.object({\n entry: channelEntryZ,\n});\n\nexport type SetChannelEntryPayload = z.infer<typeof setChannelEntryPayloadZ>;\n\n/**\n * SetChannelColor sets the display color of the entry identified by channel. The zero\n * color resets it to a palette color assigned at render time. No-op when no entry\n * references the channel.\n */\nexport const setChannelColorPayloadZ = z.object({\n channel: channel.keyZ,\n color: color.colorZ,\n});\n\nexport type SetChannelColorPayload = z.infer<typeof setChannelColorPayloadZ>;\n\n/**\n * SetChannelNotation sets the numeric notation of the entry identified by channel.\n * No-op when no entry references the channel.\n */\nexport const setChannelNotationPayloadZ = z.object({\n channel: channel.keyZ,\n notation: notation.notationZ,\n});\n\nexport type SetChannelNotationPayload = z.infer<typeof setChannelNotationPayloadZ>;\n\n/**\n * SetChannelPrecision sets the number of decimal digits displayed for the entry\n * identified by channel. -1 means \"use the log-level precision\". No-op when no entry\n * references the channel.\n */\nexport const setChannelPrecisionPayloadZ = z.object({\n channel: channel.keyZ,\n precision: z.int32(),\n});\n\nexport type SetChannelPrecisionPayload = z.infer<typeof setChannelPrecisionPayloadZ>;\n\n/**\n * SetChannelAlias sets the human-readable alias of the entry identified by channel. An\n * empty alias falls back to the channel name. No-op when no entry references the\n * channel.\n */\nexport const setChannelAliasPayloadZ = z.object({\n channel: channel.keyZ,\n alias: z.string(),\n});\n\nexport type SetChannelAliasPayload = z.infer<typeof setChannelAliasPayloadZ>;\n\n/**\n * SetChannelTimestampFormat sets the timestamp render format of the entry identified by\n * channel. No-op when no entry references the channel.\n */\nexport const setChannelTimestampFormatPayloadZ = z.object({\n channel: channel.keyZ,\n format: telem.timestampFormatZ,\n});\n\nexport type SetChannelTimestampFormatPayload = z.infer<\n typeof setChannelTimestampFormatPayloadZ\n>;\n\n/**\n * SetChannelTimestampTz sets the timestamp time zone of the entry identified by\n * channel. No-op when no entry references the channel.\n */\nexport const setChannelTimestampTzPayloadZ = z.object({\n channel: channel.keyZ,\n tz: telem.timeZoneZ,\n});\n\nexport type SetChannelTimestampTzPayload = z.infer<\n typeof setChannelTimestampTzPayloadZ\n>;\n\n/**\n * SetChannels replaces the entire ordered list of channel entries. Used for bulk\n * channel selection and reordering.\n */\nexport const setChannelsPayloadZ = z.object({\n channels: channelEntryZ.array().default(() => []),\n});\n\nexport type SetChannelsPayload = z.infer<typeof setChannelsPayloadZ>;\n\n/**\n * SwapChannel repoints the entry referencing the \"from\" channel at the \"to\" channel in\n * place, preserving the entry's position and display configuration. No-op when no entry\n * references \"from\".\n */\nexport const swapChannelPayloadZ = z.object({\n from: channel.keyZ,\n to: channel.keyZ,\n});\n\nexport type SwapChannelPayload = z.infer<typeof swapChannelPayloadZ>;\n\n/** SetTimestampPrecision sets the precision of displayed timestamps (0-3). */\nexport const setTimestampPrecisionPayloadZ = z.object({\n timestampPrecision: z.int32(),\n});\n\nexport type SetTimestampPrecisionPayload = z.infer<\n typeof setTimestampPrecisionPayloadZ\n>;\n\n/** SetChannelNamesHidden sets whether channel names are hidden. */\nexport const setChannelNamesHiddenPayloadZ = z.object({\n channelNamesHidden: z.boolean(),\n});\n\nexport type SetChannelNamesHiddenPayload = z.infer<\n typeof setChannelNamesHiddenPayloadZ\n>;\n\n/** SetReceiptTimestampHidden sets whether the receipt timestamp column is hidden. */\nexport const setReceiptTimestampHiddenPayloadZ = z.object({\n receiptTimestampHidden: z.boolean(),\n});\n\nexport type SetReceiptTimestampHiddenPayload = z.infer<\n typeof setReceiptTimestampHiddenPayloadZ\n>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({ type: z.literal(\"add_channel\"), addChannel: addChannelPayloadZ }),\n z.object({ type: z.literal(\"remove_channel\"), removeChannel: removeChannelPayloadZ }),\n z.object({\n type: z.literal(\"set_channel_entry\"),\n setChannelEntry: setChannelEntryPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_color\"),\n setChannelColor: setChannelColorPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_notation\"),\n setChannelNotation: setChannelNotationPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_precision\"),\n setChannelPrecision: setChannelPrecisionPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_alias\"),\n setChannelAlias: setChannelAliasPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_timestamp_format\"),\n setChannelTimestampFormat: setChannelTimestampFormatPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_timestamp_tz\"),\n setChannelTimestampTz: setChannelTimestampTzPayloadZ,\n }),\n z.object({ type: z.literal(\"set_channels\"), setChannels: setChannelsPayloadZ }),\n z.object({ type: z.literal(\"swap_channel\"), swapChannel: swapChannelPayloadZ }),\n z.object({\n type: z.literal(\"set_timestamp_precision\"),\n setTimestampPrecision: setTimestampPrecisionPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_channel_names_hidden\"),\n setChannelNamesHidden: setChannelNamesHiddenPayloadZ,\n }),\n z.object({\n type: z.literal(\"set_receipt_timestamp_hidden\"),\n setReceiptTimestampHidden: setReceiptTimestampHiddenPayloadZ,\n }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"log create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"log rename action payload\",\n }),\n});\n\nexport const addChannel = (payload: z.input<typeof addChannelPayloadZ>): Action => ({\n type: \"add_channel\",\n addChannel: zod.parse(addChannelPayloadZ, payload, {\n label: \"log add_channel action payload\",\n }),\n});\n\nexport const removeChannel = (\n payload: z.input<typeof removeChannelPayloadZ>,\n): Action => ({\n type: \"remove_channel\",\n removeChannel: zod.parse(removeChannelPayloadZ, payload, {\n label: \"log remove_channel action payload\",\n }),\n});\n\nexport const setChannelEntry = (\n payload: z.input<typeof setChannelEntryPayloadZ>,\n): Action => ({\n type: \"set_channel_entry\",\n setChannelEntry: zod.parse(setChannelEntryPayloadZ, payload, {\n label: \"log set_channel_entry action payload\",\n }),\n});\n\nexport const setChannelColor = (\n payload: z.input<typeof setChannelColorPayloadZ>,\n): Action => ({\n type: \"set_channel_color\",\n setChannelColor: zod.parse(setChannelColorPayloadZ, payload, {\n label: \"log set_channel_color action payload\",\n }),\n});\n\nexport const setChannelNotation = (\n payload: z.input<typeof setChannelNotationPayloadZ>,\n): Action => ({\n type: \"set_channel_notation\",\n setChannelNotation: zod.parse(setChannelNotationPayloadZ, payload, {\n label: \"log set_channel_notation action payload\",\n }),\n});\n\nexport const setChannelPrecision = (\n payload: z.input<typeof setChannelPrecisionPayloadZ>,\n): Action => ({\n type: \"set_channel_precision\",\n setChannelPrecision: zod.parse(setChannelPrecisionPayloadZ, payload, {\n label: \"log set_channel_precision action payload\",\n }),\n});\n\nexport const setChannelAlias = (\n payload: z.input<typeof setChannelAliasPayloadZ>,\n): Action => ({\n type: \"set_channel_alias\",\n setChannelAlias: zod.parse(setChannelAliasPayloadZ, payload, {\n label: \"log set_channel_alias action payload\",\n }),\n});\n\nexport const setChannelTimestampFormat = (\n payload: z.input<typeof setChannelTimestampFormatPayloadZ>,\n): Action => ({\n type: \"set_channel_timestamp_format\",\n setChannelTimestampFormat: zod.parse(setChannelTimestampFormatPayloadZ, payload, {\n label: \"log set_channel_timestamp_format action payload\",\n }),\n});\n\nexport const setChannelTimestampTz = (\n payload: z.input<typeof setChannelTimestampTzPayloadZ>,\n): Action => ({\n type: \"set_channel_timestamp_tz\",\n setChannelTimestampTz: zod.parse(setChannelTimestampTzPayloadZ, payload, {\n label: \"log set_channel_timestamp_tz action payload\",\n }),\n});\n\nexport const setChannels = (payload: z.input<typeof setChannelsPayloadZ>): Action => ({\n type: \"set_channels\",\n setChannels: zod.parse(setChannelsPayloadZ, payload, {\n label: \"log set_channels action payload\",\n }),\n});\n\nexport const swapChannel = (payload: z.input<typeof swapChannelPayloadZ>): Action => ({\n type: \"swap_channel\",\n swapChannel: zod.parse(swapChannelPayloadZ, payload, {\n label: \"log swap_channel action payload\",\n }),\n});\n\nexport const setTimestampPrecision = (\n payload: z.input<typeof setTimestampPrecisionPayloadZ>,\n): Action => ({\n type: \"set_timestamp_precision\",\n setTimestampPrecision: zod.parse(setTimestampPrecisionPayloadZ, payload, {\n label: \"log set_timestamp_precision action payload\",\n }),\n});\n\nexport const setChannelNamesHidden = (\n payload: z.input<typeof setChannelNamesHiddenPayloadZ>,\n): Action => ({\n type: \"set_channel_names_hidden\",\n setChannelNamesHidden: zod.parse(setChannelNamesHiddenPayloadZ, payload, {\n label: \"log set_channel_names_hidden action payload\",\n }),\n});\n\nexport const setReceiptTimestampHidden = (\n payload: z.input<typeof setReceiptTimestampHiddenPayloadZ>,\n): Action => ({\n type: \"set_receipt_timestamp_hidden\",\n setReceiptTimestampHidden: zod.parse(setReceiptTimestampHiddenPayloadZ, payload, {\n label: \"log set_receipt_timestamp_hidden action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<Log, Action>;\n\nexport interface Handlers {\n create: (state: Draft<Log>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<Log>, payload: RenamePayload) => HandlerResult;\n addChannel: (state: Draft<Log>, payload: AddChannelPayload) => HandlerResult;\n removeChannel: (state: Draft<Log>, payload: RemoveChannelPayload) => HandlerResult;\n setChannelEntry: (\n state: Draft<Log>,\n payload: SetChannelEntryPayload,\n ) => HandlerResult;\n setChannelColor: (\n state: Draft<Log>,\n payload: SetChannelColorPayload,\n ) => HandlerResult;\n setChannelNotation: (\n state: Draft<Log>,\n payload: SetChannelNotationPayload,\n ) => HandlerResult;\n setChannelPrecision: (\n state: Draft<Log>,\n payload: SetChannelPrecisionPayload,\n ) => HandlerResult;\n setChannelAlias: (\n state: Draft<Log>,\n payload: SetChannelAliasPayload,\n ) => HandlerResult;\n setChannelTimestampFormat: (\n state: Draft<Log>,\n payload: SetChannelTimestampFormatPayload,\n ) => HandlerResult;\n setChannelTimestampTz: (\n state: Draft<Log>,\n payload: SetChannelTimestampTzPayload,\n ) => HandlerResult;\n setChannels: (state: Draft<Log>, payload: SetChannelsPayload) => HandlerResult;\n swapChannel: (state: Draft<Log>, payload: SwapChannelPayload) => HandlerResult;\n setTimestampPrecision: (\n state: Draft<Log>,\n payload: SetTimestampPrecisionPayload,\n ) => HandlerResult;\n setChannelNamesHidden: (\n state: Draft<Log>,\n payload: SetChannelNamesHiddenPayload,\n ) => HandlerResult;\n setReceiptTimestampHidden: (\n state: Draft<Log>,\n payload: SetReceiptTimestampHiddenPayload,\n ) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<Log, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"add_channel\":\n return handlers.addChannel(state, action.addChannel);\n case \"remove_channel\":\n return handlers.removeChannel(state, action.removeChannel);\n case \"set_channel_entry\":\n return handlers.setChannelEntry(state, action.setChannelEntry);\n case \"set_channel_color\":\n return handlers.setChannelColor(state, action.setChannelColor);\n case \"set_channel_notation\":\n return handlers.setChannelNotation(state, action.setChannelNotation);\n case \"set_channel_precision\":\n return handlers.setChannelPrecision(state, action.setChannelPrecision);\n case \"set_channel_alias\":\n return handlers.setChannelAlias(state, action.setChannelAlias);\n case \"set_channel_timestamp_format\":\n return handlers.setChannelTimestampFormat(\n state,\n action.setChannelTimestampFormat,\n );\n case \"set_channel_timestamp_tz\":\n return handlers.setChannelTimestampTz(state, action.setChannelTimestampTz);\n case \"set_channels\":\n return handlers.setChannels(state, action.setChannels);\n case \"swap_channel\":\n return handlers.swapChannel(state, action.swapChannel);\n case \"set_timestamp_precision\":\n return handlers.setTimestampPrecision(state, action.setTimestampPrecision);\n case \"set_channel_names_hidden\":\n return handlers.setChannelNamesHidden(state, action.setChannelNamesHidden);\n case \"set_receipt_timestamp_hidden\":\n return handlers.setReceiptTimestampHidden(\n state,\n action.setReceiptTimestampHidden,\n );\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { color } from \"@synnaxlabs/x\";\n\nimport { actions } from \"@/actions\";\nimport {\n type Action,\n addChannel,\n createReduceAll,\n type Handlers,\n removeChannel,\n rename,\n setChannelAlias,\n setChannelColor,\n setChannelEntry,\n setChannelNamesHidden,\n setChannelNotation,\n setChannelPrecision,\n setChannels,\n setChannelTimestampFormat,\n setChannelTimestampTz,\n setReceiptTimestampHidden,\n setTimestampPrecision,\n swapChannel,\n} from \"@/log/actions.gen\";\nimport { channelEntryZ } from \"@/log/types.gen\";\n\n// Handlers report the narrowest resource each action touches as its target. Log-level\n// config (name, timestamp precision, display flags) targets the log key itself; channel\n// mutations target the specific channel so concurrent edits to distinct channels\n// neither coalesce nor invalidate each other's undoables.\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.log);\n return { inverse: [], targets: [payload.log.key] };\n },\n\n rename: (state, payload) => {\n const oldName = state.name;\n state.name = payload.name;\n return { inverse: [rename({ name: oldName })], targets: [state.key] };\n },\n\n addChannel: (state, payload) => {\n if (state.channels.some((e) => e.channel === payload.channel))\n return actions.NO_OP_RESULT;\n state.channels.push(\n channelEntryZ.parse({ channel: payload.channel, color: color.ZERO }),\n );\n return {\n inverse: [removeChannel({ channel: payload.channel })],\n targets: [`channel:${payload.channel}`],\n };\n },\n\n removeChannel: (state, payload) => {\n const idx = state.channels.findIndex((e) => e.channel === payload.channel);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldEntry = actions.snapshotDraft(state.channels[idx]);\n state.channels.splice(idx, 1);\n return {\n inverse: [\n addChannel({ channel: payload.channel }),\n setChannelEntry({ entry: oldEntry }),\n ],\n targets: [`channel:${payload.channel}`],\n };\n },\n\n setChannelEntry: (state, payload) => {\n const idx = state.channels.findIndex((e) => e.channel === payload.entry.channel);\n if (idx === -1) {\n state.channels.push(payload.entry);\n return {\n inverse: [removeChannel({ channel: payload.entry.channel })],\n targets: [`channel:${payload.entry.channel}`],\n };\n }\n const oldEntry = actions.snapshotDraft(state.channels[idx]);\n state.channels[idx] = payload.entry;\n return {\n inverse: [setChannelEntry({ entry: oldEntry })],\n targets: [`channel:${payload.entry.channel}`],\n };\n },\n\n setChannelColor: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [\n setChannelColor({\n channel: payload.channel,\n color: actions.snapshotDraft(entry.color),\n }),\n ];\n entry.color = payload.color;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannelNotation: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [\n setChannelNotation({ channel: payload.channel, notation: entry.notation }),\n ];\n entry.notation = payload.notation;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannelPrecision: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [\n setChannelPrecision({ channel: payload.channel, precision: entry.precision }),\n ];\n entry.precision = payload.precision;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannelAlias: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [setChannelAlias({ channel: payload.channel, alias: entry.alias })];\n entry.alias = payload.alias;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannelTimestampFormat: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [\n setChannelTimestampFormat({\n channel: payload.channel,\n format: entry.timestamp.format,\n }),\n ];\n entry.timestamp.format = payload.format;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannelTimestampTz: (state, payload) => {\n const entry = state.channels.find((e) => e.channel === payload.channel);\n if (entry == null) return actions.NO_OP_RESULT;\n const inverse = [\n setChannelTimestampTz({ channel: payload.channel, tz: entry.timestamp.tz }),\n ];\n entry.timestamp.tz = payload.tz;\n return { inverse, targets: [`channel:${payload.channel}`] };\n },\n\n setChannels: (state, payload) => {\n const oldChannels = actions.snapshotDraft(state.channels);\n const targets = new Set<string>();\n oldChannels.forEach((e) => targets.add(`channel:${e.channel}`));\n payload.channels.forEach((e) => targets.add(`channel:${e.channel}`));\n state.channels = payload.channels;\n return { inverse: [setChannels({ channels: oldChannels })], targets: [...targets] };\n },\n\n swapChannel: (state, payload) => {\n const idx = state.channels.findIndex((e) => e.channel === payload.from);\n if (idx === -1) return actions.NO_OP_RESULT;\n state.channels[idx].channel = payload.to;\n return {\n inverse: [swapChannel({ from: payload.to, to: payload.from })],\n targets: [`channel:${payload.from}`, `channel:${payload.to}`],\n };\n },\n\n setTimestampPrecision: (state, payload) => {\n const oldPrecision = state.timestampPrecision;\n state.timestampPrecision = payload.timestampPrecision;\n return {\n inverse: [setTimestampPrecision({ timestampPrecision: oldPrecision })],\n targets: [state.key],\n };\n },\n\n setChannelNamesHidden: (state, payload) => {\n const oldValue = state.channelNamesHidden;\n state.channelNamesHidden = payload.channelNamesHidden;\n return {\n inverse: [setChannelNamesHidden({ channelNamesHidden: oldValue })],\n targets: [state.key],\n };\n },\n\n setReceiptTimestampHidden: (state, payload) => {\n const oldValue = state.receiptTimestampHidden;\n state.receiptTimestampHidden = payload.receiptTimestampHidden;\n return {\n inverse: [setReceiptTimestampHidden({ receiptTimestampHidden: oldValue })],\n targets: [state.key],\n };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.log : undefined;\n\n// kindOf keys single-channel edits by channel so rapid edits to one\n// channel's config coalesce into a single undoable, while edits to distinct\n// channels stay separate. Log-level edits (name, precision, flags) key by their\n// action type; multi-action batches collapse into one \"transaction\" undoable.\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n if (actions.length > 1) return \"transaction\";\n const a = actions[0];\n switch (a.type) {\n case \"add_channel\":\n return `channel:${a.addChannel.channel}`;\n case \"remove_channel\":\n return `channel:${a.removeChannel.channel}`;\n case \"set_channel_entry\":\n return `channel:${a.setChannelEntry.entry.channel}`;\n case \"set_channel_color\":\n return `channel:${a.setChannelColor.channel}`;\n case \"set_channel_notation\":\n return `channel:${a.setChannelNotation.channel}`;\n case \"set_channel_precision\":\n return `channel:${a.setChannelPrecision.channel}`;\n case \"set_channel_alias\":\n return `channel:${a.setChannelAlias.channel}`;\n case \"set_channel_timestamp_format\":\n return `channel:${a.setChannelTimestampFormat.channel}`;\n case \"set_channel_timestamp_tz\":\n return `channel:${a.setChannelTimestampTz.channel}`;\n default:\n return a.type;\n }\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { createOf, kindOf, reduceAll } from \"@/log/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/log/actions.gen\";\nimport { type Key, keyZ, type Log, logZ, type New, ontologyID } from \"@/log/types.gen\";\nimport { type ontology } from \"@/ontology\";\nimport { project } from \"@/project\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_log_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_log_delete\";\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nexport const retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveReqZ]);\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveReqZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\nconst retrieveResZ = z.object({ logs: logZ.array().default(() => []) });\n\nconst createReqZ = z.object({ project: project.keyZ, logs: logZ.array() });\nconst createResZ = z.object({ logs: logZ.array() });\n\nconst emptyResZ = z.object({});\n\n/**\n * Client-side matching for a request: exact for the requested key set, the\n * only field a request carries.\n */\nconst requestFilter = (req: RetrieveRequest): ((l: Log) => boolean) => {\n const keySet = new Set(req.keys);\n return (l) => keySet.has(l.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Log> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Log>;\n private readonly dispatcher: actions.Controller<Key, Log, Action>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n // Dispatch mutates documents server-side, so fetched copies never clobber\n // a doc holding locally replayed edits: the table hydrates if-absent.\n const store = cache.createTable<Key, Log>({\n name: \"logs\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, Log, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n super(cache, {\n name: \"log\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (log, req) => requestFilter(req)(log),\n },\n });\n this.cfg = cfg;\n this.store = store;\n this.dispatcher = dispatcher;\n }\n\n async create(\n project: project.Key,\n log: New,\n opts?: query.WriteOptions<Log[]>,\n ): Promise<Log>;\n async create(\n project: project.Key,\n logs: New[],\n opts?: query.WriteOptions<Log[]>,\n ): Promise<Log[]>;\n async create(\n project: project.Key,\n logs: New | New[],\n opts: query.WriteOptions<Log[]> = {},\n ): Promise<Log | Log[]> {\n const isMany = Array.isArray(logs);\n const optimistic = array\n .toArray(logs)\n .map((l) => zod.parse(logZ, l, { label: \"log\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/log/create\",\n { project, logs: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.logs);\n return isMany ? res.logs : res.logs[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.sendDispatch(key, \"\", [renameAction({ name })]),\n });\n rename();\n }\n\n /**\n * Applies actions to the cached log and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the log isn't cached. Rolls\n * back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<Log, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the log's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the log's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the log has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the log has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the log's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/log/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/log/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every log delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<Log[]> {\n const res = await this.cfg.unary.send(\n \"/log/retrieve\",\n params,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.logs;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/log/actions\";\nexport * from \"@/log/actions.gen\";\nexport * from \"@/log/client\";\nexport * from \"@/log/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, record, spatial, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\n/**\n * View is an inline, self-describing view: a Console-owned type plus an opaque\n * configuration payload, with no backing core document. Used for app-views and tools\n * (docs, explorers, task forms, and the selector pickers).\n */\nexport const viewZ = z.object({\n /**\n * type is the Console-owned view type identifier (e.g., 'docs', 'selector') used to\n * select a renderer.\n */\n type: z.string(),\n /**\n * args is an opaque, Console-owned configuration payload for the view. Core never\n * interprets it; it round-trips as-is.\n */\n args: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\nexport interface View extends z.infer<typeof viewZ> {}\n\nexport const tabKeyZ = z.uuid();\nexport type TabKey = z.infer<typeof tabKeyZ>;\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/** TabBase carries the identity shared by every tab variant. */\nexport const tabBaseZ = z.object({\n /**\n * key is the stable unique identifier of this tab within the panel. It is independent\n * of the tab's content, so a tab's content may be swapped without changing the tab's\n * identity or position.\n */\n key: tabKeyZ.default(uuid.create),\n});\nexport interface TabBase extends z.infer<typeof tabBaseZ> {}\n\n/** ResourceTab is a tab displaying a backing core document. */\nexport const resourceTabZ = tabBaseZ.extend({\n variant: z.literal(\"resource\"),\n /**\n * resource is the visualization resource displayed by this tab, set via\n * SetTabResource.\n */\n resource: ontology.idZ,\n});\nexport interface ResourceTab extends z.infer<typeof resourceTabZ> {}\n\n/**\n * ViewTab is a tab displaying an inline, self-describing view. Unlike a resource, a\n * view has no backing core document: it carries its own type and opaque args. Used for\n * app-views and tools (docs, explorers, task forms, and the selector pickers).\n */\nexport const viewTabZ = tabBaseZ.extend(viewZ.shape).extend({\n variant: z.literal(\"view\"),\n});\nexport interface ViewTab extends z.infer<typeof viewTabZ> {}\n\nexport const TAB_TYPES = [\"resource\", \"view\"] as const;\nexport const tabTypeZ = z.enum(TAB_TYPES);\nexport type TabType = z.infer<typeof tabTypeZ>;\n\n/**\n * Tab is a single tab in a leaf. Tab content is a discriminated union: a resource (a\n * backing core document, e.g. a line plot) or a view (an inline, self-describing\n * app-view, e.g. docs). A freshly created tab is a view whose type is a selector\n * picker; SetTabResource or SetTabView swaps content in place. Display attributes\n * (name, icon, closability) are resolved at render time from the content. A resource\n * may back at most one tab per panel; views may repeat.\n */\nexport const tabZ = z.discriminatedUnion(\"variant\", [resourceTabZ, viewTabZ]);\nexport type Tab = ResourceTab | ViewTab;\n\nexport const TAB_SCHEMAS: {\n [K in TabType]: z.ZodType<Extract<Tab, { variant: K }>>;\n} = {\n resource: resourceTabZ,\n view: viewTabZ,\n};\nexport type NewTab = z.input<typeof tabZ>;\n\n/** LeafNode is a leaf node in the panel tree displaying a tab strip. */\nexport const leafNodeZ = z.object({\n variant: z.literal(\"leaf\"),\n /** tabs is the ordered list of tabs in this leaf. */\n tabs: tabZ.array().default(() => []),\n});\nexport interface LeafNode extends z.infer<typeof leafNodeZ> {}\n\n/** SplitNode is an interior split node dividing its area between two children. */\nexport const splitNodeZ = z.object({\n variant: z.literal(\"split\"),\n /** direction is the axis along which this node is split. */\n direction: spatial.directionZ,\n /**\n * size is the fraction in [0, 1] of the parent area allocated to first. The remainder\n * is allocated to last.\n */\n size: spatial.decimalZ,\n /** first is the first child (left for x, top for y). */\n get first(): z.ZodType<Node> {\n return nodeZ;\n },\n /** last is the second child (right for x, bottom for y). */\n get last(): z.ZodType<Node> {\n return nodeZ;\n },\n});\nexport interface SplitNode extends z.infer<typeof splitNodeZ> {}\n\nexport const NODE_TYPES = [\"leaf\", \"split\"] as const;\nexport const nodeTypeZ = z.enum(NODE_TYPES);\nexport type NodeType = z.infer<typeof nodeTypeZ>;\n\n/**\n * Node is a node in the panel tree: either a leaf displaying a tab strip or an interior\n * split. Nodes are identified by path-derived numeric keys during traversal (1 = root,\n * 2k = first child, 2k+1 = last child).\n */\nexport const nodeZ = z.discriminatedUnion(\"variant\", [leafNodeZ, splitNodeZ]);\nexport type Node = LeafNode | SplitNode;\n\nexport const NODE_SCHEMAS: {\n [K in NodeType]: z.ZodType<Extract<Node, { variant: K }>>;\n} = {\n leaf: leafNodeZ,\n split: splitNodeZ,\n};\n\n/** Panel is a project-owned tree of visualization tabs. */\nexport const panelZ = z.object({\n /** key is the unique identifier for this panel. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the panel. */\n name: z.string().min(1, \"name is required\"),\n /** root is the root of the panel tree. */\n root: nodeZ.prefault({ variant: \"leaf\", tabs: [] }),\n /**\n * parent is the parent resource for the panel in the ontology, required on create.\n * Parenthood lives in the ontology graph, so the field is not persisted on the panel\n * record and is absent on retrieve.\n */\n parent: ontology.idZ.optional(),\n});\nexport interface Panel extends z.infer<typeof panelZ> {}\nexport interface New extends z.input<typeof panelZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"panel\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { spatial, zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { ontology } from \"@/ontology\";\nimport { keyZ, type Panel, panelZ, tabKeyZ, tabZ, viewZ } from \"@/panel/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n panel: panelZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the panel. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/**\n * InsertTabs inserts tabs into a leaf in order, starting at the given index and\n * appending when index is absent or past the leaf's end. The destination leaf is\n * resolved from target_tab (the leaf holding that tab) when set, otherwise from the\n * target_leaf path-derived key, otherwise the first leaf in traversal order. Both are\n * hints: a target that no longer resolves to a leaf falls back to the first leaf\n * instead of failing, so a placement invalidated between the gesture and the dispatch\n * still opens the tabs. The fallback drops location too, leaving a leaf the caller\n * never pointed at unsplit. When location is an edge, the resolved leaf is split once\n * at that location and every tab is inserted into the new empty leaf; a center location\n * places the tabs directly in the resolved leaf, equivalent to absent. The split is\n * deferred to the first tab that lands, so a batch whose every tab is skipped leaves no\n * empty pane behind. A tab whose key is already in the tree has its content refreshed\n * and keeps its position unless the payload carries an explicit placement, in which\n * case it is relocated with the rest. Inserting a resource tab whose resource already\n * backs a different tab is skipped, as is a view tab of a type already backing a tab\n * when singleton is set: each may back at most one tab per panel, and callers select\n * the existing tab instead. Skipping one tab does not stop the others.\n */\nexport const insertTabsPayloadZ = z.object({\n tabs: tabZ.array().default(() => []),\n targetLeaf: z.int32().optional(),\n targetTab: tabKeyZ.optional(),\n index: z.int32().optional(),\n location: spatial.locationZ.optional(),\n singleton: z.boolean().optional(),\n});\n\nexport type InsertTabsPayload = z.infer<typeof insertTabsPayloadZ>;\n\n/**\n * RemoveTab removes the tab with the given key. If the containing leaf becomes empty\n * and has a sibling, the reducer collapses the parent split.\n */\nexport const removeTabPayloadZ = z.object({\n key: tabKeyZ,\n});\n\nexport type RemoveTabPayload = z.infer<typeof removeTabPayloadZ>;\n\n/**\n * MoveTab moves a tab to a position within the panel. When location is an edge, the\n * target leaf is first split at that location and the tab moves into the new empty\n * leaf; moving a leaf's only tab to an edge of its own leaf is a no-op. A center\n * location places the tab directly in the target leaf, equivalent to absent.\n * Cross-panel moves are RemoveTab on the source plus InsertTabs on the destination (two\n * dispatches; not atomic).\n */\nexport const moveTabPayloadZ = z.object({\n key: tabKeyZ,\n targetLeaf: z.int32(),\n index: z.int32().optional(),\n location: spatial.locationZ.optional(),\n});\n\nexport type MoveTabPayload = z.infer<typeof moveTabPayloadZ>;\n\n/**\n * SplitTab splits the tab with the given key off its leaf into a new sibling pane,\n * moving the tab into it. direction x places the new pane to the right, y to the\n * bottom. The tab must share its leaf with at least one other tab; splitting the only\n * tab in a leaf is a no-op.\n */\nexport const splitTabPayloadZ = z.object({\n key: tabKeyZ,\n direction: spatial.directionZ,\n});\n\nexport type SplitTabPayload = z.infer<typeof splitTabPayloadZ>;\n\n/** ResizeSplit adjusts the size ratio of a split node. size in [0, 1]. */\nexport const resizeSplitPayloadZ = z.object({\n split: z.int32(),\n size: spatial.decimalZ,\n});\n\nexport type ResizeSplitPayload = z.infer<typeof resizeSplitPayloadZ>;\n\n/**\n * SetTabResource sets the visualization resource displayed by the tab with the given\n * key, swapping it in place without changing the tab's identity or position. Clears any\n * view set on the tab. A no-op when the resource already backs another tab in the\n * panel. Used to fill a freshly inserted selector tab once the user picks a\n * visualization.\n */\nexport const setTabResourcePayloadZ = z.object({\n key: tabKeyZ,\n resource: ontology.idZ,\n});\n\nexport type SetTabResourcePayload = z.infer<typeof setTabResourcePayloadZ>;\n\n/**\n * SetTabView sets the inline view displayed by the tab with the given key, swapping it\n * in place without changing the tab's identity or position. Clears any resource set on\n * the tab.\n */\nexport const setTabViewPayloadZ = z.object({\n key: tabKeyZ,\n view: viewZ,\n});\n\nexport type SetTabViewPayload = z.infer<typeof setTabViewPayloadZ>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({ type: z.literal(\"insert_tabs\"), insertTabs: insertTabsPayloadZ }),\n z.object({ type: z.literal(\"remove_tab\"), removeTab: removeTabPayloadZ }),\n z.object({ type: z.literal(\"move_tab\"), moveTab: moveTabPayloadZ }),\n z.object({ type: z.literal(\"split_tab\"), splitTab: splitTabPayloadZ }),\n z.object({ type: z.literal(\"resize_split\"), resizeSplit: resizeSplitPayloadZ }),\n z.object({\n type: z.literal(\"set_tab_resource\"),\n setTabResource: setTabResourcePayloadZ,\n }),\n z.object({ type: z.literal(\"set_tab_view\"), setTabView: setTabViewPayloadZ }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"panel create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"panel rename action payload\",\n }),\n});\n\nexport const insertTabs = (payload: z.input<typeof insertTabsPayloadZ>): Action => ({\n type: \"insert_tabs\",\n insertTabs: zod.parse(insertTabsPayloadZ, payload, {\n label: \"panel insert_tabs action payload\",\n }),\n});\n\nexport const removeTab = (payload: z.input<typeof removeTabPayloadZ>): Action => ({\n type: \"remove_tab\",\n removeTab: zod.parse(removeTabPayloadZ, payload, {\n label: \"panel remove_tab action payload\",\n }),\n});\n\nexport const moveTab = (payload: z.input<typeof moveTabPayloadZ>): Action => ({\n type: \"move_tab\",\n moveTab: zod.parse(moveTabPayloadZ, payload, {\n label: \"panel move_tab action payload\",\n }),\n});\n\nexport const splitTab = (payload: z.input<typeof splitTabPayloadZ>): Action => ({\n type: \"split_tab\",\n splitTab: zod.parse(splitTabPayloadZ, payload, {\n label: \"panel split_tab action payload\",\n }),\n});\n\nexport const resizeSplit = (payload: z.input<typeof resizeSplitPayloadZ>): Action => ({\n type: \"resize_split\",\n resizeSplit: zod.parse(resizeSplitPayloadZ, payload, {\n label: \"panel resize_split action payload\",\n }),\n});\n\nexport const setTabResource = (\n payload: z.input<typeof setTabResourcePayloadZ>,\n): Action => ({\n type: \"set_tab_resource\",\n setTabResource: zod.parse(setTabResourcePayloadZ, payload, {\n label: \"panel set_tab_resource action payload\",\n }),\n});\n\nexport const setTabView = (payload: z.input<typeof setTabViewPayloadZ>): Action => ({\n type: \"set_tab_view\",\n setTabView: zod.parse(setTabViewPayloadZ, payload, {\n label: \"panel set_tab_view action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<Panel, Action>;\n\nexport interface Handlers {\n create: (state: Draft<Panel>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<Panel>, payload: RenamePayload) => HandlerResult;\n insertTabs: (state: Draft<Panel>, payload: InsertTabsPayload) => HandlerResult;\n removeTab: (state: Draft<Panel>, payload: RemoveTabPayload) => HandlerResult;\n moveTab: (state: Draft<Panel>, payload: MoveTabPayload) => HandlerResult;\n splitTab: (state: Draft<Panel>, payload: SplitTabPayload) => HandlerResult;\n resizeSplit: (state: Draft<Panel>, payload: ResizeSplitPayload) => HandlerResult;\n setTabResource: (\n state: Draft<Panel>,\n payload: SetTabResourcePayload,\n ) => HandlerResult;\n setTabView: (state: Draft<Panel>, payload: SetTabViewPayload) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<Panel, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"insert_tabs\":\n return handlers.insertTabs(state, action.insertTabs);\n case \"remove_tab\":\n return handlers.removeTab(state, action.removeTab);\n case \"move_tab\":\n return handlers.moveTab(state, action.moveTab);\n case \"split_tab\":\n return handlers.splitTab(state, action.splitTab);\n case \"resize_split\":\n return handlers.resizeSplit(state, action.resizeSplit);\n case \"set_tab_resource\":\n return handlers.setTabResource(state, action.setTabResource);\n case \"set_tab_view\":\n return handlers.setTabView(state, action.setTabView);\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type location, type spatial } from \"@synnaxlabs/x\";\n\nimport { type ontology } from \"@/ontology\";\nimport { type LeafNode, type Node, type Tab, type TabKey } from \"@/panel/types.gen\";\n\n// Nodes in the panel tree are identified by path-derived numeric keys: the root\n// is ROOT_NODE_KEY, and a split's children are childNodeKey(key, \"first\" | \"last\").\n// The scheme is shared with the Go and TypeScript reducers; every consumer that\n// addresses nodes (dispatching InsertTab/MoveTab, adapting the tree for\n// rendering) must use these helpers rather than re-deriving the math.\nexport const ROOT_NODE_KEY = 1;\n\n/** childNodeKey returns the path key of a split's child on the given side. */\nexport const childNodeKey = (pathKey: number, side: spatial.Order): number =>\n side === \"first\" ? pathKey * 2 : pathKey * 2 + 1;\n\n/**\n * splitSide returns the child slot the new empty leaf occupies when a leaf is\n * split at the given location: \"first\" for left/top, \"last\" otherwise. The\n * convention is shared by location-bearing InsertTab/MoveTab and SplitTab.\n */\nexport const splitSide = (loc: location.Outer): spatial.Order =>\n loc === \"left\" || loc === \"top\" ? \"first\" : \"last\";\n\nconst pathDirections = (pathKey: number): boolean[] => {\n if (pathKey <= ROOT_NODE_KEY) return [];\n const bits: boolean[] = [];\n while (pathKey > ROOT_NODE_KEY) {\n bits.unshift((pathKey & 1) === 1);\n pathKey >>= 1;\n }\n return bits;\n};\n\n/**\n * findNode returns the node at the given path key, or null when the path does\n * not exist in the tree.\n */\nexport const findNode = (root: Node | undefined, pathKey: number): Node | undefined => {\n if (root == null) return undefined;\n let n: Node = root;\n for (const isLast of pathDirections(pathKey)) {\n if (n.variant !== \"split\") return undefined;\n n = isLast ? n.last : n.first;\n }\n return n;\n};\n\n/** findTab returns the tab with the given key, or null when absent. */\nexport const findTab = (node: Node | undefined, key?: string): Tab | undefined => {\n if (node == null || key == null) return undefined;\n if (node.variant === \"leaf\") return node.tabs.find((t) => t.key === key);\n return findTab(node.first, key) ?? findTab(node.last, key);\n};\n\n/**\n * findTabByResource returns the tab whose resource variant displays the given\n * ontology ID, or null when no tab backs that resource. A resource may back at\n * most one tab per panel, so openers use this to select the existing tab\n * instead of inserting a duplicate.\n */\nexport const findTabByResource = (\n node: Node | undefined,\n resource: ontology.ID,\n): Tab | undefined => {\n if (node == null) return undefined;\n if (node.variant === \"leaf\")\n return node.tabs.find(\n (t) =>\n t.variant === \"resource\" &&\n t.resource.type === resource.type &&\n t.resource.key === resource.key,\n );\n return (\n findTabByResource(node.first, resource) ?? findTabByResource(node.last, resource)\n );\n};\n\n/**\n * findTabByType returns the tab whose view variant carries the given type, or\n * null when no view of that type is present. Openers of singleton views use this\n * to select the existing tab instead of inserting a duplicate.\n */\nexport const findTabByType = (\n node: Node | undefined,\n type: string,\n): Tab | undefined => {\n if (node == null) return undefined;\n if (node.variant === \"leaf\")\n return node.tabs.find((t) => t.variant === \"view\" && t.type === type);\n return findTabByType(node.first, type) ?? findTabByType(node.last, type);\n};\n\n/** leafTabGroups returns each leaf's ordered tab keys, leaves in traversal order. */\nexport const leafTabGroups = (node: Node | undefined): TabKey[][] => {\n if (node == null) return [];\n if (node.variant === \"leaf\") return [node.tabs.map((t) => t.key)];\n return [...leafTabGroups(node.first), ...leafTabGroups(node.last)];\n};\n\n/** firstTab returns the first tab in traversal order, or null for an empty tree. */\nexport const firstTab = (node: Node | undefined): Tab | undefined => {\n if (node == null) return undefined;\n if (node.variant === \"leaf\") return node.tabs[0];\n return firstTab(node.first) ?? firstTab(node.last);\n};\n\nconst findLeafPath = (\n node: Node | undefined,\n path: number,\n match: (tabs: Tab[]) => boolean,\n): number | undefined => {\n if (node == null) return undefined;\n if (node.variant === \"leaf\") return match(node.tabs) ? path : undefined;\n return (\n findLeafPath(node.first, childNodeKey(path, \"first\"), match) ??\n findLeafPath(node.last, childNodeKey(path, \"last\"), match)\n );\n};\n\n/** tabLeafPath returns the path key of the leaf holding the given tab, or null. */\nexport const tabLeafPath = (\n root: Node | undefined,\n tabKey: string,\n): number | undefined =>\n findLeafPath(root, ROOT_NODE_KEY, (tabs) => tabs.some((t) => t.key === tabKey));\n\n/** findTabLeaf returns the leaf node holding the given tab, or null when absent. */\nexport const findTabLeaf = (\n root: Node | undefined,\n tabKey: string,\n): LeafNode | undefined => {\n const leafPath = tabLeafPath(root, tabKey);\n if (leafPath == null) return undefined;\n const leaf = findNode(root, leafPath);\n return leaf?.variant === \"leaf\" ? leaf : undefined;\n};\n\n/**\n * canSplitTab reports whether the tab can be split off into its own pane: true\n * when the tab shares its leaf with at least one other tab. Splitting the only\n * tab in a leaf is a no-op (the SplitTab action rejects it), so menu\n * affordances for the split should gate on this.\n */\nexport const canSplitTab = (root: Node | undefined, tabKey: string): boolean => {\n const leafPath = tabLeafPath(root, tabKey);\n if (leafPath == null) return false;\n const leaf = findNode(root, leafPath);\n return leaf?.variant === \"leaf\" && leaf.tabs.length >= 2;\n};\n\n/** firstLeafPath returns the path key of the first leaf in traversal order. */\nexport const firstLeafPath = (root: Node | undefined): number | undefined =>\n findLeafPath(root, ROOT_NODE_KEY, () => true);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type spatial } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\n\nimport {\n type Action,\n createReduceAll,\n type HandlerResult,\n type Handlers,\n type InsertTabsPayload,\n} from \"@/panel/actions.gen\";\nimport {\n findNode,\n findTab,\n findTabByResource,\n findTabByType,\n firstLeafPath,\n ROOT_NODE_KEY,\n tabLeafPath,\n} from \"@/panel/tree\";\nimport { type LeafNode, type Node, type Panel, type Tab } from \"@/panel/types.gen\";\n\nconst NO_OP: HandlerResult = { inverse: [], targets: [] };\n\nconst walkLeaf = (root: Draft<Node>, pathKey: number): Draft<LeafNode> | null => {\n const n = findNode(root, pathKey);\n if (n == null || n.variant !== \"leaf\") return null;\n return n;\n};\n\n// replaceNodeAt swaps the node at the given path key for next, assigning through\n// the parent split (or the panel root for ROOT_PATH). Returns false when the\n// path does not resolve to a node.\nconst replaceNodeAt = (state: Draft<Panel>, pathKey: number, next: Node): boolean => {\n if (pathKey === ROOT_NODE_KEY) {\n state.root = next;\n return true;\n }\n const parent = findNode(state.root, pathKey >> 1);\n if (parent == null || parent.variant !== \"split\") return false;\n if ((pathKey & 1) === 1) parent.last = next;\n else parent.first = next;\n return true;\n};\n\n// removeTab mirrors removeTab in core/pkg/service/panel/tree.go, removing a tab\n// and leaving any emptied leaf in place. Collapsing empty leaves is the caller's\n// responsibility (collapseEmptyLeaves), deferred so that a split-then-move\n// sequence (MoveTab with an edge location, or SplitTab) can target the freshly\n// created empty sibling before the tree is tidied.\nconst removeTab = (n: Draft<Node>, key: string): Tab | null => {\n if (n.variant === \"leaf\") {\n const idx = n.tabs.findIndex((t) => t.key === key);\n if (idx < 0) return null;\n const [removed] = n.tabs.splice(idx, 1);\n return removed ?? null;\n }\n return removeTab(n.first, key) ?? removeTab(n.last, key);\n};\n\nconst isEmptyLeaf = (n: Draft<Node>): boolean =>\n n.variant === \"leaf\" && n.tabs.length === 0;\n\n// collapseEmptyLeaves mirrors collapseEmptyLeaves in core/pkg/service/panel/tree.go,\n// rewriting the tree bottom-up: every split with exactly one empty-leaf side is\n// replaced by its surviving sibling subtree.\nconst collapseEmptyLeaves = (state: Draft<Panel>): void => {\n state.root = collapseNode(state.root);\n};\n\nconst collapseNode = (n: Draft<Node>): Draft<Node> => {\n if (n.variant !== \"split\") return n;\n n.first = collapseNode(n.first);\n n.last = collapseNode(n.last);\n const firstEmpty = isEmptyLeaf(n.first);\n const lastEmpty = isEmptyLeaf(n.last);\n if (firstEmpty && !lastEmpty) return n.last;\n if (lastEmpty && !firstEmpty) return n.first;\n return n;\n};\n\n// directionAndSideForLocation maps a spatial.Location onto the (direction, side)\n// pair that places a new empty leaf on that side of the original. Returns null\n// for locations that do not divide the area in two (e.g., \"center\").\nconst directionAndSideForLocation = (\n loc: spatial.Location,\n): { direction: spatial.Direction; side: spatial.Order } | null => {\n switch (loc) {\n case \"left\":\n return { direction: \"x\", side: \"first\" };\n case \"right\":\n return { direction: \"x\", side: \"last\" };\n case \"top\":\n return { direction: \"y\", side: \"first\" };\n case \"bottom\":\n return { direction: \"y\", side: \"last\" };\n default:\n return null;\n }\n};\n\n// splitLeafAt mirrors splitLeafAt + splitLeafForPlacement in\n// core/pkg/service/panel/tree.go, replacing the leaf at the given path with a\n// split holding the original leaf and a new empty sibling on the given side.\n// Returns the path key of the new empty leaf, or null when the path does not\n// resolve to a leaf or the location cannot produce a split.\nconst splitLeafAt = (\n state: Draft<Panel>,\n leafPath: number,\n loc: spatial.Location,\n size: number,\n): number | null => {\n const node = findNode(state.root, leafPath);\n if (node == null || node.variant !== \"leaf\") return null;\n const ds = directionAndSideForLocation(loc);\n if (ds == null) return null;\n const empty: Node = { variant: \"leaf\", tabs: [] };\n const split: Node = {\n variant: \"split\",\n direction: ds.direction,\n size,\n first: ds.side === \"first\" ? empty : node,\n last: ds.side === \"first\" ? node : empty,\n };\n if (!replaceNodeAt(state, leafPath, split)) return null;\n return ds.side === \"first\" ? leafPath * 2 : leafPath * 2 + 1;\n};\n\n// replaceTab swaps the tab with the given key for next in place, keeping its\n// position within its leaf. Returns false when no tab matches the key.\nconst replaceTab = (n: Draft<Node>, key: string, next: Tab): boolean => {\n if (n.variant === \"leaf\") {\n const idx = n.tabs.findIndex((t) => t.key === key);\n if (idx < 0) return false;\n n.tabs[idx] = next;\n return true;\n }\n return replaceTab(n.first, key, next) || replaceTab(n.last, key, next);\n};\n\n// resolveTargetLeaf resolves the destination leaf from the payload's addressing\n// hints, in priority order: the leaf holding targetTab, the targetLeaf path key,\n// then the first leaf in traversal order. `stale` reports that a hint was given and\n// no longer resolves, which drops the location along with it: the tabs still land,\n// but a leaf the caller never pointed at is not split.\nconst resolveTargetLeaf = (\n root: Draft<Node>,\n payload: InsertTabsPayload,\n): { leaf: number | undefined; stale: boolean } => {\n const { targetTab, targetLeaf } = payload;\n if (targetTab != null) {\n const path = tabLeafPath(root, targetTab);\n if (path != null) return { leaf: path, stale: false };\n }\n if (targetLeaf != null && findNode(root, targetLeaf)?.variant === \"leaf\")\n return { leaf: targetLeaf, stale: false };\n return {\n leaf: firstLeafPath(root),\n stale: targetTab != null || targetLeaf != null,\n };\n};\n\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.panel);\n return { inverse: [], targets: [payload.panel.key] };\n },\n\n rename: (state, payload) => {\n state.name = payload.name;\n return { inverse: [], targets: [state.key] };\n },\n\n // insertTabs upserts each tab in order into one destination leaf. A tab whose key is\n // already in the tree always has its content refreshed; it keeps its current position\n // unless the caller gives an explicit placement (targetTab, targetLeaf, location, or\n // index), in which case it is relocated with the rest. A tab that would put a second\n // tab behind the same resource, or a second singleton view behind the same type, is\n // skipped; the rest of the batch still lands, and callers select the existing tab\n // instead. Mirrors InsertTabsPayload.Handle in core/pkg/service/panel/actions.go.\n insertTabs: (state, payload) => {\n const placementGiven =\n payload.targetTab != null ||\n payload.targetLeaf != null ||\n payload.location != null ||\n payload.index != null;\n const resolved = resolveTargetLeaf(state.root, payload);\n let targetLeaf = resolved.leaf;\n if (targetLeaf == null) return NO_OP;\n // The edge split is deferred to the first tab that actually lands, so a batch\n // whose every tab is a duplicate leaves no empty pane behind.\n let pendingSplit =\n !resolved.stale && payload.location != null && payload.location !== \"center\"\n ? payload.location\n : undefined;\n let index = payload.index;\n const targets: string[] = [];\n for (const tab of payload.tabs) {\n if (tab.variant === \"resource\") {\n const existing = findTabByResource(state.root, tab.resource);\n if (existing != null && existing.key !== tab.key) continue;\n }\n if (payload.singleton && tab.variant === \"view\") {\n const existing = findTabByType(state.root, tab.type);\n if (existing != null && existing.key !== tab.key) continue;\n }\n const exists = findTab(state.root, tab.key) != null;\n if (exists && !placementGiven) {\n replaceTab(state.root, tab.key, tab);\n targets.push(tab.key);\n continue;\n }\n if (pendingSplit != null) {\n targetLeaf = splitLeafAt(state, targetLeaf, pendingSplit, 0.5) ?? targetLeaf;\n pendingSplit = undefined;\n }\n const leaf = walkLeaf(state.root, targetLeaf);\n if (leaf == null) break;\n if (exists) removeTab(state.root, tab.key);\n // An index past the leaf's end is a drop position invalidated between the\n // gesture and the dispatch. It clamps to the end, as moveTab does.\n const at =\n index != null && index >= 0 && index <= leaf.tabs.length\n ? index\n : leaf.tabs.length;\n leaf.tabs.splice(at, 0, tab);\n if (index != null) index = at + 1;\n targets.push(tab.key);\n }\n if (targets.length === 0) return NO_OP;\n collapseEmptyLeaves(state);\n return { inverse: [], targets };\n },\n\n removeTab: (state, payload) => {\n const removed = removeTab(state.root, payload.key);\n if (removed == null) return NO_OP;\n collapseEmptyLeaves(state);\n return { inverse: [], targets: [payload.key] };\n },\n\n // The target leaf is resolved before the remove, and empty-leaf collapse is\n // deferred until after the insert, so the destination may be a leaf the\n // source's removal would otherwise collapse away (e.g. the empty sibling\n // created by the preceding edge split).\n moveTab: (state, payload) => {\n const srcLeaf = tabLeafPath(state.root, payload.key);\n const srcNode = srcLeaf != null ? findNode(state.root, srcLeaf) : undefined;\n const srcIdx =\n srcNode?.variant === \"leaf\"\n ? srcNode.tabs.findIndex((t) => t.key === payload.key)\n : -1;\n let targetLeaf = payload.targetLeaf;\n if (payload.location != null && payload.location !== \"center\") {\n const current = walkLeaf(state.root, targetLeaf);\n if (current == null) return NO_OP;\n // Moving a leaf's only tab to an edge of its own leaf is degenerate: the\n // result would be the tab beside an empty pane.\n if (current.tabs.length === 1 && current.tabs[0].key === payload.key)\n return NO_OP;\n const placed = splitLeafAt(state, targetLeaf, payload.location, 0.5);\n if (placed == null) return NO_OP;\n targetLeaf = placed;\n }\n const target = walkLeaf(state.root, targetLeaf);\n if (target == null) return NO_OP;\n const removed = removeTab(state.root, payload.key);\n if (removed == null) return NO_OP;\n let idx = payload.index ?? target.tabs.length;\n // The index counts the moved tab as still present, so a same-leaf move\n // decrements it past the tab's own slot to stay valid after the remove.\n if (payload.index != null && srcLeaf === targetLeaf && srcIdx < idx) idx--;\n if (idx < 0 || idx > target.tabs.length) target.tabs.push(removed);\n else target.tabs.splice(idx, 0, removed);\n collapseEmptyLeaves(state);\n return { inverse: [], targets: [payload.key] };\n },\n\n // splitTab resolves the tab's own leaf, splits it on the direction-mapped edge (x ->\n // right, y -> bottom), and moves the tab into the new sibling pane. A leaf holding a\n // single tab is a no-op (the result would be the tab beside an empty pane).\n splitTab: (state, payload) => {\n const leafPath = tabLeafPath(state.root, payload.key);\n if (leafPath == null) return NO_OP;\n const source = walkLeaf(state.root, leafPath);\n if (source == null || source.tabs.length < 2) return NO_OP;\n const location = payload.direction === \"y\" ? \"bottom\" : \"right\";\n const placed = splitLeafAt(state, leafPath, location, 0.5);\n if (placed == null) return NO_OP;\n const removed = removeTab(state.root, payload.key);\n if (removed == null) return NO_OP;\n const target = walkLeaf(state.root, placed);\n if (target == null) return NO_OP;\n target.tabs.splice(0, 0, removed);\n collapseEmptyLeaves(state);\n return { inverse: [], targets: [payload.key] };\n },\n\n resizeSplit: (state, payload) => {\n const node = findNode(state.root, payload.split);\n if (node == null || node.variant !== \"split\") return NO_OP;\n // An equal size must not touch the draft: the dispatch substrate detects\n // no-op vectors by reference equality and skips the server send.\n if (node.size === payload.size) return NO_OP;\n node.size = payload.size;\n return { inverse: [], targets: [String(payload.split)] };\n },\n\n // setTabResource swaps the tab's content to the resource in place, clearing any view.\n // A no-op when the resource already backs a different tab: a resource may back at\n // most one tab per panel, and callers select the existing tab instead.\n setTabResource: (state, payload) => {\n const existing = findTabByResource(state.root, payload.resource);\n if (existing != null && existing.key !== payload.key) return NO_OP;\n const next: Tab = {\n variant: \"resource\",\n key: payload.key,\n resource: payload.resource,\n };\n if (!replaceTab(state.root, payload.key, next)) return NO_OP;\n return { inverse: [], targets: [payload.key] };\n },\n\n // setTabView swaps the tab's content to the inline view in place, clearing\n // any resource.\n setTabView: (state, payload) => {\n const next: Tab = { variant: \"view\", key: payload.key, ...payload.view };\n if (!replaceTab(state.root, payload.key, next)) return NO_OP;\n return { inverse: [], targets: [payload.key] };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.panel : undefined;\n\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n // Drag-resize streams ResizeSplit; coalesce them into a single undoable per\n // gesture so one ⌘Z reverses the entire drag.\n if (actions.every((a) => a.type === \"resize_split\")) return \"resize\";\n // Same for cross-leaf drags that produce a stream of MoveTab.\n if (actions.every((a) => a.type === \"move_tab\")) return \"move\";\n if (actions.length === 1) return actions[0].type;\n return \"transaction\";\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, primitive, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { ontology } from \"@/ontology\";\nimport { createOf, kindOf, reduceAll } from \"@/panel/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/panel/actions.gen\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Panel,\n panelZ,\n} from \"@/panel/types.gen\";\nimport { query } from \"@/query\";\n\nexport const SET_CHANNEL_NAME = \"sy_panel_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_panel_delete\";\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array().optional(),\n parent: ontology.idZ.optional(),\n searchTerm: z.string().optional(),\n offset: z.int().optional(),\n limit: z.int().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nexport interface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\nconst createReqZ = z.object({ panels: panelZ.array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst retrieveResZ = z.object({ panels: panelZ.array().default(() => []) });\nconst createResZ = z.object({ panels: panelZ.array() });\nconst emptyResZ = z.object({});\n\nconst isChildOf = (rel: ontology.Relationship, parent: ontology.ID): boolean =>\n ontology.matchRelationship(rel, {\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: { type: \"panel\" },\n });\n\n/**\n * Client-side matching for a request: exact for key sets. Server-computed\n * shapes (search, limit/offset) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((p: Panel) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (p) => keySet == null || keySet.has(p.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n ontology: ontology.Client;\n cache: query.Cache;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Panel> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Panel>;\n private readonly dispatcher: actions.Controller<Key, Panel, Action>;\n\n constructor(cfg: ClientConfig) {\n const { cache, ontology: ontologyClient } = cfg;\n // Dispatch mutates documents server-side, so fetched copies never clobber\n // a doc holding locally replayed edits: the table hydrates if-absent.\n const store = cache.createTable<Key, Panel>({\n name: \"panels\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, Panel, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n super(cache, {\n name: \"panel\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.fetchRequest(req),\n matches: (panel, req) => {\n if (!requestFilter(req)(panel)) return false;\n const parent = \"parent\" in req ? req.parent : undefined;\n return parent == null || this.isCachedChild(parent, panel.key);\n },\n watch: [\n query.watch(\n ontologyClient.cache.relationships,\n (event, req: RetrieveRequest) => {\n if (req.parent == null) return null;\n const rel =\n event.variant === \"set\"\n ? event.value\n : ontology.relationshipZ.parse(event.key);\n if (!isChildOf(rel, req.parent)) return null;\n return [rel.to.key];\n },\n ),\n ],\n },\n });\n this.cfg = cfg;\n this.store = store;\n this.dispatcher = dispatcher;\n }\n\n /** All panels currently in the cache. */\n listCached(): Panel[] {\n return this.store.get();\n }\n\n private isCachedChild(parent: ontology.ID, key: Key): boolean {\n return this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString({\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(key),\n }),\n );\n }\n\n async create(panel: New, opts?: query.WriteOptions<Panel[]>): Promise<Panel>;\n async create(panels: New[], opts?: query.WriteOptions<Panel[]>): Promise<Panel[]>;\n async create(\n panels: New | New[],\n opts: query.WriteOptions<Panel[]> = {},\n ): Promise<Panel | Panel[]> {\n const isMany = Array.isArray(panels);\n const optimistic = array\n .toArray(panels)\n .map((p) => zod.parse(panelZ, p, { label: \"panel\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () => {\n // onOptimistic may dispatch further local mutations against these keys\n // before the panels exist on the cluster. Send the latest cached docs so\n // the server response doesn't stomp those changes back out.\n const latest = optimistic.map((p) => this.store.get(p.key) ?? p);\n return await this.cfg.unary.send(\n \"/panel/create\",\n { panels: latest },\n createReqZ,\n createResZ,\n );\n },\n });\n this.store.set(res.panels);\n return isMany ? res.panels : res.panels[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n // Rename routes through dispatch so the action channel broadcasts the change\n // to other connected clients.\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.sendDispatch(key, \"\", [renameAction({ name })]),\n });\n rename();\n }\n\n /**\n * Applies actions to the cached panel and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the panel isn't cached.\n * Rolls back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<Panel, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the panel's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the panel's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the panel has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the panel has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the panel's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/panel/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n async delete(key: Key, opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key[], opts?: query.WriteOptions): Promise<void>;\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteResources(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/panel/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every panel delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n /** Subscribes to every panel set delivered to the cache. */\n onSet(handler: (panel: Panel) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n private async execRetrieve(req: RetrieveRequest): Promise<Panel[]> {\n const res = await this.cfg.unary.send(\n \"/panel/retrieve\",\n req,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.panels;\n }\n\n // Parent queries resolve membership through the ontology graph, then fetch\n // the member panels; the panel retrieve endpoint knows nothing of parents.\n private async fetchRequest(req: RetrieveRequest): Promise<Panel[]> {\n const { parent, ...rest } = req;\n if (parent != null) {\n const children = await this.cfg.ontology.children.retrieve({\n ids: parent,\n types: [\"panel\"],\n });\n const keys = children.map(({ id }) => id.key);\n if (keys.length === 0) return [];\n rest.keys = keys;\n }\n return await this.execRetrieve(rest);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/panel/actions\";\nexport * from \"@/panel/actions.gen\";\nexport * from \"@/panel/client\";\nexport * from \"@/panel/tree\";\nexport * from \"@/panel/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { channel } from \"@/channel\";\nimport { type Key, keyZ } from \"@/ranger/types.gen\";\n\nconst resolveReqZ = z.object({ range: keyZ, aliases: z.string().array() });\nconst resolveResZ = z.object({ aliases: z.record(z.string(), channel.keyZ) });\n\nconst setReqZ = z.object({\n range: keyZ,\n aliases: z.record(channel.keyZ, z.string()),\n});\nconst setResZ = z.unknown();\n\nconst deleteReqZ = z.object({ range: keyZ, channels: channel.keyZ.array() });\nconst deleteResZ = z.unknown();\n\nconst listReqZ = z.object({ range: keyZ });\nconst listResZ = z.object({ aliases: z.record(z.string(), z.string()) });\n\nconst retrieveReqZ = z.object({ range: keyZ, channels: channel.keyZ.array() });\nconst retrieveResZ = z.object({ aliases: z.record(z.string(), z.string()) });\n\nexport class Client {\n private readonly cache = new Map<string, channel.Key>();\n private readonly client: UnaryClient;\n private readonly rangeKey: Key;\n\n constructor(rangeKey: Key, client: UnaryClient) {\n this.rangeKey = rangeKey;\n this.cache = new Map();\n this.client = client;\n }\n\n resolve(aliases: string): Promise<channel.Key>;\n\n resolve(aliases: string[]): Promise<Record<string, channel.Key>>;\n\n async resolve(\n aliases: string | string[],\n ): Promise<channel.Key | Record<string, channel.Key>> {\n const toFetch: string[] = [];\n const isSingle = typeof aliases === \"string\";\n const cached: Record<string, channel.Key> = {};\n if (isSingle) {\n const c = this.cache.get(aliases);\n if (c != null) return c;\n toFetch.push(aliases);\n } else\n aliases.forEach((alias) => {\n const c = this.cache.get(alias);\n if (c != null) cached[alias] = c;\n else toFetch.push(alias);\n });\n if (toFetch.length === 0) return cached;\n const res = await this.client.send(\n \"/range/alias/resolve\",\n { range: this.rangeKey, aliases: toFetch },\n resolveReqZ,\n resolveResZ,\n );\n Object.entries(res.aliases).forEach(([alias, key]) => this.cache.set(alias, key));\n return isSingle ? res.aliases[toFetch[0]] : { ...cached, ...res.aliases };\n }\n\n async set(aliases: Record<channel.Key, string>): Promise<void> {\n await this.client.send(\n \"/range/alias/set\",\n { range: this.rangeKey, aliases },\n setReqZ,\n setResZ,\n );\n }\n\n async list(): Promise<Record<channel.Key, string>> {\n return (\n await this.client.send(\n \"/range/alias/list\",\n { range: this.rangeKey },\n listReqZ,\n listResZ,\n )\n ).aliases;\n }\n\n async retrieve(alias: channel.Key): Promise<string>;\n async retrieve(aliases: channel.Key[]): Promise<Record<channel.Key, string>>;\n\n async retrieve(\n alias: channel.Key | channel.Key[],\n ): Promise<string | Record<channel.Key, string>> {\n const isSingle = typeof alias === \"number\";\n const res = await this.client.send(\n \"/range/alias/retrieve\",\n { range: this.rangeKey, channels: array.toArray(alias) },\n retrieveReqZ,\n retrieveResZ,\n );\n return isSingle ? res.aliases[alias] : res.aliases;\n }\n\n async delete(aliases: channel.Key | channel.Key[]): Promise<void> {\n await this.client.send(\n \"/range/alias/delete\",\n { range: this.rangeKey, channels: array.toArray(aliases) },\n deleteReqZ,\n deleteResZ,\n );\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nimport { channel } from \"@/channel\";\nimport * as ranger from \"@/ranger/types.gen\";\n\n/**\n * Alias associates a human-readable string alias with a channel within the\n * context of a specific range. Enables semantic naming of channels that varies by\n * range context.\n */\nexport const aliasZ = z.object({\n /** range is the unique identifier of the range containing this alias. */\n range: ranger.keyZ,\n /** channel is the unique identifier of the channel being aliased. */\n channel: channel.keyZ,\n /** alias is the human-readable name for the channel within this range context. */\n alias: z.string(),\n});\nexport interface Alias extends z.infer<typeof aliasZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/ranger/alias/client\";\nexport * from \"@/ranger/alias/payload\";\nexport * from \"@/ranger/alias/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { z } from \"zod\";\n\nimport { keyZ } from \"@/ranger/types.gen\";\n\n/**\n * Pair is a key-value metadata pair associated with a specific range, enabling\n * arbitrary metadata storage on time ranges.\n */\nexport const pairZ = z.object({\n /** range is the unique identifier of the range owning this key-value pair. */\n range: keyZ,\n /** key is the metadata key name. */\n key: z.string(),\n /** value is the metadata value stored as a string for flexibility. */\n value: z.string(),\n});\nexport interface Pair extends z.infer<typeof pairZ> {}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type Pair, pairZ } from \"@/ranger/kv/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_range_kv_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_range_kv_delete\";\n\nexport const createPairKey = ({ range, key }: Omit<Pair, \"value\">) =>\n `${range}<--->${key}`;\n\n/** @deprecated Use {@link SET_CHANNEL_NAME} instead. */\nexport const KV_SET_CHANNEL = SET_CHANNEL_NAME;\n/** @deprecated Use {@link DELETE_CHANNEL_NAME} instead. */\nexport const KV_DELETE_CHANNEL = DELETE_CHANNEL_NAME;\n/** @deprecated Use {@link pairZ} instead. */\nexport const kvPairZ = pairZ;\n/** @deprecated Use {@link Pair} instead. */\nexport type KVPair = Pair;\n/** @deprecated Use {@link createPairKey} instead. */\nexport const kvPairKey = createPairKey;\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { query } from \"@/query\";\nimport { createPairKey } from \"@/ranger/kv/payload\";\nimport { type Pair, pairZ } from \"@/ranger/kv/types.gen\";\nimport { type Key, keyZ } from \"@/ranger/types.gen\";\n\nconst getReqZ = z.object({ range: keyZ, keys: z.string().array() });\nconst getResZ = z.object({ pairs: pairZ.array().default(() => []) });\nconst setReqZ = z.object({ range: keyZ, pairs: pairZ.array() });\nconst deleteReqZ = z.object({ range: keyZ, keys: z.string().array() });\n\nexport class Client {\n private readonly rangeKey: Key;\n private readonly client: UnaryClient;\n private readonly pairs: query.Table<string, Pair>;\n\n constructor(rng: Key, client: UnaryClient, pairs: query.Table<string, Pair>) {\n this.rangeKey = rng;\n this.client = client;\n this.pairs = pairs;\n }\n\n async get(key: string): Promise<string>;\n async get(keys: string[]): Promise<Record<string, string>>;\n async get(keys: string | string[]): Promise<string | Record<string, string>> {\n const res = await this.client.send(\n \"/range/kv/get\",\n { range: this.rangeKey, keys: array.toArray(keys) },\n getReqZ,\n getResZ,\n );\n if (typeof keys === \"string\") return res.pairs[0].value;\n return Object.fromEntries(res.pairs.map((pair) => [pair.key, pair.value]));\n }\n\n async list(): Promise<Record<string, string>> {\n return await this.get([]);\n }\n\n async set(key: string, value: string, opts?: query.WriteOptions): Promise<void>;\n async set(kv: Record<string, string>, opts?: query.WriteOptions): Promise<void>;\n async set(\n key: string | Record<string, string>,\n valueOrOpts: string | query.WriteOptions = \"\",\n opts: query.WriteOptions = {},\n ): Promise<void> {\n let pairs: Pair[];\n if (typeof key === \"string\")\n pairs = [{ range: this.rangeKey, key, value: valueOrOpts as string }];\n else {\n pairs = Object.entries(key).map(([k, v]) => ({\n range: this.rangeKey,\n key: k,\n value: v,\n }));\n if (typeof valueOrOpts === \"object\") opts = valueOrOpts;\n }\n // Pair.key is the bare key; the table is keyed by createPairKey, so keyed-object\n // set would mis-key entries.\n const apply = () => pairs.map((p) => this.pairs.set(createPairKey(p), p));\n await query.optimistic({\n rollbacks: apply(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.client.send(\n \"/range/kv/set\",\n { range: this.rangeKey, pairs },\n setReqZ,\n z.unknown(),\n ),\n });\n apply();\n }\n\n async delete(key: string | string[], opts: query.WriteOptions = {}): Promise<void> {\n const keys = array.toArray(key);\n const drop = () => [\n this.pairs.delete(\n keys.map((k) => createPairKey({ range: this.rangeKey, key: k })),\n ),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.client.send(\n \"/range/kv/delete\",\n { range: this.rangeKey, keys },\n deleteReqZ,\n z.unknown(),\n ),\n });\n drop();\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/ranger/kv/client\";\nexport * from \"@/ranger/kv/payload\";\nexport * from \"@/ranger/kv/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { z } from \"zod\";\n\nimport { type Key } from \"@/ranger/types.gen\";\n\n/** Zod schema for {@link Name}. A range name cannot be empty. */\nexport const nameZ = z.string().min(1);\n/** A range's display name. */\nexport type Name = z.infer<typeof nameZ>;\n/** One or many ranges, named by key or by name. */\nexport type Params = Key | Name | Key[] | Name[];\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { z } from \"zod\";\n\nimport { nameZ } from \"@/ranger/payload\";\nimport { keyZ, type New, newZ, type Payload, payloadZ } from \"@/ranger/types.gen\";\n\nconst createReqZ = z.object({ ranges: newZ.array() });\nconst createResZ = z.object({ ranges: payloadZ.array() });\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst deleteResZ = z.object({});\n\nconst renameReqZ = z.object({ key: keyZ, name: nameZ });\nconst renameResZ = z.object({});\n\n/** Creates, renames, and deletes ranges. Reach it through `client.ranges`. */\nexport class Writer {\n client: UnaryClient;\n\n constructor(client: UnaryClient) {\n this.client = client;\n }\n\n async rename(key: string, name: string): Promise<void> {\n await this.client.send(\"/range/rename\", { key, name }, renameReqZ, renameResZ);\n }\n\n async create(ranges: New[]): Promise<Payload[]> {\n const res = await this.client.send(\n \"/range/create\",\n { ranges },\n createReqZ,\n createResZ,\n );\n return res.ranges;\n }\n\n async delete(keys: string[]): Promise<void> {\n await this.client.send(\"/range/delete\", { keys }, deleteReqZ, deleteResZ);\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport {\n array,\n color,\n type CrudeTimeRange,\n deep,\n type destructor,\n primitive,\n type Series,\n TimeRange,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { type channel } from \"@/channel\";\nimport { QueryError } from \"@/errors\";\nimport { type framer } from \"@/framer\";\nimport { label } from \"@/label\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport { alias } from \"@/ranger/alias\";\nimport { Client as AliasClient } from \"@/ranger/alias/client\";\nimport { kv } from \"@/ranger/kv\";\nimport { Client as KVClient } from \"@/ranger/kv/client\";\nimport { type Name, type Params } from \"@/ranger/payload\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Payload,\n payloadZ,\n} from \"@/ranger/types.gen\";\nimport { Writer } from \"@/ranger/writer\";\nimport { checkForMultipleOrNoResults } from \"@/util/retrieve\";\n\nexport const SET_CHANNEL_NAME = \"sy_range_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_range_delete\";\n\nconst kvDeleteZ = z\n .string()\n .transform((val) => val.split(\"<--->\"))\n .transform(([range, key]) => ({ key, range }));\n\nconst aliasDeleteZ = z.string().transform((val) => alias.decodeDeleteChange(val));\n\ninterface Stores {\n ranges: query.Table<Key, Range>;\n kvPairs: query.Table<string, kv.Pair>;\n aliases: query.Table<string, alias.Alias>;\n}\n\n/** Creates the range, range KV, and range alias tables on the given cache. */\nconst createTables = (\n cache: query.Cache,\n sugarOne: (payload: Payload) => Range,\n relationships: query.Table<string, ontology.Relationship>,\n fetch: (keys: Key[]) => Promise<Range[]>,\n backfill: (rel: ontology.Relationship) => Promise<void>,\n): Stores => {\n const ranges = cache.createTable<Key, Range>({\n name: \"ranges\",\n equal: (a, b) => deep.equal(a.payload, b.payload),\n fetch,\n listen: [\n // Labels and parents are composed from the relationship tables on read, so the\n // event only carries the base payload; enriched fields are preserved.\n query.createSetListener(SET_CHANNEL_NAME, payloadZ, {\n value: (changed, prev) =>\n sugarOne({ ...changed, labels: prev?.labels, parent: prev?.parent }),\n }),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n\n // Fetches missing relationship targets so compositions and membership\n // checks can see them.\n relationships.subscribe((event) => {\n if (event.variant === \"set\") backfill(event.value).catch(cache.onError);\n });\n\n const kvPairs = cache.createTable<string, kv.Pair>({\n name: \"range_kv\",\n listen: [\n query.createSetListener(kv.SET_CHANNEL_NAME, kv.pairZ, {\n key: (changed) => kv.createPairKey(changed),\n }),\n query.createDeleteListener(kv.DELETE_CHANNEL_NAME, kvDeleteZ, {\n key: (changed) => kv.createPairKey(changed),\n }),\n ],\n });\n\n const aliases = cache.createTable<string, alias.Alias>({\n name: \"range_aliases\",\n listen: [\n query.createSetListener(alias.SET_CHANNEL_NAME, alias.aliasZ, {\n key: (changed) => alias.createKey(changed),\n }),\n query.createDeleteListener(alias.DELETE_CHANNEL_NAME, aliasDeleteZ, {\n key: (changed) => alias.createKey(changed),\n }),\n ],\n });\n return { ranges, kvPairs, aliases };\n};\n\ninterface RangeConstructionOptions {\n frameClient: framer.Client;\n kv: KVClient;\n aliaser: AliasClient;\n channels: framer.ChannelRetriever;\n labelClient: label.Client;\n ontologyClient: ontology.Client;\n rangeClient: Client;\n}\n\n/**\n * A named window of time, with the labels, metadata, and channel aliases attached to\n * it. Its `read` and `kv` members scope those operations to its own time range.\n */\nexport class Range {\n key: string;\n name: string;\n readonly kv: KVClient;\n readonly timeRange: TimeRange;\n readonly color?: color.Color;\n readonly parent?: Payload;\n readonly labels?: label.Label[];\n readonly channels: framer.ChannelRetriever;\n private readonly aliaser: AliasClient;\n private readonly frameClient: framer.Client;\n private readonly labelClient: label.Client;\n private readonly ontologyClient: ontology.Client;\n private readonly rangeClient: Client;\n\n constructor(\n { name, timeRange = TimeRange.ZERO, key, color: color_, parent, labels }: Payload,\n {\n frameClient,\n kv,\n aliaser,\n channels,\n labelClient,\n ontologyClient,\n rangeClient,\n }: RangeConstructionOptions,\n ) {\n this.key = key;\n this.name = name;\n this.timeRange = timeRange;\n this.parent = parent;\n this.labels = labels;\n this.frameClient = frameClient;\n this.color = color_;\n this.kv = kv;\n this.aliaser = aliaser;\n this.channels = channels;\n this.labelClient = labelClient;\n this.ontologyClient = ontologyClient;\n this.rangeClient = rangeClient;\n }\n\n get ontologyID(): ontology.ID {\n return ontologyID(this.key);\n }\n\n get payload(): Payload {\n const r: Payload = {\n key: this.key,\n name: this.name,\n timeRange: this.timeRange,\n color: this.color,\n labels: this.labels,\n };\n if (this.parent != null)\n if (\"payload\" in this.parent) r.parent = (this.parent as Range).payload;\n else r.parent = this.parent;\n return r;\n }\n\n async setAlias(channel: channel.Key | Name, alias: string): Promise<void> {\n const ch = await this.channels(channel);\n if (ch.length === 0) throw new QueryError(`Channel ${channel} does not exist`);\n await this.rangeClient.setAlias(this.key, ch[0].key, alias);\n }\n\n async deleteAlias(...channels: channel.Key[]): Promise<void> {\n await this.rangeClient.deleteAlias(this.key, channels);\n }\n\n async listAliases(): Promise<Record<channel.Key, string>> {\n return await this.aliaser.list();\n }\n\n async resolveAlias(alias: string): Promise<channel.Key> {\n return await this.aliaser.resolve(alias);\n }\n\n async retrieveParent(): Promise<Range | null> {\n return await this.rangeClient.retrieveParent(this.key);\n }\n\n async retrieveChildren(): Promise<Range[]> {\n const res = (\n await this.ontologyClient.children.retrieve({\n ids: this.ontologyID,\n excludeFieldData: true,\n types: [\"range\"],\n })\n ).map((r) => r.id.key);\n return await this.rangeClient.retrieve(res);\n }\n\n async read(channel: Key | Name): Promise<Series>;\n async read(channels: Params): Promise<framer.Frame>;\n async read(channels: Params): Promise<Series | framer.Frame> {\n return await this.frameClient.read(this.timeRange, channels);\n }\n\n async retrieveLabels(): Promise<label.Label[]> {\n return await this.labelClient.retrieve({ for: ontologyID(this.key) });\n }\n\n async addLabel(...labels: label.Key[]): Promise<void> {\n await this.labelClient.label(ontologyID(this.key), labels);\n }\n\n async removeLabel(...labels: label.Key[]): Promise<void> {\n await this.labelClient.remove(ontologyID(this.key), labels);\n }\n\n static sort(a: Range, b: Range): number {\n return TimeRange.sort(a.timeRange, b.timeRange);\n }\n}\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n names: z.string().array().optional(),\n searchTerm: z.string().optional(),\n overlapsWith: TimeRange.z.optional(),\n hasLabels: label.keyZ.array().optional(),\n limit: z.int().optional(),\n offset: z.int().optional(),\n includeLabels: z.boolean().optional(),\n includeParent: z.boolean().optional(),\n ignoreNotFoundError: z.boolean().optional(),\n});\n\n/** Everything a range retrieval can filter on. */\nexport type RetrieveRequest = z.infer<typeof retrieveRequestZ>;\n\nconst retrieveParamsZ = retrieveRequestZ\n .or(keyZ.array().transform((keys) => ({ keys })))\n .or(keyZ.transform((key) => ({ keys: [key] })))\n .or(z.string().transform((name) => ({ names: [name] })))\n .or(\n z\n .string()\n .array()\n .transform((names) => ({ names })),\n )\n .or(TimeRange.z.transform((timeRange) => ({ overlapsWith: timeRange })));\n\n/** Params for a range retrieval. A bare key, name, or time range is shorthand. */\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\n\n/** Canonicalizes every retrieve shape addressing more than one range. */\nconst retrieveMultiParamsZ = retrieveRequestZ\n .or(keyZ.array().transform((keys) => ({ keys })))\n .or(\n z\n .string()\n .array()\n .transform((names) => ({ names })),\n )\n .or(TimeRange.z.transform((timeRange) => ({ overlapsWith: timeRange })));\n\nconst retrieveResZ = z.object({ ranges: payloadZ.array().default(() => []) });\n\n/** The base flags applied to every composed range fetch. */\nconst BASE_REQUEST: Partial<RetrieveRequest> = {\n includeLabels: true,\n includeParent: true,\n};\n\nconst isKeysOnly = (req: RetrieveRequest): req is RetrieveRequest & { keys: Key[] } =>\n primitive.isNonZero(req.keys) &&\n req.names == null &&\n req.searchTerm == null &&\n req.overlapsWith == null &&\n req.hasLabels == null &&\n req.limit == null &&\n req.offset == null;\n\nconst isParentChange = (rel: ontology.Relationship, id: ontology.ID): boolean =>\n ontology.matchRelationship(rel, {\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: id,\n });\n\nconst relOfEvent = (\n event: query.TableEvent<string, ontology.Relationship>,\n): ontology.Relationship =>\n event.variant === \"set\"\n ? event.value\n : zod.parse(ontology.relationshipZ, event.key, { label: \"ontology relationship\" });\n\n/** Range keys whose composed labels or parent the relationship affects. */\nconst affectedRangeKeys = (rel: ontology.Relationship): Key[] | null => {\n const keys: Key[] = [];\n const labeled = ontology.matchRelationship(rel, {\n type: label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n from: { type: \"range\" },\n });\n if (labeled) keys.push(rel.from.key);\n const parented = ontology.matchRelationship(rel, {\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: { type: \"range\" },\n });\n if (parented) keys.push(rel.to.key);\n return keys.length === 0 ? null : keys;\n};\n\n/** Projects relationship events onto the range keys they affect. */\nconst watchRelationships = <Q extends query.Params>(\n relationships: query.Table<string, ontology.Relationship>,\n): query.Watch<Q, Key> =>\n query.watch<Q, Key, string, ontology.Relationship>(relationships, (event) =>\n affectedRangeKeys(relOfEvent(event)),\n );\n\nconst rangesWithLabel = (\n relationships: query.Table<string, ontology.Relationship>,\n key: label.Key,\n): Key[] | null => {\n const keys = relationships\n .get(\n (r) =>\n r.type === label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE &&\n r.from.type === \"range\" &&\n r.to.key === key,\n )\n .map((r) => r.from.key);\n return keys.length === 0 ? null : keys;\n};\n\n/** Projects label content changes onto the ranges they label. */\nconst watchLabels = <Q extends query.Params>(\n labels: query.Table<label.Key, label.Label>,\n relationships: query.Table<string, ontology.Relationship>,\n): query.Watch<Q, Key> =>\n query.watch<Q, Key, label.Key, label.Label>(labels, (event) =>\n rangesWithLabel(relationships, event.key),\n );\n\n/** Config for {@link Client}. */\nexport interface ClientConfig {\n framer: framer.Client;\n unary: UnaryClient;\n channels: framer.ChannelRetriever;\n labels: label.Client;\n ontology: ontology.Client;\n cache: query.Cache;\n}\n\n/**\n * Creates, reads, and deletes ranges on a Core. Reach it through `client.ranges`. Reads\n * return sugared {@link Range}s, served from a cache a change stream keeps current.\n */\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Range,\n Range,\n Key | Name\n> {\n readonly type: string = \"range\";\n /** The range alias table; injected into sibling clients at wiring. */\n readonly aliases: query.Table<string, alias.Alias>;\n /** Cached queries for the children of a range, keyed by the parent's key. */\n readonly children: query.Retrieves<Key, Range[]>;\n /**\n * Cached queries for the closest range parent of a resource, keyed by the\n * child's ontology ID.\n */\n readonly parent: query.Retrieves<ontology.ID, Range | null>;\n /** Cached queries for a range's KV metadata pairs, keyed by the range's key. */\n readonly kv: query.Retrieves<Key, kv.Pair[]>;\n private readonly cfg: ClientConfig;\n private readonly writer: Writer;\n private readonly store: query.Table<Key, Range>;\n private readonly kvPairs: query.Table<string, kv.Pair>;\n\n constructor(cfg: ClientConfig) {\n const { labels: labelClient, ontology: ontologyClient, cache } = cfg;\n const labels = labelClient.store;\n const { relationships } = ontologyClient.cache;\n const { ranges, kvPairs, aliases } = createTables(\n cache,\n (payload) => this.sugarOne(payload),\n relationships,\n async (keys) => await this.fetchThrough(keys),\n async (rel) => await this.ensureRelationshipTargets(rel),\n );\n const composed = cache.derive<Key, Range, Range>({\n name: \"range.composed\",\n source: ranges,\n compose: (record) => this.composeOne(record),\n equal: (a, b) => deep.equal(a.payload, b.payload),\n watch: [\n query.deriveWatch(relationships, (event) =>\n affectedRangeKeys(relOfEvent(event)),\n ),\n query.deriveWatch(labels, (event) => rangesWithLabel(relationships, event.key)),\n ],\n });\n const single = cache.queries<Key | Name, Range, Key, Range>({\n name: \"range\",\n table: composed,\n fetch: async (query) => [(await this.fetchSingle(query)).key],\n compose: ([record]) => record,\n keyOf: (query) => (keyZ.safeParse(query).success ? query : null),\n matches: (r, query) => r.key === query || r.name === query,\n single: true,\n });\n super(cache, {\n name: \"range\",\n table: ranges,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (query) => await this.fetchRequest(query),\n matches: (r, query) => this.requestMatches(r, query),\n watch: [\n watchRelationships<RetrieveRequest>(relationships),\n watchLabels<RetrieveRequest>(labels, relationships),\n ],\n },\n compose: (r) => this.composeOne(r),\n single: { schema: z.string(), space: single },\n });\n this.cfg = cfg;\n this.writer = new Writer(cfg.unary);\n this.store = ranges;\n this.kvPairs = kvPairs;\n this.aliases = aliases;\n this.children = cache.queries<Key, Range[], Key, Range>({\n name: \"child ranges\",\n table: composed,\n fetch: async (query) => (await this.fetchChildren(query)).map((r) => r.key),\n compose: (records) => records,\n matches: (r, query) => {\n const parent = this.cfg.ontology.cache.parentID(ontologyID(r.key));\n return parent != null && ontology.idsEqual(parent, ontologyID(query));\n },\n watch: [watchRelationships<Key>(this.cfg.ontology.cache.relationships)],\n });\n this.parent = cache.queries<ontology.ID, Range | null, Key, Range>({\n name: \"parent range\",\n table: composed,\n fetch: async (query) => {\n const range = await this.fetchParent(query);\n return range == null ? [] : [range.key];\n },\n compose: (records) => records[0] ?? null,\n matches: (r, query) => {\n const parent = this.cfg.ontology.cache.parentID(query);\n return parent != null && parent.type === \"range\" && parent.key === r.key;\n },\n watch: [\n query.watch<ontology.ID, Key, string, ontology.Relationship>(\n this.cfg.ontology.cache.relationships,\n (event, query) => {\n const rel = relOfEvent(event);\n if (isParentChange(rel, query))\n return rel.from.type === \"range\" ? [rel.from.key] : \"refetch\";\n return affectedRangeKeys(rel);\n },\n ),\n ],\n });\n this.kv = cache.queries<Key, kv.Pair[], string, kv.Pair>({\n name: \"range metadata\",\n table: this.kvPairs,\n fetch: async (query) =>\n (await this.fetchKV(query)).map((p) => kv.createPairKey(p)),\n compose: (records) => records,\n matches: (pair, query) => pair.range === query,\n });\n }\n\n async create(range: New): Promise<Range>;\n async create(ranges: New[]): Promise<Range[]>;\n async create(ranges: New | New[]): Promise<Range | Range[]> {\n const single = !Array.isArray(ranges);\n const news = array.toArray(ranges);\n const res = this.sugarMany(await this.writer.create(news));\n res.forEach((r, i) => {\n this.writeThrough(r);\n const parent = news[i]?.parent;\n if (r.parent != null || parent == null) return;\n const rel: ontology.Relationship = {\n from: ontologyID(parent.key),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(r.key),\n };\n this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n );\n });\n return single ? res[0] : res;\n }\n\n async rename(key: Key, name: Name, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n this.store.set(key, (p) =>\n p == null ? undefined : this.sugarOne({ ...p.payload, name }),\n ),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.writer.rename(key, name),\n });\n rename();\n }\n\n async delete(key: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keys = array.toArray(key);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ontologyID(keys)),\n this.store.delete(keys),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.writer.delete(keys),\n });\n drop();\n }\n\n async retrieve(params: Key | Name): Promise<Range>;\n async retrieve(params: Key[] | Name[]): Promise<Range[]>;\n async retrieve(params: CrudeTimeRange): Promise<Range[]>;\n async retrieve(params: RetrieveRequest): Promise<Range[]>;\n async retrieve(params: RetrieveParams): Promise<Range | Range[]> {\n // The branches narrow params onto different base overloads.\n if (typeof params === \"string\") return await super.retrieve(params);\n return await super.retrieve(params);\n }\n\n private async execRetrieve(params: RetrieveParams): Promise<Range[]> {\n const { ranges } = await this.cfg.unary.send(\n \"/range/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ,\n );\n return this.sugarMany(ranges);\n }\n\n /** Subscribes to every range set delivered to the cache. */\n onSet(handler: (range: Range) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every range delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private createAliasClient(key: Key): AliasClient {\n return new AliasClient(key, this.cfg.unary);\n }\n\n private createKVClient(key: Key): KVClient {\n return new KVClient(key, this.cfg.unary, this.kvPairs);\n }\n\n /** Rebuilds a cached range with its cached labels and parent attached. */\n private composeOne(cached: Range): Range {\n const id = ontologyID(cached.key);\n const labels = label.cachedLabelsOf(\n this.cfg.ontology.cache.relationships,\n this.cfg.labels.store,\n id,\n );\n const next: Payload = { ...cached.payload, labels };\n const parentID = this.cfg.ontology.cache.parentID(id);\n if (parentID == null) delete next.parent;\n else {\n const parent = this.store.get(parentID.key);\n if (parent != null) next.parent = parent.payload;\n }\n return this.sugarOne(next);\n }\n\n /** Writes a fetched range and its included labels/parent relationships. */\n private writeThrough(range: Range): void {\n this.store.set(range);\n const id = ontologyID(range.key);\n if (range.labels != null) {\n this.cfg.labels.store.set(range.labels);\n range.labels.forEach((l) => {\n const rel: ontology.Relationship = {\n from: id,\n type: label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE,\n to: label.ontologyID(l.key),\n };\n this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n );\n });\n }\n if (range.parent != null) {\n const rel: ontology.Relationship = {\n from: ontologyID(range.parent.key),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: id,\n };\n this.cfg.ontology.cache.relationships.set(\n ontology.relationshipToString(rel),\n rel,\n );\n }\n }\n\n /**\n * Fetches the given keys with labels and parents included, writing them and\n * their relationships through. Powers the table's fetch primitive.\n */\n private async fetchThrough(keys: Key[]): Promise<Range[]> {\n const ranges = await this.execRetrieve({\n ...BASE_REQUEST,\n keys,\n ignoreNotFoundError: true,\n });\n ranges.forEach((r) => this.writeThrough(r));\n return ranges;\n }\n\n private async fetchSingle(query: Key | Name): Promise<Range> {\n const cached = this.store.get(query);\n if (cached != null) return this.composeOne(cached);\n const req = keyZ.safeParse(query).success ? { keys: [query] } : { names: [query] };\n const ranges = await this.execRetrieve({ ...BASE_REQUEST, ...req });\n checkForMultipleOrNoResults(\"Range\", query, ranges, true);\n this.writeThrough(ranges[0]);\n return ranges[0];\n }\n\n /**\n * Fetches records a relationship points at that the cache is missing, so compositions\n * and membership checks can include them. Presence guards make it idempotent.\n */\n private async ensureRelationshipTargets(rel: ontology.Relationship): Promise<void> {\n if (rel.type === label.LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE) {\n if (rel.to.type !== \"label\" || this.cfg.labels.store.has(rel.to.key)) return;\n const fetched = await this.cfg.labels.retrieve(rel.to.key);\n this.cfg.labels.store.set(rel.to.key, fetched);\n return;\n }\n if (rel.type === ontology.PARENT_OF_RELATIONSHIP_TYPE) {\n if (rel.from.type !== \"range\" || this.store.has(rel.from.key)) return;\n await this.store.retrieve([rel.from.key]);\n }\n }\n\n private async fetchRequest(query: RetrieveRequest): Promise<Range[]> {\n if (isKeysOnly(query)) return await this.store.retrieve(query.keys);\n const ranges = await this.execRetrieve({ ...BASE_REQUEST, ...query });\n ranges.forEach((r) => this.writeThrough(r));\n return ranges;\n }\n\n /** Exact client-side evaluation of a request against a cached range. */\n private requestMatches(r: Range, req: RetrieveRequest): boolean {\n if (primitive.isNonZero(req.keys) && !req.keys.includes(r.key)) return false;\n if (primitive.isNonZero(req.names) && !req.names.includes(r.name)) return false;\n if (\n req.overlapsWith != null &&\n !new TimeRange(req.overlapsWith).overlapsWith(r.timeRange)\n )\n return false;\n if (primitive.isNonZero(req.hasLabels)) {\n const labels = label.cachedLabelsOf(\n this.cfg.ontology.cache.relationships,\n this.cfg.labels.store,\n ontologyID(r.key),\n );\n const wanted = new Set(req.hasLabels);\n if (!labels.some((l) => wanted.has(l.key))) return false;\n }\n return true;\n }\n\n private async fetchChildren(query: Key): Promise<Range[]> {\n const resources = await this.cfg.ontology.children.retrieve({\n ids: ontologyID(query),\n types: [\"range\"],\n });\n if (resources.length === 0) return [];\n return await this.store.retrieve(resources.map(({ id: { key } }) => key));\n }\n\n private async fetchParent(query: ontology.ID): Promise<Range | null> {\n const res = await this.cfg.ontology.parents.retrieve({ ids: query });\n const parent = res.find(({ id: { type } }) => type === \"range\");\n if (parent == null) return null;\n const [range] = await this.store.retrieve([parent.id.key]);\n return range ?? null;\n }\n\n private async fetchKV(query: Key): Promise<kv.Pair[]> {\n const pairs = await this.createKVClient(query).list();\n const result: kv.Pair[] = Object.entries(pairs).map(([key, value]) => ({\n range: query,\n key,\n value,\n }));\n result.forEach((p) => this.kvPairs.set(kv.createPairKey(p), p));\n return result;\n }\n\n getKV(range: Key): KVClient {\n return this.createKVClient(range);\n }\n\n /** Returns the parent of the given range, or null when it has none. */\n async retrieveParent(range: Key): Promise<Range | null> {\n return await this.parent.retrieve(ontologyID(range));\n }\n\n sugarOntologyResource(resource: ontology.Resource): Range {\n return this.sugarOne(convertOntologyResourceToPayload(resource));\n }\n\n async retrieveAlias(range: Key, channel: channel.Key): Promise<string> {\n const aliaser = this.createAliasClient(range);\n return await aliaser.retrieve(channel);\n }\n\n async retrieveAliases(\n range: Key,\n channels: channel.Key[],\n ): Promise<Record<channel.Key, string>> {\n return await this.createAliasClient(range).retrieve(channels);\n }\n\n async listAliases(range: Key): Promise<Record<channel.Key, string>> {\n return await this.createAliasClient(range).list();\n }\n\n async setAlias(\n range: Key,\n channel: channel.Key,\n aliasName: string,\n opts: query.WriteOptions = {},\n ): Promise<void> {\n const entry: alias.Alias = { range, channel, alias: aliasName };\n const set = () => [this.aliases.set(alias.createKey(entry), entry)];\n await query.optimistic({\n rollbacks: set(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.createAliasClient(range).set({ [channel]: aliasName }),\n });\n set();\n }\n\n async deleteAlias(\n range: Key,\n channels: channel.Key | channel.Key[],\n opts: query.WriteOptions = {},\n ): Promise<void> {\n const channelsArr = array.toArray(channels);\n const drop = () => [\n this.aliases.delete(\n channelsArr.map((channel) => alias.createKey({ range, channel })),\n ),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.createAliasClient(range).delete(channelsArr),\n });\n drop();\n }\n\n sugarOne(payload: Payload): Range {\n return new Range(payload, {\n frameClient: this.cfg.framer,\n kv: this.createKVClient(payload.key),\n aliaser: this.createAliasClient(payload.key),\n channels: this.cfg.channels,\n labelClient: this.cfg.labels,\n ontologyClient: this.cfg.ontology,\n rangeClient: this,\n });\n }\n\n sugarMany(payloads: Payload[]): Range[] {\n return payloads.map((payload) => this.sugarOne(payload));\n }\n\n resourceToRange(resource: ontology.Resource): Range {\n return this.sugarOne(convertOntologyResourceToPayload(resource));\n }\n}\n\n/** @returns the ontology ID of a range's alias set. */\nexport const aliasOntologyID = (key: Key): ontology.ID => ({\n type: \"range-alias\",\n key,\n});\n\n/**\n * Rebuilds a range payload from its ontology resource, for a search result that arrives\n * through the ontology rather than the range endpoint.\n */\nexport const convertOntologyResourceToPayload = ({\n data,\n id: { key },\n name,\n}: ontology.Resource): Payload => {\n const timeRange = zod.parse(TimeRange.z, data?.timeRange, {\n label: \"range time range\",\n });\n const c = color.colorZ.safeParse(data?.color);\n return {\n key,\n name,\n timeRange,\n color: c.success ? c.data : undefined,\n labels: [],\n parent: undefined,\n };\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/ranger/alias\";\nexport * from \"@/ranger/alias\";\nexport {\n /** @deprecated Use {@link alias.createKey} instead. */\n createKey as aliasKey,\n /** @deprecated Use {@link alias.decodeDeleteChange} instead. */\n decodeDeleteChange as decodeDeleteAliasChange,\n /** @deprecated Use {@link alias.DELETE_CHANNEL_NAME} instead. */\n DELETE_CHANNEL_NAME as DELETE_ALIAS_CHANNEL_NAME,\n /** @deprecated Use {@link SET_CHANNEL_NAME} instead. */\n SET_CHANNEL_NAME as SET_ALIAS_CHANNEL_NAME,\n} from \"@/ranger/alias/payload\";\nexport * from \"@/ranger/client\";\nexport * from \"@/ranger/kv\";\nexport * from \"@/ranger/kv\";\nexport {\n /** @deprecated Use {@link kv.DELETE_CHANNEL_NAME} instead. */\n DELETE_CHANNEL_NAME as KV_DELETE_CHANNEL,\n /** @deprecated Use {@link kv.SET_CHANNEL_NAME} instead. */\n SET_CHANNEL_NAME as KV_SET_CHANNEL,\n /** @deprecated Use {@link kv.Pair} instead. */\n /** @deprecated Use {@link kv.createPairKey} instead. */\n createPairKey as kvPairKey,\n} from \"@/ranger/kv/payload\";\nexport * from \"@/ranger/payload\";\nexport * from \"@/ranger/types.gen\";\nexport * from \"@/ranger/writer\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, record, spatial, uuid, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\n/** Node is a diagram node representing a symbol in the schematic. */\nexport const nodeZ = z.object({\n /** key is the unique node identifier within the schematic. */\n key: z.string(),\n /** position is the top-left position of the node. */\n position: spatial.xyZ,\n /**\n * zIndex is the stacking order of the node within the schematic. Higher values render\n * above lower values. Set by the user via send-to-back / bring-to-front actions.\n */\n zIndex: zod.int16.default(0),\n});\nexport interface Node extends z.infer<typeof nodeZ> {}\n\n/**\n * Handle is a reference to a specific connection point on a specific node. For\n * schematics, param is the symbol handle key (e.g. inlet, outlet).\n */\nexport const handleZ = z.object({\n /** node is the node identifier. */\n node: z.string(),\n /** param is the connection point identifier on the node. */\n param: z.string(),\n});\nexport interface Handle extends z.infer<typeof handleZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/** Edge is a connection between two nodes in the schematic. */\nexport const edgeZ = z.object({\n /** key is the unique edge identifier within the schematic. */\n key: z.string(),\n /** source is the source endpoint of the edge. */\n source: handleZ,\n /** target is the target endpoint of the edge. */\n target: handleZ,\n});\nexport interface Edge extends z.infer<typeof edgeZ> {}\n\n/**\n * Schematic is a visual diagram editor component for drawing system schematics, control\n * flows, and process diagrams. Schematics support interactive symbols, connection\n * handles, and dynamic state visualization.\n */\nexport const schematicZ = z.object({\n /** key is the unique identifier for this schematic. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the schematic. */\n name: z.string().min(1, \"name is required\"),\n /** snapshot is true if this schematic is an immutable snapshot copy. */\n snapshot: z.boolean().default(false),\n /** nodes contains all diagram nodes in the schematic. */\n nodes: nodeZ.array().default(() => []),\n /** edges contains all connections between nodes. */\n edges: edgeZ.array().default(() => []),\n /**\n * configs contains per-element configuration keyed by node or edge key. The shape of\n * each value is determined by the element's variant; the wire format intentionally\n * stores it as an opaque record.\n */\n configs: caseconv.preserveCase(\n z.record(z.string(), record.unknownZ()).default(() => ({})),\n ),\n});\nexport interface Schematic extends z.infer<typeof schematicZ> {}\nexport interface New extends z.input<typeof schematicZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"schematic\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { caseconv, record, spatial, zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { edgeZ, keyZ, nodeZ, type Schematic, schematicZ } from \"@/schematic/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n schematic: schematicZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the schematic. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/** SetNodePosition moves a node to a new position. */\nexport const setNodePositionPayloadZ = z.object({\n key: z.string(),\n position: spatial.xyZ,\n});\n\nexport type SetNodePositionPayload = z.infer<typeof setNodePositionPayloadZ>;\n\n/**\n * SetNode inserts the node if no node with the same key exists, otherwise replaces the\n * existing node in place. If config is non-empty it is stored under the node's key in\n * the schematic configs map.\n */\nexport const setNodePayloadZ = z.object({\n node: nodeZ,\n config: caseconv.preserveCase(zod.nullToUndefined(record.unknownZ())),\n});\n\nexport type SetNodePayload = z.infer<typeof setNodePayloadZ>;\n\n/** RemoveNode removes a node and any config stored under its key. */\nexport const removeNodePayloadZ = z.object({\n key: z.string(),\n});\n\nexport type RemoveNodePayload = z.infer<typeof removeNodePayloadZ>;\n\n/**\n * AddEdge appends the edge to the schematic. No-op when an edge with the same key\n * already exists.\n */\nexport const addEdgePayloadZ = z.object({\n edge: edgeZ,\n});\n\nexport type AddEdgePayload = z.infer<typeof addEdgePayloadZ>;\n\n/** RemoveEdge removes the edge with the given key, if present. */\nexport const removeEdgePayloadZ = z.object({\n key: z.string(),\n});\n\nexport type RemoveEdgePayload = z.infer<typeof removeEdgePayloadZ>;\n\n/**\n * SetConfig merges the given config fields into the existing config entry for the given\n * node or edge key. Top-level fields present in the payload overwrite existing fields;\n * fields absent from the payload are preserved. When no entry exists yet and the key\n * matches an edge whose source node carries a color, the source color overrides\n * whatever color (if any) was in the payload.\n */\nexport const setConfigPayloadZ = z.object({\n key: z.string(),\n config: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\n\nexport type SetConfigPayload = z.infer<typeof setConfigPayloadZ>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({\n type: z.literal(\"set_node_position\"),\n setNodePosition: setNodePositionPayloadZ,\n }),\n z.object({ type: z.literal(\"set_node\"), setNode: setNodePayloadZ }),\n z.object({ type: z.literal(\"remove_node\"), removeNode: removeNodePayloadZ }),\n z.object({ type: z.literal(\"add_edge\"), addEdge: addEdgePayloadZ }),\n z.object({ type: z.literal(\"remove_edge\"), removeEdge: removeEdgePayloadZ }),\n z.object({ type: z.literal(\"set_config\"), setConfig: setConfigPayloadZ }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"schematic create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"schematic rename action payload\",\n }),\n});\n\nexport const setNodePosition = (\n payload: z.input<typeof setNodePositionPayloadZ>,\n): Action => ({\n type: \"set_node_position\",\n setNodePosition: zod.parse(setNodePositionPayloadZ, payload, {\n label: \"schematic set_node_position action payload\",\n }),\n});\n\nexport const setNode = (payload: z.input<typeof setNodePayloadZ>): Action => ({\n type: \"set_node\",\n setNode: zod.parse(setNodePayloadZ, payload, {\n label: \"schematic set_node action payload\",\n }),\n});\n\nexport const removeNode = (payload: z.input<typeof removeNodePayloadZ>): Action => ({\n type: \"remove_node\",\n removeNode: zod.parse(removeNodePayloadZ, payload, {\n label: \"schematic remove_node action payload\",\n }),\n});\n\nexport const addEdge = (payload: z.input<typeof addEdgePayloadZ>): Action => ({\n type: \"add_edge\",\n addEdge: zod.parse(addEdgePayloadZ, payload, {\n label: \"schematic add_edge action payload\",\n }),\n});\n\nexport const removeEdge = (payload: z.input<typeof removeEdgePayloadZ>): Action => ({\n type: \"remove_edge\",\n removeEdge: zod.parse(removeEdgePayloadZ, payload, {\n label: \"schematic remove_edge action payload\",\n }),\n});\n\nexport const setConfig = (payload: z.input<typeof setConfigPayloadZ>): Action => ({\n type: \"set_config\",\n setConfig: zod.parse(setConfigPayloadZ, payload, {\n label: \"schematic set_config action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<Schematic, Action>;\n\nexport interface Handlers {\n create: (state: Draft<Schematic>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<Schematic>, payload: RenamePayload) => HandlerResult;\n setNodePosition: (\n state: Draft<Schematic>,\n payload: SetNodePositionPayload,\n ) => HandlerResult;\n setNode: (state: Draft<Schematic>, payload: SetNodePayload) => HandlerResult;\n removeNode: (state: Draft<Schematic>, payload: RemoveNodePayload) => HandlerResult;\n addEdge: (state: Draft<Schematic>, payload: AddEdgePayload) => HandlerResult;\n removeEdge: (state: Draft<Schematic>, payload: RemoveEdgePayload) => HandlerResult;\n setConfig: (state: Draft<Schematic>, payload: SetConfigPayload) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<Schematic, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"set_node_position\":\n return handlers.setNodePosition(state, action.setNodePosition);\n case \"set_node\":\n return handlers.setNode(state, action.setNode);\n case \"remove_node\":\n return handlers.removeNode(state, action.removeNode);\n case \"add_edge\":\n return handlers.addEdge(state, action.addEdge);\n case \"remove_edge\":\n return handlers.removeEdge(state, action.removeEdge);\n case \"set_config\":\n return handlers.setConfig(state, action.setConfig);\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { color, type record } from \"@synnaxlabs/x\";\n\nimport { actions } from \"@/actions\";\nimport {\n type Action,\n addEdge,\n createReduceAll,\n type Handlers,\n removeEdge,\n removeNode,\n rename,\n setConfig,\n setNode,\n setNodePosition,\n} from \"@/schematic/actions.gen\";\n\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.schematic);\n return { inverse: [], targets: [payload.schematic.key] };\n },\n\n rename: (state, payload) => {\n const oldName = state.name;\n state.name = payload.name;\n return {\n inverse: [rename({ name: oldName })],\n targets: [state.key],\n };\n },\n setNodePosition: (state, payload) => {\n const node = state.nodes.find((n) => n.key === payload.key);\n if (node == null) return actions.NO_OP_RESULT;\n const oldPosition = { x: node.position.x, y: node.position.y };\n node.position = payload.position;\n return {\n inverse: [setNodePosition({ key: payload.key, position: oldPosition })],\n targets: [payload.key],\n };\n },\n setNode: (state, payload) => {\n const idx = state.nodes.findIndex((n) => n.key === payload.node.key);\n if (idx === -1) {\n state.nodes.push(payload.node);\n if (payload.config != null) state.configs[payload.node.key] = payload.config;\n return {\n inverse: [removeNode({ key: payload.node.key })],\n targets: [payload.node.key],\n };\n }\n const oldNode = actions.snapshotDraft(state.nodes[idx]);\n const oldConfigRaw = state.configs[payload.node.key];\n const oldConfig =\n oldConfigRaw != null ? actions.snapshotDraft(oldConfigRaw) : undefined;\n state.nodes[idx] = payload.node;\n if (payload.config != null) state.configs[payload.node.key] = payload.config;\n return {\n inverse: [\n setNode(\n oldConfig != null\n ? { node: oldNode, config: oldConfig }\n : { node: oldNode, config: undefined },\n ),\n ],\n targets: [payload.node.key],\n };\n },\n removeNode: (state, payload) => {\n const idx = state.nodes.findIndex((n) => n.key === payload.key);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldNode = actions.snapshotDraft(state.nodes[idx]);\n const oldConfigRaw = state.configs[payload.key];\n const oldConfig =\n oldConfigRaw != null ? actions.snapshotDraft(oldConfigRaw) : undefined;\n state.nodes.splice(idx, 1);\n delete state.configs[payload.key];\n return {\n inverse: [\n setNode(\n oldConfig != null\n ? { node: oldNode, config: oldConfig }\n : { node: oldNode, config: undefined },\n ),\n ],\n targets: [payload.key],\n };\n },\n addEdge: (state, payload) => {\n if (state.edges.some((e) => e.key === payload.edge.key))\n return actions.NO_OP_RESULT;\n state.edges.push(payload.edge);\n return {\n inverse: [removeEdge({ key: payload.edge.key })],\n targets: [payload.edge.key],\n };\n },\n\n removeEdge: (state, payload) => {\n const idx = state.edges.findIndex((e) => e.key === payload.key);\n if (idx === -1) return actions.NO_OP_RESULT;\n const oldEdge = actions.snapshotDraft(state.edges[idx]);\n state.edges.splice(idx, 1);\n return {\n inverse: [addEdge({ edge: oldEdge })],\n targets: [payload.key],\n };\n },\n // The inverse of SetConfig is imperfect for keys the action newly introduces:\n // SetConfig only merges, so it cannot remove keys that did not previously exist. The\n // inverse here restores values for keys that DID exist before the merge; keys added\n // by the action remain on undo as phantom fields. A future ReplaceConfig action can\n // close the gap by enabling wholesale replacement.\n setConfig: (state, payload) => {\n const existingRaw = state.configs[payload.key];\n if (existingRaw != null) {\n const existing = actions.snapshotDraft(existingRaw);\n const restoreFields: record.Unknown = {};\n for (const k of Object.keys(payload.config))\n if (existing[k] !== undefined) restoreFields[k] = existing[k];\n state.configs[payload.key] = { ...existing, ...payload.config };\n if (Object.keys(restoreFields).length === 0)\n return { inverse: [], targets: [payload.key] };\n return {\n inverse: [setConfig({ key: payload.key, config: restoreFields })],\n targets: [payload.key],\n };\n }\n let cfg = payload.config;\n const edge = state.edges.find((e) => e.key === payload.key);\n if (edge != null) {\n const srcCfg = state.configs[edge.source.node] as\n { color?: color.Crude } | undefined;\n if (srcCfg?.color != null && !color.isZero(srcCfg.color))\n cfg = { ...cfg, color: srcCfg.color };\n }\n state.configs[payload.key] = cfg;\n return { inverse: [], targets: [payload.key] };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.schematic : undefined;\n\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n // A drag dispatches a stream of `set_node_position` per frame, plus `set_config`\n // companions synthesized by augmentWithEdgeSegments for any affected edges. Both\n // shapes are part of one user gesture and must coalesce together; classify them all\n // as \"move\" so the per-kind coalesce window collapses them into a single undoable.\n const hasMove = actions.some((a) => a.type === \"set_node_position\");\n const onlyMoveOrSegment = actions.every(\n (a) => a.type === \"set_node_position\" || a.type === \"set_config\",\n );\n if (hasMove && onlyMoveOrSegment) return \"move\";\n if (actions.length === 1) return actions[0].type;\n return \"transaction\";\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { color, spatial, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\n/**\n * Region is a visual styling area within a symbol state, targeting specific SVG\n * elements for dynamic coloring.\n */\nexport const regionZ = z.object({\n /** key is the region identifier. */\n key: z.string(),\n /** name is a human-readable name for the region. */\n name: z.string(),\n /** selectors contains CSS selectors targeting SVG elements within the symbol. */\n selectors: z\n .string()\n .array()\n .default(() => []),\n /** strokeColor is an optional stroke color override for the region. */\n strokeColor: color.colorZ.optional(),\n /** fillColor is an optional fill color override for the region. */\n fillColor: color.colorZ.optional(),\n});\nexport interface Region extends z.infer<typeof regionZ> {}\n\n/** Handle is a connection point on a symbol for linking to other diagram elements. */\nexport const handleZ = z.object({\n /** key is the handle identifier. */\n key: z.string(),\n /** position is the (x, y) coordinate within the symbol's local space. */\n position: spatial.xyZ,\n /** orientation is the direction the handle faces (top, right, bottom, left). */\n orientation: spatial.outerLocationZ,\n});\nexport interface Handle extends z.infer<typeof handleZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/** State is a named visual state of a symbol with regional styling configurations. */\nexport const stateZ = z.object({\n /** key is the state identifier. */\n key: z.string(),\n /** name is a human-readable name for this state. */\n name: z.string(),\n /** regions contains style regions defining visual appearance for this state. */\n regions: regionZ.array().default(() => []),\n});\nexport interface State extends z.infer<typeof stateZ> {}\n\n/**\n * Spec is the complete symbol definition including geometry, states, handles, and\n * rendering properties.\n */\nexport const specZ = z.object({\n /** svg is the SVG markup defining the symbol's visual geometry. */\n svg: z.string().min(1),\n /** states contains available visual states with regional styling configurations. */\n states: stateZ.array().default(() => []),\n /** variant is the symbol variant: 'static' or 'actuator'. */\n variant: z.string().min(1),\n /** handles contains connection points for linking to other diagram elements. */\n handles: handleZ.array().default(() => []),\n /** scale is the symbol scale factor. */\n scale: z.number().default(1),\n /** strokeScaled is true when stroke width scales with the symbol size. */\n strokeScaled: z.boolean().default(false),\n /**\n * previewViewport is an optional viewport configuration for symbol preview rendering.\n */\n previewViewport: spatial.viewportZ.optional(),\n});\nexport interface Spec extends z.infer<typeof specZ> {}\n\n/**\n * Symbol is a persisted schematic symbol defining reusable visual components for\n * diagrams.\n */\nexport const symbolZ = z.object({\n /** key is the unique identifier for this symbol. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the symbol. */\n name: z.string().min(1),\n /** data is the complete symbol specification. */\n data: specZ,\n});\nexport interface Symbol extends z.infer<typeof symbolZ> {}\nexport interface New extends z.input<typeof symbolZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"schematic_symbol\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n type FileTransport,\n type UnaryClient,\n type UploadBody,\n} from \"@synnaxlabs/freighter\";\nimport { array, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { group } from \"@/group\";\nimport { imex } from \"@/imex\";\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Symbol,\n symbolZ,\n} from \"@/schematic/symbol/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_schematic_symbol_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_schematic_symbol_delete\";\n\nconst createReqZ = z.object({ symbols: symbolZ.array(), parent: ontology.idZ });\nconst renameReqZ = z.object({ key: keyZ, name: z.string() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\n// The server only understands keys and searchTerm; parent scoping is resolved\n// client-side through the ontology, so it never reaches the wire.\nconst wireRetrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n searchTerm: z.string().optional(),\n});\n\nconst retrieveRequestZ = wireRetrieveRequestZ.extend({\n parent: ontology.idZ.optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nconst retrieveParamsZ = z.union([singleRetrieveParamsZ, wireRetrieveRequestZ]);\n\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveRequestZ>;\nexport type RetrieveParams = RetrieveSingleParams | RetrieveMultipleParams;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst retrieveResZ = z.object({ symbols: symbolZ.array().default(() => []) });\nconst createResZ = z.object({ symbols: symbolZ.array() });\nconst emptyResZ = z.object({});\nconst retrieveGroupReqZ = z.object({});\nconst retrieveGroupResZ = z.object({ group: group.groupZ });\nconst exportGroupReqZ = z.object({ key: group.keyZ, encoding: imex.encodingZ });\nconst importGroupResZ = z.object({ group: group.groupZ });\nconst deleteGroupReqZ = z.object({ key: group.keyZ });\n\nexport interface CreateParams extends New {\n parent: ontology.ID;\n}\n\nexport interface CreateMultipleParams {\n symbols: New[];\n parent: ontology.ID;\n}\n\n/** Query fields only the server can evaluate. */\nconst SERVER_FIELDS = [\"searchTerm\"] as const;\n\nconst childRel = (parent: ontology.ID, key: Key): ontology.Relationship => ({\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: ontologyID(key),\n});\n\nconst matchChildRel = (rel: ontology.Relationship, parent: ontology.ID): boolean =>\n ontology.matchRelationship(rel, {\n from: parent,\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: { type: \"schematic_symbol\" },\n });\n\nexport interface ClientConfig {\n unary: UnaryClient;\n file: FileTransport;\n ontology: ontology.Client;\n cache: query.Cache;\n groupStore: query.Table<group.Key, group.Group>;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Symbol> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Symbol>;\n\n constructor(cfg: ClientConfig) {\n const { cache, ontology: ontologyClient } = cfg;\n const store = cache.createTable<Key, Symbol>({\n name: \"schematicSymbols\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, symbolZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"schematic symbol\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.fetchRequest(req),\n matches: (sym, req) => this.requestFilter(req)(sym),\n serverFields: SERVER_FIELDS,\n watch: [\n query.watch(\n ontologyClient.cache.relationships,\n (event, req: RetrieveRequest) => {\n if (req.parent == null) return null;\n const rel =\n event.variant === \"set\"\n ? event.value\n : ontology.relationshipZ.parse(event.key);\n if (!matchChildRel(rel, req.parent)) return null;\n return [rel.to.key];\n },\n ),\n ],\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(options: CreateParams): Promise<Symbol>;\n async create(options: CreateMultipleParams): Promise<Symbol[]>;\n async create(\n options: CreateParams | CreateMultipleParams,\n ): Promise<Symbol | Symbol[]> {\n const isMany = \"symbols\" in options;\n const symbols = isMany ? options.symbols : [options];\n const res = await this.cfg.unary.send(\n \"/schematic/symbol/create\",\n { symbols, parent: options.parent },\n createReqZ,\n createResZ,\n );\n // Relationships first: parent-scoped answers check membership when the\n // symbol write lands.\n const rels = this.cfg.ontology.cache.relationships;\n res.symbols.forEach((s) => {\n const rel = childRel(options.parent, s.key);\n rels.set(ontology.relationshipToString(rel), rel);\n });\n this.store.set(res.symbols);\n return isMany ? res.symbols : res.symbols[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => query.partialUpdate(this.store, key, { name });\n await query.optimistic({\n rollbacks: [rename()],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/schematic/symbol/rename\",\n { key, name },\n renameReqZ,\n emptyResZ,\n ),\n });\n rename();\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => this.store.delete(keysArr);\n await query.optimistic({\n rollbacks: [drop()],\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/schematic/symbol/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n this.cfg.ontology.cache.relationships.delete(\n (r) =>\n r.type === ontology.PARENT_OF_RELATIONSHIP_TYPE &&\n r.to.type === \"schematic_symbol\" &&\n keysArr.includes(r.to.key),\n );\n }\n\n /**\n * Exports every symbol in the group as a bundle: a zip archive holding one JSON file\n * per symbol beside a manifest.json naming the group. Two symbols that take the same\n * file name keep distinct names through a numeric suffix, and children that are not\n * symbols are skipped. The caller pipes the stream wherever it likes without the\n * client buffering the whole archive.\n * @param options - the export options, including the serialization member files are\n * written in.\n * @returns the bundle as a stream of zip bytes.\n */\n async exportGroup(\n key: group.Key,\n options: imex.Options,\n ): Promise<ReadableStream<Uint8Array>> {\n return await this.cfg.file.download(\n \"/schematic/symbol/group/export\",\n { key, encoding: options.encoding },\n exportGroupReqZ,\n { encoding: \"ZIP\" },\n );\n }\n\n /**\n * Imports a symbol group bundle: a zip archive holding one JSON envelope per symbol\n * beside a manifest.json naming the group. The Core creates a fresh group under the\n * permanent symbol group and imports every member in a single transaction, so a\n * failure leaves nothing behind.\n * @returns the created group.\n * @throws {ValidationError} if the manifest is missing, malformed, or of another\n * bundle kind, if two member names collide, or if a member is not a symbol.\n */\n async importGroup(data: UploadBody): Promise<group.Group> {\n const res = await this.cfg.file.upload(\n \"/schematic/symbol/group/import\",\n data,\n { encoding: \"ZIP\" },\n importGroupResZ,\n );\n const parent = await this.retrieveGroup();\n this.cfg.groupStore.set(res.group);\n const rel: ontology.Relationship = {\n from: group.ontologyID(parent.key),\n type: ontology.PARENT_OF_RELATIONSHIP_TYPE,\n to: group.ontologyID(res.group.key),\n };\n this.cfg.ontology.cache.relationships.set(ontology.relationshipToString(rel), rel);\n return res.group;\n }\n\n /**\n * Deletes the group and every symbol in it. The Core removes both in a single\n * transaction, so a failure leaves the group and its symbols untouched. A child that\n * is not a symbol survives: the Core moves it to the permanent symbol group.\n */\n async deleteGroup(key: group.Key, opts: query.WriteOptions = {}): Promise<void> {\n const groupID = group.ontologyID(key);\n const rels = this.cfg.ontology.cache.relationships;\n // Read the members before the delete drops the relationships naming them.\n const memberKeys = rels.get((r) => matchChildRel(r, groupID)).map((r) => r.to.key);\n const drop = () => [\n this.store.delete(memberKeys),\n this.cfg.groupStore.delete(key),\n // Both the relationships to the group's children and the one naming the group as\n // its parent's child: the group and every symbol in it are gone.\n rels.delete(\n (r) =>\n r.type === ontology.PARENT_OF_RELATIONSHIP_TYPE &&\n (ontology.idsEqual(r.from, groupID) || ontology.idsEqual(r.to, groupID)),\n ),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/schematic/symbol/group/delete\",\n { key },\n deleteGroupReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n async retrieveGroup(): Promise<group.Group> {\n const res = await this.cfg.unary.send(\n \"/schematic/symbol/retrieve-group\",\n {},\n retrieveGroupReqZ,\n retrieveGroupResZ,\n );\n return res.group;\n }\n\n private async execRetrieve(\n params: RetrieveSingleParams | z.input<typeof wireRetrieveRequestZ>,\n ): Promise<Symbol[]> {\n const res = await this.cfg.unary.send(\n \"/schematic/symbol/retrieve\",\n params,\n retrieveParamsZ,\n retrieveResZ,\n );\n return res.symbols;\n }\n\n /** Resolves a parent scope to its symbol children's keys via the ontology. */\n private async resolveChildKeys(parent: ontology.ID): Promise<Key[]> {\n // The children space writes the parent relationships through, so\n // membership checks in requestFilter see them.\n const children = await this.cfg.ontology.children.retrieve({\n ids: parent,\n types: [\"schematic_symbol\"],\n });\n return children.map(({ id: { key } }) => key);\n }\n\n private async fetchRequest(req: RetrieveRequest): Promise<Symbol[]> {\n const { parent, ...rest } = req;\n if (parent == null) return await this.execRetrieve(rest);\n const keys = await this.resolveChildKeys(parent);\n if (keys.length === 0) return [];\n if (primitive.isZero(rest.searchTerm)) return await this.store.retrieve(keys);\n return await this.execRetrieve({ keys, searchTerm: rest.searchTerm });\n }\n\n /**\n * Client-side matching for a request: exact for key sets and parent\n * membership via the relationship table. Server-computed shapes (search)\n * never reach this filter; they refetch instead.\n */\n private requestFilter(req: RetrieveRequest): (s: Symbol) => boolean {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (s) => {\n if (keySet != null && !keySet.has(s.key)) return false;\n if (req.parent != null && !this.isChildOf(req.parent, s.key)) return false;\n return true;\n };\n }\n\n private isChildOf(parent: ontology.ID, key: Key): boolean {\n return this.cfg.ontology.cache.relationships.has(\n ontology.relationshipToString(childRel(parent, key)),\n );\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/schematic/symbol/client\";\nexport * from \"@/schematic/symbol/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type FileTransport, type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, primitive, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { type group } from \"@/group\";\nimport { type ontology } from \"@/ontology\";\nimport { project } from \"@/project\";\nimport { query } from \"@/query\";\nimport { createOf, kindOf, reduceAll } from \"@/schematic/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/schematic/actions.gen\";\nimport { symbol } from \"@/schematic/symbol\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Schematic,\n schematicZ,\n} from \"@/schematic/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_schematic_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_schematic_delete\";\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst copyReqZ = z.object({\n key: keyZ,\n name: z.string(),\n snapshot: z.boolean(),\n});\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nexport const retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveReqZ]);\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveReqZ>;\nexport type CopyParams = z.input<typeof copyReqZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\nconst retrieveResZ = z.object({ schematics: schematicZ.array() });\n\nconst createReqZ = z.object({\n project: project.keyZ,\n schematics: schematicZ.array(),\n});\nconst createResZ = z.object({ schematics: schematicZ.array() });\n\nconst copyResZ = z.object({ schematic: schematicZ });\nconst emptyResZ = z.object({});\n\n/**\n * Client-side matching for a request: exact for key sets, the only shape a\n * schematic request carries.\n */\nconst requestFilter = (req: RetrieveRequest): ((s: Schematic) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n return (s) => keySet == null || keySet.has(s.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n file: FileTransport;\n ontology: ontology.Client;\n cache: query.Cache;\n groupStore: query.Table<group.Key, group.Group>;\n}\n\nexport class Client extends query.Retriever<\n typeof retrieveMultiParamsZ,\n Key,\n Schematic\n> {\n readonly symbols: symbol.Client;\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Schematic>;\n private readonly dispatcher: actions.Controller<Key, Schematic, Action>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n // Dispatch mutates documents server-side, so fetched copies never clobber\n // a doc holding locally replayed edits: the table hydrates if-absent.\n const store = cache.createTable<Key, Schematic>({\n name: \"schematics\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, Schematic, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n super(cache, {\n name: \"schematic\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (schematic, req) => requestFilter(req)(schematic),\n },\n });\n this.cfg = cfg;\n this.symbols = new symbol.Client(cfg);\n this.store = store;\n this.dispatcher = dispatcher;\n }\n\n async create(\n project: project.Key,\n schematic: New,\n opts?: query.WriteOptions<Schematic[]>,\n ): Promise<Schematic>;\n async create(\n project: project.Key,\n schematics: New[],\n opts?: query.WriteOptions<Schematic[]>,\n ): Promise<Schematic[]>;\n async create(\n project: project.Key,\n schematics: New | New[],\n opts: query.WriteOptions<Schematic[]> = {},\n ): Promise<Schematic | Schematic[]> {\n const isMany = Array.isArray(schematics);\n const optimistic = array\n .toArray(schematics)\n .map((s) => zod.parse(schematicZ, s, { label: \"schematic\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/schematic/create\",\n { project, schematics: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.schematics);\n return isMany ? res.schematics : res.schematics[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.sendDispatch(key, \"\", [renameAction({ name })]),\n });\n rename();\n }\n\n /**\n * Applies actions to the cached document and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the document isn't cached.\n * Rolls back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<Schematic, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the document's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the document's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the document has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the document has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the document's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/schematic/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/schematic/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every schematic delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n async copy(params: CopyParams): Promise<Schematic> {\n const res = await this.cfg.unary.send(\n \"/schematic/copy\",\n params,\n copyReqZ,\n copyResZ,\n );\n this.store.set(res.schematic);\n return res.schematic;\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<Schematic[]> {\n const res = await this.cfg.unary.send(\n \"/schematic/retrieve\",\n params,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.schematics;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/schematic/actions\";\nexport * from \"@/schematic/actions.gen\";\nexport * from \"@/schematic/client\";\nexport * from \"@/schematic/symbol\";\nexport * from \"@/schematic/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { caseconv, record, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\n/** Cell is a single cell in a table, identified by key and variant. */\nexport const cellZ = z.object({\n /** key is the unique identifier for this cell within the table. */\n key: z.string(),\n /**\n * variant is the cell variant identifier (e.g. \"text\", \"value\"). The variant\n * determines the shape of props and which Pluto cell component renders the cell.\n */\n variant: z.string(),\n /**\n * props is the variant-specific cell configuration. The shape is determined by the\n * variant; the wire format intentionally stores it as an opaque record so new\n * variants can be added without a schema migration.\n */\n props: caseconv.preserveCase(record.unknownZ().default(() => ({}))),\n});\nexport interface Cell extends z.infer<typeof cellZ> {}\n\n/** Row is a single row in a table, with height and ordered cell keys. */\nexport const rowZ = z.object({\n /** size is the height of the row in pixels. */\n size: z.number(),\n /**\n * cells is the ordered list of cell keys in this row from left to right. Each key\n * points at an entry in the table's cells map.\n */\n cells: z\n .string()\n .array()\n .default(() => []),\n});\nexport interface Row extends z.infer<typeof rowZ> {}\n\n/** Column is a single column in a table, with width. */\nexport const columnZ = z.object({\n /** size is the width of the column in pixels. */\n size: z.number(),\n});\nexport interface Column extends z.infer<typeof columnZ> {}\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\nexport const cellTemplateZ = cellZ.omit({ key: true });\nexport interface CellTemplate extends z.infer<typeof cellTemplateZ> {}\n\n/**\n * Table is a tabular data display component for viewing structured telemetry data.\n * Tables support multiple columns, channel data sources, and customizable formatting\n * options.\n */\nexport const tableZ = z.object({\n /** key is the unique identifier for this table. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the table. */\n name: z.string().min(1, \"name is required\"),\n /** rows are the table rows in display order, top to bottom. */\n rows: rowZ.array().default(() => []),\n /** columns are the table columns in display order, left to right. */\n columns: columnZ.array().default(() => []),\n /**\n * cells contains all cells in the table, keyed by cell key. Cell positions are\n * derived from rows[*].cells[*] references; cells not referenced by any row are\n * orphaned and will be pruned on the next structural edit.\n */\n cells: caseconv.preserveCase(z.record(z.string(), cellZ).default(() => ({}))),\n});\nexport interface Table extends z.infer<typeof tableZ> {}\nexport interface New extends z.input<typeof tableZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"table\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\nimport { zod } from \"@synnaxlabs/x\";\nimport { type Draft } from \"immer\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { cellTemplateZ, cellZ, keyZ, type Table, tableZ } from \"@/table/types.gen\";\n\n/**\n * Create replaces the document with the given created state. Emitted by the Core on\n * create so remote caches ingest new documents; clients never dispatch it.\n */\nexport const createPayloadZ = z.object({\n table: tableZ,\n});\n\nexport type CreatePayload = z.infer<typeof createPayloadZ>;\n\n/** Rename renames the table. */\nexport const renamePayloadZ = z.object({\n name: z.string(),\n});\n\nexport type RenamePayload = z.infer<typeof renamePayloadZ>;\n\n/**\n * AddRow inserts a row at the given index. Three flows:\n *\n * 1. User gesture with cell_template against a non-empty table: replicate the template\n * once per existing column. 2. User gesture with cell_template against a fully-empty\n * table: seed a 1x1 grid (one template replica plus one default-sized column). 3. Undo\n * replay of RemoveRow (cell_template is null, cells is non-empty): use cells as-is. If\n * the original RemoveRow had stripped the table down to no columns, the explicit cells\n * trigger the same column-bootstrap as flow 2.\n *\n * Derived replica keys come from the template's key with the last four hex digits\n * replaced by the column index. Out-of-range indices clamp to the end.\n */\nexport const addRowPayloadZ = z.object({\n index: z.uint32(),\n size: z.number(),\n cells: cellZ.array().default(() => []),\n cellTemplate: cellZ.optional(),\n});\n\nexport type AddRowPayload = z.infer<typeof addRowPayloadZ>;\n\n/**\n * RemoveRow removes the row at the given index. All cells referenced by the removed row\n * are also dropped from the cells map. No-op if the index is out of range.\n */\nexport const removeRowPayloadZ = z.object({\n index: z.uint32(),\n});\n\nexport type RemoveRowPayload = z.infer<typeof removeRowPayloadZ>;\n\n/**\n * AddCol inserts a column at the given index. Three flows:\n *\n * 1. User gesture with cell_template against a non-empty table: replicate the template\n * once per existing row. 2. User gesture with cell_template against a fully-empty\n * table: seed a 1x1 grid (one template replica plus one default-sized row). 3. Undo\n * replay of RemoveCol (cell_template is null, cells is non-empty): use cells as-is. If\n * the original RemoveCol had stripped the table down to no rows, the explicit cells\n * trigger the same row-bootstrap as flow 2.\n *\n * Derived replica keys come from the template's key with the last four hex digits\n * replaced by the row index. Cells whose row index exceeds the row count are added to\n * the cells map but not referenced by any row. Out-of-range indices clamp to the end of\n * every row's cells list.\n */\nexport const addColPayloadZ = z.object({\n index: z.uint32(),\n size: z.number(),\n cells: cellZ.array().default(() => []),\n cellTemplate: cellZ.optional(),\n});\n\nexport type AddColPayload = z.infer<typeof addColPayloadZ>;\n\n/**\n * RemoveCol removes the column at the given index. All cells in that column (across\n * every row) are dropped from the cells map. No-op if the index is out of range.\n */\nexport const removeColPayloadZ = z.object({\n index: z.uint32(),\n});\n\nexport type RemoveColPayload = z.infer<typeof removeColPayloadZ>;\n\n/** ResizeRow resizes the row at the given index. No-op if the index is out of range. */\nexport const resizeRowPayloadZ = z.object({\n index: z.uint32(),\n size: z.number(),\n});\n\nexport type ResizeRowPayload = z.infer<typeof resizeRowPayloadZ>;\n\n/**\n * ResizeCol resizes the column at the given index. No-op if the index is out of range.\n */\nexport const resizeColPayloadZ = z.object({\n index: z.uint32(),\n size: z.number(),\n});\n\nexport type ResizeColPayload = z.infer<typeof resizeColPayloadZ>;\n\n/**\n * SetCell replaces the cell at cell.key with the provided value. No-op if no cell with\n * that key exists in the table.\n */\nexport const setCellPayloadZ = z.object({\n cell: cellZ,\n});\n\nexport type SetCellPayload = z.infer<typeof setCellPayloadZ>;\n\n/**\n * EraseCells erases the cells whose keys are in cells. Any row whose every cell is in\n * the selection is removed entirely; same for columns. Cells that survive that\n * row/column removal have their variant and props replaced with the template's, keeping\n * their original keys. Cells in the selection whose keys are not in the table's cells\n * map are silently skipped.\n */\nexport const eraseCellsPayloadZ = z.object({\n cells: z\n .string()\n .array()\n .default(() => []),\n template: cellTemplateZ,\n});\n\nexport type EraseCellsPayload = z.infer<typeof eraseCellsPayloadZ>;\n\nexport const actionZ = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"create\"), create: createPayloadZ }),\n z.object({ type: z.literal(\"rename\"), rename: renamePayloadZ }),\n z.object({ type: z.literal(\"add_row\"), addRow: addRowPayloadZ }),\n z.object({ type: z.literal(\"remove_row\"), removeRow: removeRowPayloadZ }),\n z.object({ type: z.literal(\"add_col\"), addCol: addColPayloadZ }),\n z.object({ type: z.literal(\"remove_col\"), removeCol: removeColPayloadZ }),\n z.object({ type: z.literal(\"resize_row\"), resizeRow: resizeRowPayloadZ }),\n z.object({ type: z.literal(\"resize_col\"), resizeCol: resizeColPayloadZ }),\n z.object({ type: z.literal(\"set_cell\"), setCell: setCellPayloadZ }),\n z.object({ type: z.literal(\"erase_cells\"), eraseCells: eraseCellsPayloadZ }),\n]);\n\nexport type Action = z.infer<typeof actionZ>;\n\nexport const create = (payload: z.input<typeof createPayloadZ>): Action => ({\n type: \"create\",\n create: zod.parse(createPayloadZ, payload, {\n label: \"table create action payload\",\n }),\n});\n\nexport const rename = (payload: z.input<typeof renamePayloadZ>): Action => ({\n type: \"rename\",\n rename: zod.parse(renamePayloadZ, payload, {\n label: \"table rename action payload\",\n }),\n});\n\nexport const addRow = (payload: z.input<typeof addRowPayloadZ>): Action => ({\n type: \"add_row\",\n addRow: zod.parse(addRowPayloadZ, payload, {\n label: \"table add_row action payload\",\n }),\n});\n\nexport const removeRow = (payload: z.input<typeof removeRowPayloadZ>): Action => ({\n type: \"remove_row\",\n removeRow: zod.parse(removeRowPayloadZ, payload, {\n label: \"table remove_row action payload\",\n }),\n});\n\nexport const addCol = (payload: z.input<typeof addColPayloadZ>): Action => ({\n type: \"add_col\",\n addCol: zod.parse(addColPayloadZ, payload, {\n label: \"table add_col action payload\",\n }),\n});\n\nexport const removeCol = (payload: z.input<typeof removeColPayloadZ>): Action => ({\n type: \"remove_col\",\n removeCol: zod.parse(removeColPayloadZ, payload, {\n label: \"table remove_col action payload\",\n }),\n});\n\nexport const resizeRow = (payload: z.input<typeof resizeRowPayloadZ>): Action => ({\n type: \"resize_row\",\n resizeRow: zod.parse(resizeRowPayloadZ, payload, {\n label: \"table resize_row action payload\",\n }),\n});\n\nexport const resizeCol = (payload: z.input<typeof resizeColPayloadZ>): Action => ({\n type: \"resize_col\",\n resizeCol: zod.parse(resizeColPayloadZ, payload, {\n label: \"table resize_col action payload\",\n }),\n});\n\nexport const setCell = (payload: z.input<typeof setCellPayloadZ>): Action => ({\n type: \"set_cell\",\n setCell: zod.parse(setCellPayloadZ, payload, {\n label: \"table set_cell action payload\",\n }),\n});\n\nexport const eraseCells = (payload: z.input<typeof eraseCellsPayloadZ>): Action => ({\n type: \"erase_cells\",\n eraseCells: zod.parse(eraseCellsPayloadZ, payload, {\n label: \"table erase_cells action payload\",\n }),\n});\n\nexport type HandlerResult = actions.HandlerResult<Action>;\n\nexport type ReduceAllResult = actions.ReduceAllResult<Table, Action>;\n\nexport interface Handlers {\n create: (state: Draft<Table>, payload: CreatePayload) => HandlerResult;\n rename: (state: Draft<Table>, payload: RenamePayload) => HandlerResult;\n addRow: (state: Draft<Table>, payload: AddRowPayload) => HandlerResult;\n removeRow: (state: Draft<Table>, payload: RemoveRowPayload) => HandlerResult;\n addCol: (state: Draft<Table>, payload: AddColPayload) => HandlerResult;\n removeCol: (state: Draft<Table>, payload: RemoveColPayload) => HandlerResult;\n resizeRow: (state: Draft<Table>, payload: ResizeRowPayload) => HandlerResult;\n resizeCol: (state: Draft<Table>, payload: ResizeColPayload) => HandlerResult;\n setCell: (state: Draft<Table>, payload: SetCellPayload) => HandlerResult;\n eraseCells: (state: Draft<Table>, payload: EraseCellsPayload) => HandlerResult;\n}\n\nexport const createReduceAll = (handlers: Handlers) =>\n actions.createReduceAll<Table, Action>((state, action) => {\n switch (action.type) {\n case \"create\":\n return handlers.create(state, action.create);\n case \"rename\":\n return handlers.rename(state, action.rename);\n case \"add_row\":\n return handlers.addRow(state, action.addRow);\n case \"remove_row\":\n return handlers.removeRow(state, action.removeRow);\n case \"add_col\":\n return handlers.addCol(state, action.addCol);\n case \"remove_col\":\n return handlers.removeCol(state, action.removeCol);\n case \"resize_row\":\n return handlers.resizeRow(state, action.resizeRow);\n case \"resize_col\":\n return handlers.resizeCol(state, action.resizeCol);\n case \"set_cell\":\n return handlers.setCell(state, action.setCell);\n case \"erase_cells\":\n return handlers.eraseCells(state, action.eraseCells);\n }\n });\n\nexport const scopedActionZ = actions.scopedZ(keyZ, actionZ);\n\nexport const dispatchReqZ = actions.dispatchReqZ(keyZ, actionZ);\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { actions } from \"@/actions\";\nimport {\n type Action,\n addCol,\n addRow,\n createReduceAll,\n type Handlers,\n removeCol,\n removeRow,\n rename,\n resizeCol,\n resizeRow,\n setCell,\n} from \"@/table/actions.gen\";\nimport { type Cell } from \"@/table/types.gen\";\n\nconst MIN_CELL_DIM = 32;\n// BASE_ROW_DIM and BASE_COL_DIM are the defaults used when an action\n// bootstraps the opposing axis on an empty table.\nconst BASE_ROW_DIM = 36;\nconst BASE_COL_DIM = 72;\n\n// deriveCellKey returns the key for the index-th replica of template. Both reducers run\n// the same scheme so optimistic client state agrees with the server.\nconst deriveCellKey = (templateKey: string, index: number): string => {\n const suffix = index.toString(16).padStart(4, \"0\");\n if (templateKey.length < 36) return `${templateKey}-${suffix}`;\n return templateKey.slice(0, 32) + suffix;\n};\n\n// expandTemplate returns count replicas of template with keys derived via\n// deriveCellKey.\nconst expandTemplate = (template: Cell, count: number): Cell[] =>\n Array.from({ length: count }, (_, i) => ({\n key: deriveCellKey(template.key, i),\n variant: template.variant,\n props: template.props,\n }));\n\nconst handlers: Handlers = {\n create: (state, payload) => {\n Object.assign(state, payload.table);\n return { inverse: [], targets: [payload.table.key] };\n },\n\n rename: (state, payload) => {\n const oldName = state.name;\n state.name = payload.name;\n return {\n inverse: [rename({ name: oldName })],\n targets: [state.key],\n };\n },\n\n addRow: (state, payload) => {\n const cells = payload.cellTemplate\n ? expandTemplate(\n payload.cellTemplate,\n state.columns.length === 0 && state.rows.length === 0\n ? 1\n : state.columns.length,\n )\n : payload.cells;\n if (state.columns.length === 0 && cells.length > 0)\n for (let i = 0; i < cells.length; i++) state.columns.push({ size: BASE_COL_DIM });\n const idx = Math.min(payload.index, state.rows.length);\n const keys = cells.map((c) => c.key);\n state.rows.splice(idx, 0, {\n size: Math.max(payload.size, MIN_CELL_DIM),\n cells: keys,\n });\n for (const c of cells) state.cells[c.key] = c;\n return {\n inverse: [removeRow({ index: idx })],\n targets: keys,\n };\n },\n\n removeRow: (state, payload) => {\n if (payload.index >= state.rows.length) return actions.NO_OP_RESULT;\n const removed = actions.snapshotDraft(state.rows[payload.index]);\n const cells: Cell[] = [];\n for (const k of removed.cells) {\n const c = state.cells[k];\n if (c != null) cells.push(actions.snapshotDraft(c));\n }\n state.rows.splice(payload.index, 1);\n for (const k of removed.cells) delete state.cells[k];\n return {\n inverse: [addRow({ index: payload.index, size: removed.size, cells })],\n targets: removed.cells,\n };\n },\n\n addCol: (state, payload) => {\n const cells = payload.cellTemplate\n ? expandTemplate(\n payload.cellTemplate,\n state.rows.length === 0 && state.columns.length === 0 ? 1 : state.rows.length,\n )\n : payload.cells;\n if (state.rows.length === 0 && cells.length > 0)\n for (let i = 0; i < cells.length; i++)\n state.rows.push({ size: BASE_ROW_DIM, cells: [] });\n const idx = Math.min(payload.index, state.columns.length);\n state.columns.splice(idx, 0, { size: Math.max(payload.size, MIN_CELL_DIM) });\n for (let i = 0; i < state.rows.length; i++) {\n if (i >= cells.length) break;\n const rowIdx = Math.min(idx, state.rows[i].cells.length);\n state.rows[i].cells.splice(rowIdx, 0, cells[i].key);\n }\n for (const c of cells) state.cells[c.key] = c;\n return {\n inverse: [removeCol({ index: idx })],\n targets: cells.map((c) => c.key),\n };\n },\n\n removeCol: (state, payload) => {\n if (payload.index >= state.columns.length) return actions.NO_OP_RESULT;\n const oldSize = state.columns[payload.index].size;\n const removedCells: Cell[] = [];\n state.columns.splice(payload.index, 1);\n // Rows missing a cell at this column are skipped, not padded. Go AddCol\n // short-circuits when len(cells) < len(rows), so the inverse repopulates\n // only the rows we captured.\n for (let i = 0; i < state.rows.length; i++) {\n if (payload.index >= state.rows[i].cells.length) continue;\n const k = state.rows[i].cells[payload.index];\n const c = state.cells[k];\n if (c != null) removedCells.push(actions.snapshotDraft(c));\n delete state.cells[k];\n state.rows[i].cells.splice(payload.index, 1);\n }\n return {\n inverse: [addCol({ index: payload.index, size: oldSize, cells: removedCells })],\n targets: removedCells.map((c) => c.key),\n };\n },\n\n resizeRow: (state, payload) => {\n if (payload.index >= state.rows.length) return actions.NO_OP_RESULT;\n const oldSize = state.rows[payload.index].size;\n state.rows[payload.index].size = Math.max(payload.size, MIN_CELL_DIM);\n return {\n inverse: [resizeRow({ index: payload.index, size: oldSize })],\n targets: [...state.rows[payload.index].cells],\n };\n },\n\n resizeCol: (state, payload) => {\n if (payload.index >= state.columns.length) return actions.NO_OP_RESULT;\n const oldSize = state.columns[payload.index].size;\n state.columns[payload.index].size = Math.max(payload.size, MIN_CELL_DIM);\n const targets = state.rows\n .map((r) => r.cells[payload.index])\n .filter((k): k is string => k != null);\n return {\n inverse: [resizeCol({ index: payload.index, size: oldSize })],\n targets,\n };\n },\n\n setCell: (state, payload) => {\n const existing = state.cells[payload.cell.key];\n if (existing == null) return actions.NO_OP_RESULT;\n const oldCell = actions.snapshotDraft(existing);\n state.cells[payload.cell.key] = payload.cell;\n return {\n inverse: [setCell({ cell: oldCell })],\n targets: [payload.cell.key],\n };\n },\n\n eraseCells: (state, payload) => {\n if (payload.cells.length === 0) return actions.NO_OP_RESULT;\n const selected = new Set(payload.cells);\n const rowPosOf = new Map<string, { row: number; col: number }>();\n for (let r = 0; r < state.rows.length; r++) {\n const cells = state.rows[r].cells;\n for (let c = 0; c < cells.length; c++) rowPosOf.set(cells[c], { row: r, col: c });\n }\n const rowTally = new Map<number, number>();\n const colTally = new Map<number, number>();\n for (const k of selected) {\n const pos = rowPosOf.get(k);\n if (pos == null) continue;\n rowTally.set(pos.row, (rowTally.get(pos.row) ?? 0) + 1);\n colTally.set(pos.col, (colTally.get(pos.col) ?? 0) + 1);\n }\n const fullRowIdx: number[] = [];\n for (const [rowIdx, tally] of rowTally)\n if (tally > 0 && tally === state.rows[rowIdx].cells.length)\n fullRowIdx.push(rowIdx);\n fullRowIdx.sort((a, b) => a - b);\n const fullColIdx: number[] = [];\n for (const [colIdx, tally] of colTally)\n if (tally === state.rows.length) fullColIdx.push(colIdx);\n fullColIdx.sort((a, b) => a - b);\n const inverse: Action[] = [];\n const targets: string[] = [];\n // Iterate highest-first so earlier removals don't shift later indices;\n // unshift the inverse so undo replays it in ascending order.\n for (let i = fullRowIdx.length - 1; i >= 0; i--) {\n const idx = fullRowIdx[i];\n const removed = actions.snapshotDraft(state.rows[idx]);\n const cells: Cell[] = [];\n for (const k of removed.cells) {\n const c = state.cells[k];\n if (c != null) cells.push(actions.snapshotDraft(c));\n }\n state.rows.splice(idx, 1);\n for (const k of removed.cells) delete state.cells[k];\n inverse.unshift(addRow({ index: idx, size: removed.size, cells }));\n targets.push(...removed.cells);\n }\n for (let i = fullColIdx.length - 1; i >= 0; i--) {\n const idx = fullColIdx[i];\n const oldSize = state.columns[idx].size;\n const removedCells: Cell[] = [];\n state.columns.splice(idx, 1);\n for (let r = 0; r < state.rows.length; r++) {\n if (idx >= state.rows[r].cells.length) continue;\n const k = state.rows[r].cells[idx];\n const c = state.cells[k];\n if (c != null) removedCells.push(actions.snapshotDraft(c));\n delete state.cells[k];\n state.rows[r].cells.splice(idx, 1);\n }\n inverse.unshift(addCol({ index: idx, size: oldSize, cells: removedCells }));\n targets.push(...removedCells.map((c) => c.key));\n }\n for (const k of selected) {\n const existing = state.cells[k];\n if (existing == null) continue;\n const oldCell = actions.snapshotDraft(existing);\n state.cells[k] = {\n key: k,\n variant: payload.template.variant,\n props: payload.template.props,\n };\n inverse.push(setCell({ cell: oldCell }));\n targets.push(k);\n }\n return { inverse, targets };\n },\n};\n\nexport const reduceAll = createReduceAll(handlers);\n\n// createOf hands the dispatch controller the document carried by a create\n// action so frames for never-cached documents ingest instead of drop.\nexport const createOf = (action: Action) =>\n action.type === \"create\" ? action.create.table : undefined;\n\n// kindOf classifies an action batch for the undoable store's per-kind coalesce window.\n// Continuous resize gestures (a stream of resize_row or resize_col actions) collapse\n// into a single undo step; successive set_cell actions on the same cell coalesce\n// per-cell so typing inside one cell collapses to one undo step but switching cells\n// starts a fresh entry; everything else is treated as a discrete user action.\nexport const kindOf = (actions: Action[]): string => {\n if (actions.length === 0) return \"default\";\n if (actions.every((a) => a.type === \"resize_row\" || a.type === \"resize_col\"))\n return \"resize\";\n if (actions.length === 1) {\n const a = actions[0];\n if (a.type === \"set_cell\") return `set_cell:${a.setCell.cell.key}`;\n return a.type;\n }\n return \"transaction\";\n};\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, zod } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { actions } from \"@/actions\";\nimport { type ontology } from \"@/ontology\";\nimport { project } from \"@/project\";\nimport { query } from \"@/query\";\nimport { createOf, kindOf, reduceAll } from \"@/table/actions\";\nimport {\n type Action,\n dispatchReqZ,\n rename as renameAction,\n scopedActionZ,\n} from \"@/table/actions.gen\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type Table,\n tableZ,\n} from \"@/table/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_table_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_table_delete\";\n\nconst deleteReqZ = z.object({ keys: keyZ.array() });\n\nconst retrieveReqZ = z.object({\n keys: keyZ.array(),\n ignoreNotFoundError: z.boolean().optional(),\n});\nconst retrieveMultiParamsZ = retrieveReqZ.or(query.keyListZ(keyZ));\nconst singleRetrieveParamsZ = z\n .object({ key: keyZ })\n .transform(({ key }) => ({ keys: [key] }));\n\nexport const retrieveParamsZ = z.union([singleRetrieveParamsZ, retrieveReqZ]);\nexport type RetrieveParams = z.input<typeof retrieveParamsZ>;\nexport type RetrieveSingleParams = z.input<typeof singleRetrieveParamsZ>;\nexport type RetrieveMultipleParams = z.input<typeof retrieveReqZ>;\n\ninterface RetrieveRequest extends z.infer<typeof retrieveReqZ> {}\n\nconst retrieveResZ = z.object({ tables: tableZ.array().default(() => []) });\n\nconst createReqZ = z.object({ project: project.keyZ, tables: tableZ.array() });\nconst createResZ = z.object({ tables: tableZ.array() });\n\nconst emptyResZ = z.object({});\n\n/**\n * Client-side matching for a request: exact for the requested key set, the\n * only field a request carries.\n */\nconst requestFilter = (req: RetrieveRequest): ((t: Table) => boolean) => {\n const keySet = new Set(req.keys);\n return (t) => keySet.has(t.key);\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, Table> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, Table>;\n private readonly dispatcher: actions.Controller<Key, Table, Action>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n // Dispatch mutates documents server-side, so fetched copies never clobber\n // a doc holding locally replayed edits: the table hydrates if-absent.\n const store = cache.createTable<Key, Table>({\n name: \"tables\",\n hydrate: \"if-absent\",\n fetch: async (keys) =>\n await this.execRetrieve({ keys, ignoreNotFoundError: true }),\n listen: [query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ)],\n });\n const dispatcher = new actions.Controller<Key, Table, Action>({\n store,\n onError: cache.onError,\n reduce: reduceAll,\n kindOf,\n createOf,\n });\n cache.listen(dispatcher.listener(SET_CHANNEL_NAME, scopedActionZ));\n super(cache, {\n name: \"table\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (table, req) => requestFilter(req)(table),\n },\n });\n this.cfg = cfg;\n this.store = store;\n this.dispatcher = dispatcher;\n }\n\n async create(\n project: project.Key,\n table: New,\n opts?: query.WriteOptions<Table[]>,\n ): Promise<Table>;\n async create(\n project: project.Key,\n tables: New[],\n opts?: query.WriteOptions<Table[]>,\n ): Promise<Table[]>;\n async create(\n project: project.Key,\n tables: New | New[],\n opts: query.WriteOptions<Table[]> = {},\n ): Promise<Table | Table[]> {\n const isMany = Array.isArray(tables);\n const optimistic = array\n .toArray(tables)\n .map((t) => zod.parse(tableZ, t, { label: \"table\" }));\n const res = await query.optimistic({\n rollbacks: [this.store.set(optimistic)],\n onOptimistic: () => opts.onOptimistic?.(optimistic),\n commit: async () =>\n await this.cfg.unary.send(\n \"/table/create\",\n { project, tables: optimistic },\n createReqZ,\n createResZ,\n ),\n });\n this.store.set(res.tables);\n return isMany ? res.tables : res.tables[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => await this.sendDispatch(key, \"\", [renameAction({ name })]),\n });\n rename();\n }\n\n /**\n * Applies actions to the cached table and sends them to the server, recording an\n * undoable entry. Returns false without side effects when the table isn't cached.\n * Rolls back the local apply and rethrows on send failure.\n */\n async dispatch(\n key: Key,\n actions: Action | Action[],\n opts: actions.Options<Table, Action> = {},\n ): Promise<boolean> {\n return await this.dispatcher.dispatch(\n key,\n array.toArray(actions),\n this.dispatchSender(key),\n opts,\n );\n }\n\n /**\n * Reverts the table's most recent undoable entry. Returns false when\n * nothing is undoable.\n */\n async undo(key: Key): Promise<boolean> {\n return await this.dispatcher.undo(key, this.dispatchSender(key));\n }\n\n /**\n * Re-applies the table's most recently undone entry. Returns false when\n * nothing is redoable.\n */\n async redo(key: Key): Promise<boolean> {\n return await this.dispatcher.redo(key, this.dispatchSender(key));\n }\n\n /** Whether the table has a live undo entry. */\n hasUndo(key: Key): boolean {\n return this.dispatcher.hasUndo(key);\n }\n\n /** Whether the table has a live redo entry. */\n hasRedo(key: Key): boolean {\n return this.dispatcher.hasRedo(key);\n }\n\n /**\n * Subscribes to changes in the table's undo/redo stacks. Returns a\n * destructor that unsubscribes.\n */\n onUndoStateChange(callback: () => void, key?: Key): destructor.Destructor {\n return this.dispatcher.onUndoStateChange(callback, key);\n }\n\n /** Stages actions committed atomically as one undoable entry. */\n beginTransaction(key: Key, kind?: string): actions.Transaction<Action> {\n return this.dispatcher.transaction(key, this.dispatchSender(key), kind);\n }\n\n private dispatchSender(key: Key): actions.SendDispatch<Action> {\n return async (actions, dispatchKey) =>\n await this.sendDispatch(key, dispatchKey, actions);\n }\n\n private async sendDispatch(\n key: Key,\n dispatchKey: string,\n actions: Action[],\n ): Promise<void> {\n await this.cfg.unary.send(\n \"/table/dispatch\",\n { key, dispatchKey, actions },\n dispatchReqZ,\n emptyResZ,\n );\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ontologyID(keysArr)),\n this.store.delete(keysArr),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/table/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every table delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<Table[]> {\n const res = await this.cfg.unary.send(\n \"/table/retrieve\",\n params,\n retrieveReqZ,\n retrieveResZ,\n );\n return res.tables;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/table/actions\";\nexport * from \"@/table/actions.gen\";\nexport * from \"@/table/client\";\nexport * from \"@/table/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\n// Code generated by Oracle. DO NOT EDIT.\n\nimport { record, uuid } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\n\nexport const keyZ = z.uuid();\nexport type Key = z.infer<typeof keyZ>;\n\n/**\n * View is a persisted view configuration storing visualization settings and query\n * parameters for line plots, tables, schematics, and other view types.\n */\nexport const viewZ = z.object({\n /** key is the unique identifier for this view. */\n key: keyZ.default(uuid.create),\n /** name is a human-readable name for the view. */\n name: z.string(),\n /** type is the view type identifier (e.g., 'lineplot', 'table', 'schematic'). */\n type: z.string(),\n /**\n * query is a type-agnostic JSON object containing view-specific configuration and\n * query parameters.\n */\n query: record.unknownZ().default(() => ({})),\n});\nexport interface View extends z.infer<typeof viewZ> {}\nexport interface New extends z.input<typeof viewZ> {}\n\nexport const ontologyID = ontology.createIDFactory<Key>(\"view\");\nexport const TYPE_ONTOLOGY_ID = ontologyID(\"\");\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport { type UnaryClient } from \"@synnaxlabs/freighter\";\nimport { array, type destructor, primitive } from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { ontology } from \"@/ontology\";\nimport { query } from \"@/query\";\nimport {\n type Key,\n keyZ,\n type New,\n ontologyID,\n type View,\n viewZ,\n} from \"@/view/types.gen\";\n\nexport const SET_CHANNEL_NAME = \"sy_view_set\";\nexport const DELETE_CHANNEL_NAME = \"sy_view_delete\";\n\nconst createReqZ = z.object({ views: viewZ.array() });\nconst createResZ = z.object({ views: viewZ.array() });\nconst deleteReqZ = z.object({ keys: keyZ.array() });\nconst emptyResZ = z.object({});\n\nconst retrieveRequestZ = z.object({\n keys: keyZ.array().optional(),\n types: z.string().array().optional(),\n searchTerm: z.string().optional(),\n offset: z.number().optional(),\n limit: z.number().optional(),\n});\nconst retrieveMultiParamsZ = retrieveRequestZ.or(query.keyListZ(keyZ));\n\nexport type RetrieveSingleParams = { key: Key };\nexport interface RetrieveMultipleParams extends z.input<typeof retrieveRequestZ> {}\n\ninterface RetrieveRequest extends z.infer<typeof retrieveRequestZ> {}\n\nconst retrieveResponseZ = z.object({ views: viewZ.array().default(() => []) });\n\n/**\n * Client-side matching for a request: key and type sets. Server-computed\n * shapes (search, limit/offset) never reach this filter; they refetch instead.\n */\nconst requestFilter = (req: RetrieveRequest): ((v: View) => boolean) => {\n const keySet = primitive.isNonZero(req.keys) ? new Set(req.keys) : undefined;\n const typeSet = primitive.isNonZero(req.types) ? new Set(req.types) : undefined;\n return (v) => {\n if (keySet != null && !keySet.has(v.key)) return false;\n if (typeSet != null && !typeSet.has(v.type)) return false;\n return true;\n };\n};\n\nexport interface ClientConfig {\n unary: UnaryClient;\n cache: query.Cache;\n ontology: ontology.Client;\n}\n\nexport class Client extends query.Retriever<typeof retrieveMultiParamsZ, Key, View> {\n private readonly cfg: ClientConfig;\n private readonly store: query.Table<Key, View>;\n\n constructor(cfg: ClientConfig) {\n const { cache } = cfg;\n const store = cache.createTable<Key, View>({\n name: \"views\",\n fetch: async (keys) => await this.execRetrieve({ keys }),\n listen: [\n query.createSetListener(SET_CHANNEL_NAME, viewZ),\n query.createDeleteListener(DELETE_CHANNEL_NAME, keyZ),\n ],\n });\n super(cache, {\n name: \"view\",\n table: store,\n request: {\n schema: retrieveMultiParamsZ,\n fetch: async (req) => await this.execRetrieve(req),\n matches: (view, req) => requestFilter(req)(view),\n },\n });\n this.cfg = cfg;\n this.store = store;\n }\n\n async create(view: New): Promise<View>;\n async create(views: New[]): Promise<View[]>;\n async create(views: New | New[]): Promise<View | View[]> {\n const isMany = Array.isArray(views);\n const res = await this.cfg.unary.send(\n \"/view/create\",\n { views: array.toArray(views) },\n createReqZ,\n createResZ,\n );\n this.store.set(res.views);\n return isMany ? res.views : res.views[0];\n }\n\n async rename(key: Key, name: string, opts: query.WriteOptions = {}): Promise<void> {\n const v = await this.retrieve(key);\n const rename = () => [\n query.partialUpdate(this.store, key, { name }),\n this.cfg.ontology.cache.renameResource(ontologyID(key), name),\n ];\n await query.optimistic({\n rollbacks: rename(),\n onOptimistic: opts.onOptimistic,\n commit: async () => {\n await this.create({ ...v, name });\n },\n });\n rename();\n }\n\n async delete(keys: Key | Key[], opts: query.WriteOptions = {}): Promise<void> {\n const keysArr = array.toArray(keys);\n const ids = ontologyID(keysArr);\n const drop = () => [\n this.cfg.ontology.cache.deleteRelationships(ids),\n this.store.delete(keysArr),\n this.cfg.ontology.cache.resources.delete(ontology.idToString(ids)),\n ];\n await query.optimistic({\n rollbacks: drop(),\n onOptimistic: opts.onOptimistic,\n commit: async () =>\n await this.cfg.unary.send(\n \"/view/delete\",\n { keys: keysArr },\n deleteReqZ,\n emptyResZ,\n ),\n });\n drop();\n }\n\n /** Subscribes to every view set delivered to the cache. */\n onSet(handler: (view: View) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"set\") handler(event.value);\n });\n }\n\n /** Subscribes to every view delete delivered to the cache. */\n onDelete(handler: (key: Key) => void): destructor.Destructor {\n return this.store.subscribe((event) => {\n if (event.variant === \"delete\") handler(event.key);\n });\n }\n\n private async execRetrieve(params: RetrieveMultipleParams): Promise<View[]> {\n const res = await this.cfg.unary.send(\n \"/view/retrieve\",\n params,\n retrieveRequestZ,\n retrieveResponseZ,\n );\n return res.views;\n }\n}\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nexport * from \"@/view/client\";\nexport * from \"@/view/types.gen\";\n","// Copyright 2026 Synnax Labs, Inc.\n//\n// Use of this software is governed by the Business Source License included in the file\n// licenses/BSL.txt.\n//\n// As of the Change Date specified in that file, in accordance with the Business Source\n// License, use of this software will be governed by the Apache License, Version 2.0,\n// included in the file licenses/APL.txt.\n\nimport {\n array,\n breaker,\n type CrudeTimeSpan,\n TimeSpan,\n TimeStamp,\n url,\n uuid,\n zod,\n} from \"@synnaxlabs/x\";\nimport { z } from \"zod\";\n\nimport { access } from \"@/access\";\nimport { arc } from \"@/arc\";\nimport { auth } from \"@/auth\";\nimport { channel } from \"@/channel\";\nimport { connection } from \"@/connection\";\nimport { control } from \"@/control\";\nimport { device } from \"@/device\";\nimport { errorsMiddleware } from \"@/errors\";\nimport { framer } from \"@/framer\";\nimport { group } from \"@/group\";\nimport { imex } from \"@/imex\";\nimport { label } from \"@/label\";\nimport { lineplot } from \"@/lineplot\";\nimport { log } from \"@/log\";\nimport { ontology } from \"@/ontology\";\nimport { panel } from \"@/panel\";\nimport { project } from \"@/project\";\nimport { query } from \"@/query\";\nimport { rack } from \"@/rack\";\nimport { ranger } from \"@/ranger\";\nimport { schematic } from \"@/schematic\";\nimport { status } from \"@/status\";\nimport { table } from \"@/table\";\nimport { task } from \"@/task\";\nimport { Transport } from \"@/transport\";\nimport { user } from \"@/user\";\nimport { view } from \"@/view\";\n\nexport const synnaxParamsZ = z.object({\n host: z.string({ error: \"Host is required\" }).min(1, \"Host is required\"),\n port: z\n .number({ error: \"Port is required\" })\n .or(z.string({ error: \"Port is required\" })),\n username: z.string().min(1, \"Username is required\"),\n password: z.string().min(1, \"Password is required\"),\n connectivityPollFrequency: TimeSpan.z.default(TimeSpan.seconds(30)),\n clockSkewThreshold: TimeSpan.z.default(TimeSpan.seconds(1)),\n secure: z.boolean().default(false),\n name: z.string().optional(),\n retry: breaker.breakerConfigZ.optional(),\n cache: z.boolean().default(true),\n /**\n * Receives cache errors that have no caller to throw to (listener fan-out, streamer\n * frame handling, background reconciliation). Defaults to console logging.\n */\n // output is unknown, not void: strict void validation would make a\n // caller's `(e) => list.push(e)` throw at error-report time\n onInternalError: z\n .function({ input: z.tuple([z.instanceof(Error)]), output: z.unknown() })\n .optional(),\n});\n\nexport interface SynnaxParams extends z.input<typeof synnaxParamsZ> {}\nexport interface ParsedSynnaxParams extends z.infer<typeof synnaxParamsZ> {}\n\n/**\n * Client to perform operations against a Synnax cluster.\n * @property channel - Channel client for creating and retrieving channels.\n * @property data - Data client for reading and writing telemetry.\n * @property connection - The connection state machine.\n * @property ontology - Client for querying the cluster's ontology.\n */\nexport default class Synnax extends framer.Client {\n readonly key: string;\n readonly createdAt: TimeStamp;\n readonly params: ParsedSynnaxParams;\n readonly ranges: ranger.Client;\n readonly channels: channel.Client;\n readonly auth: auth.Client;\n readonly users: user.Client;\n readonly access: access.Client;\n readonly connection: connection.Handle;\n readonly ontology: ontology.Client;\n readonly projects: project.Client;\n readonly labels: label.Client;\n readonly statuses: status.Client;\n readonly tasks: task.Client;\n readonly racks: rack.Client;\n readonly devices: device.Client;\n readonly control: control.Client;\n readonly arcs: arc.Client;\n readonly views: view.Client;\n readonly schematics: schematic.Client;\n readonly lineplots: lineplot.Client;\n readonly panels: panel.Client;\n readonly logs: log.Client;\n readonly tables: table.Client;\n readonly groups: group.Client;\n readonly imex: imex.Client;\n private readonly cache: query.Cache;\n private readonly transport: Transport;\n private readonly conn: connection.Client;\n\n /** The version of the client. */\n readonly clientVersion: string = __VERSION__;\n\n /**\n * @param props.host - Hostname of a node in the cluster.\n * @param props.port - Port of the node in the cluster.\n * @param props.username - Username for authentication. Not required if the cluster is\n * insecure.\n * @param props.password - Password for authentication. Not required if the cluster is\n * insecure.\n * @param props.connectivityPollFrequency - Heartbeat cadence while the connection is\n * healthy. Defaults to 30 seconds.\n * @param props.secure - Whether to connect to the cluster using TLS. The cluster must\n * be configured to support TLS. Defaults to false. A Synnax client must be closed\n * when it is no longer needed. This stops the connection machine and closes the\n * change stream.\n */\n constructor(params: SynnaxParams) {\n const parsedParams = zod.parse(synnaxParamsZ, params);\n const {\n host,\n port,\n username,\n password,\n connectivityPollFrequency,\n clockSkewThreshold,\n secure,\n retry,\n } = parsedParams;\n const transport = new Transport(\n new url.URL({ host, port: Number(port) }),\n retry,\n secure,\n );\n transport.use(errorsMiddleware);\n // The arrow reads this.channels only when called, after construction completes.\n const retrieveChannels: framer.ChannelRetriever = async (toRetrieve) => {\n const result = await this.channels.retrieve(\n array.toArray(toRetrieve) as channel.Key[] | channel.Name[],\n );\n return result.map((ch) => ch.payload);\n };\n super({ stream: transport.stream, unary: transport.unary, retrieveChannels });\n const cache = new query.Cache({\n openStreamer: parsedParams.cache\n ? async (config) => await this.openStreamer(config)\n : null,\n breaker: retry,\n onStreamLive: () => this.conn.notify({ type: \"stream.live\" }),\n onStreamDrop: (error) => this.conn.notify({ type: \"stream.drop\", error }),\n onStreamDenied: (error) => this.conn.notify({ type: \"stream.denied\", error }),\n onError: parsedParams.onInternalError,\n });\n this.cache = cache;\n this.conn = new connection.Client({\n unary: transport.unaryNoRetry,\n address: `${host}:${Number(port)}`,\n name: parsedParams.name,\n clockSkewThreshold: new TimeSpan(clockSkewThreshold).abs(),\n requiresStream: parsedParams.cache,\n retry,\n heartbeatInterval: connectivityPollFrequency,\n stream: {\n reset: async () => await cache.reset(),\n ensure: async () => await cache.ensureStreaming(),\n },\n onInternalError: parsedParams.onInternalError,\n });\n this.connection = this.conn;\n cache.onEpoch((epoch) => this.conn.notify({ type: \"epoch.advanced\", epoch }));\n transport.unary.use(this.conn.middleware());\n // The auth client fails fast: login retries belong to the request that triggered\n // them (the breaker-wrapped unary or the check loop), never stacked beneath it.\n this.auth = new auth.Client(\n transport.unaryNoRetry,\n { username, password },\n {\n onSuccess: () => this.conn.notify({ type: \"auth.success\" }),\n onFailure: (error) => this.conn.notify({ type: \"auth.failure\", error }),\n },\n );\n transport.use(this.auth.middleware());\n const chCreator = new channel.Writer(transport.unary);\n this.key = uuid.create();\n this.createdAt = TimeStamp.now();\n this.params = parsedParams;\n this.transport = transport;\n const unary = this.transport.unary;\n this.ontology = new ontology.Client({ unary, cache });\n this.labels = new label.Client({ unary, cache, ontology: this.ontology });\n this.statuses = new status.Client({\n unary,\n cache,\n ontology: this.ontology,\n labels: this.labels,\n });\n this.ranges = new ranger.Client({\n framer: this,\n unary,\n channels: retrieveChannels,\n labels: this.labels,\n ontology: this.ontology,\n cache,\n });\n this.channels = new channel.Client({\n framer: this,\n unary,\n writer: chCreator,\n statuses: this.statuses,\n ranges: this.ranges,\n cache,\n ontology: this.ontology,\n });\n this.control = new control.Client({ unary, cache });\n this.access = new access.Client({ unary, cache, ontology: this.ontology });\n this.users = new user.Client({ unary, cache, ontology: this.ontology });\n this.projects = new project.Client({\n unary,\n file: this.transport.file,\n cache,\n ontology: this.ontology,\n });\n this.tasks = new task.Client({\n unary,\n framer: this,\n ontology: this.ontology,\n ranges: this.ranges,\n cache,\n statusStore: this.statuses.store,\n });\n this.racks = new rack.Client({\n unary,\n tasks: this.tasks,\n cache,\n statusStore: this.statuses.store,\n ontology: this.ontology,\n });\n this.devices = new device.Client({\n unary,\n cache,\n statusStore: this.statuses.store,\n ontology: this.ontology,\n });\n this.arcs = new arc.Client({\n unary,\n stream: this.transport.stream,\n ontology: this.ontology,\n tasks: this.tasks,\n cache,\n statusStore: this.statuses.store,\n });\n this.views = new view.Client({ unary, cache, ontology: this.ontology });\n this.groups = new group.Client({\n unary,\n ontology: this.ontology,\n cache,\n });\n this.schematics = new schematic.Client({\n unary,\n file: this.transport.file,\n ontology: this.ontology,\n cache,\n groupStore: this.groups.store,\n });\n this.lineplots = new lineplot.Client({ unary, cache, ontology: this.ontology });\n this.panels = new panel.Client({\n unary,\n ontology: this.ontology,\n cache,\n });\n this.logs = new log.Client({ unary, cache, ontology: this.ontology });\n this.tables = new table.Client({ unary, cache, ontology: this.ontology });\n this.imex = new imex.Client({ file: this.transport.file });\n }\n\n /**\n * Awaits the connection becoming usable: success, or warning when the cluster refuses\n * live updates. Idempotent: resolves immediately when already connected.\n * @throws {AuthError} on a definitive credential rejection.\n * @throws {DisconnectedError} when the cluster cannot be reached after the configured\n * retry budget, or when the client is closed while waiting.\n * @throws {Error} if the timeout elapses first.\n */\n async connect({ timeout }: ConnectOptions = {}): Promise<connection.Status> {\n return await this.conn.connect(timeout);\n }\n\n /** Supplies new credentials after an auth failure and resumes connecting. */\n reauthenticate(credentials: auth.Credentials): void {\n this.auth.setCredentials(credentials);\n this.conn.notify({ type: \"credentials.replaced\" });\n }\n\n /**\n * Closes the client, stopping the connection check loop and tearing down the\n * query cache and its change stream. Resolves once both are closed.\n * @throws {AggregateError} carrying every underlying close failure.\n */\n async close(): Promise<void> {\n const results = await Promise.allSettled([this.conn.close(), this.cache.close()]);\n const failures = results.filter((r) => r.status === \"rejected\");\n if (failures.length > 0)\n throw new AggregateError(\n failures.map((f) => f.reason),\n \"failed to close the client\",\n );\n }\n}\n\nexport interface ConnectOptions {\n /**\n * Maximum time to wait before rejecting. Without it, connect rejects when\n * the connection escalates to error(unreachable) after its retry budget.\n */\n timeout?: CrudeTimeSpan;\n}\n"],"x_google_ignoreList":[31,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81],"mappings":";;;;;;;;;;;;GAaa,KAAU;CAAC;CAAU;CAAU;CAAY;AAAQ,GACnD,KAAU,EAAE,KAAK,EAAO,GCgCxB,MAAgB,GAAc,MAAgC;CACzE,IAAM,IAAO,EAAM,QAAQ,EAAI,OAAO,GAChC,EAAE,cAAW;CACnB,KAAK,IAAM,KAAgB,GAAM;EAC/B,IAAI,IAAU;EAEd,KAAK,IAAM,KAAU,GACG,MAAO,QAAQ,SAAS,CACzC,GAIL;QAAK,IAAM,KAAa,EAAO,SAC7B,IAAI,EAAU,QAAQ,IAChB;QAAA,EAAU,SAAS,EAAa,MAAM;KACxC,IAAU;KACV;IACF;UACK,IACL,EAAU,SAAS,EAAa,QAChC,EAA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