@party-stack/ontology-backend 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,13 +51,23 @@ registered and buffering, even if the returned stream stays quiet indefinitely.
51
51
  Closing the acquisition Scope releases the subscription.
52
52
 
53
53
  ```ts
54
- // Inside the caller's Scope; undefined means this subset needs polling.
55
- const acquire = backend.watchSubset?.(subset);
56
- if (acquire) {
57
- const changes = yield * acquire;
58
- const snapshot = yield * backend.loadSubset(subset);
54
+ import { Effect } from "effect";
55
+ import type { OntologyBackendService } from "@party-stack/ontology-backend";
56
+ import type { ObjectSubset } from "@party-stack/ontology-spec/query";
57
+
58
+ // Runs in the caller's Scope, which owns the subscription.
59
+ export const readAndWatch = Effect.fn("App.readAndWatch")(function* (
60
+ backend: OntologyBackendService,
61
+ subset: ObjectSubset
62
+ ) {
63
+ // undefined means this subset needs polling.
64
+ const acquire = backend.watchSubset?.(subset);
65
+ if (!acquire) return;
66
+ const changes = yield* acquire;
67
+ const snapshot = yield* backend.loadSubset(subset);
59
68
  // Process the snapshot, then consume changes to refresh it.
60
- }
69
+ return { snapshot, changes };
70
+ });
61
71
  ```
62
72
 
63
73
  Changes between acquisition and snapshot consumption remain observable. Merely
@@ -106,9 +116,18 @@ normally remain actions.
106
116
  Configuration:
107
117
 
108
118
  ```ts
109
- const owned =
110
- yield *
111
- makeOwnedBackend({
119
+ import { makeOwnedBackend } from "@party-stack/ontology-backend/owned";
120
+ import { Tables } from "@party-stack/ontology-storage/tables";
121
+ import { Effect } from "effect";
122
+ import type { OwnedBackendOptions } from "@party-stack/ontology-backend/owned";
123
+
124
+ // Requires Scope: the backend's maintenance sweep runs in it.
125
+ export const openOwnedBackend = Effect.fn("App.openOwnedBackend")(function* (
126
+ options: Pick<OwnedBackendOptions, "namespace" | "ir" | "mutators">
127
+ ) {
128
+ const { namespace, ir, mutators } = options;
129
+ const tables = yield* Tables;
130
+ return yield* makeOwnedBackend({
112
131
  namespace,
113
132
  ir,
114
133
  tables,
@@ -117,6 +136,7 @@ const owned =
117
136
  history: { maxCommits: 10_000, maxAgeMs: 24 * 60 * 60 * 1_000 },
118
137
  maintenance: { intervalMs: 60_000 },
119
138
  });
139
+ });
120
140
  ```
121
141
 
122
142
  Result retention is measured from completion, independent of journal retention and
