@rocicorp/zero 0.25.0-canary.18 → 0.25.0-canary.21
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/out/replicache/src/persist/idb-databases-store.d.ts +1 -0
- package/out/replicache/src/persist/idb-databases-store.d.ts.map +1 -1
- package/out/replicache/src/persist/idb-databases-store.js +13 -2
- package/out/replicache/src/persist/idb-databases-store.js.map +1 -1
- package/out/zero/package.json.js +1 -1
- package/out/zero/src/adapters/drizzle.d.ts +1 -1
- package/out/zero/src/adapters/drizzle.d.ts.map +1 -1
- package/out/zero/src/adapters/drizzle.js +4 -1
- package/out/zero/src/bindings.d.ts +2 -0
- package/out/zero/src/bindings.d.ts.map +1 -0
- package/out/zero/src/bindings.js +27 -0
- package/out/zero/src/bindings.js.map +1 -0
- package/out/zero/src/react.js +2 -4
- package/out/zero/src/react.js.map +1 -1
- package/out/zero/src/solid.js +2 -2
- package/out/zero/src/zero.js +3 -5
- package/out/zero-cache/src/auth/read-authorizer.d.ts +1 -1
- package/out/zero-cache/src/auth/read-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/read-authorizer.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +5 -4
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +24 -0
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +23 -4
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/server/anonymous-otel-start.d.ts +10 -1
- package/out/zero-cache/src/server/anonymous-otel-start.d.ts.map +1 -1
- package/out/zero-cache/src/server/anonymous-otel-start.js +34 -18
- package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +1 -0
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/analyze.d.ts +1 -1
- package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
- package/out/zero-cache/src/services/analyze.js +5 -5
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.d.ts +4 -4
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.d.ts +2 -1
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +26 -13
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-purger.d.ts +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-purger.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-purger.js +39 -15
- package/out/zero-cache/src/services/view-syncer/cvr-purger.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts +4 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +31 -9
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts +3 -0
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +11 -0
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +1 -2
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +6 -6
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/cvr.d.ts +1 -0
- package/out/zero-cache/src/services/view-syncer/schema/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/cvr.js +23 -10
- package/out/zero-cache/src/services/view-syncer/schema/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js +31 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +1 -0
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +20 -16
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/workers/connect-params.d.ts +1 -0
- package/out/zero-cache/src/workers/connect-params.d.ts.map +1 -1
- package/out/zero-cache/src/workers/connect-params.js +2 -0
- package/out/zero-cache/src/workers/connect-params.js.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.d.ts.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js +2 -0
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
- package/out/zero-client/src/client/bindings.d.ts +12 -41
- package/out/zero-client/src/client/bindings.d.ts.map +1 -1
- package/out/zero-client/src/client/custom.d.ts +3 -0
- package/out/zero-client/src/client/custom.d.ts.map +1 -1
- package/out/zero-client/src/client/custom.js +3 -0
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/delete-clients-manager.d.ts +1 -1
- package/out/zero-client/src/client/delete-clients-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/delete-clients-manager.js +30 -3
- package/out/zero-client/src/client/delete-clients-manager.js.map +1 -1
- package/out/zero-client/src/client/make-replicache-mutators.js +1 -3
- package/out/zero-client/src/client/make-replicache-mutators.js.map +1 -1
- package/out/zero-client/src/client/options.d.ts +1 -1
- package/out/zero-client/src/client/options.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts +1 -0
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +43 -26
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-client/src/mod.d.ts +6 -4
- package/out/zero-client/src/mod.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.d.ts +2 -2
- package/out/zero-protocol/src/analyze-query-result.js +2 -2
- package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-protocol/src/inspect-down.d.ts +6 -6
- package/out/zero-protocol/src/inspect-up.d.ts +4 -4
- package/out/zero-protocol/src/inspect-up.js +1 -1
- package/out/zero-protocol/src/inspect-up.js.map +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts +1 -1
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/up.d.ts +1 -1
- package/out/zero-react/src/bindings.d.ts +2 -0
- package/out/zero-react/src/bindings.d.ts.map +1 -0
- package/out/zero-react/src/mod.d.ts +1 -10
- package/out/zero-react/src/mod.d.ts.map +1 -1
- package/out/zero-react/src/{use-zero-connection-state.d.ts → use-connection-state.d.ts} +3 -3
- package/out/zero-react/src/use-connection-state.d.ts.map +1 -0
- package/out/zero-react/src/{use-zero-connection-state.js → use-connection-state.js} +3 -3
- package/out/zero-react/src/use-connection-state.js.map +1 -0
- package/out/zero-react/src/use-query.d.ts +2 -10
- package/out/zero-react/src/use-query.d.ts.map +1 -1
- package/out/zero-react/src/use-query.js +24 -22
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-react/src/use-zero-online.d.ts +1 -1
- package/out/zero-react/src/use-zero-online.js.map +1 -1
- package/out/zero-react/src/zero-provider.d.ts +1 -5
- package/out/zero-react/src/zero-provider.d.ts.map +1 -1
- package/out/zero-react/src/zero-provider.js +16 -0
- package/out/zero-react/src/zero-provider.js.map +1 -1
- package/out/zero-react/src/zero.d.ts +2 -0
- package/out/zero-react/src/zero.d.ts.map +1 -0
- package/out/zero-schema/src/permissions.d.ts.map +1 -1
- package/out/zero-schema/src/permissions.js +2 -8
- package/out/zero-schema/src/permissions.js.map +1 -1
- package/out/zero-server/src/custom.d.ts +3 -0
- package/out/zero-server/src/custom.d.ts.map +1 -1
- package/out/zero-server/src/custom.js +3 -0
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zero-solid/src/bindings.d.ts +2 -0
- package/out/zero-solid/src/bindings.d.ts.map +1 -0
- package/out/zero-solid/src/mod.d.ts +1 -8
- package/out/zero-solid/src/mod.d.ts.map +1 -1
- package/out/zero-solid/src/solid-view.d.ts +1 -8
- package/out/zero-solid/src/solid-view.d.ts.map +1 -1
- package/out/zero-solid/src/solid-view.js +31 -0
- package/out/zero-solid/src/solid-view.js.map +1 -1
- package/out/zero-solid/src/{use-zero-connection-state.d.ts → use-connection-state.d.ts} +3 -3
- package/out/zero-solid/src/use-connection-state.d.ts.map +1 -0
- package/out/zero-solid/src/{use-zero-connection-state.js → use-connection-state.js} +3 -3
- package/out/zero-solid/src/use-connection-state.js.map +1 -0
- package/out/zero-solid/src/use-query.d.ts +1 -7
- package/out/zero-solid/src/use-query.d.ts.map +1 -1
- package/out/zero-solid/src/use-query.js +43 -12
- package/out/zero-solid/src/use-query.js.map +1 -1
- package/out/zero-solid/src/use-zero-online.d.ts +1 -1
- package/out/zero-solid/src/use-zero-online.js.map +1 -1
- package/out/zero-solid/src/use-zero.d.ts +1 -5
- package/out/zero-solid/src/use-zero.d.ts.map +1 -1
- package/out/zero-solid/src/use-zero.js +16 -0
- package/out/zero-solid/src/use-zero.js.map +1 -1
- package/out/zero-solid/src/zero.d.ts +2 -0
- package/out/zero-solid/src/zero.d.ts.map +1 -0
- package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +29 -27
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/join-utils.d.ts +7 -1
- package/out/zql/src/ivm/join-utils.d.ts.map +1 -1
- package/out/zql/src/ivm/join-utils.js +12 -0
- package/out/zql/src/ivm/join-utils.js.map +1 -1
- package/out/zql/src/ivm/join.d.ts.map +1 -1
- package/out/zql/src/ivm/join.js +11 -25
- package/out/zql/src/ivm/join.js.map +1 -1
- package/out/zql/src/mutate/custom.d.ts +3 -0
- package/out/zql/src/mutate/custom.d.ts.map +1 -1
- package/out/zql/src/mutate/custom.js.map +1 -1
- package/out/zql/src/mutate/mutator-registry.d.ts +2 -2
- package/out/zql/src/mutate/mutator-registry.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator-registry.js.map +1 -1
- package/out/zql/src/mutate/mutator.d.ts +1 -1
- package/out/zql/src/mutate/mutator.d.ts.map +1 -1
- package/out/zql/src/mutate/mutator.js.map +1 -1
- package/out/zql/src/planner/planner-debug.d.ts +3 -3
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/query/create-builder.d.ts +2 -1
- package/out/zql/src/query/create-builder.d.ts.map +1 -1
- package/out/zql/src/query/create-builder.js +3 -0
- package/out/zql/src/query/create-builder.js.map +1 -1
- package/out/zql/src/query/query-impl.d.ts +39 -6
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js +414 -23
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-registry.d.ts +2 -2
- package/out/zql/src/query/query-registry.d.ts.map +1 -1
- package/out/zql/src/query/query-registry.js.map +1 -1
- package/out/zql/src/query/runnable-query-impl.d.ts +2 -2
- package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.js +2 -2
- package/out/zql/src/query/runnable-query-impl.js.map +1 -1
- package/out/zql/src/query/schema-query.d.ts +4 -2
- package/out/zql/src/query/schema-query.d.ts.map +1 -1
- package/out/zql/src/query/static-query.d.ts +2 -16
- package/out/zql/src/query/static-query.d.ts.map +1 -1
- package/out/zql/src/query/static-query.js +10 -37
- package/out/zql/src/query/static-query.js.map +1 -1
- package/package.json +7 -3
- package/out/zero-client/src/client/bindings.js +0 -33
- package/out/zero-client/src/client/bindings.js.map +0 -1
- package/out/zero-react/src/components/inspector.d.ts +0 -9
- package/out/zero-react/src/components/inspector.d.ts.map +0 -1
- package/out/zero-react/src/components/inspector.js +0 -38
- package/out/zero-react/src/components/inspector.js.map +0 -1
- package/out/zero-react/src/components/mark-icon.d.ts +0 -3
- package/out/zero-react/src/components/mark-icon.d.ts.map +0 -1
- package/out/zero-react/src/components/mark-icon.js +0 -28
- package/out/zero-react/src/components/mark-icon.js.map +0 -1
- package/out/zero-react/src/components/zero-inspector.d.ts +0 -8
- package/out/zero-react/src/components/zero-inspector.d.ts.map +0 -1
- package/out/zero-react/src/components/zero-inspector.js +0 -44
- package/out/zero-react/src/components/zero-inspector.js.map +0 -1
- package/out/zero-react/src/use-zero-connection-state.d.ts.map +0 -1
- package/out/zero-react/src/use-zero-connection-state.js.map +0 -1
- package/out/zero-solid/src/use-zero-connection-state.d.ts.map +0 -1
- package/out/zero-solid/src/use-zero-connection-state.js.map +0 -1
- package/out/zql/src/query/abstract-query.d.ts +0 -42
- package/out/zql/src/query/abstract-query.d.ts.map +0 -1
- package/out/zql/src/query/abstract-query.js +0 -405
- package/out/zql/src/query/abstract-query.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join-utils.js","sources":["../../../../../zql/src/ivm/join-utils.ts"],"sourcesContent":["import type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\nimport {compareValues, valuesEqual, type Node} from './data.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\n\nexport type JoinChangeOverlay = {\n change: Change;\n position: Row | undefined;\n};\n\nexport function generateWithOverlayNoYield(\n stream: Stream<Node>,\n overlay: Change,\n schema: SourceSchema,\n): Stream<Node> {\n return generateWithOverlay(stream, overlay, schema) as Stream<Node>;\n}\n\nexport function* generateWithOverlay(\n stream: Stream<Node | 'yield'>,\n overlay: Change,\n schema: SourceSchema,\n): Stream<Node | 'yield'> {\n let applied = false;\n let editOldApplied = false;\n let editNewApplied = false;\n for (const node of stream) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n let yieldNode = true;\n if (!applied) {\n switch (overlay.type) {\n case 'add': {\n if (schema.compareRows(overlay.node.row, node.row) === 0) {\n applied = true;\n yieldNode = false;\n }\n break;\n }\n case 'remove': {\n if (schema.compareRows(overlay.node.row, node.row) < 0) {\n applied = true;\n yield overlay.node;\n }\n break;\n }\n case 'edit': {\n if (\n !editOldApplied &&\n schema.compareRows(overlay.oldNode.row, node.row) < 0\n ) {\n editOldApplied = true;\n if (editNewApplied) {\n applied = true;\n }\n yield overlay.oldNode;\n }\n if (\n !editNewApplied &&\n schema.compareRows(overlay.node.row, node.row) === 0\n ) {\n editNewApplied = true;\n if (editOldApplied) {\n applied = true;\n }\n yieldNode = false;\n }\n break;\n }\n case 'child': {\n if (schema.compareRows(overlay.node.row, node.row) === 0) {\n applied = true;\n yield {\n row: node.row,\n relationships: {\n ...node.relationships,\n [overlay.child.relationshipName]: () =>\n generateWithOverlay(\n node.relationships[overlay.child.relationshipName](),\n overlay.child.change,\n schema.relationships[overlay.child.relationshipName],\n ),\n },\n };\n yieldNode = false;\n }\n break;\n }\n }\n }\n if (yieldNode) {\n yield node;\n }\n }\n if (!applied) {\n if (overlay.type === 'remove') {\n applied = true;\n yield overlay.node;\n } else if (overlay.type === 'edit') {\n assert(editNewApplied);\n editOldApplied = true;\n applied = true;\n yield overlay.oldNode;\n }\n }\n\n assert(applied);\n}\n\nexport function rowEqualsForCompoundKey(\n a: Row,\n b: Row,\n key: CompoundKey,\n): boolean {\n for (let i = 0; i < key.length; i++) {\n if (compareValues(a[key[i]], b[key[i]]) !== 0) {\n return false;\n }\n }\n return true;\n}\n\nexport function isJoinMatch(\n parent: Row,\n parentKey: CompoundKey,\n child: Row,\n childKey: CompoundKey,\n) {\n for (let i = 0; i < parentKey.length; i++) {\n if (!valuesEqual(parent[parentKey[i]], child[childKey[i]])) {\n return false;\n }\n }\n return true;\n}\n"],"names":[],"mappings":";;AAaO,SAAS,2BACd,QACA,SACA,QACc;AACd,SAAO,oBAAoB,QAAQ,SAAS,MAAM;AACpD;AAEO,UAAU,oBACf,QACA,SACA,QACwB;AACxB,MAAI,UAAU;AACd,MAAI,iBAAiB;AACrB,MAAI,iBAAiB;AACrB,aAAW,QAAQ,QAAQ;AACzB,QAAI,SAAS,SAAS;AACpB,YAAM;AACN;AAAA,IACF;AACA,QAAI,YAAY;AAChB,QAAI,CAAC,SAAS;AACZ,cAAQ,QAAQ,MAAA;AAAA,QACd,KAAK,OAAO;AACV,cAAI,OAAO,YAAY,QAAQ,KAAK,KAAK,KAAK,GAAG,MAAM,GAAG;AACxD,sBAAU;AACV,wBAAY;AAAA,UACd;AACA;AAAA,QACF;AAAA,QACA,KAAK,UAAU;AACb,cAAI,OAAO,YAAY,QAAQ,KAAK,KAAK,KAAK,GAAG,IAAI,GAAG;AACtD,sBAAU;AACV,kBAAM,QAAQ;AAAA,UAChB;AACA;AAAA,QACF;AAAA,QACA,KAAK,QAAQ;AACX,cACE,CAAC,kBACD,OAAO,YAAY,QAAQ,QAAQ,KAAK,KAAK,GAAG,IAAI,GACpD;AACA,6BAAiB;AACjB,gBAAI,gBAAgB;AAClB,wBAAU;AAAA,YACZ;AACA,kBAAM,QAAQ;AAAA,UAChB;AACA,cACE,CAAC,kBACD,OAAO,YAAY,QAAQ,KAAK,KAAK,KAAK,GAAG,MAAM,GACnD;AACA,6BAAiB;AACjB,gBAAI,gBAAgB;AAClB,wBAAU;AAAA,YACZ;AACA,wBAAY;AAAA,UACd;AACA;AAAA,QACF;AAAA,QACA,KAAK,SAAS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ts"],"sourcesContent":["import type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {Change} from './change.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\nimport {compareValues, valuesEqual, type Node} from './data.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey} from '../../../zero-protocol/src/ast.ts';\n\nexport type JoinChangeOverlay = {\n change: Change;\n position: Row | undefined;\n};\n\nexport function generateWithOverlayNoYield(\n stream: Stream<Node>,\n overlay: Change,\n schema: SourceSchema,\n): Stream<Node> {\n return generateWithOverlay(stream, overlay, schema) as Stream<Node>;\n}\n\nexport function* generateWithOverlay(\n stream: Stream<Node | 'yield'>,\n overlay: Change,\n schema: SourceSchema,\n): Stream<Node | 'yield'> {\n let applied = false;\n let editOldApplied = false;\n let editNewApplied = false;\n for (const node of stream) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n let yieldNode = true;\n if (!applied) {\n switch (overlay.type) {\n case 'add': {\n if (schema.compareRows(overlay.node.row, node.row) === 0) {\n applied = true;\n yieldNode = false;\n }\n break;\n }\n case 'remove': {\n if (schema.compareRows(overlay.node.row, node.row) < 0) {\n applied = true;\n yield overlay.node;\n }\n break;\n }\n case 'edit': {\n if (\n !editOldApplied &&\n schema.compareRows(overlay.oldNode.row, node.row) < 0\n ) {\n editOldApplied = true;\n if (editNewApplied) {\n applied = true;\n }\n yield overlay.oldNode;\n }\n if (\n !editNewApplied &&\n schema.compareRows(overlay.node.row, node.row) === 0\n ) {\n editNewApplied = true;\n if (editOldApplied) {\n applied = true;\n }\n yieldNode = false;\n }\n break;\n }\n case 'child': {\n if (schema.compareRows(overlay.node.row, node.row) === 0) {\n applied = true;\n yield {\n row: node.row,\n relationships: {\n ...node.relationships,\n [overlay.child.relationshipName]: () =>\n generateWithOverlay(\n node.relationships[overlay.child.relationshipName](),\n overlay.child.change,\n schema.relationships[overlay.child.relationshipName],\n ),\n },\n };\n yieldNode = false;\n }\n break;\n }\n }\n }\n if (yieldNode) {\n yield node;\n }\n }\n if (!applied) {\n if (overlay.type === 'remove') {\n applied = true;\n yield overlay.node;\n } else if (overlay.type === 'edit') {\n assert(editNewApplied);\n editOldApplied = true;\n applied = true;\n yield overlay.oldNode;\n }\n }\n\n assert(applied);\n}\n\nexport function rowEqualsForCompoundKey(\n a: Row,\n b: Row,\n key: CompoundKey,\n): boolean {\n for (let i = 0; i < key.length; i++) {\n if (compareValues(a[key[i]], b[key[i]]) !== 0) {\n return false;\n }\n }\n return true;\n}\n\nexport function isJoinMatch(\n parent: Row,\n parentKey: CompoundKey,\n child: Row,\n childKey: CompoundKey,\n) {\n for (let i = 0; i < parentKey.length; i++) {\n if (!valuesEqual(parent[parentKey[i]], child[childKey[i]])) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Builds a constraint object by mapping values from `sourceRow` using `sourceKey`\n * to keys specified by `targetKey`. Returns `undefined` if any source value is `null`,\n * since null foreign keys cannot match any rows.\n */\nexport function buildJoinConstraint(\n sourceRow: Row,\n sourceKey: CompoundKey,\n targetKey: CompoundKey,\n): Record<string, Value> | undefined {\n const constraint: Record<string, Value> = {};\n for (let i = 0; i < targetKey.length; i++) {\n const value = sourceRow[sourceKey[i]];\n if (value === null) {\n return undefined;\n }\n constraint[targetKey[i]] = value;\n }\n return constraint;\n}\n"],"names":[],"mappings":";;AAaO,SAAS,2BACd,QACA,SACA,QACc;AACd,SAAO,oBAAoB,QAAQ,SAAS,MAAM;AACpD;AAEO,UAAU,oBACf,QACA,SACA,QACwB;AACxB,MAAI,UAAU;AACd,MAAI,iBAAiB;AACrB,MAAI,iBAAiB;AACrB,aAAW,QAAQ,QAAQ;AACzB,QAAI,SAAS,SAAS;AACpB,YAAM;AACN;AAAA,IACF;AACA,QAAI,YAAY;AAChB,QAAI,CAAC,SAAS;AACZ,cAAQ,QAAQ,MAAA;AAAA,QACd,KAAK,OAAO;AACV,cAAI,OAAO,YAAY,QAAQ,KAAK,KAAK,KAAK,GAAG,MAAM,GAAG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AiB;AACjB,gBAAU;AACV,YAAM,QAAQ;AAAA,IAChB;AAAA,EACF;AAEA,SAAO,OAAO;AAChB;AAEO,SAAS,wBACd,GACA,GACA,KACS;AACT,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,QAAI,cAAc,EAAE,IAAI,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG;AAC7C,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,YACd,QACA,WACA,OACA,UACA;AACA,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,QAAI,CAAC,YAAY,OAAO,UAAU,CAAC,CAAC,GAAG,MAAM,SAAS,CAAC,CAAC,CAAC,GAAG;AAC1D,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,oBACd,WACA,WACA,WACmC;AACnC,QAAM,aAAoC,CAAA;AAC1C,WAAS,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK;AACzC,UAAM,QAAQ,UAAU,UAAU,CAAC,CAAC;AACpC,QAAI,UAAU,MAAM;AAClB,aAAO;AAAA,IACT;AACA,eAAW,UAAU,CAAC,CAAC,IAAI;AAAA,EAC7B;AACA,SAAO;AACT;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/join.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,WAAW,EAAE,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAG3E,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"join.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/join.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,WAAW,EAAE,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAG3E,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,WAAW,CAAC;AAQpC,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,KAAK,EACV,KAAK,MAAM,EACZ,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAC,KAAK,MAAM,EAAC,MAAM,aAAa,CAAC;AAExC,KAAK,IAAI,GAAG;IACV,MAAM,EAAE,KAAK,CAAC;IACd,KAAK,EAAE,KAAK,CAAC;IAEb,SAAS,EAAE,WAAW,CAAC;IACvB,QAAQ,EAAE,WAAW,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,OAAO,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;;;;;GASG;AACH,qBAAa,IAAK,YAAW,KAAK;;gBAYpB,EACV,MAAM,EACN,KAAK,EACL,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,MAAM,EACN,MAAM,GACP,EAAE,IAAI;IAkCP,OAAO,IAAI,IAAI;IAKf,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B,SAAS,IAAI,YAAY;IAIxB,KAAK,CAAC,GAAG,EAAE,YAAY,GAAG,MAAM,CAAC,IAAI,GAAG,OAAO,CAAC;CA0LlD"}
|
package/out/zql/src/ivm/join.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
2
|
-
import { rowEqualsForCompoundKey, isJoinMatch, generateWithOverlay } from "./join-utils.js";
|
|
2
|
+
import { rowEqualsForCompoundKey, buildJoinConstraint, isJoinMatch, generateWithOverlay } from "./join-utils.js";
|
|
3
3
|
import { throwOutput } from "./operator.js";
|
|
4
4
|
class Join {
|
|
5
5
|
#parent;
|
|
@@ -165,19 +165,12 @@ class Join {
|
|
|
165
165
|
position: void 0
|
|
166
166
|
};
|
|
167
167
|
try {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
this.#
|
|
171
|
-
|
|
172
|
-
if (value === null) {
|
|
173
|
-
anyNull = true;
|
|
174
|
-
}
|
|
175
|
-
return [key, value];
|
|
176
|
-
})
|
|
168
|
+
const constraint = buildJoinConstraint(
|
|
169
|
+
childRow,
|
|
170
|
+
this.#childKey,
|
|
171
|
+
this.#parentKey
|
|
177
172
|
);
|
|
178
|
-
const parentNodes =
|
|
179
|
-
constraint
|
|
180
|
-
});
|
|
173
|
+
const parentNodes = constraint ? this.#parent.fetch({ constraint }) : [];
|
|
181
174
|
for (const parentNode of parentNodes) {
|
|
182
175
|
if (parentNode === "yield") {
|
|
183
176
|
yield parentNode;
|
|
@@ -203,19 +196,12 @@ class Join {
|
|
|
203
196
|
}
|
|
204
197
|
#processParentNode(parentNodeRow, parentNodeRelations) {
|
|
205
198
|
const childStream = () => {
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
this.#
|
|
209
|
-
|
|
210
|
-
if (value === null) {
|
|
211
|
-
anyNull = true;
|
|
212
|
-
}
|
|
213
|
-
return [key, value];
|
|
214
|
-
})
|
|
199
|
+
const constraint = buildJoinConstraint(
|
|
200
|
+
parentNodeRow,
|
|
201
|
+
this.#parentKey,
|
|
202
|
+
this.#childKey
|
|
215
203
|
);
|
|
216
|
-
const stream =
|
|
217
|
-
constraint
|
|
218
|
-
});
|
|
204
|
+
const stream = constraint ? this.#child.fetch({ constraint }) : [];
|
|
219
205
|
if (this.#inprogressChildChange && isJoinMatch(
|
|
220
206
|
parentNodeRow,
|
|
221
207
|
this.#parentKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join.js","sources":["../../../../../zql/src/ivm/join.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change, ChildChange} from './change.ts';\nimport type {Node} from './data.ts';\nimport {\n generateWithOverlay,\n isJoinMatch,\n rowEqualsForCompoundKey,\n type JoinChangeOverlay,\n} from './join-utils.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n relationshipName: string;\n hidden: boolean;\n system: System;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: JoinChangeOverlay | undefined;\n\n constructor({\n parent,\n child,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n this.#parent = parent;\n this.#child = child;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n });\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n for (const parentNode of this.#parent.fetch(req)) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n yield this.#processParentNode(parentNode.row, parentNode.relationships);\n }\n }\n\n *#pushParent(change: Change): Stream<'yield'> {\n switch (change.type) {\n case 'add':\n yield* this.#output.push(\n {\n type: 'add',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n case 'remove':\n yield* this.#output.push(\n {\n type: 'remove',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n case 'child':\n yield* this.#output.push(\n {\n type: 'child',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n child: change.child,\n },\n this,\n );\n break;\n case 'edit': {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change.oldNode.row,\n change.node.row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n yield* this.#output.push(\n {\n type: 'edit',\n oldNode: this.#processParentNode(\n change.oldNode.row,\n change.oldNode.relationships,\n ),\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n *#pushChild(change: Change): Stream<'yield'> {\n switch (change.type) {\n case 'add':\n case 'remove':\n yield* this.#pushChildChange(change.node.row, change);\n break;\n case 'child':\n yield* this.#pushChildChange(change.node.row, change);\n break;\n case 'edit': {\n const childRow = change.node.row;\n const oldChildRow = change.oldNode.row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n yield* this.#pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#pushChildChange(childRow: Row, change: Change): Stream<'yield'> {\n this.#inprogressChildChange = {\n change,\n position: undefined,\n };\n try {\n let anyNull = false;\n const constraint = Object.fromEntries(\n this.#parentKey.map((key, i) => {\n const value = childRow[this.#childKey[i]];\n if (value === null) {\n anyNull = true;\n }\n return [key, value];\n }),\n );\n const parentNodes = anyNull\n ? []\n : this.#parent.fetch({\n constraint,\n });\n\n for (const parentNode of parentNodes) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#inprogressChildChange.position = parentNode.row;\n const childChange: ChildChange = {\n type: 'child',\n node: this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n ),\n child: {\n relationshipName: this.#relationshipName,\n change,\n },\n };\n yield* this.#output.push(childChange, this);\n }\n } finally {\n this.#inprogressChildChange = undefined;\n }\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node | 'yield'>>,\n ): Node {\n const childStream = () => {\n let anyNull = false;\n const constraint = Object.fromEntries(\n this.#childKey.map((key, i) => {\n const value = parentNodeRow[this.#parentKey[i]];\n if (value === null) {\n anyNull = true;\n }\n return [key, value];\n }),\n );\n const stream = anyNull\n ? []\n : this.#child.fetch({\n constraint,\n });\n\n if (\n this.#inprogressChildChange &&\n isJoinMatch(\n parentNodeRow,\n this.#parentKey,\n this.#inprogressChildChange.change.node.row,\n this.#childKey,\n ) &&\n this.#inprogressChildChange.position &&\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChange.position,\n ) > 0\n ) {\n return generateWithOverlay(\n stream,\n this.#inprogressChildChange.change,\n this.#child.getSchema(),\n );\n }\n return stream;\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n}\n"],"names":[],"mappings":";;;AAyCO,MAAM,KAAsB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,UAAkB;AAAA,EAElB;AAAA,EAEA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,GACO;AACP,WAAO,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ACZ;AACA,iBAAO,CAAC,KAAK,KAAK;AAAA,QACpB,CAAC;AAAA,MAAA;AAEH,YAAM,SAAS,UACX,CAAA,IACA,KAAK,OAAO,MAAM;AAAA,QAChB;AAAA,MAAA,CACD;AAEL,UACE,KAAK,0BACL;AAAA,QACE;AAAA,QACA,KAAK;AAAA,QACL,KAAK,uBAAuB,OAAO,KAAK;AAAA,QACxC,KAAK;AAAA,MAAA,KAEP,KAAK,uBAAuB,YAC5B,KAAK,QAAQ;AAAA,QACX;AAAA,QACA,KAAK,uBAAuB;AAAA,MAAA,IAC1B,GACJ;AACA,eAAO;AAAA,UACL;AAAA,UACA,KAAK,uBAAuB;AAAA,UAC5B,KAAK,OAAO,UAAA;AAAA,QAAU;AAAA,MAE1B;AACA,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,MACL,KAAK;AAAA,MACL,eAAe;AAAA,QACb,GAAG;AAAA,QACH,CAAC,KAAK,iBAAiB,GAAG;AAAA,MAAA;AAAA,IAC5B;AAAA,EAEJ;AACF;"}
|
|
1
|
+
{"version":3,"file":"join.js","sources":["../../../../../zql/src/ivm/join.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {CompoundKey, System} from '../../../zero-protocol/src/ast.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport type {Change, ChildChange} from './change.ts';\nimport type {Node} from './data.ts';\nimport {\n buildJoinConstraint,\n generateWithOverlay,\n isJoinMatch,\n rowEqualsForCompoundKey,\n type JoinChangeOverlay,\n} from './join-utils.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Output,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\ntype Args = {\n parent: Input;\n child: Input;\n // The nth key in parentKey corresponds to the nth key in childKey.\n parentKey: CompoundKey;\n childKey: CompoundKey;\n relationshipName: string;\n hidden: boolean;\n system: System;\n};\n\n/**\n * The Join operator joins the output from two upstream inputs. Zero's join\n * is a little different from SQL's join in that we output hierarchical data,\n * not a flat table. This makes it a lot more useful for UI programming and\n * avoids duplicating tons of data like left join would.\n *\n * The Nodes output from Join have a new relationship added to them, which has\n * the name #relationshipName. The value of the relationship is a stream of\n * child nodes which are the corresponding values from the child source.\n */\nexport class Join implements Input {\n readonly #parent: Input;\n readonly #child: Input;\n readonly #parentKey: CompoundKey;\n readonly #childKey: CompoundKey;\n readonly #relationshipName: string;\n readonly #schema: SourceSchema;\n\n #output: Output = throwOutput;\n\n #inprogressChildChange: JoinChangeOverlay | undefined;\n\n constructor({\n parent,\n child,\n parentKey,\n childKey,\n relationshipName,\n hidden,\n system,\n }: Args) {\n assert(parent !== child, 'Parent and child must be different operators');\n assert(\n parentKey.length === childKey.length,\n 'The parentKey and childKey keys must have same length',\n );\n this.#parent = parent;\n this.#child = child;\n this.#parentKey = parentKey;\n this.#childKey = childKey;\n this.#relationshipName = relationshipName;\n\n const parentSchema = parent.getSchema();\n const childSchema = child.getSchema();\n this.#schema = {\n ...parentSchema,\n relationships: {\n ...parentSchema.relationships,\n [relationshipName]: {\n ...childSchema,\n isHidden: hidden,\n system,\n },\n },\n };\n\n parent.setOutput({\n push: (change: Change) => this.#pushParent(change),\n });\n child.setOutput({\n push: (change: Change) => this.#pushChild(change),\n });\n }\n\n destroy(): void {\n this.#parent.destroy();\n this.#child.destroy();\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n for (const parentNode of this.#parent.fetch(req)) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n yield this.#processParentNode(parentNode.row, parentNode.relationships);\n }\n }\n\n *#pushParent(change: Change): Stream<'yield'> {\n switch (change.type) {\n case 'add':\n yield* this.#output.push(\n {\n type: 'add',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n case 'remove':\n yield* this.#output.push(\n {\n type: 'remove',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n case 'child':\n yield* this.#output.push(\n {\n type: 'child',\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n child: change.child,\n },\n this,\n );\n break;\n case 'edit': {\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(\n change.oldNode.row,\n change.node.row,\n this.#parentKey,\n ),\n `Parent edit must not change relationship.`,\n );\n yield* this.#output.push(\n {\n type: 'edit',\n oldNode: this.#processParentNode(\n change.oldNode.row,\n change.oldNode.relationships,\n ),\n node: this.#processParentNode(\n change.node.row,\n change.node.relationships,\n ),\n },\n this,\n );\n break;\n }\n default:\n unreachable(change);\n }\n }\n\n *#pushChild(change: Change): Stream<'yield'> {\n switch (change.type) {\n case 'add':\n case 'remove':\n yield* this.#pushChildChange(change.node.row, change);\n break;\n case 'child':\n yield* this.#pushChildChange(change.node.row, change);\n break;\n case 'edit': {\n const childRow = change.node.row;\n const oldChildRow = change.oldNode.row;\n // Assert the edit could not change the relationship.\n assert(\n rowEqualsForCompoundKey(oldChildRow, childRow, this.#childKey),\n 'Child edit must not change relationship.',\n );\n yield* this.#pushChildChange(childRow, change);\n break;\n }\n\n default:\n unreachable(change);\n }\n }\n\n *#pushChildChange(childRow: Row, change: Change): Stream<'yield'> {\n this.#inprogressChildChange = {\n change,\n position: undefined,\n };\n try {\n const constraint = buildJoinConstraint(\n childRow,\n this.#childKey,\n this.#parentKey,\n );\n const parentNodes = constraint ? this.#parent.fetch({constraint}) : [];\n\n for (const parentNode of parentNodes) {\n if (parentNode === 'yield') {\n yield parentNode;\n continue;\n }\n this.#inprogressChildChange.position = parentNode.row;\n const childChange: ChildChange = {\n type: 'child',\n node: this.#processParentNode(\n parentNode.row,\n parentNode.relationships,\n ),\n child: {\n relationshipName: this.#relationshipName,\n change,\n },\n };\n yield* this.#output.push(childChange, this);\n }\n } finally {\n this.#inprogressChildChange = undefined;\n }\n }\n\n #processParentNode(\n parentNodeRow: Row,\n parentNodeRelations: Record<string, () => Stream<Node | 'yield'>>,\n ): Node {\n const childStream = () => {\n const constraint = buildJoinConstraint(\n parentNodeRow,\n this.#parentKey,\n this.#childKey,\n );\n const stream = constraint ? this.#child.fetch({constraint}) : [];\n\n if (\n this.#inprogressChildChange &&\n isJoinMatch(\n parentNodeRow,\n this.#parentKey,\n this.#inprogressChildChange.change.node.row,\n this.#childKey,\n ) &&\n this.#inprogressChildChange.position &&\n this.#schema.compareRows(\n parentNodeRow,\n this.#inprogressChildChange.position,\n ) > 0\n ) {\n return generateWithOverlay(\n stream,\n this.#inprogressChildChange.change,\n this.#child.getSchema(),\n );\n }\n return stream;\n };\n\n return {\n row: parentNodeRow,\n relationships: {\n ...parentNodeRelations,\n [this.#relationshipName]: childStream,\n },\n };\n }\n}\n"],"names":[],"mappings":";;;AA0CO,MAAM,KAAsB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,UAAkB;AAAA,EAElB;AAAA,EAEA,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA,GACO;AACP,WAAO,WAAW,OAAO,8CAA8C;AACvE;AAAA,MACE,UAAU,WAAW,SAAS;AAAA,MAC9B;AAAA,IAAA;AAEF,SAAK,UAAU;AACf,SAAK,SAAS;AACd,SAAK,aAAa;AAClB,SAAK,YAAY;AACjB,SAAK,oBAAoB;AAEzB,UAAM,eAAe,OAAO,UAAA;AAC5B,UAAM,cAAc,MAAM,UAAA;AAC1B,SAAK,UAAU;AAAA,MACb,GAAG;AAAA,MACH,eAAe;AAAA,QACb,GAAG,aAAa;AAAA,QAChB,CAAC,gBAAgB,GAAG;AAAA,UAClB,GAAG;AAAA,UACH,UAAU;AAAA,UACV;AAAA,QAAA;AAAA,MACF;AAAA,IACF;AAGF,WAAO,UAAU;AAAA,MACf,MAAM,CAAC,W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AACN;AAAA,QACF;AACA,aAAK,uBAAuB,WAAW,WAAW;AAClD,cAAM,cAA2B;AAAA,UAC/B,MAAM;AAAA,UACN,MAAM,KAAK;AAAA,YACT,WAAW;AAAA,YACX,WAAW;AAAA,UAAA;AAAA,UAEb,OAAO;AAAA,YACL,kBAAkB,KAAK;AAAA,YACvB;AAAA,UAAA;AAAA,QACF;AAEF,eAAO,KAAK,QAAQ,KAAK,aAAa,IAAI;AAAA,MAC5C;AAAA,IACF,UAAA;AACE,WAAK,yBAAyB;AAAA,IAChC;AAAA,EACF;AAAA,EAEA,mBACE,eACA,qBACM;AACN,UAAM,cAAc,MAAM;AACxB,YAAM,aAAa;AAAA,QACjB;AAAA,QACA,KAAK;AAAA,QACL,KAAK;AAAA,MAAA;AAEP,YAAM,SAAS,aAAa,KAAK,OAAO,MAAM,EAAC,WAAA,CAAW,IAAI,CAAA;AAE9D,UACE,KAAK,0BACL;AAAA,QACE;AAAA,QACA,KAAK;AAAA,QACL,KAAK,uBAAuB,OAAO,KAAK;AAAA,QACxC,KAAK;AAAA,MAAA,KAEP,KAAK,uBAAuB,YAC5B,KAAK,QAAQ;AAAA,QACX;AAAA,QACA,KAAK,uBAAuB;AAAA,MAAA,IAC1B,GACJ;AACA,eAAO;AAAA,UACL;AAAA,UACA,KAAK,uBAAuB;AAAA,UAC5B,KAAK,OAAO,UAAA;AAAA,QAAU;AAAA,MAE1B;AACA,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,MACL,KAAK;AAAA,MACL,eAAe;AAAA,QACb,GAAG;AAAA,QACH,CAAC,KAAK,iBAAiB,GAAG;AAAA,MAAA;AAAA,IAC5B;AAAA,EAEJ;AACF;"}
|
|
@@ -33,6 +33,9 @@ export interface TransactionBase<S extends Schema> {
|
|
|
33
33
|
*/
|
|
34
34
|
readonly reason: TransactionReason;
|
|
35
35
|
readonly mutate: MutateCRUD<S>;
|
|
36
|
+
/**
|
|
37
|
+
* @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.
|
|
38
|
+
*/
|
|
36
39
|
readonly query: SchemaQuery<S>;
|
|
37
40
|
run<TTable extends keyof S['tables'] & string, TReturn>(query: Query<TTable, S, TReturn>, options?: RunOptions): Promise<HumanReadable<TReturn>>;
|
|
38
41
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.d.ts","sourceRoot":"","sources":["../../../../../zql/src/mutate/custom.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,mCAAmC,CAAC;AAC3D,OAAO,KAAK,EACV,aAAa,EACb,yBAAyB,EAC1B,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAC9D,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,0CAA0C,CAAC;AAC3E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gBAAgB,CAAC;AAC3C,OAAO,KAAK,EAAC,aAAa,EAAE,KAAK,EAAE,UAAU,EAAC,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAC,iBAAiB,EAAE,UAAU,EAAC,MAAM,WAAW,CAAC;AAC7D,YAAY,EACV,QAAQ,EACR,WAAW,EACX,UAAU,EACV,SAAS,EACT,WAAW,EACX,WAAW,GACZ,MAAM,WAAW,CAAC;AAEnB,KAAK,QAAQ,GAAG,MAAM,CAAC;AAEvB;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,iBAAiB,CAAC;CACpC;AAED,MAAM,MAAM,QAAQ,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC3C,MAAM,M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CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;CAC3B;AAED,MAAM,WAAW,YAAY,CAAC,mBAAmB;IAC/C,WAAW,EAAE,CAAC,CAAC,EACb,EAAE,EAAE,CAAC,EAAE,EAAE,aAAa,CAAC,mBAAmB,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,KACvD,OAAO,CAAC,CAAC,CAAC,CAAC;CACjB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC,CAAE,SAAQ,SAAS;IACjD,QAAQ,CAAC,kBAAkB,EAAE,CAAC,CAAC;IAC/B,QAAQ,CAAC,OAAO,EACd,GAAG,EAAE,GAAG,EACR,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,GACzB,OAAO,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC;CACpC;AAED,UAAU,SAAS;IACjB,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC;CACnE;AAED;;;;GAIG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,MAAM,IAAI;IAEzC,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/D,GAAG,CAAC,CAAC,CAAC,sBAAsB,CAAC,SAAS,IAAI,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AAElE,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAQ5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","sources":["../../../../../zql/src/mutate/custom.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {AST} from '../../../zero-protocol/src/ast.ts';\nimport type {\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../../zero-types/src/server-schema.ts';\nimport type {Format} from '../ivm/view.ts';\nimport type {HumanReadable, Query, RunOptions} from '../query/query.ts';\nimport type {SchemaQuery} from '../query/schema-query.ts';\nimport type {CRUDMutateRequest, SchemaCRUD} from './crud.ts';\nexport type {\n DeleteID,\n InsertValue,\n SchemaCRUD,\n TableCRUD,\n UpdateValue,\n UpsertValue,\n} from './crud.ts';\n\ntype ClientID = string;\n\n/**\n * A base transaction interface that any Transaction<S, T> is assignable to.\n * Used in places where the schema type doesn't need to be preserved,\n * like the public signature of Mutator.fn.\n */\nexport interface AnyTransaction {\n readonly location: Location;\n readonly clientID: string;\n readonly mutationID: number;\n readonly reason: TransactionReason;\n}\n\nexport type Location = 'client' | 'server';\nexport type TransactionReason = 'optimistic' | 'rebase' | 'authoritative';\n\nexport interface TransactionBase<S extends Schema> {\n readonly location: Location;\n readonly clientID: ClientID;\n /**\n * The ID of the mutation that is being applied.\n */\n readonly mutationID: number;\n\n /**\n * The reason for the transaction.\n */\n readonly reason: TransactionReason;\n\n readonly mutate: MutateCRUD<S>;\n readonly query: SchemaQuery<S>;\n\n run<TTable extends keyof S['tables'] & string, TReturn>(\n query: Query<TTable, S, TReturn>,\n options?: RunOptions,\n ): Promise<HumanReadable<TReturn>>;\n}\n\nexport type Transaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = ServerTransaction<S, TWrappedTransaction> | ClientTransaction<S>;\n\nexport interface ServerTransaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> extends TransactionBase<S> {\n readonly location: 'server';\n readonly reason: 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n}\n\n/**\n * An instance of this is passed to custom mutator implementations and\n * allows reading and writing to the database and IVM at the head at which the\n * mutator is being applied.\n */\nexport interface ClientTransaction<S extends Schema = DefaultSchema>\n extends TransactionBase<S> {\n readonly location: 'client';\n readonly reason: 'optimistic' | 'rebase';\n}\n\nexport interface Row {\n [column: string]: unknown;\n}\n\nexport interface DBConnection<TWrappedTransaction> {\n transaction: <T>(\n cb: (tx: DBTransaction<TWrappedTransaction>) => Promise<T>,\n ) => Promise<T>;\n}\n\nexport interface DBTransaction<T> extends Queryable {\n readonly wrappedTransaction: T;\n runQuery<TReturn>(\n ast: AST,\n format: Format,\n schema: Schema,\n serverSchema: ServerSchema,\n ): Promise<HumanReadable<TReturn>>;\n}\n\ninterface Queryable {\n query: (query: string, args: unknown[]) => Promise<Iterable<Row>>;\n}\n\n/**\n * The type of `tx.mutate` which is:\n * 1. A callable function that accepts a `CRUDMutateRequest`\n * 2. When `enableLegacyMutators` is true, also an object with CRUD methods per table\n */\nexport type MutateCRUD<S extends Schema> = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (request: CRUDMutateRequest<S, any, any, any>): Promise<void>;\n} & (S['enableLegacyMutators'] extends true ? SchemaCRUD<S> : {});\n\nexport function customMutatorKey(sep: string, parts: string[]) {\n for (const part of parts) {\n assert(\n !part.includes(sep),\n `mutator names/namespaces must not include a ${sep}`,\n );\n }\n return parts.join(sep);\n}\n"],"names":[],"mappings":";
|
|
1
|
+
{"version":3,"file":"custom.js","sources":["../../../../../zql/src/mutate/custom.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {AST} from '../../../zero-protocol/src/ast.ts';\nimport type {\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../../zero-types/src/server-schema.ts';\nimport type {Format} from '../ivm/view.ts';\nimport type {HumanReadable, Query, RunOptions} from '../query/query.ts';\nimport type {SchemaQuery} from '../query/schema-query.ts';\nimport type {CRUDMutateRequest, SchemaCRUD} from './crud.ts';\nexport type {\n DeleteID,\n InsertValue,\n SchemaCRUD,\n TableCRUD,\n UpdateValue,\n UpsertValue,\n} from './crud.ts';\n\ntype ClientID = string;\n\n/**\n * A base transaction interface that any Transaction<S, T> is assignable to.\n * Used in places where the schema type doesn't need to be preserved,\n * like the public signature of Mutator.fn.\n */\nexport interface AnyTransaction {\n readonly location: Location;\n readonly clientID: string;\n readonly mutationID: number;\n readonly reason: TransactionReason;\n}\n\nexport type Location = 'client' | 'server';\nexport type TransactionReason = 'optimistic' | 'rebase' | 'authoritative';\n\nexport interface TransactionBase<S extends Schema> {\n readonly location: Location;\n readonly clientID: ClientID;\n /**\n * The ID of the mutation that is being applied.\n */\n readonly mutationID: number;\n\n /**\n * The reason for the transaction.\n */\n readonly reason: TransactionReason;\n\n readonly mutate: MutateCRUD<S>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: SchemaQuery<S>;\n\n run<TTable extends keyof S['tables'] & string, TReturn>(\n query: Query<TTable, S, TReturn>,\n options?: RunOptions,\n ): Promise<HumanReadable<TReturn>>;\n}\n\nexport type Transaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = ServerTransaction<S, TWrappedTransaction> | ClientTransaction<S>;\n\nexport interface ServerTransaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> extends TransactionBase<S> {\n readonly location: 'server';\n readonly reason: 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n}\n\n/**\n * An instance of this is passed to custom mutator implementations and\n * allows reading and writing to the database and IVM at the head at which the\n * mutator is being applied.\n */\nexport interface ClientTransaction<S extends Schema = DefaultSchema>\n extends TransactionBase<S> {\n readonly location: 'client';\n readonly reason: 'optimistic' | 'rebase';\n}\n\nexport interface Row {\n [column: string]: unknown;\n}\n\nexport interface DBConnection<TWrappedTransaction> {\n transaction: <T>(\n cb: (tx: DBTransaction<TWrappedTransaction>) => Promise<T>,\n ) => Promise<T>;\n}\n\nexport interface DBTransaction<T> extends Queryable {\n readonly wrappedTransaction: T;\n runQuery<TReturn>(\n ast: AST,\n format: Format,\n schema: Schema,\n serverSchema: ServerSchema,\n ): Promise<HumanReadable<TReturn>>;\n}\n\ninterface Queryable {\n query: (query: string, args: unknown[]) => Promise<Iterable<Row>>;\n}\n\n/**\n * The type of `tx.mutate` which is:\n * 1. A callable function that accepts a `CRUDMutateRequest`\n * 2. When `enableLegacyMutators` is true, also an object with CRUD methods per table\n */\nexport type MutateCRUD<S extends Schema> = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (request: CRUDMutateRequest<S, any, any, any>): Promise<void>;\n} & (S['enableLegacyMutators'] extends true ? SchemaCRUD<S> : {});\n\nexport function customMutatorKey(sep: string, parts: string[]) {\n for (const part of parts) {\n assert(\n !part.includes(sep),\n `mutator names/namespaces must not include a ${sep}`,\n );\n }\n return parts.join(sep);\n}\n"],"names":[],"mappings":";AA0HO,SAAS,iBAAiB,KAAa,OAAiB;AAC7D,aAAW,QAAQ,OAAO;AACxB;AAAA,MACE,CAAC,KAAK,SAAS,GAAG;AAAA,MAClB,+CAA+C,GAAG;AAAA,IAAA;AAAA,EAEtD;AACA,SAAO,MAAM,KAAK,GAAG;AACvB;"}
|
|
@@ -102,11 +102,11 @@ export declare function iterateMutators(registry: AnyMutatorRegistry): Iterable<
|
|
|
102
102
|
* Gets a Mutator by its dot-separated name from a MutatorRegistry.
|
|
103
103
|
* Returns undefined if not found.
|
|
104
104
|
*/
|
|
105
|
-
export declare function getMutator<MD extends MutatorDefinitions, TSchema extends Schema
|
|
105
|
+
export declare function getMutator<MD extends MutatorDefinitions, TSchema extends Schema>(registry: MutatorRegistry<MD, TSchema>, name: string): FromMutatorTree<MD, TSchema> | undefined;
|
|
106
106
|
/**
|
|
107
107
|
* Gets a Mutator by its dot-separated name from a MutatorRegistry.
|
|
108
108
|
* Throws if not found.
|
|
109
109
|
*/
|
|
110
|
-
export declare function mustGetMutator<MD extends MutatorDefinitions, TSchema extends Schema
|
|
110
|
+
export declare function mustGetMutator<MD extends MutatorDefinitions, TSchema extends Schema>(registry: MutatorRegistry<MD, TSchema>, name: string): FromMutatorTree<MD, TSchema>;
|
|
111
111
|
export {};
|
|
112
112
|
//# sourceMappingURL=mutator-registry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator-registry.d.ts","sourceRoot":"","sources":["../../../../../zql/src/mutate/mutator-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,SAAS,EACf,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAKnE,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,0CAA0C,CAAC;AAC5E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAG9D,OAAO,EAGL,KAAK,UAAU,EACf,KAAK,oBAAoB,EAGzB,KAAK,OAAO,EAIb,MAAM,cAAc,CAAC;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,wBAAgB,cAAc,CAE5B,KAAK,CAAC,EAAE,EACR,CAAC,SAAS,MAAM,GAAG,aAAa,EAGhC,WAAW,EAAE,EAAE,GAAG,wBAAwB,CAAC,EAAE,CAAC,GAC7C,eAAe,CAAC,wBAAwB,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;AAEpD,wBAAgB,cAAc,CAE5B,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,UAAU,EAChB,CAAC,SAAS,MAAM,GAAG,aAAa,EAEhC,IAAI,EACA,eAAe,CAAC,wBAAwB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GACnD,CAAC,KAAK,GAAG,wBAAwB,CAAC,KAAK,CAAC,CAAC,EAC7C,SAAS,EAAE,UAAU,GAAG,wBAAwB,CAAC,UAAU,CAAC,GAC3D,eAAe,CAChB,SAAS,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AExD,OAAO,CACL,iBAAiB,GAAG,SAAS,EAAE,yDAAyD;IACxF,OAAO,EACP,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,EACtB,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,qBAAqB,CAAC,CAClC,GACD,EAAE,CAAC,CAAC,CAAC,SAAS,kBAAkB,GAC9B,eAAe,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,GAC/B,KAAK;CACZ,CAAC,MAAM,EAAE,CAAC,CAAC;AAEZ;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,oBAAoB,GAAG,kBAAkB,CAAC;CACnE,CAAC;AAkEF,wBAAiB,eAAe,CAC9B,QAAQ,EAAE,kBAAkB,GAC3B,QAAQ,CAAC,UAAU,CAAC,CAEtB;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,EAAE,SAAS,kBAAkB,EAC7B,OAAO,SAAS,MAAM,EAEtB,QAAQ,EAAE,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,EACtC,IAAI,EAAE,MAAM,GACX,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,GAAG,SAAS,CAG1C;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,EAAE,SAAS,kBAAkB,EAC7B,OAAO,SAAS,MAAM,EAEtB,QAAQ,EAAE,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,EACtC,IAAI,EAAE,MAAM,GACX,eAAe,CAAC,EAAE,EAAE,OAAO,CAAC,CAM9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator-registry.js","sources":["../../../../../zql/src/mutate/mutator-registry.ts"],"sourcesContent":["import {\n deepMerge,\n isPlainObject,\n type DeepMerge,\n} from '../../../shared/src/deep-merge.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {\n getValueAtPath,\n iterateLeaves,\n} from '../../../shared/src/object-traversal.ts';\nimport type {DefaultSchema} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {validateInput} from '../query/validate-input.ts';\nimport type {Transaction} from './custom.ts';\nimport {\n isMutator,\n isMutatorDefinition,\n type AnyMutator,\n type AnyMutatorDefinition,\n type MutateRequest,\n type MutateRequestTypes,\n type Mutator,\n type MutatorDefinition,\n type MutatorDefinitionFunction,\n type MutatorTypes,\n} from './mutator.ts';\n\n/**\n * Creates a MutatorRegistry from a tree of MutatorDefinitions,\n * optionally extending a base MutatorRegistry.\n *\n * @example\n * ```ts\n * // Create a new registry\n * const mutators = defineMutators({\n * user: {\n * create: defineMutator(...),\n * delete: defineMutator(...),\n * },\n * post: {\n * publish: defineMutator(...),\n * },\n * });\n *\n * // Extend an existing registry (e.g., for server-side overrides)\n * const serverMutators = defineMutators(mutators, {\n * user: {\n * create: defineMutator(...), // overrides mutators.user.create\n * },\n * // post.publish is inherited from mutators\n * });\n *\n * // Access mutators by path\n * const mr = mutators.user.create({name: 'Alice'});\n *\n * // Execute on client\n * zero.mutate(mr);\n *\n * // Execute on server\n * mr.mutator.fn({tx, ctx, args: mr.args});\n *\n * // Lookup by name (for server-side dispatch)\n * const mutator = getMutator(mutators, 'user.create');\n * ```\n */\nexport function defineMutators<\n // let MD infer freely so defaults aren't erased by a MutatorDefinitions constraint\n const MD,\n S extends Schema = DefaultSchema,\n>(\n // we assert types here for clear error messages\n definitions: MD & AssertMutatorDefinitions<MD>,\n): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\nexport function defineMutators<\n // same as MD above, but for TBase and TOverrides\n const TBase,\n const TOverrides,\n S extends Schema = DefaultSchema,\n>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides & AssertMutatorDefinitions<TOverrides>,\n): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n>;\n\nexport function defineMutators(\n definitionsOrBase: MutatorDefinitions | AnyMutatorRegistry,\n maybeOverrides?: MutatorDefinitions,\n): AnyMutatorRegistry {\n function processDefinitions(\n definitions: MutatorDefinitions,\n path: string[],\n ): Record<string | symbol, unknown> {\n const result: Record<string | symbol, unknown> = {\n ['~']: 'MutatorRegistry',\n };\n\n for (const [key, value] of Object.entries(definitions)) {\n path.push(key);\n const name = path.join('.');\n\n if (isMutatorDefinition(value)) {\n result[key] = createMutator(name, value);\n } else {\n // Nested definitions\n result[key] = processDefinitions(value as MutatorDefinitions, path);\n }\n path.pop();\n }\n\n return result;\n }\n\n if (maybeOverrides !== undefined) {\n // Merge base and overrides\n let base: Record<string | symbol, unknown>;\n if (!isMutatorRegistry(definitionsOrBase)) {\n base = processDefinitions(definitionsOrBase, []);\n } else {\n base = definitionsOrBase;\n }\n\n const processed = processDefinitions(maybeOverrides, []);\n\n const merged = deepMerge(base, processed, isMutatorLeaf);\n merged['~'] = 'MutatorRegistry';\n return merged as AnyMutatorRegistry;\n }\n\n return processDefinitions(\n definitionsOrBase as MutatorDefinitions,\n [],\n ) as AnyMutatorRegistry;\n}\n\nconst isMutatorLeaf = (value: unknown): boolean =>\n !isPlainObject(value) || isMutator(value);\n\n/**\n * Creates a function that can be used to define mutators with a specific schema.\n */\nexport function defineMutatorsWithType<\n TSchema extends Schema,\n>(): TypedDefineMutators<TSchema> {\n return defineMutators;\n}\n\n/**\n * The return type of defineMutatorsWithType. A function matching the\n * defineMutators overloads but with Schema pre-bound.\n */\ntype TypedDefineMutators<S extends Schema> = {\n // Single definitions\n <MD>(\n definitions: MD & AssertMutatorDefinitions<MD>,\n ): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\n // Base and overrides\n <TBase, TOverrides>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides,\n ): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n >;\n};\n\nexport type AssertMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? unknown\n : never;\n\nexport type EnsureMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? MD\n : never;\n\n/**\n * Checks if a value is a MutatorRegistry.\n */\nexport function isMutatorRegistry(value: unknown): value is AnyMutatorRegistry {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)['~'] === 'MutatorRegistry'\n );\n}\n\nexport type MutatorRegistryTypes<TSchema extends Schema> = 'MutatorRegistry' & {\n readonly $schema: TSchema;\n};\n\n/**\n * The result of defineMutators(). A tree of Mutators with a tag for detection.\n */\nexport type MutatorRegistry<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = ToMutatorTree<MD, TSchema> & {\n ['~']: MutatorRegistryTypes<TSchema>;\n};\n\n/**\n * A branded type for use in type constraints. Use this instead of\n * `MutatorRegistry<S, C, any>` to avoid TypeScript drilling into\n * the complex ToMutatorTree structure and hitting variance issues.\n */\nexport type AnyMutatorRegistry = {\n ['~']: MutatorRegistryTypes<Schema>;\n [key: string]: unknown;\n};\n\n/**\n * Transforms a MutatorDefinitions into a tree of Mutators.\n * Each MutatorDefinition becomes a Mutator at the same path.\n * Uses TInput for the callable args (TOutput is only used internally for validation).\n */\nexport type ToMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n MD[K]['~']['$input'],\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? ToMutatorTree<MD[K], TSchema>\n : never;\n};\n\nexport type FromMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n ReadonlyJSONValue | undefined, // intentionally left as generic to avoid variance issues\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? FromMutatorTree<MD[K], TSchema>\n : never;\n}[keyof MD];\n\n/**\n * A tree of MutatorDefinitions, possibly nested.\n */\nexport type MutatorDefinitions = {\n readonly [key: string]: AnyMutatorDefinition | MutatorDefinitions;\n};\n\nfunction createMutator<\n ArgsInput extends ReadonlyJSONValue | undefined,\n ArgsOutput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n C,\n TWrappedTransaction,\n>(\n name: string,\n definition: MutatorDefinition<ArgsInput, ArgsOutput, C, TWrappedTransaction>,\n): Mutator<ArgsInput, TSchema, C, TWrappedTransaction> {\n const {validator} = definition;\n\n // fn takes ReadonlyJSONValue args because it's called during rebase (from\n // stored JSON) and on the server (from wire format). Validation happens here.\n const fn: MutatorDefinitionFunction<\n ArgsInput,\n C,\n Transaction<TSchema, TWrappedTransaction>\n > = async options => {\n const validatedArgs = validator\n ? validateInput(name, options.args, validator, 'mutator')\n : (options.args as unknown as ArgsOutput);\n await definition.fn({\n args: validatedArgs,\n ctx: options.ctx,\n tx: options.tx,\n });\n };\n\n const mutator = (\n args: ArgsInput,\n ): MutateRequest<ArgsInput, TSchema, C, TWrappedTransaction> => ({\n args,\n '~': 'MutateRequest' as MutateRequestTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n 'mutator': mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n });\n\n mutator.mutatorName = name;\n mutator.fn = fn;\n mutator['~'] = 'Mutator' as unknown as MutatorTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n\n return mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n}\n\nexport function* iterateMutators(\n registry: AnyMutatorRegistry,\n): Iterable<AnyMutator> {\n yield* iterateLeaves(registry, isMutator);\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Returns undefined if not found.\n */\nexport function getMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema = DefaultSchema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> | undefined {\n const m = getValueAtPath(registry, name, '.');\n return m as FromMutatorTree<MD, TSchema> | undefined;\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Throws if not found.\n */\nexport function mustGetMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema = DefaultSchema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> {\n const mutator = getMutator(registry, name);\n if (mutator === undefined) {\n throw new Error(`Mutator not found: ${name}`);\n }\n return mutator;\n}\n"],"names":[],"mappings":";;;;AA6FO,SAAS,eACd,mBACA,gBACoB;AACpB,WAAS,mBACP,aACA,MACkC;AAClC,UAAM,SAA2C;AAAA,MAC/C,CAAC,GAAG,GAAG;AAAA,IAAA;AAGT,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtD,WAAK,KAAK,GAAG;AACb,YAAM,OAAO,KAAK,KAAK,GAAG;AAE1B,UAAI,oBAAoB,KAAK,GAAG;AAC9B,eAAO,GAAG,IAAI,cAAc,MAAM,KAAK;AAAA,MACzC,OAAO;AAEL,eAAO,GAAG,IAAI,mBAAmB,OAA6B,IAAI;AAAA,MACpE;AACA,WAAK,IAAA;AAAA,IACP;AAEA,WAAO;AAAA,EACT;AAEA,MAAI,mBAAmB,QAAW;AAEhC,QAAI;AACJ,QAAI,CAAC,kBAAkB,iBAAiB,GAAG;AACzC,aAAO,mBAAmB,mBAAmB,EAAE;AAAA,IACjD,OAAO;AACL,aAAO;AAAA,IACT;AAEA,UAAM,YAAY,mBAAmB,gBAAgB,EAAE;AAEvD,UAAM,SAAS,UAAU,MAAM,WAAW,aAAa;AACvD,WAAO,GAAG,IAAI;AACd,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL;AAAA,IACA,CAAA;AAAA,EAAC;AAEL;AAEA,MAAM,gBAAgB,CAAC,UACrB,CAAC,cAAc,KAAK,KAAK,UAAU,KAAK;AAKnC,SAAS,yBAEkB;AAChC,SAAO;AACT;AAuCO,SAAS,kBAAkB,OAA6C;AAC7E,SACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,GAAG,MAAM;AAEhD;AAwEA,SAAS,cAOP,MACA,YACqD;AACrD,QAAM,EAAC,cAAa;AAIpB,QAAM,KAIF,OAAM,YAAW;AACnB,UAAM,gBAAgB,YAClB,cAAc,MAAM,QAAQ,MAAM,WAAW,SAAS,IACrD,QAAQ;AACb,UAAM,WAAW,GAAG;AAAA,MAClB,MAAM;AAAA,MACN,KAAK,QAAQ;AAAA,MACb,IAAI,QAAQ;AAAA,IAAA,CACb;AAAA,EACH;AAEA,QAAM,UAAU,CACd,UAC+D;AAAA,IAC/D;AAAA,IACA,KAAK;AAAA,IAML,WAAW;AAAA,EAAA;AAQb,UAAQ,cAAc;AACtB,UAAQ,KAAK;AACb,UAAQ,GAAG,IAAI;AAOf,SAAO;AAMT;AAEO,UAAU,gBACf,UACsB;AACtB,SAAO,cAAc,UAAU,SAAS;AAC1C;AAMO,SAAS,WAId,UACA,MAC0C;AAC1C,QAAM,IAAI,eAAe,UAAU,MAAM,GAAG;AAC5C,SAAO;AACT;AAMO,SAAS,eAId,UACA,MAC8B;AAC9B,QAAM,UAAU,WAAW,UAAU,IAAI;AACzC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,sBAAsB,IAAI,EAAE;AAAA,EAC9C;AACA,SAAO;AACT;"}
|
|
1
|
+
{"version":3,"file":"mutator-registry.js","sources":["../../../../../zql/src/mutate/mutator-registry.ts"],"sourcesContent":["import {\n deepMerge,\n isPlainObject,\n type DeepMerge,\n} from '../../../shared/src/deep-merge.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {\n getValueAtPath,\n iterateLeaves,\n} from '../../../shared/src/object-traversal.ts';\nimport type {DefaultSchema} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {validateInput} from '../query/validate-input.ts';\nimport type {Transaction} from './custom.ts';\nimport {\n isMutator,\n isMutatorDefinition,\n type AnyMutator,\n type AnyMutatorDefinition,\n type MutateRequest,\n type MutateRequestTypes,\n type Mutator,\n type MutatorDefinition,\n type MutatorDefinitionFunction,\n type MutatorTypes,\n} from './mutator.ts';\n\n/**\n * Creates a MutatorRegistry from a tree of MutatorDefinitions,\n * optionally extending a base MutatorRegistry.\n *\n * @example\n * ```ts\n * // Create a new registry\n * const mutators = defineMutators({\n * user: {\n * create: defineMutator(...),\n * delete: defineMutator(...),\n * },\n * post: {\n * publish: defineMutator(...),\n * },\n * });\n *\n * // Extend an existing registry (e.g., for server-side overrides)\n * const serverMutators = defineMutators(mutators, {\n * user: {\n * create: defineMutator(...), // overrides mutators.user.create\n * },\n * // post.publish is inherited from mutators\n * });\n *\n * // Access mutators by path\n * const mr = mutators.user.create({name: 'Alice'});\n *\n * // Execute on client\n * zero.mutate(mr);\n *\n * // Execute on server\n * mr.mutator.fn({tx, ctx, args: mr.args});\n *\n * // Lookup by name (for server-side dispatch)\n * const mutator = getMutator(mutators, 'user.create');\n * ```\n */\nexport function defineMutators<\n // let MD infer freely so defaults aren't erased by a MutatorDefinitions constraint\n const MD,\n S extends Schema = DefaultSchema,\n>(\n // we assert types here for clear error messages\n definitions: MD & AssertMutatorDefinitions<MD>,\n): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\nexport function defineMutators<\n // same as MD above, but for TBase and TOverrides\n const TBase,\n const TOverrides,\n S extends Schema = DefaultSchema,\n>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides & AssertMutatorDefinitions<TOverrides>,\n): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n>;\n\nexport function defineMutators(\n definitionsOrBase: MutatorDefinitions | AnyMutatorRegistry,\n maybeOverrides?: MutatorDefinitions,\n): AnyMutatorRegistry {\n function processDefinitions(\n definitions: MutatorDefinitions,\n path: string[],\n ): Record<string | symbol, unknown> {\n const result: Record<string | symbol, unknown> = {\n ['~']: 'MutatorRegistry',\n };\n\n for (const [key, value] of Object.entries(definitions)) {\n path.push(key);\n const name = path.join('.');\n\n if (isMutatorDefinition(value)) {\n result[key] = createMutator(name, value);\n } else {\n // Nested definitions\n result[key] = processDefinitions(value, path);\n }\n path.pop();\n }\n\n return result;\n }\n\n if (maybeOverrides !== undefined) {\n // Merge base and overrides\n let base: Record<string | symbol, unknown>;\n if (!isMutatorRegistry(definitionsOrBase)) {\n base = processDefinitions(definitionsOrBase, []);\n } else {\n base = definitionsOrBase;\n }\n\n const processed = processDefinitions(maybeOverrides, []);\n\n const merged = deepMerge(base, processed, isMutatorLeaf);\n merged['~'] = 'MutatorRegistry';\n return merged as AnyMutatorRegistry;\n }\n\n return processDefinitions(\n definitionsOrBase as MutatorDefinitions,\n [],\n ) as AnyMutatorRegistry;\n}\n\nconst isMutatorLeaf = (value: unknown): boolean =>\n !isPlainObject(value) || isMutator(value);\n\n/**\n * Creates a function that can be used to define mutators with a specific schema.\n */\nexport function defineMutatorsWithType<\n TSchema extends Schema,\n>(): TypedDefineMutators<TSchema> {\n return defineMutators;\n}\n\n/**\n * The return type of defineMutatorsWithType. A function matching the\n * defineMutators overloads but with Schema pre-bound.\n */\ntype TypedDefineMutators<S extends Schema> = {\n // Single definitions\n <MD>(\n definitions: MD & AssertMutatorDefinitions<MD>,\n ): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\n // Base and overrides\n <TBase, TOverrides>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides,\n ): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n >;\n};\n\nexport type AssertMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? unknown\n : never;\n\nexport type EnsureMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? MD\n : never;\n\n/**\n * Checks if a value is a MutatorRegistry.\n */\nexport function isMutatorRegistry(value: unknown): value is AnyMutatorRegistry {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)['~'] === 'MutatorRegistry'\n );\n}\n\nexport type MutatorRegistryTypes<TSchema extends Schema> = 'MutatorRegistry' & {\n readonly $schema: TSchema;\n};\n\n/**\n * The result of defineMutators(). A tree of Mutators with a tag for detection.\n */\nexport type MutatorRegistry<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = ToMutatorTree<MD, TSchema> & {\n ['~']: MutatorRegistryTypes<TSchema>;\n};\n\n/**\n * A branded type for use in type constraints. Use this instead of\n * `MutatorRegistry<S, C, any>` to avoid TypeScript drilling into\n * the complex ToMutatorTree structure and hitting variance issues.\n */\nexport type AnyMutatorRegistry = {\n ['~']: MutatorRegistryTypes<Schema>;\n [key: string]: unknown;\n};\n\n/**\n * Transforms a MutatorDefinitions into a tree of Mutators.\n * Each MutatorDefinition becomes a Mutator at the same path.\n * Uses TInput for the callable args (TOutput is only used internally for validation).\n */\nexport type ToMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n MD[K]['~']['$input'],\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? ToMutatorTree<MD[K], TSchema>\n : never;\n};\n\nexport type FromMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n ReadonlyJSONValue | undefined, // intentionally left as generic to avoid variance issues\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? FromMutatorTree<MD[K], TSchema>\n : never;\n}[keyof MD];\n\n/**\n * A tree of MutatorDefinitions, possibly nested.\n */\nexport type MutatorDefinitions = {\n readonly [key: string]: AnyMutatorDefinition | MutatorDefinitions;\n};\n\nfunction createMutator<\n ArgsInput extends ReadonlyJSONValue | undefined,\n ArgsOutput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n C,\n TWrappedTransaction,\n>(\n name: string,\n definition: MutatorDefinition<ArgsInput, ArgsOutput, C, TWrappedTransaction>,\n): Mutator<ArgsInput, TSchema, C, TWrappedTransaction> {\n const {validator} = definition;\n\n // fn takes ReadonlyJSONValue args because it's called during rebase (from\n // stored JSON) and on the server (from wire format). Validation happens here.\n const fn: MutatorDefinitionFunction<\n ArgsInput,\n C,\n Transaction<TSchema, TWrappedTransaction>\n > = async options => {\n const validatedArgs = validator\n ? validateInput(name, options.args, validator, 'mutator')\n : (options.args as unknown as ArgsOutput);\n await definition.fn({\n args: validatedArgs,\n ctx: options.ctx,\n tx: options.tx,\n });\n };\n\n const mutator = (\n args: ArgsInput,\n ): MutateRequest<ArgsInput, TSchema, C, TWrappedTransaction> => ({\n args,\n '~': 'MutateRequest' as MutateRequestTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n 'mutator': mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n });\n\n mutator.mutatorName = name;\n mutator.fn = fn;\n mutator['~'] = 'Mutator' as unknown as MutatorTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n\n return mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n}\n\nexport function* iterateMutators(\n registry: AnyMutatorRegistry,\n): Iterable<AnyMutator> {\n yield* iterateLeaves(registry, isMutator);\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Returns undefined if not found.\n */\nexport function getMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> | undefined {\n const m = getValueAtPath(registry, name, '.');\n return m as FromMutatorTree<MD, TSchema> | undefined;\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Throws if not found.\n */\nexport function mustGetMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> {\n const mutator = getMutator(registry, name);\n if (mutator === undefined) {\n throw new Error(`Mutator not found: ${name}`);\n }\n return mutator;\n}\n"],"names":[],"mappings":";;;;AA6FO,SAAS,eACd,mBACA,gBACoB;AACpB,WAAS,mBACP,aACA,MACkC;AAClC,UAAM,SAA2C;AAAA,MAC/C,CAAC,GAAG,GAAG;AAAA,IAAA;AAGT,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACtD,WAAK,KAAK,GAAG;AACb,YAAM,OAAO,KAAK,KAAK,GAAG;AAE1B,UAAI,oBAAoB,KAAK,GAAG;AAC9B,eAAO,GAAG,IAAI,cAAc,MAAM,KAAK;AAAA,MACzC,OAAO;AAEL,eAAO,GAAG,IAAI,mBAAmB,OAAO,IAAI;AAAA,MAC9C;AACA,WAAK,IAAA;AAAA,IACP;AAEA,WAAO;AAAA,EACT;AAEA,MAAI,mBAAmB,QAAW;AAEhC,QAAI;AACJ,QAAI,CAAC,kBAAkB,iBAAiB,GAAG;AACzC,aAAO,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,7 +72,7 @@ export type AnyMutator = Mutator<any, any, any, any>;
|
|
|
72
72
|
* Checks if a value is a Mutator (the result of processing a MutatorDefinition
|
|
73
73
|
* through defineMutators).
|
|
74
74
|
*/
|
|
75
|
-
export declare function isMutator(value: unknown): value is
|
|
75
|
+
export declare function isMutator<S extends Schema>(value: unknown): value is Mutator<any, S, any, any>;
|
|
76
76
|
export type MutateRequestTypes<TInput extends ReadonlyJSONValue | undefined, TSchema extends Schema, TContext, TWrappedTransaction> = 'MutateRequest' & {
|
|
77
77
|
readonly $input: TInput;
|
|
78
78
|
readonly $schema: TSchema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator.d.ts","sourceRoot":"","sources":["../../../../../zql/src/mutate/mutator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,uBAAuB,CAAC;AAC5D,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,6BAA6B,CAAC;AAEnE,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,yBAAyB,EAC1B,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAC9D,OAAO,KAAK,EAAC,cAAc,EAAE,WAAW,EAAC,MAAM,aAAa,CAAC;AAM7D,MAAM,MAAM,sBAAsB,CAChC,MAAM,SAAS,iBAAiB,GAAG,SAAS,EAC5C,OAAO,EACP,QAAQ,EACR,mBAAmB,IACjB,mBAAmB,GAAG;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;CACnD,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAC3B,MAAM,SAAS,iBAAiB,GAAG,SAAS,EAC5C,OAAO,SAAS,iBAAiB,GAAG,SA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ard-schema/spec';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n DefaultContext,\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {AnyTransaction, Transaction} from './custom.ts';\n\n// ----------------------------------------------------------------------------\n// defineMutator\n// ----------------------------------------------------------------------------\n\nexport type MutatorDefinitionTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput,\n TContext,\n TWrappedTransaction,\n> = 'MutatorDefinition' & {\n readonly $input: TInput;\n readonly $output: TOutput;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\nexport type MutatorDefinition<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'fn': MutatorDefinitionFunction<TOutput, TContext, AnyTransaction>;\n readonly 'validator': StandardSchemaV1<TInput, TOutput> | undefined;\n readonly '~': MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutatorDefinition = MutatorDefinition<any, any, any, any>;\n\nexport function isMutatorDefinition(f: unknown): f is AnyMutatorDefinition {\n return (\n typeof f === 'object' &&\n f !== null &&\n (f as {['~']?: unknown})['~'] === 'MutatorDefinition'\n );\n}\n\n// Overload for no validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n mutator: MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TInput, TContext, TWrappedTransaction>;\n\n// Overload for validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n\n// Implementation\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validatorOrMutator:\n | StandardSchemaV1<TInput, TOutput>\n | MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n mutator?: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction> {\n let validator: StandardSchemaV1<TInput, TOutput> | undefined;\n let actualMutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n\n if (typeof validatorOrMutator === 'function') {\n // defineMutator(mutator) - no validator\n validator = undefined;\n actualMutator = validatorOrMutator;\n } else {\n // defineMutator(validator, mutator)\n validator = validatorOrMutator;\n actualMutator = must(mutator);\n }\n\n const mutatorDefinition: MutatorDefinition<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n > = {\n 'fn': actualMutator as MutatorDefinitionFunction<\n TOutput,\n TContext,\n AnyTransaction\n >,\n 'validator': validator,\n '~': 'MutatorDefinition' as unknown as MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >,\n };\n return mutatorDefinition;\n}\n\n// intentionally not using DefaultSchema, DefaultContext, or DefaultWrappedTransaction\nexport function defineMutatorWithType<\n TSchema extends Schema,\n TContext = unknown,\n TWrappedTransaction = unknown,\n>(): TypedDefineMutator<TSchema, TContext, TWrappedTransaction> {\n return defineMutator;\n}\n\n/**\n * The return type of defineMutatorWithType. A function matching the\n * defineMutator overloads but with Schema, Context, and WrappedTransaction\n * pre-bound.\n *\n * This is used as a workaround to using DefaultTypes (e.g. when using\n * multiple Zero instances).\n */\ntype TypedDefineMutator<\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = {\n // Without validator\n <TArgs extends ReadonlyJSONValue | undefined>(\n mutator: MutatorDefinitionFunction<\n TArgs,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TArgs, TArgs, TContext, TWrappedTransaction>;\n\n // With validator\n <\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n >(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n};\n\nexport type MutatorDefinitionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (options: {\n args: TOutput;\n ctx: TContext;\n tx: TTransaction;\n}) => Promise<void>;\n\n// ----------------------------------------------------------------------------\n// Mutator and MutateRequest types\n// ----------------------------------------------------------------------------\n\nexport type MutatorTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'Mutator' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * A callable wrapper around a MutatorDefinition, created by `defineMutators()`.\n *\n * Accessed like `mutators.foo.bar`, and called to create a MutateRequest:\n * `mutators.foo.bar(42)` returns a `MutateRequest`.\n *\n * The `fn` property is used for execution and takes raw JSON args (for rebase\n * and server wire format cases) that are validated internally.\n */\nexport type Mutator<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutatorName': string;\n /**\n * Execute the mutation. Args are ReadonlyJSONValue because this is called\n * during rebase (from stored JSON) and on the server (from wire format).\n * Validation happens internally before the recipe function runs.\n */\n readonly 'fn': MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n readonly '~': MutatorTypes<TInput, TSchema, TContext, TWrappedTransaction>;\n} & MutatorCallable<TInput, TSchema, TContext, TWrappedTransaction>;\n\n// Helper type for the callable part of Mutator\n// When TInput is undefined, the function is callable with 0 args\n// When TInput includes undefined (optional), args is optional\n// Otherwise, args is required\ntype MutatorCallable<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = [TInput] extends [undefined]\n ? () => MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>\n : undefined extends TInput\n ? {\n (): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n (\n args?: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n }\n : {\n (\n args: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n };\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutator = Mutator<any, any, any, any>;\n\n/**\n * Checks if a value is a Mutator (the result of processing a MutatorDefinition\n * through defineMutators).\n */\nexport function isMutator(value: unknown): value is AnyMutator {\n return (\n typeof value === 'function' &&\n typeof (value as {mutatorName?: unknown}).mutatorName === 'string' &&\n typeof (value as {fn?: unknown}).fn === 'function'\n );\n}\n\nexport type MutateRequestTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'MutateRequest' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * The result of calling a Mutator with arguments.\n *\n * Created by `mutators.foo.bar(42)`, executed by `zero.mutate(mr)` on the client\n * or `mr.mutator.fn({tx, ctx, args: mr.args})` on the server.\n */\nexport type MutateRequest<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutator': Mutator<TInput, TSchema, TContext, TWrappedTransaction>;\n readonly 'args': TInput;\n readonly '~': MutateRequestTypes<\n TInput,\n TSchema,\n TContext,\n TWrappedTransaction\n >;\n};\n"],"names":[],"mappings":";AA8CO,SAAS,oBAAoB,GAAuC;AACzE,SACE,OAAO,MAAM,YACb,MAAM,QACL,EAAwB,GAAG,MAAM;AAEtC;AAiCO,SAAS,cAOd,oBAOA,SAKmE;AACnE,MAAI;AACJ,MAAI;AAMJ,MAAI,OAAO,uBAAuB,YAAY;AAE5C,gBAAY;AACZ,oBAAgB;AAAA,EAClB,OAAO;AAEL,gBAAY;AACZ,oBAAgB,KAAK,OAAO;AAAA,EAC9B;AAEA,QAAM,oBAKF;AAAA,IACF,MAAM;AAAA,IAKN,aAAa;AAAA,IACb,KAAK;AAAA,EAAA;AAOP,SAAO;AACT;AAGO,SAAS,wBAIgD;AAC9D,SAAO;AACT;AA4HO,SAAS,UAAU,OAAqC;AAC7D,SACE,OAAO,UAAU,cACjB,OAAQ,MAAkC,gBAAgB,YAC1D,OAAQ,MAAyB,OAAO;AAE5C;"}
|
|
1
|
+
{"version":3,"file":"mutator.js","sources":["../../../../../zql/src/mutate/mutator.ts"],"sourcesContent":["import type {StandardSchemaV1} from '@standard-schema/spec';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n DefaultContext,\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {AnyTransaction, Transaction} from './custom.ts';\n\n// ----------------------------------------------------------------------------\n// defineMutator\n// ----------------------------------------------------------------------------\n\nexport type MutatorDefinitionTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput,\n TContext,\n TWrappedTransaction,\n> = 'MutatorDefinition' & {\n readonly $input: TInput;\n readonly $output: TOutput;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\nexport type MutatorDefinition<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'fn': MutatorDefinitionFunction<TOutput, TContext, AnyTransaction>;\n readonly 'validator': StandardSchemaV1<TInput, TOutput> | undefined;\n readonly '~': MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutatorDefinition = MutatorDefinition<any, any, any, any>;\n\nexport function isMutatorDefinition(f: unknown): f is AnyMutatorDefinition {\n return (\n typeof f === 'object' &&\n f !== null &&\n (f as {['~']?: unknown})['~'] === 'MutatorDefinition'\n );\n}\n\n// Overload for no validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n mutator: MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TInput, TContext, TWrappedTransaction>;\n\n// Overload for validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n\n// Implementation\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validatorOrMutator:\n | StandardSchemaV1<TInput, TOutput>\n | MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n mutator?: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction> {\n let validator: StandardSchemaV1<TInput, TOutput> | undefined;\n let actualMutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n\n if (typeof validatorOrMutator === 'function') {\n // defineMutator(mutator) - no validator\n validator = undefined;\n actualMutator = validatorOrMutator;\n } else {\n // defineMutator(validator, mutator)\n validator = validatorOrMutator;\n actualMutator = must(mutator);\n }\n\n const mutatorDefinition: MutatorDefinition<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n > = {\n 'fn': actualMutator as MutatorDefinitionFunction<\n TOutput,\n TContext,\n AnyTransaction\n >,\n 'validator': validator,\n '~': 'MutatorDefinition' as unknown as MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >,\n };\n return mutatorDefinition;\n}\n\n// intentionally not using DefaultSchema, DefaultContext, or DefaultWrappedTransaction\nexport function defineMutatorWithType<\n TSchema extends Schema,\n TContext = unknown,\n TWrappedTransaction = unknown,\n>(): TypedDefineMutator<TSchema, TContext, TWrappedTransaction> {\n return defineMutator;\n}\n\n/**\n * The return type of defineMutatorWithType. A function matching the\n * defineMutator overloads but with Schema, Context, and WrappedTransaction\n * pre-bound.\n *\n * This is used as a workaround to using DefaultTypes (e.g. when using\n * multiple Zero instances).\n */\ntype TypedDefineMutator<\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = {\n // Without validator\n <TArgs extends ReadonlyJSONValue | undefined>(\n mutator: MutatorDefinitionFunction<\n TArgs,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TArgs, TArgs, TContext, TWrappedTransaction>;\n\n // With validator\n <\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n >(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n};\n\nexport type MutatorDefinitionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (options: {\n args: TOutput;\n ctx: TContext;\n tx: TTransaction;\n}) => Promise<void>;\n\n// ----------------------------------------------------------------------------\n// Mutator and MutateRequest types\n// ----------------------------------------------------------------------------\n\nexport type MutatorTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'Mutator' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * A callable wrapper around a MutatorDefinition, created by `defineMutators()`.\n *\n * Accessed like `mutators.foo.bar`, and called to create a MutateRequest:\n * `mutators.foo.bar(42)` returns a `MutateRequest`.\n *\n * The `fn` property is used for execution and takes raw JSON args (for rebase\n * and server wire format cases) that are validated internally.\n */\nexport type Mutator<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutatorName': string;\n /**\n * Execute the mutation. Args are ReadonlyJSONValue because this is called\n * during rebase (from stored JSON) and on the server (from wire format).\n * Validation happens internally before the recipe function runs.\n */\n readonly 'fn': MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n readonly '~': MutatorTypes<TInput, TSchema, TContext, TWrappedTransaction>;\n} & MutatorCallable<TInput, TSchema, TContext, TWrappedTransaction>;\n\n// Helper type for the callable part of Mutator\n// When TInput is undefined, the function is callable with 0 args\n// When TInput includes undefined (optional), args is optional\n// Otherwise, args is required\ntype MutatorCallable<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = [TInput] extends [undefined]\n ? () => MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>\n : undefined extends TInput\n ? {\n (): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n (\n args?: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n }\n : {\n (\n args: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n };\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutator = Mutator<any, any, any, any>;\n\n/**\n * Checks if a value is a Mutator (the result of processing a MutatorDefinition\n * through defineMutators).\n */\nexport function isMutator<S extends Schema>(\n value: unknown,\n // oxlint-disable-next-line no-explicit-any\n): value is Mutator<any, S, any, any> {\n return (\n typeof value === 'function' &&\n typeof (value as {mutatorName?: unknown}).mutatorName === 'string' &&\n typeof (value as {fn?: unknown}).fn === 'function'\n );\n}\n\nexport type MutateRequestTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'MutateRequest' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * The result of calling a Mutator with arguments.\n *\n * Created by `mutators.foo.bar(42)`, executed by `zero.mutate(mr)` on the client\n * or `mr.mutator.fn({tx, ctx, args: mr.args})` on the server.\n */\nexport type MutateRequest<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutator': Mutator<TInput, TSchema, TContext, TWrappedTransaction>;\n readonly 'args': TInput;\n readonly '~': MutateRequestTypes<\n TInput,\n TSchema,\n TContext,\n TWrappedTransaction\n >;\n};\n"],"names":[],"mappings":";AA8CO,SAAS,oBAAoB,GAAuC;AACzE,SACE,OAAO,MAAM,YACb,MAAM,QACL,EAAwB,GAAG,MAAM;AAEtC;AAiCO,SAAS,cAOd,oBAOA,SAKmE;AACnE,MAAI;AACJ,MAAI;AAMJ,MAAI,OAAO,uBAAuB,YAAY;AAE5C,gBAAY;AACZ,oBAAgB;AAAA,EAClB,OAAO;AAEL,gBAAY;AACZ,oBAAgB,KAAK,OAAO;AAAA,EAC9B;AAEA,QAAM,oBAKF;AAAA,IACF,MAAM;AAAA,IAKN,aAAa;AAAA,IACb,KAAK;AAAA,EAAA;AAOP,SAAO;AACT;AAGO,SAAS,wBAIgD;AAC9D,SAAO;AACT;AA4HO,SAAS,UACd,OAEoC;AACpC,SACE,OAAO,UAAU,cACjB,OAAQ,MAAkC,gBAAgB,YAC1D,OAAQ,MAAyB,OAAO;AAE5C;"}
|
|
@@ -133,9 +133,9 @@ export declare function serializePlanDebugEvents(events: PlanDebugEvent[]): Plan
|
|
|
133
133
|
*
|
|
134
134
|
* @example
|
|
135
135
|
* ```typescript
|
|
136
|
-
* const result = await inspector.analyzeQuery(query, {
|
|
137
|
-
* if (result.
|
|
138
|
-
* console.log(formatPlannerEvents(result.
|
|
136
|
+
* const result = await inspector.analyzeQuery(query, { joinPlans: true });
|
|
137
|
+
* if (result.joinPlans) {
|
|
138
|
+
* console.log(formatPlannerEvents(result.joinPlans));
|
|
139
139
|
* }
|
|
140
140
|
* ```
|
|
141
141
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-debug.js","sources":["../../../../../zql/src/planner/planner-debug.ts"],"sourcesContent":["import type * as v from '../../../shared/src/valita.ts';\nimport type {\n Condition,\n Ordering,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {\n attemptStartEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n connectionSelectedEventJSONSchema,\n nodeConstraintEventJSONSchema,\n PlanDebugEventJSON,\n planFailedEventJSONSchema,\n} from '../../../zero-protocol/src/analyze-query-result.ts';\nimport type {PlannerConstraint} from './planner-constraint.ts';\nimport type {CostEstimate, JoinType} from './planner-node.ts';\nimport type {PlanState} from './planner-graph.ts';\n\n/**\n * Structured debug events emitted during query planning.\n * These events can be accumulated, printed, or analyzed to understand\n * the planner's decision-making process.\n */\n\n/**\n * Starting a new planning attempt with a different root connection.\n */\nexport type AttemptStartEvent = v.Infer<typeof attemptStartEventJSONSchema>;\n\n/**\n * Snapshot of connection costs before selecting the next connection.\n */\nexport type ConnectionCostsEvent = {\n type: 'connection-costs';\n attemptNumber: number;\n costs: Array<{\n connection: string;\n cost: number;\n costEstimate: Omit<CostEstimate, 'fanout'>;\n pinned: boolean;\n constraints: Record<string, PlannerConstraint | undefined>;\n constraintCosts: Record<string, Omit<CostEstimate, 'fanout'>>;\n }>;\n};\n\n/**\n * A connection was chosen and pinned.\n */\nexport type ConnectionSelectedEvent = v.Infer<\n typeof connectionSelectedEventJSONSchema\n>;\n\n/**\n * Constraints have been propagated through the graph.\n */\nexport type ConstraintsPropagatedEvent = {\n type: 'constraints-propagated';\n attemptNumber: number;\n connectionConstraints: Array<{\n connection: string;\n constraints: Record<string, PlannerConstraint | undefined>;\n constraintCosts: Record<string, Omit<CostEstimate, 'fanout'>>;\n }>;\n};\n\n/**\n * A complete plan was found for this attempt.\n */\nexport type PlanCompleteEvent = {\n type: 'plan-complete';\n attemptNumber: number;\n totalCost: number;\n flipPattern: number; // Bitmask indicating which joins are flipped\n joinStates: Array<{\n join: string;\n type: JoinType;\n }>;\n // Planning snapshot that can be restored and applied to AST\n planSnapshot: PlanState;\n};\n\n/**\n * Planning attempt failed (e.g., unflippable join).\n */\nexport type PlanFailedEvent = v.Infer<typeof planFailedEventJSONSchema>;\n\n/**\n * The best plan across all attempts was selected.\n */\nexport type BestPlanSelectedEvent = v.Infer<\n typeof bestPlanSelectedEventJSONSchema\n>;\n\n/**\n * A node computed its cost estimate during planning.\n * Emitted by nodes during estimateCost() traversal.\n * attemptNumber is added by the debugger.\n */\nexport type NodeCostEvent = {\n type: 'node-cost';\n attemptNumber?: number;\n nodeType: 'connection' | 'join' | 'fan-out' | 'fan-in' | 'terminus';\n node: string;\n branchPattern: number[];\n downstreamChildSelectivity: number;\n costEstimate: Omit<CostEstimate, 'fanout'>;\n filters?: Condition | undefined; // Only for connections\n ordering?: Ordering | undefined; // Only for connections\n joinType?: JoinType | undefined; // Only for joins\n};\n\n/**\n * A node received constraints during constraint propagation.\n * Emitted by nodes during propagateConstraints() traversal.\n * attemptNumber is added by the debugger.\n */\nexport type NodeConstraintEvent = v.Infer<typeof nodeConstraintEventJSONSchema>;\n\n/**\n * Union of all debug event types.\n */\nexport type PlanDebugEvent =\n | AttemptStartEvent\n | ConnectionCostsEvent\n | ConnectionSelectedEvent\n | ConstraintsPropagatedEvent\n | PlanCompleteEvent\n | PlanFailedEvent\n | BestPlanSelectedEvent\n | NodeCostEvent\n | NodeConstraintEvent;\n\n/**\n * Interface for objects that receive debug events during planning.\n */\nexport interface PlanDebugger {\n log(event: PlanDebugEvent): void;\n}\n\n/**\n * Simple accumulator debugger that stores all events.\n * Useful for tests and debugging.\n */\nexport class AccumulatorDebugger implements PlanDebugger {\n readonly events: PlanDebugEvent[] = [];\n private currentAttempt = 0;\n\n log(event: PlanDebugEvent): void {\n // Track current attempt number\n if (event.type === 'attempt-start') {\n this.currentAttempt = event.attemptNumber;\n }\n\n // Add attempt number to node events\n if (event.type === 'node-cost' || event.type === 'node-constraint') {\n (event as NodeCostEvent | NodeConstraintEvent).attemptNumber =\n this.currentAttempt;\n }\n\n this.events.push(event);\n }\n\n /**\n * Get all events of a specific type.\n */\n getEvents<T extends PlanDebugEvent['type']>(\n type: T,\n ): Extract<PlanDebugEvent, {type: T}>[] {\n return this.events.filter(e => e.type === type) as Extract<\n PlanDebugEvent,\n {type: T}\n >[];\n }\n\n /**\n * Format events as a human-readable string.\n */\n format(): string {\n return formatPlannerEvents(this.events);\n }\n}\n\n/**\n * Format a constraint object as a human-readable string.\n */\nfunction formatConstraint(\n constraint: PlannerConstraint | Record<string, unknown> | null | undefined,\n): string {\n if (!constraint) return '{}';\n const keys = Object.keys(constraint);\n if (keys.length === 0) return '{}';\n return '{' + keys.join(', ') + '}';\n}\n\n/**\n * Format a ValuePosition (column, literal, or static parameter) as a human-readable string.\n */\nfunction formatValuePosition(value: ValuePosition): string {\n switch (value.type) {\n case 'column':\n return value.name;\n case 'literal':\n // Format literal values with SQL-style quoting for strings\n if (typeof value.value === 'string') {\n return `'${value.value}'`;\n }\n return JSON.stringify(value.value);\n case 'static':\n return `@${value.anchor}.${Array.isArray(value.field) ? value.field.join('.') : value.field}`;\n }\n}\n\n/**\n * Format a Condition (filter) as a human-readable string.\n */\nfunction formatFilter(filter: Condition | undefined): string {\n if (!filter) return 'none';\n\n switch (filter.type) {\n case 'simple':\n return `${formatValuePosition(filter.left)} ${filter.op} ${formatValuePosition(filter.right)}`;\n case 'and':\n return `(${filter.conditions.map(formatFilter).join(' AND ')})`;\n case 'or':\n return `(${filter.conditions.map(formatFilter).join(' OR ')})`;\n case 'correlatedSubquery':\n return `EXISTS(${filter.related.subquery.table})`;\n default:\n return JSON.stringify(filter);\n }\n}\n\n/**\n * Format an Ordering as a human-readable string.\n */\nfunction formatOrdering(ordering: Ordering | undefined): string {\n if (!ordering || ordering.length === 0) return 'none';\n return ordering\n .map(([field, direction]) => `${field} ${direction}`)\n .join(', ');\n}\n\n/**\n * Format a compact summary for a single planning attempt.\n */\nfunction formatAttemptSummary(\n attemptNum: number,\n events: (PlanDebugEvent | PlanDebugEventJSON)[],\n): string[] {\n const lines: string[] = [];\n\n // Find the attempt-start event to get total attempts\n const startEvent = events.find(e => e.type === 'attempt-start') as\n | AttemptStartEvent\n | undefined;\n const totalAttempts = startEvent?.totalAttempts ?? '?';\n\n // Calculate number of bits needed for pattern\n const numBits =\n typeof totalAttempts === 'number'\n ? Math.ceil(Math.log2(totalAttempts)) || 1\n : 1;\n const bitPattern = attemptNum.toString(2).padStart(numBits, '0');\n\n lines.push(\n `[Attempt ${attemptNum + 1}/${totalAttempts}] Pattern ${attemptNum} (${bitPattern})`,\n );\n\n // Collect connection costs (use array to preserve all connections, including duplicates)\n const connectionCostEvents: (\n | NodeCostEvent\n | Extract<PlanDebugEventJSON, {type: 'node-cost'}>\n )[] = [];\n const connectionConstraintEvents: (\n | NodeConstraintEvent\n | Extract<PlanDebugEventJSON, {type: 'node-constraint'}>\n )[] = [];\n\n for (const event of events) {\n if (event.type === 'node-cost' && event.nodeType === 'connection') {\n connectionCostEvents.push(event);\n }\n if (event.type === 'node-constraint' && event.nodeType === 'connection') {\n connectionConstraintEvents.push(event);\n }\n }\n\n // Show connection summary\n if (connectionCostEvents.length > 0) {\n lines.push(' Connections:');\n for (const cost of connectionCostEvents) {\n // Find matching constraint event (same node name and branch pattern)\n const constraint = connectionConstraintEvents.find(\n c =>\n c.node === cost.node &&\n c.branchPattern.join(',') === cost.branchPattern.join(','),\n )?.constraint;\n\n const constraintStr = formatConstraint(constraint);\n const filterStr = formatFilter(cost.filters);\n const orderingStr = formatOrdering(cost.ordering);\n const limitStr =\n cost.costEstimate.limit !== undefined\n ? cost.costEstimate.limit.toString()\n : 'none';\n\n lines.push(` ${cost.node}:`);\n lines.push(\n ` cost=${cost.costEstimate.cost.toFixed(2)}, startup=${cost.costEstimate.startupCost.toFixed(2)}, scan=${cost.costEstimate.scanEst.toFixed(2)}`,\n );\n lines.push(\n ` rows=${cost.costEstimate.returnedRows.toFixed(2)}, selectivity=${cost.costEstimate.selectivity.toFixed(8)}, limit=${limitStr}`,\n );\n lines.push(\n ` downstreamChildSelectivity=${cost.downstreamChildSelectivity.toFixed(8)}`,\n );\n lines.push(` constraints=${constraintStr}`);\n lines.push(` filters=${filterStr}`);\n lines.push(` ordering=${orderingStr}`);\n }\n }\n\n // Collect join costs from node-cost events\n const joinCosts: (\n | NodeCostEvent\n | Extract<PlanDebugEventJSON, {type: 'node-cost'}>\n )[] = [];\n for (const event of events) {\n if (event.type === 'node-cost' && event.nodeType === 'join') {\n joinCosts.push(event);\n }\n }\n\n if (joinCosts.length > 0) {\n lines.push(' Joins:');\n for (const cost of joinCosts) {\n const typeStr = cost.joinType ? ` (${cost.joinType})` : '';\n const limitStr =\n cost.costEstimate.limit !== undefined\n ? cost.costEstimate.limit.toString()\n : 'none';\n\n lines.push(` ${cost.node}${typeStr}:`);\n lines.push(\n ` cost=${cost.costEstimate.cost.toFixed(2)}, startup=${cost.costEstimate.startupCost.toFixed(2)}, scan=${cost.costEstimate.scanEst.toFixed(2)}`,\n );\n lines.push(\n ` rows=${cost.costEstimate.returnedRows.toFixed(2)}, selectivity=${cost.costEstimate.selectivity.toFixed(8)}, limit=${limitStr}`,\n );\n lines.push(\n ` downstreamChildSelectivity=${cost.downstreamChildSelectivity.toFixed(8)}`,\n );\n }\n }\n\n // Find completion/failure events\n const completeEvent = events.find(e => e.type === 'plan-complete') as\n | PlanCompleteEvent\n | undefined;\n const failedEvent = events.find(e => e.type === 'plan-failed') as\n | PlanFailedEvent\n | undefined;\n\n // Show final status\n\n if (completeEvent) {\n lines.push(\n ` ✓ Plan complete: total cost = ${completeEvent.totalCost.toFixed(2)}`,\n );\n } else if (failedEvent) {\n lines.push(` ✗ Plan failed: ${failedEvent.reason}`);\n }\n\n return lines;\n}\n\n/**\n * Convert undefined values to null in a constraint object for JSON serialization.\n * PlannerConstraint uses Record<string, undefined> which loses keys during JSON.stringify.\n */\nfunction convertConstraintUndefinedToNull(\n constraint: PlannerConstraint | Record<string, unknown> | undefined | null,\n): Record<string, unknown> | undefined | null {\n if (constraint === undefined) {\n return undefined;\n }\n if (constraint === null) {\n return null;\n }\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(constraint)) {\n result[key] = val === undefined ? null : val;\n }\n return result;\n}\n\n/**\n * Serialize a single debug event to JSON-compatible format.\n * The fanout function is already omitted when events are created.\n * The planSnapshot is excluded as it's internal state not needed for debugging.\n * Undefined values in constraints are converted to null for JSON serialization.\n */\nfunction serializeEvent(event: PlanDebugEvent): PlanDebugEventJSON {\n // Remove planSnapshot from plan-complete events\n if (event.type === 'plan-complete') {\n const {planSnapshot: _, ...rest} = event;\n return rest as PlanDebugEventJSON;\n }\n\n // Convert constraint undefined values to null for specific event types\n if (event.type === 'node-constraint') {\n return {\n ...event,\n constraint: convertConstraintUndefinedToNull(event.constraint),\n } as PlanDebugEventJSON;\n }\n\n if (event.type === 'connection-costs') {\n return {\n ...event,\n costs: event.costs.map(cost => ({\n ...cost,\n constraints: Object.fromEntries(\n Object.entries(cost.constraints).map(([key, val]) => [\n key,\n convertConstraintUndefinedToNull(val),\n ]),\n ),\n })),\n } as PlanDebugEventJSON;\n }\n\n if (event.type === 'constraints-propagated') {\n return {\n ...event,\n connectionConstraints: event.connectionConstraints.map(cc => ({\n ...cc,\n constraints: Object.fromEntries(\n Object.entries(cc.constraints).map(([key, val]) => [\n key,\n convertConstraintUndefinedToNull(val),\n ]),\n ),\n })),\n } as PlanDebugEventJSON;\n }\n\n return event as PlanDebugEventJSON;\n}\n\n/**\n * Serialize an array of debug events to JSON-compatible format.\n * The fanout function is already omitted when events are created.\n * The planSnapshot is excluded as it's internal state not needed for debugging.\n */\nexport function serializePlanDebugEvents(\n events: PlanDebugEvent[],\n): PlanDebugEventJSON[] {\n return events.map(serializeEvent);\n}\n\n/**\n * Format planner debug events as a human-readable string.\n * Works with JSON-serialized events (from inspector API) or native events (from AccumulatorDebugger).\n *\n * @param events - Array of planner debug events (either JSON or native format)\n * @returns Formatted string showing planning attempts, costs, and final plan selection\n *\n * @example\n * ```typescript\n * const result = await inspector.analyzeQuery(query, { plannerDebug: true });\n * if (result.plannerEvents) {\n * console.log(formatPlannerEvents(result.plannerEvents));\n * }\n * ```\n */\nexport function formatPlannerEvents(\n events: PlanDebugEventJSON[] | PlanDebugEvent[],\n): string {\n const lines: string[] = [];\n\n // Group events by attempt\n const eventsByAttempt = new Map<\n number,\n (PlanDebugEventJSON | PlanDebugEvent)[]\n >();\n let bestPlanEvent:\n | {\n type: 'best-plan-selected';\n bestAttemptNumber: number;\n totalCost: number;\n flipPattern: number;\n joinStates: Array<{join: string; type: string}>;\n }\n | undefined;\n\n for (const event of events) {\n if ('attemptNumber' in event) {\n const attempt = event.attemptNumber;\n if (attempt !== undefined) {\n let attemptEvents = eventsByAttempt.get(attempt);\n if (!attemptEvents) {\n attemptEvents = [];\n eventsByAttempt.set(attempt, attemptEvents);\n }\n attemptEvents.push(event);\n }\n } else if (event.type === 'best-plan-selected') {\n // Save for displaying at the end\n bestPlanEvent = event;\n }\n }\n\n // Format each attempt as a compact summary\n for (const [attemptNum, events] of eventsByAttempt.entries()) {\n lines.push(...formatAttemptSummary(attemptNum, events));\n lines.push(''); // Blank line between attempts\n }\n\n // Show the final plan selection\n if (bestPlanEvent) {\n lines.push('─'.repeat(60));\n lines.push(\n `✓ Best plan: Attempt ${bestPlanEvent.bestAttemptNumber + 1} (cost=${bestPlanEvent.totalCost.toFixed(2)})`,\n );\n if (bestPlanEvent.joinStates.length > 0) {\n lines.push(' Join types:');\n for (const j of bestPlanEvent.joinStates) {\n lines.push(` ${j.join}: ${j.type}`);\n }\n }\n lines.push('─'.repeat(60));\n }\n\n return lines.join('\\n');\n}\n"],"names":["events"],"mappings":"AA+IO,MAAM,oBAA4C;AAAA,EAC9C,SAA2B,CAAA;AAAA,EAC5B,iBAAiB;AAAA,EAEzB,IAAI,OAA6B;AAE/B,QAAI,MAAM,SAAS,iBAAiB;AAClC,WAAK,iBAAiB,MAAM;AAAA,IAC9B;AAGA,QAAI,MAAM,SAAS,eAAe,MAAM,SAAS,mBAAmB;AACjE,YAA8C,gBAC7C,KAAK;AAAA,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;AAAA,MACJ,wBAAwB,cAAc,oBAAoB,CAAC,UAAU,cAAc,UAAU,QAAQ,CAAC,CAAC;AAAA,IAAA;AAEzG,QAAI,cAAc,WAAW,SAAS,GAAG;AACvC,YAAM,KAAK,eAAe;AAC1B,iBAAW,KAAK,cAAc,YAAY;AACxC,cAAM,KAAK,OAAO,EAAE,IAAI,KAAK,EAAE,IAAI,EAAE;AAAA,MACvC;AAAA,IACF;AACA,UAAM,KAAK,IAAI,OAAO,EAAE,CAAC;AAAA,EAC3B;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;"}
|
|
1
|
+
{"version":3,"file":"planner-debug.js","sources":["../../../../../zql/src/planner/planner-debug.ts"],"sourcesContent":["import type * as v from '../../../shared/src/valita.ts';\nimport type {\n Condition,\n Ordering,\n ValuePosition,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {\n attemptStartEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n connectionSelectedEventJSONSchema,\n nodeConstraintEventJSONSchema,\n PlanDebugEventJSON,\n planFailedEventJSONSchema,\n} from '../../../zero-protocol/src/analyze-query-result.ts';\nimport type {PlannerConstraint} from './planner-constraint.ts';\nimport type {CostEstimate, JoinType} from './planner-node.ts';\nimport type {PlanState} from './planner-graph.ts';\n\n/**\n * Structured debug events emitted during query planning.\n * These events can be accumulated, printed, or analyzed to understand\n * the planner's decision-making process.\n */\n\n/**\n * Starting a new planning attempt with a different root connection.\n */\nexport type AttemptStartEvent = v.Infer<typeof attemptStartEventJSONSchema>;\n\n/**\n * Snapshot of connection costs before selecting the next connection.\n */\nexport type ConnectionCostsEvent = {\n type: 'connection-costs';\n attemptNumber: number;\n costs: Array<{\n connection: string;\n cost: number;\n costEstimate: Omit<CostEstimate, 'fanout'>;\n pinned: boolean;\n constraints: Record<string, PlannerConstraint | undefined>;\n constraintCosts: Record<string, Omit<CostEstimate, 'fanout'>>;\n }>;\n};\n\n/**\n * A connection was chosen and pinned.\n */\nexport type ConnectionSelectedEvent = v.Infer<\n typeof connectionSelectedEventJSONSchema\n>;\n\n/**\n * Constraints have been propagated through the graph.\n */\nexport type ConstraintsPropagatedEvent = {\n type: 'constraints-propagated';\n attemptNumber: number;\n connectionConstraints: Array<{\n connection: string;\n constraints: Record<string, PlannerConstraint | undefined>;\n constraintCosts: Record<string, Omit<CostEstimate, 'fanout'>>;\n }>;\n};\n\n/**\n * A complete plan was found for this attempt.\n */\nexport type PlanCompleteEvent = {\n type: 'plan-complete';\n attemptNumber: number;\n totalCost: number;\n flipPattern: number; // Bitmask indicating which joins are flipped\n joinStates: Array<{\n join: string;\n type: JoinType;\n }>;\n // Planning snapshot that can be restored and applied to AST\n planSnapshot: PlanState;\n};\n\n/**\n * Planning attempt failed (e.g., unflippable join).\n */\nexport type PlanFailedEvent = v.Infer<typeof planFailedEventJSONSchema>;\n\n/**\n * The best plan across all attempts was selected.\n */\nexport type BestPlanSelectedEvent = v.Infer<\n typeof bestPlanSelectedEventJSONSchema\n>;\n\n/**\n * A node computed its cost estimate during planning.\n * Emitted by nodes during estimateCost() traversal.\n * attemptNumber is added by the debugger.\n */\nexport type NodeCostEvent = {\n type: 'node-cost';\n attemptNumber?: number;\n nodeType: 'connection' | 'join' | 'fan-out' | 'fan-in' | 'terminus';\n node: string;\n branchPattern: number[];\n downstreamChildSelectivity: number;\n costEstimate: Omit<CostEstimate, 'fanout'>;\n filters?: Condition | undefined; // Only for connections\n ordering?: Ordering | undefined; // Only for connections\n joinType?: JoinType | undefined; // Only for joins\n};\n\n/**\n * A node received constraints during constraint propagation.\n * Emitted by nodes during propagateConstraints() traversal.\n * attemptNumber is added by the debugger.\n */\nexport type NodeConstraintEvent = v.Infer<typeof nodeConstraintEventJSONSchema>;\n\n/**\n * Union of all debug event types.\n */\nexport type PlanDebugEvent =\n | AttemptStartEvent\n | ConnectionCostsEvent\n | ConnectionSelectedEvent\n | ConstraintsPropagatedEvent\n | PlanCompleteEvent\n | PlanFailedEvent\n | BestPlanSelectedEvent\n | NodeCostEvent\n | NodeConstraintEvent;\n\n/**\n * Interface for objects that receive debug events during planning.\n */\nexport interface PlanDebugger {\n log(event: PlanDebugEvent): void;\n}\n\n/**\n * Simple accumulator debugger that stores all events.\n * Useful for tests and debugging.\n */\nexport class AccumulatorDebugger implements PlanDebugger {\n readonly events: PlanDebugEvent[] = [];\n private currentAttempt = 0;\n\n log(event: PlanDebugEvent): void {\n // Track current attempt number\n if (event.type === 'attempt-start') {\n this.currentAttempt = event.attemptNumber;\n }\n\n // Add attempt number to node events\n if (event.type === 'node-cost' || event.type === 'node-constraint') {\n (event as NodeCostEvent | NodeConstraintEvent).attemptNumber =\n this.currentAttempt;\n }\n\n this.events.push(event);\n }\n\n /**\n * Get all events of a specific type.\n */\n getEvents<T extends PlanDebugEvent['type']>(\n type: T,\n ): Extract<PlanDebugEvent, {type: T}>[] {\n return this.events.filter(e => e.type === type) as Extract<\n PlanDebugEvent,\n {type: T}\n >[];\n }\n\n /**\n * Format events as a human-readable string.\n */\n format(): string {\n return formatPlannerEvents(this.events);\n }\n}\n\n/**\n * Format a constraint object as a human-readable string.\n */\nfunction formatConstraint(\n constraint: PlannerConstraint | Record<string, unknown> | null | undefined,\n): string {\n if (!constraint) return '{}';\n const keys = Object.keys(constraint);\n if (keys.length === 0) return '{}';\n return '{' + keys.join(', ') + '}';\n}\n\n/**\n * Format a ValuePosition (column, literal, or static parameter) as a human-readable string.\n */\nfunction formatValuePosition(value: ValuePosition): string {\n switch (value.type) {\n case 'column':\n return value.name;\n case 'literal':\n // Format literal values with SQL-style quoting for strings\n if (typeof value.value === 'string') {\n return `'${value.value}'`;\n }\n return JSON.stringify(value.value);\n case 'static':\n return `@${value.anchor}.${Array.isArray(value.field) ? value.field.join('.') : value.field}`;\n }\n}\n\n/**\n * Format a Condition (filter) as a human-readable string.\n */\nfunction formatFilter(filter: Condition | undefined): string {\n if (!filter) return 'none';\n\n switch (filter.type) {\n case 'simple':\n return `${formatValuePosition(filter.left)} ${filter.op} ${formatValuePosition(filter.right)}`;\n case 'and':\n return `(${filter.conditions.map(formatFilter).join(' AND ')})`;\n case 'or':\n return `(${filter.conditions.map(formatFilter).join(' OR ')})`;\n case 'correlatedSubquery':\n return `EXISTS(${filter.related.subquery.table})`;\n default:\n return JSON.stringify(filter);\n }\n}\n\n/**\n * Format an Ordering as a human-readable string.\n */\nfunction formatOrdering(ordering: Ordering | undefined): string {\n if (!ordering || ordering.length === 0) return 'none';\n return ordering\n .map(([field, direction]) => `${field} ${direction}`)\n .join(', ');\n}\n\n/**\n * Format a compact summary for a single planning attempt.\n */\nfunction formatAttemptSummary(\n attemptNum: number,\n events: (PlanDebugEvent | PlanDebugEventJSON)[],\n): string[] {\n const lines: string[] = [];\n\n // Find the attempt-start event to get total attempts\n const startEvent = events.find(e => e.type === 'attempt-start') as\n | AttemptStartEvent\n | undefined;\n const totalAttempts = startEvent?.totalAttempts ?? '?';\n\n // Calculate number of bits needed for pattern\n const numBits =\n typeof totalAttempts === 'number'\n ? Math.ceil(Math.log2(totalAttempts)) || 1\n : 1;\n const bitPattern = attemptNum.toString(2).padStart(numBits, '0');\n\n lines.push(\n `[Attempt ${attemptNum + 1}/${totalAttempts}] Pattern ${attemptNum} (${bitPattern})`,\n );\n\n // Collect connection costs (use array to preserve all connections, including duplicates)\n const connectionCostEvents: (\n | NodeCostEvent\n | Extract<PlanDebugEventJSON, {type: 'node-cost'}>\n )[] = [];\n const connectionConstraintEvents: (\n | NodeConstraintEvent\n | Extract<PlanDebugEventJSON, {type: 'node-constraint'}>\n )[] = [];\n\n for (const event of events) {\n if (event.type === 'node-cost' && event.nodeType === 'connection') {\n connectionCostEvents.push(event);\n }\n if (event.type === 'node-constraint' && event.nodeType === 'connection') {\n connectionConstraintEvents.push(event);\n }\n }\n\n // Show connection summary\n if (connectionCostEvents.length > 0) {\n lines.push(' Connections:');\n for (const cost of connectionCostEvents) {\n // Find matching constraint event (same node name and branch pattern)\n const constraint = connectionConstraintEvents.find(\n c =>\n c.node === cost.node &&\n c.branchPattern.join(',') === cost.branchPattern.join(','),\n )?.constraint;\n\n const constraintStr = formatConstraint(constraint);\n const filterStr = formatFilter(cost.filters);\n const orderingStr = formatOrdering(cost.ordering);\n const limitStr =\n cost.costEstimate.limit !== undefined\n ? cost.costEstimate.limit.toString()\n : 'none';\n\n lines.push(` ${cost.node}:`);\n lines.push(\n ` cost=${cost.costEstimate.cost.toFixed(2)}, startup=${cost.costEstimate.startupCost.toFixed(2)}, scan=${cost.costEstimate.scanEst.toFixed(2)}`,\n );\n lines.push(\n ` rows=${cost.costEstimate.returnedRows.toFixed(2)}, selectivity=${cost.costEstimate.selectivity.toFixed(8)}, limit=${limitStr}`,\n );\n lines.push(\n ` downstreamChildSelectivity=${cost.downstreamChildSelectivity.toFixed(8)}`,\n );\n lines.push(` constraints=${constraintStr}`);\n lines.push(` filters=${filterStr}`);\n lines.push(` ordering=${orderingStr}`);\n }\n }\n\n // Collect join costs from node-cost events\n const joinCosts: (\n | NodeCostEvent\n | Extract<PlanDebugEventJSON, {type: 'node-cost'}>\n )[] = [];\n for (const event of events) {\n if (event.type === 'node-cost' && event.nodeType === 'join') {\n joinCosts.push(event);\n }\n }\n\n if (joinCosts.length > 0) {\n lines.push(' Joins:');\n for (const cost of joinCosts) {\n const typeStr = cost.joinType ? ` (${cost.joinType})` : '';\n const limitStr =\n cost.costEstimate.limit !== undefined\n ? cost.costEstimate.limit.toString()\n : 'none';\n\n lines.push(` ${cost.node}${typeStr}:`);\n lines.push(\n ` cost=${cost.costEstimate.cost.toFixed(2)}, startup=${cost.costEstimate.startupCost.toFixed(2)}, scan=${cost.costEstimate.scanEst.toFixed(2)}`,\n );\n lines.push(\n ` rows=${cost.costEstimate.returnedRows.toFixed(2)}, selectivity=${cost.costEstimate.selectivity.toFixed(8)}, limit=${limitStr}`,\n );\n lines.push(\n ` downstreamChildSelectivity=${cost.downstreamChildSelectivity.toFixed(8)}`,\n );\n }\n }\n\n // Find completion/failure events\n const completeEvent = events.find(e => e.type === 'plan-complete') as\n | PlanCompleteEvent\n | undefined;\n const failedEvent = events.find(e => e.type === 'plan-failed') as\n | PlanFailedEvent\n | undefined;\n\n // Show final status\n\n if (completeEvent) {\n lines.push(\n ` ✓ Plan complete: total cost = ${completeEvent.totalCost.toFixed(2)}`,\n );\n } else if (failedEvent) {\n lines.push(` ✗ Plan failed: ${failedEvent.reason}`);\n }\n\n return lines;\n}\n\n/**\n * Convert undefined values to null in a constraint object for JSON serialization.\n * PlannerConstraint uses Record<string, undefined> which loses keys during JSON.stringify.\n */\nfunction convertConstraintUndefinedToNull(\n constraint: PlannerConstraint | Record<string, unknown> | undefined | null,\n): Record<string, unknown> | undefined | null {\n if (constraint === undefined) {\n return undefined;\n }\n if (constraint === null) {\n return null;\n }\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(constraint)) {\n result[key] = val === undefined ? null : val;\n }\n return result;\n}\n\n/**\n * Serialize a single debug event to JSON-compatible format.\n * The fanout function is already omitted when events are created.\n * The planSnapshot is excluded as it's internal state not needed for debugging.\n * Undefined values in constraints are converted to null for JSON serialization.\n */\nfunction serializeEvent(event: PlanDebugEvent): PlanDebugEventJSON {\n // Remove planSnapshot from plan-complete events\n if (event.type === 'plan-complete') {\n const {planSnapshot: _, ...rest} = event;\n return rest as PlanDebugEventJSON;\n }\n\n // Convert constraint undefined values to null for specific event types\n if (event.type === 'node-constraint') {\n return {\n ...event,\n constraint: convertConstraintUndefinedToNull(event.constraint),\n } as PlanDebugEventJSON;\n }\n\n if (event.type === 'connection-costs') {\n return {\n ...event,\n costs: event.costs.map(cost => ({\n ...cost,\n constraints: Object.fromEntries(\n Object.entries(cost.constraints).map(([key, val]) => [\n key,\n convertConstraintUndefinedToNull(val),\n ]),\n ),\n })),\n } as PlanDebugEventJSON;\n }\n\n if (event.type === 'constraints-propagated') {\n return {\n ...event,\n connectionConstraints: event.connectionConstraints.map(cc => ({\n ...cc,\n constraints: Object.fromEntries(\n Object.entries(cc.constraints).map(([key, val]) => [\n key,\n convertConstraintUndefinedToNull(val),\n ]),\n ),\n })),\n } as PlanDebugEventJSON;\n }\n\n return event as PlanDebugEventJSON;\n}\n\n/**\n * Serialize an array of debug events to JSON-compatible format.\n * The fanout function is already omitted when events are created.\n * The planSnapshot is excluded as it's internal state not needed for debugging.\n */\nexport function serializePlanDebugEvents(\n events: PlanDebugEvent[],\n): PlanDebugEventJSON[] {\n return events.map(serializeEvent);\n}\n\n/**\n * Format planner debug events as a human-readable string.\n * Works with JSON-serialized events (from inspector API) or native events (from AccumulatorDebugger).\n *\n * @param events - Array of planner debug events (either JSON or native format)\n * @returns Formatted string showing planning attempts, costs, and final plan selection\n *\n * @example\n * ```typescript\n * const result = await inspector.analyzeQuery(query, { joinPlans: true });\n * if (result.joinPlans) {\n * console.log(formatPlannerEvents(result.joinPlans));\n * }\n * ```\n */\nexport function formatPlannerEvents(\n events: PlanDebugEventJSON[] | PlanDebugEvent[],\n): string {\n const lines: string[] = [];\n\n // Group events by attempt\n const eventsByAttempt = new Map<\n number,\n (PlanDebugEventJSON | PlanDebugEvent)[]\n >();\n let bestPlanEvent:\n | {\n type: 'best-plan-selected';\n bestAttemptNumber: number;\n totalCost: number;\n flipPattern: number;\n joinStates: Array<{join: string; type: string}>;\n }\n | undefined;\n\n for (const event of events) {\n if ('attemptNumber' in event) {\n const attempt = event.attemptNumber;\n if (attempt !== undefined) {\n let attemptEvents = eventsByAttempt.get(attempt);\n if (!attemptEvents) {\n attemptEvents = [];\n eventsByAttempt.set(attempt, attemptEvents);\n }\n attemptEvents.push(event);\n }\n } else if (event.type === 'best-plan-selected') {\n // Save for displaying at the end\n bestPlanEvent = event;\n }\n }\n\n // Format each attempt as a compact summary\n for (const [attemptNum, events] of eventsByAttempt.entries()) {\n lines.push(...formatAttemptSummary(attemptNum, events));\n lines.push(''); // Blank line between attempts\n }\n\n // Show the final plan selection\n if (bestPlanEvent) {\n lines.push('─'.repeat(60));\n lines.push(\n `✓ Best plan: Attempt ${bestPlanEvent.bestAttemptNumber + 1} (cost=${bestPlanEvent.totalCost.toFixed(2)})`,\n );\n if (bestPlanEvent.joinStates.length > 0) {\n lines.push(' Join types:');\n for (const j of bestPlanEvent.joinStates) {\n lines.push(` ${j.join}: ${j.type}`);\n }\n }\n lines.push('─'.repeat(60));\n }\n\n return lines.join('\\n');\n}\n"],"names":["events"],"mappings":"AA+IO,MAAM,oBAA4C;AAAA,EAC9C,SAA2B,CAAA;AAAA,EAC5B,iBAAiB;AAAA,EAEzB,IAAI,OAA6B;AAE/B,QAAI,MAAM,SAAS,iBAAiB;AAClC,WAAK,iBAAiB,MAAM;AAAA,IAC9B;AAGA,QAAI,MAAM,SAAS,eAAe,MAAM,SAAS,mBAAmB;AACjE,YAA8C,gBAC7C,KAAK;AAAA,IACT;AAEA,SAAK,OAAO,KAAK,KAAK;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA,EAKA,UACE,MACsC;AACtC,WAAO,KAAK,OAAO,OAAO,CAAA,MAAK,EAAE,SAAS,IAAI;AAAA,EAIhD;AAAA;AAAA;AAAA;AAAA,EAKA,SAAiB;AACf,WAAO,oBAAoB,KAAK,MAAM;AAAA,EACxC;AACF;AAKA,SAAS,iBACP,YACQ;AACR,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,OAAO,OAAO,KAAK,UAAU;AACnC,MAAI,KAAK,WAAW,EAAG,QAAO;AAC9B,SAAO,MAAM,KAAK,KAAK,IAAI,IAAI;AACjC;AAKA,SAAS,oBAAoB,OAA8B;AACzD,UAAQ,MAAM,MAAA;AAAA,IACZ,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AAEH,UAAI,OAAO,MAAM,UAAU,UAAU;AACnC,eAAO,IAAI,MAAM,KAAK;AAAA,MACxB;AACA,aAAO,KAAK,UAAU,MAAM,KAAK;AAAA,IACnC,KAAK;AACH,aAAO,IAAI,MAAM,MAAM,IAAI,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,MAAM,KAAK,GAAG,IAAI,MAAM,KAAK;A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AY,QAAW;AACzB,YAAI,gBAAgB,gBAAgB,IAAI,OAAO;AAC/C,YAAI,CAAC,eAAe;AAClB,0BAAgB,CAAA;AAChB,0BAAgB,IAAI,SAAS,aAAa;AAAA,QAC5C;AACA,sBAAc,KAAK,KAAK;AAAA,MAC1B;AAAA,IACF,WAAW,MAAM,SAAS,sBAAsB;AAE9C,sBAAgB;AAAA,IAClB;AAAA,EACF;AAGA,aAAW,CAAC,YAAYA,OAAM,KAAK,gBAAgB,WAAW;AAC5D,UAAM,KAAK,GAAG,qBAAqB,YAAYA,OAAM,CAAC;AACtD,UAAM,KAAK,EAAE;AAAA,EACf;AAGA,MAAI,eAAe;AACjB,UAAM,KAAK,IAAI,OAAO,EAAE,CAAC;AACzB,UAAM;AAAA,MACJ,wBAAwB,cAAc,oBAAoB,CAAC,UAAU,cAAc,UAAU,QAAQ,CAAC,CAAC;AAAA,IAAA;AAEzG,QAAI,cAAc,WAAW,SAAS,GAAG;AACvC,YAAM,KAAK,eAAe;AAC1B,iBAAW,KAAK,cAAc,YAAY;AACxC,cAAM,KAAK,OAAO,EAAE,IAAI,KAAK,EAAE,IAAI,EAAE;AAAA,MACvC;AAAA,IACF;AACA,UAAM,KAAK,IAAI,OAAO,EAAE,CAAC;AAAA,EAC3B;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;"}
|
|
@@ -4,6 +4,7 @@ import type { SchemaQuery } from './schema-query.ts';
|
|
|
4
4
|
/**
|
|
5
5
|
* Returns a set of query builders for the given schema.
|
|
6
6
|
*/
|
|
7
|
-
export declare function createBuilder<S extends Schema>(schema: S): SchemaQuery<S>;
|
|
7
|
+
export declare function createBuilder<S extends Schema>(schema: S): SchemaQuery<S, true>;
|
|
8
|
+
/** @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead. */
|
|
8
9
|
export declare function createRunnableBuilder<S extends Schema>(delegate: QueryDelegate, schema: S): SchemaQuery<S>;
|
|
9
10
|
//# sourceMappingURL=create-builder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-builder.d.ts","sourceRoot":"","sources":["../../../../../zql/src/query/create-builder.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAC9D,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,qBAAqB,CAAC;AAIvD,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,mBAAmB,CAAC;AAEnD;;GAEG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,
|
|
1
|
+
{"version":3,"file":"create-builder.d.ts","sourceRoot":"","sources":["../../../../../zql/src/query/create-builder.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,mCAAmC,CAAC;AAC9D,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,qBAAqB,CAAC;AAIvD,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,mBAAmB,CAAC;AAEnD;;GAEG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,MAAM,EAC5C,MAAM,EAAE,CAAC,GACR,WAAW,CAAC,CAAC,EAAE,IAAI,CAAC,CAItB;AAED,6FAA6F;AAC7F,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,EACpD,QAAQ,EAAE,aAAa,EACvB,MAAM,EAAE,CAAC,GACR,WAAW,CAAC,CAAC,CAAC,CAQhB"}
|
|
@@ -8,6 +8,9 @@ function createBuilder(schema) {
|
|
|
8
8
|
);
|
|
9
9
|
}
|
|
10
10
|
function createRunnableBuilder(delegate, schema) {
|
|
11
|
+
if (!schema.enableLegacyQueries) {
|
|
12
|
+
return void 0;
|
|
13
|
+
}
|
|
11
14
|
return createBuilderWithQueryFactory(
|
|
12
15
|
schema,
|
|
13
16
|
(table) => newRunnableQuery(delegate, schema, table)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-builder.js","sources":["../../../../../zql/src/query/create-builder.ts"],"sourcesContent":["import {recordProxy} from '../../../shared/src/record-proxy.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {QueryDelegate} from './query-delegate.ts';\nimport {newQuery} from './query-impl.ts';\nimport type {Query} from './query.ts';\nimport {newRunnableQuery} from './runnable-query-impl.ts';\nimport type {SchemaQuery} from './schema-query.ts';\n\n/**\n * Returns a set of query builders for the given schema.\n */\nexport function createBuilder<S extends Schema>(schema: S): SchemaQuery<S> {\n return createBuilderWithQueryFactory(schema, table =>\n newQuery(schema, table),\n );\n}\n\nexport function createRunnableBuilder<S extends Schema>(\n delegate: QueryDelegate,\n schema: S,\n): SchemaQuery<S> {\n return createBuilderWithQueryFactory(schema, table =>\n newRunnableQuery(delegate, schema, table),\n );\n}\n\nfunction createBuilderWithQueryFactory
|
|
1
|
+
{"version":3,"file":"create-builder.js","sources":["../../../../../zql/src/query/create-builder.ts"],"sourcesContent":["import {recordProxy} from '../../../shared/src/record-proxy.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {QueryDelegate} from './query-delegate.ts';\nimport {newQuery} from './query-impl.ts';\nimport type {Query} from './query.ts';\nimport {newRunnableQuery} from './runnable-query-impl.ts';\nimport type {SchemaQuery} from './schema-query.ts';\n\n/**\n * Returns a set of query builders for the given schema.\n */\nexport function createBuilder<S extends Schema>(\n schema: S,\n): SchemaQuery<S, true> {\n return createBuilderWithQueryFactory<S, true>(schema, table =>\n newQuery(schema, table),\n );\n}\n\n/** @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead. */\nexport function createRunnableBuilder<S extends Schema>(\n delegate: QueryDelegate,\n schema: S,\n): SchemaQuery<S> {\n if (!schema.enableLegacyQueries) {\n return undefined as SchemaQuery<S>;\n }\n\n return createBuilderWithQueryFactory<S, false>(schema, table =>\n newRunnableQuery(delegate, schema, table),\n );\n}\n\nfunction createBuilderWithQueryFactory<\n S extends Schema,\n ForceEnable extends boolean,\n>(\n schema: S,\n queryFactory: (table: keyof S['tables'] & string) => Query<string, S>,\n): SchemaQuery<S, ForceEnable> {\n return recordProxy(\n schema.tables,\n (_tableSchema, prop) => queryFactory(prop),\n prop => {\n throw new Error(`Table ${prop} does not exist in schema`);\n },\n ) as SchemaQuery<S, ForceEnable>;\n}\n"],"names":[],"mappings":";;;AAWO,SAAS,cACd,QACsB;AACtB,SAAO;AAAA,IAAuC;AAAA,IAAQ,CAAA,UACpD,SAAS,QAAQ,KAAK;AAAA,EAAA;AAE1B;AAGO,SAAS,sBACd,UACA,QACgB;AAChB,MAAI,CAAC,OAAO,qBAAqB;AAC/B,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IAAwC;AAAA,IAAQ,CAAA,UACrD,iBAAiB,UAAU,QAAQ,KAAK;AAAA,EAAA;AAE5C;AAEA,SAAS,8BAIP,QACA,cAC6B;AAC7B,SAAO;AAAA,IACL,OAAO;AAAA,IACP,CAAC,cAAc,SAAS,aAAa,IAAI;AAAA,IACzC,CAAA,SAAQ;AACN,YAAM,IAAI,MAAM,SAAS,IAAI,2BAA2B;AAAA,IAC1D;AAAA,EAAA;AAEJ;"}
|