package/lib/actions.js CHANGED
@@ -168,7 +168,7 @@ const actionExpressions = (options) => {
168
168
  return yield* child(e.value.else, "else");
169
169
  case "exists": return yield* failure("EXISTS is not supported in action expressions yet.", "NotImplemented");
170
170
  default: {
171
- const nodes = e.kind === "not" ? [e.value.expression] : "expressions" in e.value ? e.value.expressions : [e.value.left, e.value.right];
171
+ const nodes = e.kind === "not" || e.kind === "length" ? [e.value.expression] : "expressions" in e.value ? e.value.expressions : [e.value.left, e.value.right];
172
172
  const values = [];
173
173
  for (const [index, node] of nodes.entries()) {
174
174
  const resolved = yield* raw(node, [
@@ -1 +1 @@
1
- {"version":3,"file":"actions.js","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import { booleanValue, evaluateOperator } from \"@party-stack/ontology-spec/query\";\nimport {\n getAtPath,\n setAtPath,\n resolveType,\n unwrapType,\n unwrapValueType,\n resolveRelatedLink,\n isRelatedFromForeignKeySource,\n resolveLookupReference,\n certain,\n} from \"@party-stack/ontology-spec/utils\";\nimport { eq, field } from \"@party-stack/ontology-storage\";\nimport { Effect, Schema } from \"effect\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { BackendError } from \"./errors.js\";\nimport { executeQuery } from \"./query.js\";\nimport type { ActionRequest } from \"./index.js\";\nimport type { OwnedReadTransaction, OwnedTransaction } from \"./owned.js\";\nimport type {\n Expression,\n OntologyIR,\n ObjectTypeDef,\n TypeDef,\n QueryDocument,\n} from \"@party-stack/ontology-spec\";\nimport type { Uncertain } from \"@party-stack/ontology-spec/utils\";\nimport type { Key } from \"@party-stack/ontology-storage\";\n\nexport type ActionMutator = (\n tx: ActionTransaction,\n request: ActionRequest,\n context: Record<string, unknown>\n) => Effect.Effect<unknown, BackendError>;\nexport interface ActionTransaction extends OwnedTransaction {\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n}\nexport type ActionMutatorRegistry = Readonly<Record<string, ActionMutator>>;\nexport interface ActionExecutionOptions {\n readonly ir: OntologyIR;\n readonly tx: OwnedTransaction;\n readonly request: ActionRequest;\n readonly context?: Record<string, unknown>;\n readonly mutators?: ActionMutatorRegistry;\n readonly resolveOnly?: boolean;\n}\nconst failure = (message: string, kind: BackendError[\"kind\"] = \"InvalidRequest\", cause?: unknown) =>\n new BackendError({ operation: \"action.execute\", kind, retryable: false, message, cause });\nconst scalar = <A>(compute: () => A) =>\n Effect.try({\n try: compute,\n catch: (cause) =>\n failure(\n cause instanceof Error ? cause.message : \"Invalid expression values.\",\n \"InvalidRequest\",\n cause\n ),\n });\nconst defect = (cause: unknown) =>\n Effect.fail(\n cause instanceof BackendError ? cause : failure(\"Action execution failed.\", \"Internal\", cause)\n );\nclass Reference {\n constructor(\n readonly objectType: string,\n readonly key: unknown,\n readonly optional: boolean\n ) {}\n}\nclass Loaded {\n constructor(\n readonly objectType: string,\n readonly value: Record<string, unknown>\n ) {}\n}\n/** Internal partial-default evaluation; never part of the backend error contract. */\nclass UnresolvedInput extends Schema.TaggedError<UnresolvedInput>()(\"UnresolvedActionInput\", {\n parameter: Schema.String,\n}) {}\nconst unwrapped = (value: unknown): unknown => {\n if (value instanceof Reference) return value.key;\n if (value instanceof Loaded) return value.value;\n if (Array.isArray(value)) return value.map(unwrapped);\n if (value !== null && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype)\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, unwrapped(v)]));\n return value;\n};\nconst keyOf = (value: unknown) =>\n typeof value === \"string\" || typeof value === \"number\"\n ? Effect.succeed(value)\n : Effect.fail(failure(\"Object reference requires a primary key.\"));\n\n/** Portable action expressions read only the supplied transaction. No collection, remote demand or runtime lifecycle. */\nexport const actionExpressions = (options: {\n readonly ir: OntologyIR;\n readonly tx: OwnedReadTransaction;\n readonly request: ActionRequest;\n readonly context?: Record<string, unknown>;\n readonly resolveParameter?: (name: string) => Effect.Effect<unknown, BackendError>;\n}) => {\n const { ir, tx, request } = options;\n const action = ir.actionTypes.find((a) => a.name === request.name);\n const parameters: Record<string, unknown> = { ...request.parameters };\n const resolving = new Set<string>();\n const object = (name: string) => {\n const type = ir.objectTypes.find((t) => t.name === name);\n return type\n ? Effect.succeed(type)\n : Effect.fail(failure(`Unknown object type \"${name}\".`, \"InvalidConfiguration\"));\n };\n const resolveParameter = Effect.fnUntraced(function* (\n name: string\n ): Effect.fn.Return<unknown, BackendError | UnresolvedInput> {\n if (parameters[name] !== undefined) return parameters[name];\n const parameter = action?.parameters.find((p) => p.name === name);\n if (!parameter?.defaultValue) return undefined;\n if (resolving.has(name))\n return yield* failure(`Circular action parameter default for \"${name}\".`, \"InvalidConfiguration\");\n resolving.add(name);\n return yield* raw(parameter.defaultValue, [\"parameter\", name], new Map()).pipe(\n Effect.map(unwrapped),\n Effect.tap((value) =>\n Effect.sync(() => {\n if (value !== undefined) parameters[name] = value;\n })\n ),\n Effect.ensuring(Effect.sync(() => resolving.delete(name)))\n );\n });\n const raw = Effect.fnUntraced(function* (\n e: Expression,\n location: readonly (string | number)[],\n locals: ReadonlyMap<string, unknown>\n ): Effect.fn.Return<unknown, BackendError | UnresolvedInput> {\n const child = (node: Expression, segment: string) => raw(node, [...location, segment], locals);\n switch (e.kind) {\n case \"literal\":\n return e.value.value;\n case \"inputReference\": {\n const value = yield* (\n options.resolveParameter?.(e.value.name) ?? resolveParameter(e.value.name)\n );\n const parameter = action?.parameters.find((p) => p.name === e.value.name);\n if (!parameter) return yield* failure(`Unknown action parameter \"${e.value.name}\".`);\n const { type, isOptional } = unwrapType(resolveType(ir, parameter.type));\n if (value === undefined && !isOptional)\n return yield* new UnresolvedInput({ parameter: parameter.name });\n return type.kind === \"objectReference\"\n ? new Reference(type.value.objectType, value, isOptional)\n : value;\n }\n case \"contextReference\":\n return options.context?.[e.value.name];\n case \"localReference\":\n if (!locals.has(e.value.name))\n return yield* failure(`Unknown expression binding \"${e.value.name}\".`);\n return locals.get(e.value.name);\n case \"getAt\": {\n const source = yield* child(e.value.source, \"source\");\n if (source instanceof Reference)\n return yield* failure(\n \"An object reference must be looked up before accessing properties.\"\n );\n return getAtPath(source instanceof Loaded ? source.value : source, e.value.path);\n }\n case \"lookup\": {\n const reference = resolveLookupReference(ir, e.value.reference, action?.parameters);\n if (!reference)\n return yield* failure(\"Lookup requires an input/context object-reference path.\");\n const valueKey = unwrapped(yield* child(e.value.reference, \"reference\"));\n if (valueKey == null) return undefined;\n const key = yield* keyOf(valueKey);\n const value = yield* tx.get(reference.objectType, key);\n if (!value && !reference.optional)\n return yield* failure(`Missing loaded \"${reference.objectType}\" object.`, \"NotFound\");\n return value ? new Loaded(reference.objectType, value) : undefined;\n }\n case \"related\": {\n const source = yield* child(e.value.source, \"source\");\n if (!(source instanceof Loaded))\n return yield* failure(\"Related requires an ontology object.\");\n const link = resolveRelatedLink(ir, source.objectType, e.value.link);\n if (!link) return yield* failure(`Unknown relationship \"${e.value.link}\".`);\n const ownFK = isRelatedFromForeignKeySource(link, source.objectType, e.value.link);\n if (!ownFK && link.cardinality === \"many\")\n return yield* failure(\n \"To-many related expressions are not supported in action execution yet.\",\n \"NotImplemented\"\n );\n const sourceType = yield* object(source.objectType);\n const target = yield* object(ownFK ? link.target.objectType : link.source.objectType);\n const key = ownFK\n ? getAtPath(source.value, link.foreignKey.split(\".\"))\n : source.value[sourceType.primaryKey];\n if (key == null) return undefined;\n const rows = yield* tx.loadSubset(target.name, {\n where: eq(\n field(...(ownFK ? target.primaryKey : link.foreignKey).split(\".\")),\n yield* keyOf(key)\n ),\n limit: 2,\n });\n if (rows.length > 1)\n return yield* failure(\n \"To-one relationship returned multiple objects.\",\n \"InvalidResponse\"\n );\n return rows[0] ? new Loaded(target.name, rows[0].value) : undefined;\n }\n case \"struct\": {\n const entries = [];\n for (const f of e.value.fields)\n entries.push([f.name, yield* raw(f.value, [...location, \"field\", f.name], locals)]);\n return Object.fromEntries(entries);\n }\n case \"map\": {\n const source = yield* child(e.value.source, \"source\");\n if (source === undefined) return undefined;\n if (!Array.isArray(source)) return yield* failure(\"Map source must resolve to a list.\");\n return yield* Effect.forEach(source, (item, index) =>\n raw(\n e.value.body,\n [...location, \"item\", index],\n new Map([...locals, [e.value.binding, item]])\n )\n );\n }\n case \"uuid\": {\n if (!request.replay) return crypto.randomUUID();\n const digest = yield* Effect.tryPromise({\n try: () =>\n crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(JSON.stringify([request.replay!.seed, location]))\n ),\n catch: (cause) => failure(\"Could not derive replay UUID.\", \"Internal\", cause),\n });\n const bytes = new Uint8Array(digest).slice(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n case \"now\":\n return yield* Effect.try({\n try: () =>\n request.replay ? Temporal.Instant.from(request.replay.now) : Temporal.Now.instant(),\n catch: (cause) => failure(\"Invalid replay time.\", \"InvalidRequest\", cause),\n });\n case \"case\": {\n for (const [index, branch] of e.value.branches.entries()) {\n const condition = unwrapped(\n yield* raw(branch.condition, [...location, \"branch\", index, \"condition\"], locals)\n );\n if (yield* scalar(() => booleanValue(condition)))\n return yield* raw(branch.result, [...location, \"branch\", index, \"result\"], locals);\n }\n return yield* child(e.value.else, \"else\");\n }\n case \"exists\":\n return yield* failure(\"EXISTS is not supported in action expressions yet.\", \"NotImplemented\");\n default: {\n const nodes =\n e.kind === \"not\"\n ? [e.value.expression]\n : \"expressions\" in e.value\n ? e.value.expressions\n : [e.value.left, e.value.right];\n const values: Uncertain<unknown>[] = [];\n for (const [index, node] of nodes.entries()) {\n const resolved = yield* raw(node, [...location, \"operand\", index], locals);\n const value = unwrapped(resolved);\n // Preserve reference/entity identity for subsequent traversal.\n if (e.kind === \"coalesce\" && value != null) return resolved;\n values.push(certain(value));\n if (\n (e.kind === \"and\" || e.kind === \"or\") &&\n (yield* scalar(() => booleanValue(value))) === (e.kind === \"or\")\n )\n break;\n }\n const result = yield* scalar(() => evaluateOperator(e.kind, values));\n // All action inputs are concrete; uncertainty belongs to draft/query evaluation.\n if (!result.certain) return yield* failure(\"Action expression depends on unavailable data.\");\n return result.value;\n }\n }\n });\n const evaluate = (expression: Expression, location: readonly (string | number)[] = []) =>\n raw(expression, location, new Map()).pipe(\n Effect.map(unwrapped),\n Effect.catchTag(\"UnresolvedActionInput\", (error) =>\n Effect.fail(failure(`Missing action parameter \"${error.parameter}\".`))\n ),\n Effect.catchDefect(defect)\n );\n return {\n evaluate,\n resolve: Effect.gen(function* () {\n if (!action) return yield* failure(\"Action is unavailable.\", \"NotFound\");\n for (const parameter of action.parameters)\n yield* resolveParameter(parameter.name).pipe(\n Effect.catchTag(\"UnresolvedActionInput\", () => Effect.void)\n );\n return parameters;\n }).pipe(Effect.catchDefect(defect)),\n };\n};\n\nconst targetType = (ir: OntologyIR, object: ObjectTypeDef, path: readonly string[]): TypeDef | undefined => {\n let current: TypeDef | undefined = { kind: \"struct\", value: { fields: object.properties } };\n for (const segment of path) {\n if (!current) break;\n current = resolveType(ir, current);\n while (current.kind === \"optional\") current = resolveType(ir, current.value.type);\n current =\n current.kind === \"struct\"\n ? current.value.fields.find((f) => f.name === segment)?.type\n : current.kind === \"map\"\n ? current.value.valueType\n : current.kind === \"list\"\n ? current.value.elementType\n : undefined;\n }\n return current;\n};\n/** Shared authoritative execution and local replay. Transaction/commit ownership stays with the caller. */\nexport const executeAction = Effect.fn(\"Action.execute\")(function* (options: ActionExecutionOptions) {\n const { ir, tx, request } = options;\n const action = ir.actionTypes.find((a) => a.name === request.name);\n if (!action) return yield* failure(\"Action is unavailable.\", \"NotFound\");\n const expressions = actionExpressions(options);\n const parameters = yield* expressions.resolve;\n if (options.resolveOnly) return { parameters, result: undefined };\n for (const [index, step] of action.logic.entries()) {\n let type: ObjectTypeDef | undefined;\n let key: Key | undefined;\n if (step.kind === \"createObject\") type = ir.objectTypes.find((t) => t.name === step.value.objectType);\n else {\n const parameter = action.parameters.find((p) => p.name === step.value.object.name);\n const resolved = parameter && unwrapType(resolveType(ir, parameter.type)).type;\n type =\n resolved?.kind === \"objectReference\"\n ? ir.objectTypes.find((t) => t.name === resolved.value.objectType)\n : undefined;\n key = yield* keyOf(parameters[step.value.object.name]);\n }\n if (!type)\n return yield* failure(\"Action logic references an unknown object type.\", \"InvalidConfiguration\");\n if (step.kind === \"deleteObject\") {\n yield* tx.delete(type.name, key!);\n continue;\n }\n const changes = [];\n for (const assignment of step.value.values) {\n const value = yield* expressions.evaluate(assignment.value, [\n \"logic\",\n index,\n ...assignment.property,\n ]);\n if (value === undefined) continue;\n const target = targetType(ir, type, assignment.property);\n changes.push({\n path: assignment.property,\n value:\n value === null && target && resolveType(ir, target).kind === \"optional\"\n ? undefined\n : value,\n });\n }\n if (step.kind === \"updateObject\") yield* tx.patch(type.name, key!, changes);\n else {\n let value: Record<string, unknown> = {};\n for (const change of changes) value = setAtPath(value, change.path, change.value);\n if (value[type.primaryKey] === undefined) {\n const pk = type.properties.find((p) => p.name === type!.primaryKey);\n if (!pk || unwrapValueType(ir, pk.type).kind !== \"string\") continue;\n value[type.primaryKey] = `optimistic:${request.id}:${type.name}:${index}`;\n }\n const key = yield* keyOf(value[type.primaryKey]);\n if (yield* tx.get(type.name, key)) return yield* failure(\"Object already exists.\", \"Conflict\");\n yield* tx.put(type.name, value);\n }\n }\n const mutator = options.mutators?.[request.name];\n const result = mutator\n ? yield* mutator(\n {\n get: (type, key) => tx.get(type, key),\n loadSubset: (type, scan) => tx.loadSubset(type, scan),\n put: (type, value) => tx.put(type, value),\n patch: (type, key, changes) => tx.patch(type, key, changes),\n delete: (type, key) => tx.delete(type, key),\n query: (document, settings) =>\n executeQuery(document, {\n reader: { ir, loadSubset: (type, scan) => tx.loadSubset(type, scan) },\n context: options.context,\n inputs: settings?.inputs,\n }).pipe(Effect.map((result) => result.value)),\n },\n { ...request, parameters },\n options.context ?? {}\n )\n : undefined;\n return { parameters, result };\n}, Effect.catchDefect(defect));\n\n/** Resolve defaults against an authorized transaction-consistent native reader. */\nexport const resolveReadActionParameters = Effect.fn(\"Action.resolveParameters\")(function* (options: {\n readonly ir: OntologyIR;\n readonly read: OwnedReadTransaction;\n readonly context?: Record<string, unknown>;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n}) {\n return yield* actionExpressions({\n ir: options.ir,\n tx: options.read,\n request: { id: \"resolve\", name: options.name, parameters: options.parameters },\n context: options.context,\n }).resolve;\n});\n"],"mappings":";;;;;;;;AAiDA,MAAM,WAAW,SAAiB,OAA6B,kBAAkB,UAC7E,IAAI,aAAa;CAAE,WAAW;CAAkB;CAAM,WAAW;CAAO;CAAS;AAAM,CAAC;AAC5F,MAAM,UAAa,YACf,OAAO,IAAI;CACP,KAAK;CACL,QAAQ,UACJ,QACI,iBAAiB,QAAQ,MAAM,UAAU,8BACzC,kBACA,KACJ;AACR,CAAC;AACL,MAAM,UAAU,UACZ,OAAO,KACH,iBAAiB,eAAe,QAAQ,QAAQ,4BAA4B,YAAY,KAAK,CACjG;AACJ,IAAM,YAAN,MAAgB;CAEC;CACA;CACA;CAHb,YACI,YACA,KACA,UACF;EAHW,KAAA,aAAA;EACA,KAAA,MAAA;EACA,KAAA,WAAA;CACV;AACP;AACA,IAAM,SAAN,MAAa;CAEI;CACA;CAFb,YACI,YACA,OACF;EAFW,KAAA,aAAA;EACA,KAAA,QAAA;CACV;AACP;;AAEA,IAAM,kBAAN,cAA8B,OAAO,YAA6B,CAAC,CAAC,yBAA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3C,OAAO;EAAE;EAAY,QAnBN,UACT,OAAO,QACH;GACI,MAAM,MAAM,QAAQ,GAAG,IAAI,MAAM,GAAG;GACpC,aAAa,MAAM,SAAS,GAAG,WAAW,MAAM,IAAI;GACpD,MAAM,MAAM,UAAU,GAAG,IAAI,MAAM,KAAK;GACxC,QAAQ,MAAM,KAAK,YAAY,GAAG,MAAM,MAAM,KAAK,OAAO;GAC1D,SAAS,MAAM,QAAQ,GAAG,OAAO,MAAM,GAAG;GAC1C,QAAQ,UAAU,aACd,aAAa,UAAU;IACnB,QAAQ;KAAE;KAAI,aAAa,MAAM,SAAS,GAAG,WAAW,MAAM,IAAI;IAAE;IACpE,SAAS,QAAQ;IACjB,QAAQ,UAAU;GACtB,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK,WAAW,OAAO,KAAK,CAAC;EACpD,GACA;GAAE,GAAG;GAAS;EAAW,GACzB,QAAQ,WAAW,CAAC,CACxB,IACA,KAAA;CACsB;AAChC,GAAG,OAAO,YAAY,MAAM,CAAC;;AAG7B,MAAa,8BAA8B,OAAO,GAAG,0BAA0B,CAAC,CAAC,WAAW,SAMzF;CACC,OAAO,OAAO,kBAAkB;EAC5B,IAAI,QAAQ;EACZ,IAAI,QAAQ;EACZ,SAAS;GAAE,IAAI;GAAW,MAAM,QAAQ;GAAM,YAAY,QAAQ;EAAW;EAC7E,SAAS,QAAQ;CACrB,CAAC,CAAC,CAAC;AACP,CAAC"}
1
+ {"version":3,"file":"actions.js","names":[],"sources":["../src/actions.ts"],"sourcesContent":["import { booleanValue, evaluateOperator } from \"@party-stack/ontology-spec/query\";\nimport {\n getAtPath,\n setAtPath,\n resolveType,\n unwrapType,\n unwrapValueType,\n resolveRelatedLink,\n isRelatedFromForeignKeySource,\n resolveLookupReference,\n certain,\n} from \"@party-stack/ontology-spec/utils\";\nimport { eq, field } from \"@party-stack/ontology-storage\";\nimport { Effect, Schema } from \"effect\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { BackendError } from \"./errors.js\";\nimport { executeQuery } from \"./query.js\";\nimport type { ActionRequest } from \"./index.js\";\nimport type { OwnedReadTransaction, OwnedTransaction } from \"./owned.js\";\nimport type {\n Expression,\n OntologyIR,\n ObjectTypeDef,\n TypeDef,\n QueryDocument,\n} from \"@party-stack/ontology-spec\";\nimport type { Uncertain } from \"@party-stack/ontology-spec/utils\";\nimport type { Key } from \"@party-stack/ontology-storage\";\n\nexport type ActionMutator = (\n tx: ActionTransaction,\n request: ActionRequest,\n context: Record<string, unknown>\n) => Effect.Effect<unknown, BackendError>;\nexport interface ActionTransaction extends OwnedTransaction {\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n}\nexport type ActionMutatorRegistry = Readonly<Record<string, ActionMutator>>;\nexport interface ActionExecutionOptions {\n readonly ir: OntologyIR;\n readonly tx: OwnedTransaction;\n readonly request: ActionRequest;\n readonly context?: Record<string, unknown>;\n readonly mutators?: ActionMutatorRegistry;\n readonly resolveOnly?: boolean;\n}\nconst failure = (message: string, kind: BackendError[\"kind\"] = \"InvalidRequest\", cause?: unknown) =>\n new BackendError({ operation: \"action.execute\", kind, retryable: false, message, cause });\nconst scalar = <A>(compute: () => A) =>\n Effect.try({\n try: compute,\n catch: (cause) =>\n failure(\n cause instanceof Error ? cause.message : \"Invalid expression values.\",\n \"InvalidRequest\",\n cause\n ),\n });\nconst defect = (cause: unknown) =>\n Effect.fail(\n cause instanceof BackendError ? cause : failure(\"Action execution failed.\", \"Internal\", cause)\n );\nclass Reference {\n constructor(\n readonly objectType: string,\n readonly key: unknown,\n readonly optional: boolean\n ) {}\n}\nclass Loaded {\n constructor(\n readonly objectType: string,\n readonly value: Record<string, unknown>\n ) {}\n}\n/** Internal partial-default evaluation; never part of the backend error contract. */\nclass UnresolvedInput extends Schema.TaggedError<UnresolvedInput>()(\"UnresolvedActionInput\", {\n parameter: Schema.String,\n}) {}\nconst unwrapped = (value: unknown): unknown => {\n if (value instanceof Reference) return value.key;\n if (value instanceof Loaded) return value.value;\n if (Array.isArray(value)) return value.map(unwrapped);\n if (value !== null && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype)\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, unwrapped(v)]));\n return value;\n};\nconst keyOf = (value: unknown) =>\n typeof value === \"string\" || typeof value === \"number\"\n ? Effect.succeed(value)\n : Effect.fail(failure(\"Object reference requires a primary key.\"));\n\n/** Portable action expressions read only the supplied transaction. No collection, remote demand or runtime lifecycle. */\nexport const actionExpressions = (options: {\n readonly ir: OntologyIR;\n readonly tx: OwnedReadTransaction;\n readonly request: ActionRequest;\n readonly context?: Record<string, unknown>;\n readonly resolveParameter?: (name: string) => Effect.Effect<unknown, BackendError>;\n}) => {\n const { ir, tx, request } = options;\n const action = ir.actionTypes.find((a) => a.name === request.name);\n const parameters: Record<string, unknown> = { ...request.parameters };\n const resolving = new Set<string>();\n const object = (name: string) => {\n const type = ir.objectTypes.find((t) => t.name === name);\n return type\n ? Effect.succeed(type)\n : Effect.fail(failure(`Unknown object type \"${name}\".`, \"InvalidConfiguration\"));\n };\n const resolveParameter = Effect.fnUntraced(function* (\n name: string\n ): Effect.fn.Return<unknown, BackendError | UnresolvedInput> {\n if (parameters[name] !== undefined) return parameters[name];\n const parameter = action?.parameters.find((p) => p.name === name);\n if (!parameter?.defaultValue) return undefined;\n if (resolving.has(name))\n return yield* failure(`Circular action parameter default for \"${name}\".`, \"InvalidConfiguration\");\n resolving.add(name);\n return yield* raw(parameter.defaultValue, [\"parameter\", name], new Map()).pipe(\n Effect.map(unwrapped),\n Effect.tap((value) =>\n Effect.sync(() => {\n if (value !== undefined) parameters[name] = value;\n })\n ),\n Effect.ensuring(Effect.sync(() => resolving.delete(name)))\n );\n });\n const raw = Effect.fnUntraced(function* (\n e: Expression,\n location: readonly (string | number)[],\n locals: ReadonlyMap<string, unknown>\n ): Effect.fn.Return<unknown, BackendError | UnresolvedInput> {\n const child = (node: Expression, segment: string) => raw(node, [...location, segment], locals);\n switch (e.kind) {\n case \"literal\":\n return e.value.value;\n case \"inputReference\": {\n const value = yield* (\n options.resolveParameter?.(e.value.name) ?? resolveParameter(e.value.name)\n );\n const parameter = action?.parameters.find((p) => p.name === e.value.name);\n if (!parameter) return yield* failure(`Unknown action parameter \"${e.value.name}\".`);\n const { type, isOptional } = unwrapType(resolveType(ir, parameter.type));\n if (value === undefined && !isOptional)\n return yield* new UnresolvedInput({ parameter: parameter.name });\n return type.kind === \"objectReference\"\n ? new Reference(type.value.objectType, value, isOptional)\n : value;\n }\n case \"contextReference\":\n return options.context?.[e.value.name];\n case \"localReference\":\n if (!locals.has(e.value.name))\n return yield* failure(`Unknown expression binding \"${e.value.name}\".`);\n return locals.get(e.value.name);\n case \"getAt\": {\n const source = yield* child(e.value.source, \"source\");\n if (source instanceof Reference)\n return yield* failure(\n \"An object reference must be looked up before accessing properties.\"\n );\n return getAtPath(source instanceof Loaded ? source.value : source, e.value.path);\n }\n case \"lookup\": {\n const reference = resolveLookupReference(ir, e.value.reference, action?.parameters);\n if (!reference)\n return yield* failure(\"Lookup requires an input/context object-reference path.\");\n const valueKey = unwrapped(yield* child(e.value.reference, \"reference\"));\n if (valueKey == null) return undefined;\n const key = yield* keyOf(valueKey);\n const value = yield* tx.get(reference.objectType, key);\n if (!value && !reference.optional)\n return yield* failure(`Missing loaded \"${reference.objectType}\" object.`, \"NotFound\");\n return value ? new Loaded(reference.objectType, value) : undefined;\n }\n case \"related\": {\n const source = yield* child(e.value.source, \"source\");\n if (!(source instanceof Loaded))\n return yield* failure(\"Related requires an ontology object.\");\n const link = resolveRelatedLink(ir, source.objectType, e.value.link);\n if (!link) return yield* failure(`Unknown relationship \"${e.value.link}\".`);\n const ownFK = isRelatedFromForeignKeySource(link, source.objectType, e.value.link);\n if (!ownFK && link.cardinality === \"many\")\n return yield* failure(\n \"To-many related expressions are not supported in action execution yet.\",\n \"NotImplemented\"\n );\n const sourceType = yield* object(source.objectType);\n const target = yield* object(ownFK ? link.target.objectType : link.source.objectType);\n const key = ownFK\n ? getAtPath(source.value, link.foreignKey.split(\".\"))\n : source.value[sourceType.primaryKey];\n if (key == null) return undefined;\n const rows = yield* tx.loadSubset(target.name, {\n where: eq(\n field(...(ownFK ? target.primaryKey : link.foreignKey).split(\".\")),\n yield* keyOf(key)\n ),\n limit: 2,\n });\n if (rows.length > 1)\n return yield* failure(\n \"To-one relationship returned multiple objects.\",\n \"InvalidResponse\"\n );\n return rows[0] ? new Loaded(target.name, rows[0].value) : undefined;\n }\n case \"struct\": {\n const entries = [];\n for (const f of e.value.fields)\n entries.push([f.name, yield* raw(f.value, [...location, \"field\", f.name], locals)]);\n return Object.fromEntries(entries);\n }\n case \"map\": {\n const source = yield* child(e.value.source, \"source\");\n if (source === undefined) return undefined;\n if (!Array.isArray(source)) return yield* failure(\"Map source must resolve to a list.\");\n return yield* Effect.forEach(source, (item, index) =>\n raw(\n e.value.body,\n [...location, \"item\", index],\n new Map([...locals, [e.value.binding, item]])\n )\n );\n }\n case \"uuid\": {\n if (!request.replay) return crypto.randomUUID();\n const digest = yield* Effect.tryPromise({\n try: () =>\n crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(JSON.stringify([request.replay!.seed, location]))\n ),\n catch: (cause) => failure(\"Could not derive replay UUID.\", \"Internal\", cause),\n });\n const bytes = new Uint8Array(digest).slice(0, 16);\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n }\n case \"now\":\n return yield* Effect.try({\n try: () =>\n request.replay ? Temporal.Instant.from(request.replay.now) : Temporal.Now.instant(),\n catch: (cause) => failure(\"Invalid replay time.\", \"InvalidRequest\", cause),\n });\n case \"case\": {\n for (const [index, branch] of e.value.branches.entries()) {\n const condition = unwrapped(\n yield* raw(branch.condition, [...location, \"branch\", index, \"condition\"], locals)\n );\n if (yield* scalar(() => booleanValue(condition)))\n return yield* raw(branch.result, [...location, \"branch\", index, \"result\"], locals);\n }\n return yield* child(e.value.else, \"else\");\n }\n case \"exists\":\n return yield* failure(\"EXISTS is not supported in action expressions yet.\", \"NotImplemented\");\n default: {\n const nodes =\n e.kind === \"not\" || e.kind === \"length\"\n ? [e.value.expression]\n : \"expressions\" in e.value\n ? e.value.expressions\n : [e.value.left, e.value.right];\n const values: Uncertain<unknown>[] = [];\n for (const [index, node] of nodes.entries()) {\n const resolved = yield* raw(node, [...location, \"operand\", index], locals);\n const value = unwrapped(resolved);\n // Preserve reference/entity identity for subsequent traversal.\n if (e.kind === \"coalesce\" && value != null) return resolved;\n values.push(certain(value));\n if (\n (e.kind === \"and\" || e.kind === \"or\") &&\n (yield* scalar(() => booleanValue(value))) === (e.kind === \"or\")\n )\n break;\n }\n const result = yield* scalar(() => evaluateOperator(e.kind, values));\n // All action inputs are concrete; uncertainty belongs to draft/query evaluation.\n if (!result.certain) return yield* failure(\"Action expression depends on unavailable data.\");\n return result.value;\n }\n }\n });\n const evaluate = (expression: Expression, location: readonly (string | number)[] = []) =>\n raw(expression, location, new Map()).pipe(\n Effect.map(unwrapped),\n Effect.catchTag(\"UnresolvedActionInput\", (error) =>\n Effect.fail(failure(`Missing action parameter \"${error.parameter}\".`))\n ),\n Effect.catchDefect(defect)\n );\n return {\n evaluate,\n resolve: Effect.gen(function* () {\n if (!action) return yield* failure(\"Action is unavailable.\", \"NotFound\");\n for (const parameter of action.parameters)\n yield* resolveParameter(parameter.name).pipe(\n Effect.catchTag(\"UnresolvedActionInput\", () => Effect.void)\n );\n return parameters;\n }).pipe(Effect.catchDefect(defect)),\n };\n};\n\nconst targetType = (ir: OntologyIR, object: ObjectTypeDef, path: readonly string[]): TypeDef | undefined => {\n let current: TypeDef | undefined = { kind: \"struct\", value: { fields: object.properties } };\n for (const segment of path) {\n if (!current) break;\n current = resolveType(ir, current);\n while (current.kind === \"optional\") current = resolveType(ir, current.value.type);\n current =\n current.kind === \"struct\"\n ? current.value.fields.find((f) => f.name === segment)?.type\n : current.kind === \"map\"\n ? current.value.valueType\n : current.kind === \"list\"\n ? current.value.elementType\n : undefined;\n }\n return current;\n};\n/** Shared authoritative execution and local replay. Transaction/commit ownership stays with the caller. */\nexport const executeAction = Effect.fn(\"Action.execute\")(function* (options: ActionExecutionOptions) {\n const { ir, tx, request } = options;\n const action = ir.actionTypes.find((a) => a.name === request.name);\n if (!action) return yield* failure(\"Action is unavailable.\", \"NotFound\");\n const expressions = actionExpressions(options);\n const parameters = yield* expressions.resolve;\n if (options.resolveOnly) return { parameters, result: undefined };\n for (const [index, step] of action.logic.entries()) {\n let type: ObjectTypeDef | undefined;\n let key: Key | undefined;\n if (step.kind === \"createObject\") type = ir.objectTypes.find((t) => t.name === step.value.objectType);\n else {\n const parameter = action.parameters.find((p) => p.name === step.value.object.name);\n const resolved = parameter && unwrapType(resolveType(ir, parameter.type)).type;\n type =\n resolved?.kind === \"objectReference\"\n ? ir.objectTypes.find((t) => t.name === resolved.value.objectType)\n : undefined;\n key = yield* keyOf(parameters[step.value.object.name]);\n }\n if (!type)\n return yield* failure(\"Action logic references an unknown object type.\", \"InvalidConfiguration\");\n if (step.kind === \"deleteObject\") {\n yield* tx.delete(type.name, key!);\n continue;\n }\n const changes = [];\n for (const assignment of step.value.values) {\n const value = yield* expressions.evaluate(assignment.value, [\n \"logic\",\n index,\n ...assignment.property,\n ]);\n if (value === undefined) continue;\n const target = targetType(ir, type, assignment.property);\n changes.push({\n path: assignment.property,\n value:\n value === null && target && resolveType(ir, target).kind === \"optional\"\n ? undefined\n : value,\n });\n }\n if (step.kind === \"updateObject\") yield* tx.patch(type.name, key!, changes);\n else {\n let value: Record<string, unknown> = {};\n for (const change of changes) value = setAtPath(value, change.path, change.value);\n if (value[type.primaryKey] === undefined) {\n const pk = type.properties.find((p) => p.name === type!.primaryKey);\n if (!pk || unwrapValueType(ir, pk.type).kind !== \"string\") continue;\n value[type.primaryKey] = `optimistic:${request.id}:${type.name}:${index}`;\n }\n const key = yield* keyOf(value[type.primaryKey]);\n if (yield* tx.get(type.name, key)) return yield* failure(\"Object already exists.\", \"Conflict\");\n yield* tx.put(type.name, value);\n }\n }\n const mutator = options.mutators?.[request.name];\n const result = mutator\n ? yield* mutator(\n {\n get: (type, key) => tx.get(type, key),\n loadSubset: (type, scan) => tx.loadSubset(type, scan),\n put: (type, value) => tx.put(type, value),\n patch: (type, key, changes) => tx.patch(type, key, changes),\n delete: (type, key) => tx.delete(type, key),\n query: (document, settings) =>\n executeQuery(document, {\n reader: { ir, loadSubset: (type, scan) => tx.loadSubset(type, scan) },\n context: options.context,\n inputs: settings?.inputs,\n }).pipe(Effect.map((result) => result.value)),\n },\n { ...request, parameters },\n options.context ?? {}\n )\n : undefined;\n return { parameters, result };\n}, Effect.catchDefect(defect));\n\n/** Resolve defaults against an authorized transaction-consistent native reader. */\nexport const resolveReadActionParameters = Effect.fn(\"Action.resolveParameters\")(function* (options: {\n readonly ir: OntologyIR;\n readonly read: OwnedReadTransaction;\n readonly context?: Record<string, unknown>;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n}) {\n return yield* actionExpressions({\n ir: options.ir,\n tx: options.read,\n request: { id: \"resolve\", name: options.name, parameters: options.parameters },\n context: options.context,\n }).resolve;\n});\n"],"mappings":";;;;;;;;AAiDA,MAAM,WAAW,SAAiB,OAA6B,kBAAkB,UAC7E,IAAI,aAAa;CAAE,WAAW;CAAkB;CAAM,WAAW;CAAO;CAAS;AAAM,CAAC;AAC5F,MAAM,UAAa,YACf,OAAO,IAAI;CACP,KAAK;CACL,QAAQ,UACJ,QACI,iBAAiB,QAAQ,MAAM,UAAU,8BACzC,kBACA,KACJ;AACR,CAAC;AACL,MAAM,UAAU,UACZ,OAAO,KACH,iBAAiB,eAAe,QAAQ,QAAQ,4BAA4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ts CHANGED
@@ -83,6 +83,9 @@ export declare const DeliveryRecordSchema: Schema.Union<readonly [Schema.Struct<
83
83
  readonly clientId: Schema.NonEmptyString;
84
84
  readonly sequence: Schema.Int;
85
85
  }>>;
86
+ readonly prediction: Schema.optional<Schema.Literals<readonly ["applied", "dropped", "none"]>>;
87
+ readonly predictionFailure: Schema.optional<Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>>;
88
+ readonly predictionMessage: Schema.optional<Schema.String>;
86
89
  }>;
87
90
  }>]>;
88
91
  export type DeliveryRef = Schema.Schema.Type<typeof DeliveryRefSchema>;
@@ -160,6 +163,9 @@ export declare const DeliveryChangeSchema: Schema.Union<readonly [Schema.Struct<
160
163
  readonly clientId: Schema.NonEmptyString;
161
164
  readonly sequence: Schema.Int;
162
165
  }>>;
166
+ readonly prediction: Schema.optional<Schema.Literals<readonly ["applied", "dropped", "none"]>>;
167
+ readonly predictionFailure: Schema.optional<Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>>;
168
+ readonly predictionMessage: Schema.optional<Schema.String>;
163
169
  }>;
164
170
  }>]>;
165
171
  }>, Schema.Struct<{
@@ -292,6 +298,9 @@ export declare const DeliveryFrameSchema: Schema.Struct<{
292
298
  readonly clientId: Schema.NonEmptyString;
293
299
  readonly sequence: Schema.Int;
294
300
  }>>;
301
+ readonly prediction: Schema.optional<Schema.Literals<readonly ["applied", "dropped", "none"]>>;
302
+ readonly predictionFailure: Schema.optional<Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>>;
303
+ readonly predictionMessage: Schema.optional<Schema.String>;
295
304
  }>;
296
305
  }>]>;
297
306
  }>, Schema.Struct<{
@@ -426,6 +435,9 @@ export declare const DeliveryFrameCodec: Schema.Codec<{
426
435
  readonly clientId: string;
427
436
  readonly sequence: number;
428
437
  } | undefined;
438
+ readonly prediction?: "applied" | "dropped" | "none" | undefined;
439
+ readonly predictionFailure?: "Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced" | undefined;
440
+ readonly predictionMessage?: string | undefined;
429
441
  };
430
442
  };
431
443
  } | {
@@ -655,6 +667,9 @@ export declare const makeDeliveryReceiver: (options: {
655
667
  readonly clientId: string;
656
668
  readonly sequence: number;
657
669
  } | undefined;
670
+ readonly prediction?: "applied" | "dropped" | "none" | undefined;
671
+ readonly predictionFailure?: "Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced" | undefined;
672
+ readonly predictionMessage?: string | undefined;
658
673
  };
659
674
  };
660
675
  } | {
@@ -1 +1 @@
1
- {"version":3,"file":"delivery.d.ts","names":[],"sources":["../src/delivery.ts"],"mappings":";;;;;;qBAaa,mBAAiB,O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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA2RjC;MACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsB1C,iWAAA,MAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"fulfillment.d.ts","names":["_$__index_js0.SourceQueryPlan"],"sources":["../src/fulfillment.ts"],"mappings":";;;;;;;;wBAwCgB,aAAa,SAAS,gBAAgB,WAAW;;qBAiBpD,wBAAqB,IAAA,YAAA,SAAA,cAAA,UAAA,iBAAA,UAAA,wCAAA,OAAA;;;;;;;;;;;;GAoEhC"}
1
+ {"version":3,"file":"fulfillment.d.ts","names":["_$__index_js0.SourceQueryPlan"],"sources":["../src/fulfillment.ts"],"mappings":";;;;;;;;wBAkDgB,aAAa,SAAS,gBAAgB,WAAW;;qBAiBpD,wBAAqB,IAAA,YAAA,SAAA,cAAA,UAAA,iBAAA,UAAA,wCAAA,OAAA;;;;;;;;;;;;GAoEhC"}
@@ -1,9 +1,9 @@
1
1
  import { BackendError } from "./errors.js";
2
2
  import { BackendSnapshotSchema } from "./index.js";
3
3
  import { compileObjectSubset } from "./subset.js";
4
- import { evaluateQuery } from "@party-stack/ontology-storage";
4
+ import { evaluateQuery, filterOperand, inValues } from "@party-stack/ontology-storage";
5
5
  import { Effect, Redacted, Schema } from "effect";
6
- import { Table, isField } from "@party-stack/ontology-storage/tables";
6
+ import { Table } from "@party-stack/ontology-storage/tables";
7
7
  //#region src/fulfillment.ts
8
8
  const codec = Table.make({ name: "subset-fulfillment" });
9
9
  const same = (left, right) => codec.encode(left) === codec.encode(right);
@@ -13,16 +13,17 @@ function implies(request, fulfilled) {
13
13
  if (!fulfilled) return true;
14
14
  if (!request) return false;
15
15
  if (same(request, fulfilled)) return true;
16
- if (request.op === "or") return request.predicates.every((child) => implies(child, fulfilled));
17
- if (fulfilled.op === "and") return fulfilled.predicates.every((child) => implies(request, child));
18
- if (request.op === "and" && request.predicates.some((child) => implies(child, fulfilled))) return true;
19
- if (fulfilled.op === "or" && fulfilled.predicates.some((child) => implies(request, child))) return true;
20
- if (fulfilled.op === "in") {
21
- if (request.op === "in" && same(request.left, fulfilled.left)) return request.values.every((value) => fulfilled.values.some((other) => same(value, other)));
22
- if (request.op === "eq") {
23
- const field = isField(request.left) ? request.left : request.right;
24
- const value = field === request.left ? request.right : request.left;
25
- if (isField(field) && !isField(value) && same(field, fulfilled.left)) return fulfilled.values.some((other) => same(value, other));
16
+ if (request.kind === "or") return request.value.expressions.every((child) => implies(child, fulfilled));
17
+ if (fulfilled.kind === "and") return fulfilled.value.expressions.every((child) => implies(request, child));
18
+ if (request.kind === "and" && request.value.expressions.some((child) => implies(child, fulfilled))) return true;
19
+ if (fulfilled.kind === "or" && fulfilled.value.expressions.some((child) => implies(request, child))) return true;
20
+ if (fulfilled.kind === "in") {
21
+ const allowed = inValues(fulfilled);
22
+ if (request.kind === "in" && same(request.value.left, fulfilled.value.left)) return inValues(request).every((value) => allowed.some((other) => same(value, other)));
23
+ if (request.kind === "eq") {
24
+ const left = filterOperand(request.value.left), right = filterOperand(request.value.right);
25
+ const [field, value] = left?.kind === "field" ? [request.value.left, right] : [request.value.right, left];
26
+ if (filterOperand(field)?.kind === "field" && value?.kind === "literal" && same(field, fulfilled.value.left)) return allowed.some((other) => same(value.value, other));
26
27
  }
27
28
  }
28
29
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"fulfillment.js","names":[],"sources":["../src/fulfillment.ts"],"sourcesContent":["import { evaluateQuery } from \"@party-stack/ontology-storage\";\nimport { Table, isField } from \"@party-stack/ontology-storage/tables\";\nimport { Effect, Redacted, Schema } from \"effect\";\nimport { BackendError } from \"./errors.js\";\nimport { compileObjectSubset } from \"./subset.js\";\nimport { BackendSnapshotSchema } from \"./index.js\";\nimport type { BackendSnapshot } from \"./index.js\";\nimport type { CompiledSubset } from \"./subset.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { Predicate, Query } from \"@party-stack/ontology-storage\";\n\nconst codec = Table.make<unknown>({ name: \"subset-fulfillment\" });\nconst same = (left: unknown, right: unknown) => codec.encode(left) === codec.encode(right);\nconst windowed = (query: Query) =>\n query.limit !== undefined || Boolean(query.offset) || query.after !== undefined;\n\n/** Sound, deliberately small implication rules for declared coverage; no data-dependent inference. */\nfunction implies(request: Predicate | undefined, fulfilled: Predicate | undefined): boolean {\n if (!fulfilled) return true;\n if (!request) return false;\n if (same(request, fulfilled)) return true;\n if (request.op === \"or\") return request.predicates.every((child) => implies(child, fulfilled));\n if (fulfilled.op === \"and\") return fulfilled.predicates.every((child) => implies(request, child));\n if (request.op === \"and\" && request.predicates.some((child) => implies(child, fulfilled))) return true;\n if (fulfilled.op === \"or\" && fulfilled.predicates.some((child) => implies(request, child))) return true;\n if (fulfilled.op === \"in\") {\n if (request.op === \"in\" && same(request.left, fulfilled.left))\n return request.values.every((value) => fulfilled.values.some((other) => same(value, other)));\n if (request.op === \"eq\") {\n const field = isField(request.left) ? request.left : request.right;\n const value = field === request.left ? request.right : request.left;\n if (isField(field) && !isField(value) && same(field, fulfilled.left))\n return fulfilled.values.some((other) => same(value, other));\n }\n }\n return false;\n}\n\n/** A windowed source can supply a wider prefix of the same ordered/filtered result. */\nexport function coversSubset(request: CompiledSubset, fulfilled: CompiledSubset): boolean {\n if (request.objectType !== fulfilled.objectType) return false;\n const wanted = request.query ?? {},\n actual = fulfilled.query ?? {};\n if (!windowed(actual)) return implies(wanted.where, actual.where);\n if (\n !same(wanted.where, actual.where) ||\n !same(wanted.orderBy ?? [], actual.orderBy ?? []) ||\n !same(wanted.after, actual.after)\n )\n return false;\n const delta = (wanted.offset ?? 0) - (actual.offset ?? 0);\n if (delta < 0) return false;\n return actual.limit === undefined || (wanted.limit !== undefined && delta + wanted.limit <= actual.limit);\n}\n\n/** Normalize exactly once at a consumer boundary; provider windows must not be applied twice. */\nexport const resolveSubsetSnapshot = Effect.fnUntraced(function* (\n ir: OntologyIR,\n request: ObjectSubset,\n snapshot: BackendSnapshot,\n context?: Record<string, unknown>\n) {\n snapshot = yield* Schema.decodeUnknownEffect(BackendSnapshotSchema)(snapshot).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider returned an invalid snapshot.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n );\n const requested = yield* compileObjectSubset(ir, request, context);\n const fulfilled = snapshot.fulfilledSubset\n ? yield* compileObjectSubset(ir, snapshot.fulfilledSubset, context).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider reported an invalid fulfilled subset.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n )\n : requested;\n return yield* Effect.try({\n try: () => {\n if (!coversSubset(requested, fulfilled))\n throw new Error(\"The fulfilled subset does not cover the request.\");\n const primaryKey = ir.objectTypes.find((type) => type.name === requested.objectType)!.primaryKey;\n const keys = new Set<string | number>();\n for (const row of snapshot.rows) {\n if (row.value[primaryKey] !== row.key || keys.has(row.key))\n throw new Error(\"Invalid or duplicate snapshot identity.\");\n keys.add(row.key);\n }\n const query = requested.query ?? {};\n const actual = fulfilled.query ?? {};\n // Rows from an explicitly fulfilled window have already skipped its offset.\n const requestedQuery = {\n ...query,\n offset: Math.max(0, (query.offset ?? 0) - (actual.offset ?? 0)),\n };\n const rows = evaluateQuery(snapshot.rows, requestedQuery);\n return {\n requested,\n fulfilled,\n fulfilledRows: evaluateQuery(snapshot.rows, { ...actual, offset: 0 }),\n snapshot: { ...snapshot, fulfilledSubset: undefined, rows },\n };\n },\n catch: (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"The provider returned an incompatible subset snapshot.\",\n cause: Redacted.make(cause),\n }),\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E,MAAM,aAAa,GAAG,YAAY,MAAM,SAAS,KAAK,SAAS,UAAU,UAAU,CAAC,CAAE;GACtF,MAAM,uBAAO,IAAI,IAAqB;GACtC,KAAK,MAAM,OAAO,SAAS,MAAM;IAC7B,IAAI,IAAI,MAAM,gBAAgB,IAAI,OAAO,KAAK,IAAI,IAAI,GAAG,GACrD,MAAM,IAAI,MAAM,yCAAyC;IAC7D,KAAK,IAAI,IAAI,GAAG;GACpB;GACA,MAAM,QAAQ,UAAU,SAAS,CAAC;GAClC,MAAM,SAAS,UAAU,SAAS,CAAC;GAEnC,MAAM,iBAAiB;IACnB,GAAG;IACH,QAAQ,KAAK,IAAI,IAAI,MAAM,UAAU,MAAM,OAAO,UAAU,EAAE;GAClE;GACA,MAAM,OAAO,cAAc,SAAS,MAAM,cAAc;GACxD,OAAO;IACH;IACA;IACA,eAAe,cAAc,SAAS,MAAM;KAAE,GAAG;KAAQ,QAAQ;IAAE,CAAC;IACpE,UAAU;KAAE,GAAG;KAAU,iBAAiB,KAAA;KAAW;IAAK;GAC9D;EACJ;EACA,QAAQ,UACJ,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS;GACT,OAAO,SAAS,KAAK,KAAK;EAC9B,CAAC;CACT,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"fulfillment.js","names":[],"sources":["../src/fulfillment.ts"],"sourcesContent":["import { evaluateQuery, filterOperand, inValues } from \"@party-stack/ontology-storage\";\nimport { Table } from \"@party-stack/ontology-storage/tables\";\nimport { Effect, Redacted, Schema } from \"effect\";\nimport { BackendError } from \"./errors.js\";\nimport { compileObjectSubset } from \"./subset.js\";\nimport { BackendSnapshotSchema } from \"./index.js\";\nimport type { BackendSnapshot } from \"./index.js\";\nimport type { CompiledSubset } from \"./subset.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { Filter, Query } from \"@party-stack/ontology-storage\";\n\nconst codec = Table.make<unknown>({ name: \"subset-fulfillment\" });\nconst same = (left: unknown, right: unknown) => codec.encode(left) === codec.encode(right);\nconst windowed = (query: Query) =>\n query.limit !== undefined || Boolean(query.offset) || query.after !== undefined;\n\n/** Sound, deliberately small implication rules for declared coverage; no data-dependent inference. */\nfunction implies(request: Filter | undefined, fulfilled: Filter | undefined): boolean {\n if (!fulfilled) return true;\n if (!request) return false;\n if (same(request, fulfilled)) return true;\n if (request.kind === \"or\") return request.value.expressions.every((child) => implies(child, fulfilled));\n if (fulfilled.kind === \"and\")\n return fulfilled.value.expressions.every((child) => implies(request, child));\n if (request.kind === \"and\" && request.value.expressions.some((child) => implies(child, fulfilled)))\n return true;\n if (fulfilled.kind === \"or\" && fulfilled.value.expressions.some((child) => implies(request, child)))\n return true;\n if (fulfilled.kind === \"in\") {\n const allowed = inValues(fulfilled);\n if (request.kind === \"in\" && same(request.value.left, fulfilled.value.left))\n return inValues(request).every((value) => allowed.some((other) => same(value, other)));\n if (request.kind === \"eq\") {\n const left = filterOperand(request.value.left),\n right = filterOperand(request.value.right);\n const [field, value] =\n left?.kind === \"field\" ? [request.value.left, right] : [request.value.right, left];\n if (\n filterOperand(field)?.kind === \"field\" &&\n value?.kind === \"literal\" &&\n same(field, fulfilled.value.left)\n )\n return allowed.some((other) => same(value.value, other));\n }\n }\n return false;\n}\n\n/** A windowed source can supply a wider prefix of the same ordered/filtered result. */\nexport function coversSubset(request: CompiledSubset, fulfilled: CompiledSubset): boolean {\n if (request.objectType !== fulfilled.objectType) return false;\n const wanted = request.query ?? {},\n actual = fulfilled.query ?? {};\n if (!windowed(actual)) return implies(wanted.where, actual.where);\n if (\n !same(wanted.where, actual.where) ||\n !same(wanted.orderBy ?? [], actual.orderBy ?? []) ||\n !same(wanted.after, actual.after)\n )\n return false;\n const delta = (wanted.offset ?? 0) - (actual.offset ?? 0);\n if (delta < 0) return false;\n return actual.limit === undefined || (wanted.limit !== undefined && delta + wanted.limit <= actual.limit);\n}\n\n/** Normalize exactly once at a consumer boundary; provider windows must not be applied twice. */\nexport const resolveSubsetSnapshot = Effect.fnUntraced(function* (\n ir: OntologyIR,\n request: ObjectSubset,\n snapshot: BackendSnapshot,\n context?: Record<string, unknown>\n) {\n snapshot = yield* Schema.decodeUnknownEffect(BackendSnapshotSchema)(snapshot).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider returned an invalid snapshot.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n );\n const requested = yield* compileObjectSubset(ir, request, context);\n const fulfilled = snapshot.fulfilledSubset\n ? yield* compileObjectSubset(ir, snapshot.fulfilledSubset, context).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n message: \"The provider reported an invalid fulfilled subset.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n )\n : requested;\n return yield* Effect.try({\n try: () => {\n if (!coversSubset(requested, fulfilled))\n throw new Error(\"The fulfilled subset does not cover the request.\");\n const primaryKey = ir.objectTypes.find((type) => type.name === requested.objectType)!.primaryKey;\n const keys = new Set<string | number>();\n for (const row of snapshot.rows) {\n if (row.value[primaryKey] !== row.key || keys.has(row.key))\n throw new Error(\"Invalid or duplicate snapshot identity.\");\n keys.add(row.key);\n }\n const query = requested.query ?? {};\n const actual = fulfilled.query ?? {};\n // Rows from an explicitly fulfilled window have already skipped its offset.\n const requestedQuery = {\n ...query,\n offset: Math.max(0, (query.offset ?? 0) - (actual.offset ?? 0)),\n };\n const rows = evaluateQuery(snapshot.rows, requestedQuery);\n return {\n requested,\n fulfilled,\n fulfilledRows: evaluateQuery(snapshot.rows, { ...actual, offset: 0 }),\n snapshot: { ...snapshot, fulfilledSubset: undefined, rows },\n };\n },\n catch: (cause) =>\n new BackendError({\n operation: \"loadSubset\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"The provider returned an incompatible subset snapshot.\",\n cause: Redacted.make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EACX,OAAO,SAAS,KAAK,KAAK;CAC9B,CAAC,CACT,CACJ,IACA;CACN,OAAO,OAAO,OAAO,IAAI;EACrB,WAAW;GACP,IAAI,CAAC,aAAa,WAAW,SAAS,GAClC,MAAM,IAAI,MAAM,kDAAkD;GACtE,MAAM,aAAa,GAAG,YAAY,MAAM,SAAS,KAAK,SAAS,UAAU,UAAU,CAAC,CAAE;GACtF,MAAM,uBAAO,IAAI,IAAqB;GACtC,KAAK,MAAM,OAAO,SAAS,MAAM;IAC7B,IAAI,IAAI,MAAM,gBAAgB,IAAI,OAAO,KAAK,IAAI,IAAI,GAAG,GACrD,MAAM,IAAI,MAAM,yCAAyC;IAC7D,KAAK,IAAI,IAAI,GAAG;GACpB;GACA,MAAM,QAAQ,UAAU,SAAS,CAAC;GAClC,MAAM,SAAS,UAAU,SAAS,CAAC;GAEnC,MAAM,iBAAiB;IACnB,GAAG;IACH,QAAQ,KAAK,IAAI,IAAI,MAAM,UAAU,MAAM,OAAO,UAAU,EAAE;GAClE;GACA,MAAM,OAAO,cAAc,SAAS,MAAM,cAAc;GACxD,OAAO;IACH;IACA;IACA,eAAe,cAAc,SAAS,MAAM;KAAE,GAAG;KAAQ,QAAQ;IAAE,CAAC;IACpE,UAAU;KAAE,GAAG;KAAU,iBAAiB,KAAA;KAAW;IAAK;GAC9D;EACJ;EACA,QAAQ,UACJ,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS;GACT,OAAO,SAAS,KAAK,KAAK;EAC9B,CAAC;CACT,CAAC;AACL,CAAC"}
package/lib/index.d.ts CHANGED
@@ -224,10 +224,32 @@ export interface BackendEncryptedValues {
224
224
  /** Explicit operation. Ordinary record loads return handles and never decrypt them. */
225
225
  readonly decrypt: (value: Encrypted<unknown>) => Effect.Effect<DecryptedValue, BackendError>;
226
226
  }
227
+ /** One object a watch reports, in the watched subset's object type.
228
+ * - `put`: the object is now in the subset with this complete value.
229
+ * - `exit`: the object left the subset. It may have changed or been deleted; the
230
+ * replica reads it back by primary key to tell which.
231
+ * - `delete`: the object no longer exists anywhere.
232
+ */
233
+ export type SubsetWatchChange = {
234
+ readonly kind: "put";
235
+ readonly key: Key;
236
+ readonly value: Record<string, unknown>;
237
+ } | {
238
+ readonly kind: "exit";
239
+ readonly key: Key;
240
+ } | {
241
+ readonly kind: "delete";
242
+ readonly key: Key;
243
+ };
227
244
  /** A reset requests repair after starting/restarting a watch; it does not
228
245
  * assert that data changed. Ordinary void hints always invalidate coverage.
246
+ * `changes` describes exactly what changed, so the replica can apply it without
247
+ * reloading the subset. Report only what is certain: a `put` must carry every
248
+ * property; anything less precise must be an invalidation hint instead.
229
249
  */
230
- export type SubsetWatchEvent = void | "reset";
250
+ export type SubsetWatchEvent = void | "reset" | {
251
+ readonly changes: readonly SubsetWatchChange[];
252
+ };
231
253
  export interface OntologyBackendService {
232
254
  readonly name: string;
233
255
  /** Stable identity for the source whose cursors and receipts this binding returns. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["_$__encrypted_js0.DecryptedValue","_$__delivery_js0.DeliveryPolicy","_$__delivery_js0.DeliveryPosition","_$__delivery_js0.DeliverySubscription","_$__errors_js0.ValidationReport"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;iBAuCiB;WACJ,kBAAkB;;iBAEd;;;;;;;WAOJ,kBAAkB;WAClB,eAAe,IAAI;;WAEnB;;;;WAIA;;WAEA,WAAW;;WAEX;;qBAEA,uBAAqB,OAAA;;;;;;;;;;;;;;;;YAetB,kBAAkB,OAAO,OAAO,YAAY;YAC5C;WAEO;WACA;WACA,KAAK;WACL,OAAO;;WAET;WAAyB;WAA6B,KAAK;;iBAC3D;WACJ;WACA,kBAAkB;WAClB;;iBAEI;WACJ,kBAAkB;WAClB;WACA;;iBAEI;WACJ,YAAY;WACZ,MAAM;WACN,SAAS;;iBAEL;;WAEJ;WACA;WACA,YAAY;WACZ,6BAA6B;;WAE7B;aAAoB;aAAsB;;;iBAEtC;;WAEJ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BACX,OAAO,gBAAgB;WACnB;aACI,OAAO;eACH;eACA;UACP,OAAO,OAAO,mBAAmB;;;;aAI9B,QAAQ,OAAO,OAAO,OAAO,aAAa,eAAe,cAAc,MAAM;;WAEjF,cAAc;WACd,YAAY;;;;qBAIZ,wBAAwB"}
1
+ {"version":3,"file":"index.d.ts","names":["_$__encrypted_js0.DecryptedValue","_$__delivery_js0.DeliveryPolicy","_$__delivery_js0.DeliveryPosition","_$__delivery_js0.DeliverySubscription","_$__errors_js0.ValidationReport"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;iBAuCiB;WACJ,kBAAkB;;iBAEd;;;;;;;WAOJ,kBAAkB;WAClB,eAAe,IAAI;;WAEnB;;;;WAIA;;WAEA,WAAW;;WAEX;;qBAEA,uBAAqB,OAAA;;;;;;;;;;;;;;;;YAetB,kBAAkB,OAAO,OAAO,YAAY;YAC5C;WAEO;WACA;WACA,KAAK;WACL,OAAO;;WAET;WAAyB;WAA6B,KAAK;;iBAC3D;WACJ;WACA,kBAAkB;WAClB;;iBAEI;WACJ,kBAAkB;WAClB;WACA;;iBAEI;WACJ,YAAY;WACZ,MAAM;WACN,SAAS;;iBAEL;;WAEJ;WACA;WACA,YAAY;WACZ,6BAA6B;;WAE7B;aAAoB;aAAsB;;;iBAEtC;;WAEJ;;WAEA;;WAEA;WACA;;WAEA;;;;;;WAMA;aACI;aACA,gBAAgB;;;;;WAKpB;WACA;aAA2C;aAA0B;;;qBAGrE,oBAAkB,OAAA,gBAAA,OAAA;;;;;;;;;;qBASlB,qBAAmB,OAAA;;;;;;;;;;;;;;;;qBAgBnB,qBAAmB,OAAA;;;;;;;;;;;;;;qBAKnB,uBAAqB,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;qBAUrB,yBAAuB,OAAA;;;;;;;;;;;;;;;;;;iBAMnB;;WAEJ,SACL,OAAO,YACP,OAAO,WACP;aAAqB,SAAS;QAC7B,OAAO,OAAO,YAAY;;WAEtB,OACL,OAAO,YACP;aAAqB;aAA0B;QAC9C,OAAO,OAAO,WAAW,cAAc,MAAM;WACzC,WACL,OAAO,YACP;aAAqB;QACpB,OAAO;aAEK;aACA;aACA;aACA;eAAwB;eAAwB;;KAE7D;;iBAWS;;WAEJ,UACL,OAAO,uBACN,OAAO,OADDA,gBACiD;;;;;;;;YAQpD;WACK;WAAsB,KAAK;WAAc,OAAO;;WAChD;WAAuB,KAAK;;WAC5B;WAAyB,KAAK;;;;;;;;YAOnC;WAA+C,kBAAkB;;iBAE5D;WACJ;;WAEA;;;;;;WAMA;;WAEA,cAAc,OAAO,aAAa;;;;WAIlC,aAAa,QAAQ,iBAAiB,OAAO,OAAO,iBAAiB;;;;;WAKrE,QACL,UAAU,eACV;aAAqB,SAAS;QAC7B,OAAO,OAAO,yBAAyB;;WAEnC,sBACL,WAAW,iBACX,SADWC,gBAEX,SADiCC,qBAEhC,OAAO,OADyBC,sBAC4B,cAAc,MAAM;WAC5E,uBACL,UAFQD,qBAGP,OAAO,aAAa;;WAEhB,2BACL,cACA,YAAY,4BACX,OAAO,OAAO,yBAAyB;;;;;;;;;WASnC,eACL,QAAQ,iBACP,OAAO,OAAO,OAAO,OAAO,kBAAkB,eAAe,cAAc,MAAM;;;WAG7E,WAAW,QAAQ;aAET;aACA;;WAGV,kBACL,cACA,YAAY,yBACZ;aAAqB;QACpB,OAAO,OAFIE,kBAE2C;WAClD,cAAc,YAAY,kBAAkB,OAAO,OAAO,eAAe;WACzE,gBACL,cACA,YAAY,4BACX,OAAO,gBAAgB;WACnB;aACI,OAAO;eACH;eACA;UACP,OAAO,OAAO,mBAAmB;;;;aAI9B,QAAQ,OAAO,OAAO,OAAO,aAAa,eAAe,cAAc,MAAM;;WAEjF,cAAc;WACd,YAAY;;;;qBAIZ,wBAAwB"}
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { Context, Schema } from \"effect\";\nimport { ObjectSubsetSchema } from \"./subsetSchema.js\";\nimport type { AttachmentTypeDef, QueryDocument } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { attachment, Encrypted } from \"@party-stack/ontology-spec/values\";\nimport type { Key, Row } from \"@party-stack/ontology-storage\";\nimport type { ByteInput } from \"@party-stack/ontology-storage/blobs\";\nimport type { Scope, Effect, Stream } from \"effect\";\n\nexport {\n schemaValidationIssues,\n BackendError,\n BackendErrorKindSchema,\n backendErrorStatus,\n ValidationIssueSchema,\n ValidationReportSchema,\n unauthenticated,\n isUnauthenticatedError,\n classifyBackendFailure,\n projectBackendError,\n projectValidationIssue,\n isUnknownActionOutcome,\n} from \"./errors.js\";\nexport type {\n BackendErrorKind,\n ReplicationErrorKind,\n ReplicationError,\n ErrorProjection,\n ErrorProjectionContext,\n ValidationReport,\n ValidationIssue,\n UnauthenticatedError,\n ApplyActionError,\n ValidateActionError,\n LoadSubsetError,\n} from \"./errors.js\";\nimport { BackendError } from \"./errors.js\";\nexport { makeOntologyBackend } from \"./query.js\";\n\nexport interface ObjectSelection {\n readonly subsets: readonly ObjectSubset[];\n}\nexport interface BackendSnapshot {\n /** Region represented by these rows, including any window already applied.\n * Omitted means the requested subset. A broader unwindowed region lets the\n * engine finish filtering/ordering/windowing and optionally cache extra objects.\n * Rows may include residual candidates outside this region; consumers discard\n * them before installing its objects or recording complete coverage.\n */\n readonly fulfilledSubset?: ObjectSubset;\n readonly rows: readonly Row<Record<string, unknown>>[];\n /** Complete for fulfilledSubset (or the request when omitted), including its window. */\n readonly complete: boolean;\n /** Rows fetched from the provider, before adapter-side filtering/windowing.\n * Diagnostic only; omitted when the adapter cannot report it. Not a DB scan count.\n */\n readonly fetchedRows?: number;\n /** Diagnostic provider filter, not a query-capability or coverage contract. */\n readonly pushdown?: SourceQueryPlan;\n /** Position coordinated with this snapshot, when the backend exposes a durable change stream. */\n readonly cursor?: string;\n}\nexport const SourceQueryPlanSchema = Schema.Struct({\n source: Schema.String,\n /** Paths into the request's portable where tree: AND/OR child indices, NOT child 0, [] for the root. */\n predicates: Schema.Array(\n Schema.Struct({\n path: Schema.Array(Schema.Int),\n execution: Schema.Literals([\"source\", \"candidate\", \"adapter\", \"engine\"]),\n })\n ),\n sorting: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n pagination: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n rechecksFilter: Schema.Boolean,\n /** Optional native syntax for raw inspection. Consumers must not parse it to infer execution. */\n native: Schema.optional(Schema.Struct({ language: Schema.String, text: Schema.String })),\n});\nexport type SourceQueryPlan = Schema.Schema.Type<typeof SourceQueryPlanSchema>;\nexport type ObjectChange =\n | {\n readonly kind: \"put\";\n readonly objectType: string;\n readonly key: Key;\n readonly value: Record<string, unknown>;\n }\n | { readonly kind: \"delete\"; readonly objectType: string; readonly key: Key };\nexport interface BackendCommit {\n readonly cursor: string;\n readonly changes: readonly ObjectChange[];\n readonly operationId?: string;\n}\nexport interface BackendChangePage {\n readonly commits: readonly BackendCommit[];\n readonly cursor: string;\n readonly hasMore: boolean;\n}\nexport interface AttachmentUpload {\n readonly attachment: attachment;\n readonly blob: ByteInput;\n readonly target?: AttachmentTypeDef;\n}\nexport interface ActionRequest {\n /** Stable across retries. The source must separately guarantee keyed idempotency. */\n readonly id: string;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n readonly attachmentUploads?: readonly AttachmentUpload[];\n /** Portable replay inputs, preserved across rebases, forwarding and authoritative execution. */\n readonly replay?: { readonly now: string; readonly seed: string };\n}\nexport interface ActionReceipt {\n /** The submitted ActionRequest.id, also supplied as the application's idempotencyKey. */\n readonly operationId: string;\n /** Provider commitment is recorded before local read-back/reconciliation. Parent acceptance is separate. */\n readonly outcome: \"committed\";\n /** Encoded authoritative return value, interpreted using the action returnType. Never a journal payload. */\n readonly result?: unknown;\n readonly cursor?: string;\n /** Optional upstream execution ID. Never substitutes for our stable retry identity. */\n readonly providerOperationId?: string;\n /** Read-back targets for a committed non-journal action. Missing keys\n * means the whole type; an empty list means no modeled object changes.\n * Omission conservatively refreshes every modeled type.\n * Targets are complete unless affectedComplete is explicitly false.\n */\n readonly affected?: readonly {\n readonly objectType: string;\n readonly keys?: readonly Key[];\n }[];\n /** False when these are known targets but automation may have changed other\n * modeled records. Confirmation must not use them as an exhaustive edit list.\n */\n readonly affectedComplete?: boolean;\n readonly attachmentIdMappings?: readonly { readonly localId: string; readonly remoteId: string }[];\n}\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nexport const ObjectChangeSchema = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"put\"),\n objectType: Schema.String,\n key: KeySchema,\n value: Schema.Record(Schema.String, Schema.Unknown),\n }),\n Schema.Struct({ kind: Schema.Literal(\"delete\"), objectType: Schema.String, key: KeySchema }),\n]);\nexport const ActionReceiptSchema = Schema.Struct({\n operationId: Schema.String,\n outcome: Schema.Literal(\"committed\"),\n result: Schema.optional(Schema.Unknown),\n cursor: Schema.optional(Schema.String),\n providerOperationId: Schema.optional(Schema.String),\n affected: Schema.optional(\n Schema.Array(\n Schema.Struct({ objectType: Schema.String, keys: Schema.optional(Schema.Array(KeySchema)) })\n )\n ),\n affectedComplete: Schema.optional(Schema.Boolean),\n attachmentIdMappings: Schema.optional(\n Schema.Array(Schema.Struct({ localId: Schema.String, remoteId: Schema.String }))\n ),\n});\nexport const BackendCommitSchema = Schema.Struct({\n cursor: Schema.String,\n changes: Schema.Array(ObjectChangeSchema),\n operationId: Schema.optional(Schema.String),\n});\nexport const BackendSnapshotSchema = Schema.Struct({\n fulfilledSubset: Schema.optional(ObjectSubsetSchema),\n fetchedRows: Schema.optional(Schema.Number),\n pushdown: Schema.optional(SourceQueryPlanSchema),\n rows: Schema.Array(\n Schema.Struct({ key: KeySchema, value: Schema.Record(Schema.String, Schema.Unknown) })\n ),\n complete: Schema.Boolean,\n cursor: Schema.optional(Schema.String),\n});\nexport const BackendChangePageSchema = Schema.Struct({\n commits: Schema.Array(BackendCommitSchema),\n cursor: Schema.String,\n hasMore: Schema.Boolean,\n});\n\nexport interface BackendAttachments {\n /** Optional authoritative staging before a subsequent action references the handle. */\n readonly stage?: (\n value: attachment,\n bytes: ByteInput,\n options?: { readonly target?: AttachmentTypeDef }\n ) => Effect.Effect<attachment, BackendError>;\n /** Keep the caller Scope open through consumption; closing it cancels an unconsumed download too. */\n readonly read: (\n value: attachment,\n options?: { readonly offset?: number; readonly length?: number }\n ) => Effect.Effect<ByteInput, BackendError, Scope.Scope>;\n readonly metadata: (\n value: attachment,\n options?: { readonly select?: readonly (\"size\" | \"type\" | \"name\" | \"dimensions\")[] }\n ) => Effect.Effect<\n {\n readonly size?: number;\n readonly type?: string;\n readonly name?: string;\n readonly dimensions?: { readonly width: number; readonly height: number };\n },\n BackendError\n >;\n}\nexport {\n EncryptedValueSchema,\n DecryptedValueSchema,\n encryptedPropertyCodec,\n makePropertyDecryption,\n} from \"./encrypted.js\";\nexport type { DecryptedValue } from \"./encrypted.js\";\n\nexport interface BackendEncryptedValues {\n /** Explicit operation. Ordinary record loads return handles and never decrypt them. */\n readonly decrypt: (\n value: Encrypted<unknown>\n ) => Effect.Effect<import(\"./encrypted.js\").DecryptedValue, BackendError>;\n}\n/** A reset requests repair after starting/restarting a watch; it does not\n * assert that data changed. Ordinary void hints always invalidate coverage.\n */\nexport type SubsetWatchEvent = void | \"reset\";\n\nexport interface OntologyBackendService {\n readonly name: string;\n /** Stable identity for the source whose cursors and receipts this binding returns. */\n readonly sourceId: string;\n /** Durable keyed idempotency within the configured receipt-retention window:\n * repeated IDs return the recorded result, with\n * conflicting payloads rejected. The guarantee must survive source restart.\n * Merely receiving an ID, or an action being naturally idempotent, is insufficient.\n */\n readonly supportsIdempotency: boolean;\n /** Indexed bounded local maintenance; the backend owner schedules it. */\n readonly maintenance?: Effect.Effect<void, BackendError>;\n /** Return the request or explicitly describe the region actually fulfilled.\n * Consumers use the shared subset normalizer before applying requested windows.\n */\n readonly loadSubset: (subset: ObjectSubset) => Effect.Effect<BackendSnapshot, BackendError>;\n /** Finite Query IR execution using this binding's trusted context and read path.\n * Provider adapters may evaluate through subset loads; owned storage uses one\n * read transaction. Callers supply query inputs, never authentication context.\n */\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Optional selected committed rows. Closing the Scope releases demand; delivery state expires by policy. */\n readonly subscribeSelection?: (\n selection: ObjectSelection,\n policy?: import(\"./delivery.js\").DeliveryPolicy,\n resume?: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<import(\"./delivery.js\").DeliverySubscription, BackendError, Scope.Scope>;\n readonly acknowledgeDelivery?: (\n position: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<void, BackendError>;\n /** Read-only defaults and edit prefills; never invokes the action. */\n readonly resolveActionParameters?: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Acquire a demand-scoped watch before reading its snapshot. Completion proves\n * registration and buffering are active, even before the returned stream is pulled.\n * The acquiring Scope owns registration and release. Undefined means polling.\n * Reconnect within the same stream must fail or emit reset/invalidation;\n * reacquisition establishes a new readiness boundary for a fresh read.\n * Must cover every change relevant to the requested subset; broader watches\n * may emit extra hints. It does not maintain broader fulfilledSubset coverage.\n */\n readonly watchSubset?: (\n subset: ObjectSubset\n ) => Effect.Effect<Stream.Stream<SubsetWatchEvent, BackendError>, BackendError, Scope.Scope> | undefined;\n /** Recommended demand refresh defaults. Caller configuration wins; healthy\n * watches/journals keep coverage current independently of snapshot age. */\n readonly refresh?: (subset: ObjectSubset) =>\n | {\n readonly pollIntervalMs?: number | false;\n readonly maxCoverageAgeMs?: number;\n }\n | undefined;\n readonly validateAction?: (\n name: string,\n parameters: Record<string, unknown>,\n options?: { readonly knownParameters?: readonly string[] }\n ) => Effect.Effect<import(\"./errors.js\").ValidationReport, BackendError>;\n readonly applyAction: (invocation: ActionRequest) => Effect.Effect<ActionReceipt, BackendError>;\n readonly queryFunction: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<unknown, BackendError>;\n readonly changes?: {\n readonly pull: (options: {\n readonly cursor?: string;\n readonly limit?: number;\n }) => Effect.Effect<BackendChangePage, BackendError>;\n /** Acquire registered, buffered wake-up hints in the caller's Scope before\n * pulling durable changes. Stream consumption does not initiate registration.\n * Call pull to recover changes after reconnect or restart. */\n readonly watch?: Effect.Effect<Stream.Stream<void, BackendError>, BackendError, Scope.Scope>;\n };\n readonly attachments?: BackendAttachments;\n readonly encrypted?: BackendEncryptedValues;\n}\n\n/** Backend protocol independent of TanStack collections and client lifecycle management. */\nexport class OntologyBackend extends Context.Service<OntologyBackend, OntologyBackendService>()(\n \"@party-stack/ontology-backend/OntologyBackend\"\n) {}\n"],"mappings":";;;;;;AA8DA,MAAa,wBAAwB,OAAO,OAAO;CAC/C,QAAQ,OAAO;;CAEf,YAAY,OAAO,MACf,OAAO,OAAO;EACV,MAAM,OAAO,MAAM,OAAO,GAAG;EAC7B,WAAW,OAAO,SAAS;GAAC;GAAU;GAAa;GAAW;EAAQ,CAAC;CAC3E,CAAC,CACL;CACA,SAAS,OAAO,SAAS;EAAC;EAAU;EAAW;EAAU;CAAM,CAAC;CAChE,YAAY,OAAO,SAAS;EAAC;EAAU;EAAW;EAAU;CAAM,CAAC;CACnE,gBAAgB,OAAO;;CAEvB,QAAQ,OAAO,SAAS,OAAO,OAAO;EAAE,UAAU,OAAO;EAAQ,MAAM,OAAO;CAAO,CAAC,CAAC;AAC3F,CAAC;AA2DD,MAAM,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAa,qBAAqB,OAAO,MAAM,CAC3C,OAAO,OAAO;CACV,MAAM,OAAO,QAAQ,KAAK;CAC1B,YAAY,OAAO;CACnB,KAAK;CACL,OAAO,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;AACtD,CAAC,GACD,OAAO,OAA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1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { Context, Schema } from \"effect\";\nimport { ObjectSubsetSchema } from \"./subsetSchema.js\";\nimport type { AttachmentTypeDef, QueryDocument } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { attachment, Encrypted } from \"@party-stack/ontology-spec/values\";\nimport type { Key, Row } from \"@party-stack/ontology-storage\";\nimport type { ByteInput } from \"@party-stack/ontology-storage/blobs\";\nimport type { Scope, Effect, Stream } from \"effect\";\n\nexport {\n schemaValidationIssues,\n BackendError,\n BackendErrorKindSchema,\n backendErrorStatus,\n ValidationIssueSchema,\n ValidationReportSchema,\n unauthenticated,\n isUnauthenticatedError,\n classifyBackendFailure,\n projectBackendError,\n projectValidationIssue,\n isUnknownActionOutcome,\n} from \"./errors.js\";\nexport type {\n BackendErrorKind,\n ReplicationErrorKind,\n ReplicationError,\n ErrorProjection,\n ErrorProjectionContext,\n ValidationReport,\n ValidationIssue,\n UnauthenticatedError,\n ApplyActionError,\n ValidateActionError,\n LoadSubsetError,\n} from \"./errors.js\";\nimport { BackendError } from \"./errors.js\";\nexport { makeOntologyBackend } from \"./query.js\";\n\nexport interface ObjectSelection {\n readonly subsets: readonly ObjectSubset[];\n}\nexport interface BackendSnapshot {\n /** Region represented by these rows, including any window already applied.\n * Omitted means the requested subset. A broader unwindowed region lets the\n * engine finish filtering/ordering/windowing and optionally cache extra objects.\n * Rows may include residual candidates outside this region; consumers discard\n * them before installing its objects or recording complete coverage.\n */\n readonly fulfilledSubset?: ObjectSubset;\n readonly rows: readonly Row<Record<string, unknown>>[];\n /** Complete for fulfilledSubset (or the request when omitted), including its window. */\n readonly complete: boolean;\n /** Rows fetched from the provider, before adapter-side filtering/windowing.\n * Diagnostic only; omitted when the adapter cannot report it. Not a DB scan count.\n */\n readonly fetchedRows?: number;\n /** Diagnostic provider filter, not a query-capability or coverage contract. */\n readonly pushdown?: SourceQueryPlan;\n /** Position coordinated with this snapshot, when the backend exposes a durable change stream. */\n readonly cursor?: string;\n}\nexport const SourceQueryPlanSchema = Schema.Struct({\n source: Schema.String,\n /** Paths into the request's portable where tree: AND/OR child indices, NOT child 0, [] for the root. */\n predicates: Schema.Array(\n Schema.Struct({\n path: Schema.Array(Schema.Int),\n execution: Schema.Literals([\"source\", \"candidate\", \"adapter\", \"engine\"]),\n })\n ),\n sorting: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n pagination: Schema.Literals([\"source\", \"adapter\", \"engine\", \"none\"]),\n rechecksFilter: Schema.Boolean,\n /** Optional native syntax for raw inspection. Consumers must not parse it to infer execution. */\n native: Schema.optional(Schema.Struct({ language: Schema.String, text: Schema.String })),\n});\nexport type SourceQueryPlan = Schema.Schema.Type<typeof SourceQueryPlanSchema>;\nexport type ObjectChange =\n | {\n readonly kind: \"put\";\n readonly objectType: string;\n readonly key: Key;\n readonly value: Record<string, unknown>;\n }\n | { readonly kind: \"delete\"; readonly objectType: string; readonly key: Key };\nexport interface BackendCommit {\n readonly cursor: string;\n readonly changes: readonly ObjectChange[];\n readonly operationId?: string;\n}\nexport interface BackendChangePage {\n readonly commits: readonly BackendCommit[];\n readonly cursor: string;\n readonly hasMore: boolean;\n}\nexport interface AttachmentUpload {\n readonly attachment: attachment;\n readonly blob: ByteInput;\n readonly target?: AttachmentTypeDef;\n}\nexport interface ActionRequest {\n /** Stable across retries. The source must separately guarantee keyed idempotency. */\n readonly id: string;\n readonly name: string;\n readonly parameters: Record<string, unknown>;\n readonly attachmentUploads?: readonly AttachmentUpload[];\n /** Portable replay inputs, preserved across rebases, forwarding and authoritative execution. */\n readonly replay?: { readonly now: string; readonly seed: string };\n}\nexport interface ActionReceipt {\n /** The submitted ActionRequest.id, also supplied as the application's idempotencyKey. */\n readonly operationId: string;\n /** Provider commitment is recorded before local read-back/reconciliation. Parent acceptance is separate. */\n readonly outcome: \"committed\";\n /** Encoded authoritative return value, interpreted using the action returnType. Never a journal payload. */\n readonly result?: unknown;\n readonly cursor?: string;\n /** Optional upstream execution ID. Never substitutes for our stable retry identity. */\n readonly providerOperationId?: string;\n /** Read-back targets for a committed non-journal action. Missing keys\n * means the whole type; an empty list means no modeled object changes.\n * Omission conservatively refreshes every modeled type.\n * Targets are complete unless affectedComplete is explicitly false.\n */\n readonly affected?: readonly {\n readonly objectType: string;\n readonly keys?: readonly Key[];\n }[];\n /** False when these are known targets but automation may have changed other\n * modeled records. Confirmation must not use them as an exhaustive edit list.\n */\n readonly affectedComplete?: boolean;\n readonly attachmentIdMappings?: readonly { readonly localId: string; readonly remoteId: string }[];\n}\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nexport const ObjectChangeSchema = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"put\"),\n objectType: Schema.String,\n key: KeySchema,\n value: Schema.Record(Schema.String, Schema.Unknown),\n }),\n Schema.Struct({ kind: Schema.Literal(\"delete\"), objectType: Schema.String, key: KeySchema }),\n]);\nexport const ActionReceiptSchema = Schema.Struct({\n operationId: Schema.String,\n outcome: Schema.Literal(\"committed\"),\n result: Schema.optional(Schema.Unknown),\n cursor: Schema.optional(Schema.String),\n providerOperationId: Schema.optional(Schema.String),\n affected: Schema.optional(\n Schema.Array(\n Schema.Struct({ objectType: Schema.String, keys: Schema.optional(Schema.Array(KeySchema)) })\n )\n ),\n affectedComplete: Schema.optional(Schema.Boolean),\n attachmentIdMappings: Schema.optional(\n Schema.Array(Schema.Struct({ localId: Schema.String, remoteId: Schema.String }))\n ),\n});\nexport const BackendCommitSchema = Schema.Struct({\n cursor: Schema.String,\n changes: Schema.Array(ObjectChangeSchema),\n operationId: Schema.optional(Schema.String),\n});\nexport const BackendSnapshotSchema = Schema.Struct({\n fulfilledSubset: Schema.optional(ObjectSubsetSchema),\n fetchedRows: Schema.optional(Schema.Number),\n pushdown: Schema.optional(SourceQueryPlanSchema),\n rows: Schema.Array(\n Schema.Struct({ key: KeySchema, value: Schema.Record(Schema.String, Schema.Unknown) })\n ),\n complete: Schema.Boolean,\n cursor: Schema.optional(Schema.String),\n});\nexport const BackendChangePageSchema = Schema.Struct({\n commits: Schema.Array(BackendCommitSchema),\n cursor: Schema.String,\n hasMore: Schema.Boolean,\n});\n\nexport interface BackendAttachments {\n /** Optional authoritative staging before a subsequent action references the handle. */\n readonly stage?: (\n value: attachment,\n bytes: ByteInput,\n options?: { readonly target?: AttachmentTypeDef }\n ) => Effect.Effect<attachment, BackendError>;\n /** Keep the caller Scope open through consumption; closing it cancels an unconsumed download too. */\n readonly read: (\n value: attachment,\n options?: { readonly offset?: number; readonly length?: number }\n ) => Effect.Effect<ByteInput, BackendError, Scope.Scope>;\n readonly metadata: (\n value: attachment,\n options?: { readonly select?: readonly (\"size\" | \"type\" | \"name\" | \"dimensions\")[] }\n ) => Effect.Effect<\n {\n readonly size?: number;\n readonly type?: string;\n readonly name?: string;\n readonly dimensions?: { readonly width: number; readonly height: number };\n },\n BackendError\n >;\n}\nexport {\n EncryptedValueSchema,\n DecryptedValueSchema,\n encryptedPropertyCodec,\n makePropertyDecryption,\n} from \"./encrypted.js\";\nexport type { DecryptedValue } from \"./encrypted.js\";\n\nexport interface BackendEncryptedValues {\n /** Explicit operation. Ordinary record loads return handles and never decrypt them. */\n readonly decrypt: (\n value: Encrypted<unknown>\n ) => Effect.Effect<import(\"./encrypted.js\").DecryptedValue, BackendError>;\n}\n/** One object a watch reports, in the watched subset's object type.\n * - `put`: the object is now in the subset with this complete value.\n * - `exit`: the object left the subset. It may have changed or been deleted; the\n * replica reads it back by primary key to tell which.\n * - `delete`: the object no longer exists anywhere.\n */\nexport type SubsetWatchChange =\n | { readonly kind: \"put\"; readonly key: Key; readonly value: Record<string, unknown> }\n | { readonly kind: \"exit\"; readonly key: Key }\n | { readonly kind: \"delete\"; readonly key: Key };\n/** A reset requests repair after starting/restarting a watch; it does not\n * assert that data changed. Ordinary void hints always invalidate coverage.\n * `changes` describes exactly what changed, so the replica can apply it without\n * reloading the subset. Report only what is certain: a `put` must carry every\n * property; anything less precise must be an invalidation hint instead.\n */\nexport type SubsetWatchEvent = void | \"reset\" | { readonly changes: readonly SubsetWatchChange[] };\n\nexport interface OntologyBackendService {\n readonly name: string;\n /** Stable identity for the source whose cursors and receipts this binding returns. */\n readonly sourceId: string;\n /** Durable keyed idempotency within the configured receipt-retention window:\n * repeated IDs return the recorded result, with\n * conflicting payloads rejected. The guarantee must survive source restart.\n * Merely receiving an ID, or an action being naturally idempotent, is insufficient.\n */\n readonly supportsIdempotency: boolean;\n /** Indexed bounded local maintenance; the backend owner schedules it. */\n readonly maintenance?: Effect.Effect<void, BackendError>;\n /** Return the request or explicitly describe the region actually fulfilled.\n * Consumers use the shared subset normalizer before applying requested windows.\n */\n readonly loadSubset: (subset: ObjectSubset) => Effect.Effect<BackendSnapshot, BackendError>;\n /** Finite Query IR execution using this binding's trusted context and read path.\n * Provider adapters may evaluate through subset loads; owned storage uses one\n * read transaction. Callers supply query inputs, never authentication context.\n */\n readonly query: (\n document: QueryDocument,\n options?: { readonly inputs?: Record<string, unknown> }\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Optional selected committed rows. Closing the Scope releases demand; delivery state expires by policy. */\n readonly subscribeSelection?: (\n selection: ObjectSelection,\n policy?: import(\"./delivery.js\").DeliveryPolicy,\n resume?: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<import(\"./delivery.js\").DeliverySubscription, BackendError, Scope.Scope>;\n readonly acknowledgeDelivery?: (\n position: import(\"./delivery.js\").DeliveryPosition\n ) => Effect.Effect<void, BackendError>;\n /** Read-only defaults and edit prefills; never invokes the action. */\n readonly resolveActionParameters?: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<Record<string, unknown>, BackendError>;\n /** Acquire a demand-scoped watch before reading its snapshot. Completion proves\n * registration and buffering are active, even before the returned stream is pulled.\n * The acquiring Scope owns registration and release. Undefined means polling.\n * Reconnect within the same stream must fail or emit reset/invalidation;\n * reacquisition establishes a new readiness boundary for a fresh read.\n * Must cover every change relevant to the requested subset; broader watches\n * may emit extra hints. It does not maintain broader fulfilledSubset coverage.\n */\n readonly watchSubset?: (\n subset: ObjectSubset\n ) => Effect.Effect<Stream.Stream<SubsetWatchEvent, BackendError>, BackendError, Scope.Scope> | undefined;\n /** Recommended demand refresh defaults. Caller configuration wins; healthy\n * watches/journals keep coverage current independently of snapshot age. */\n readonly refresh?: (subset: ObjectSubset) =>\n | {\n readonly pollIntervalMs?: number | false;\n readonly maxCoverageAgeMs?: number;\n }\n | undefined;\n readonly validateAction?: (\n name: string,\n parameters: Record<string, unknown>,\n options?: { readonly knownParameters?: readonly string[] }\n ) => Effect.Effect<import(\"./errors.js\").ValidationReport, BackendError>;\n readonly applyAction: (invocation: ActionRequest) => Effect.Effect<ActionReceipt, BackendError>;\n readonly queryFunction: (\n name: string,\n parameters: Record<string, unknown>\n ) => Effect.Effect<unknown, BackendError>;\n readonly changes?: {\n readonly pull: (options: {\n readonly cursor?: string;\n readonly limit?: number;\n }) => Effect.Effect<BackendChangePage, BackendError>;\n /** Acquire registered, buffered wake-up hints in the caller's Scope before\n * pulling durable changes. Stream consumption does not initiate registration.\n * Call pull to recover changes after reconnect or restart. */\n readonly watch?: Effect.Effect<Stream.Stream<void, BackendError>, BackendError, Scope.Scope>;\n };\n readonly attachments?: BackendAttachments;\n readonly encrypted?: BackendEncryptedValues;\n}\n\n/** Backend protocol independent of TanStack collections and client lifecycle management. */\nexport class OntologyBackend extends Context.Service<OntologyBackend, OntologyBackendService>()(\n \"@party-stack/ontology-backend/OntologyBackend\"\n) {}\n"],"mappings":";;;;;;AA8DA,MAAa,wBAAwB,OAAO,OAAO;CAC/C,QAAQ,OAAO;;CAEf,YAAY,OAAO,MACf,OAAO,OAAO;EACV,MAAM,OAAO,MAAM,OAAO,GAAG;EAC7B,WAAW,OAAO,SAAS;GAAC;GAAU;GAAa;GAAW;EAAQ,CAAC;CAC3E,CAAC,CACL;CACA,SAAS,OAAO,SAAS;EA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C/C,iBAAiB,OAAO,SAAS,kBAAkB;CACnD,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,UAAU,OAAO,SAAS,qBAAqB;CAC/C,MAAM,OAAO,MACT,OAAO,OAAO;EAAE,KAAK;EAAW,OAAO,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CAAE,CAAC,CACzF;CACA,UAAU,OAAO;CACjB,QAAQ,OAAO,SAAS,OAAO,MAAM;AACzC,CAAC;AACD,MAAa,0BAA0B,OAAO,OAAO;CACjD,SAAS,OAAO,MAAM,mBAAmB;CACzC,QAAQ,OAAO;CACf,SAAS,OAAO;AACpB,CAAC;;AA6ID,IAAa,kBAAb,cAAqC,QAAQ,QAAiD,CAAC,CAC3F,+CACJ,CAAC,CAAC,CAAC"}
package/lib/owned.js CHANGED
@@ -11,7 +11,7 @@ import { OntologyStorageError, field, indexesForQuery, lte, makeOntologyStorage,
11
11
  import { Clock, Effect, PubSub, Redacted, Schema, Semaphore, Stream } from "effect";
12
12
  import { byteSource, digestBytes } from "@party-stack/ontology-storage/blobs";
13
13
  import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
14
- import { Table } from "@party-stack/ontology-storage/tables";
14
+ import { Table, gt } from "@party-stack/ontology-storage/tables";
15
15
  //#region src/owned.ts
16
16
  const fault = (operation, kind, message, cause) => new BackendError({
17
17
  operation,
@@ -489,7 +489,7 @@ const makeOwnedBackend = Effect.fnUntraced(function* (options) {
489
489
  loadSubset: (request) => boundary(Effect.gen(function* () {
490
490
  const subset = yield* compileObjectSubset(options.ir, request, yield* CurrentExecutionContext);
491
491
  const object = model.objects[subset.objectType];
492
- if (object) for (const index of indexesForQuery(subset.query ?? {}, new Set(object.definition.properties.map((property) => property.name)))) yield* storage.ensureIndex(object, index);
492
+ if (object) for (const index of indexesForQuery(subset.query ?? {}, options.ir, object.definition)) yield* storage.ensureIndex(object, index);
493
493
  return yield* storage.read((native) => Effect.gen(function* () {
494
494
  return {
495
495
  rows: yield* read(native).loadSubset(subset.objectType, subset.query),
@@ -560,14 +560,7 @@ const makeOwnedBackend = Effect.fnUntraced(function* (options) {
560
560
  const limit = request.limit ?? 100;
561
561
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1e3) return yield* fault("changes", "InvalidRequest", "Change page limit must be between 1 and 1000.");
562
562
  const rows = yield* tables.query(journal, {
563
- where: {
564
- op: "gt",
565
- left: {
566
- _tag: "Field",
567
- path: ["revision"]
568
- },
569
- right: after
570
- },
563
+ where: gt(field("revision"), after),
571
564
  orderBy: [{ field: {
572
565
  _tag: "Field",
573
566
  path: ["revision"]