@party-stack/foundry-ontology 0.20.1 → 0.20.3

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
@@ -8,15 +8,17 @@ Open a native metadata backend with selected Connect egress:
8
8
 
9
9
  ```ts
10
10
  import { makeFoundryMetadataBackend } from "@party-stack/foundry-ontology";
11
+ import { Effect } from "effect";
12
+ import type { ConnectionAccess } from "@party-stack/connect";
11
13
 
12
- const backend =
13
- yield *
14
- makeFoundryMetadataBackend({
15
- baseUrl,
14
+ export const openMetadataBackend = Effect.fn("App.openMetadataBackend")(function* (access: ConnectionAccess) {
15
+ return yield* makeFoundryMetadataBackend({
16
+ baseUrl: access.serviceInstance.instanceUrl,
16
17
  ontologyId: "ri.ontology.main.ontology.example",
17
- egress,
18
+ egress: access.egress,
18
19
  refetchInterval: 30_000,
19
20
  });
21
+ });
20
22
  ```
21
23
 
22
24
  Object-type name and RID filters use Foundry's batch lookup endpoints. Value-type
@@ -28,6 +30,15 @@ The backend narrows provider requests where it can prove they include every
28
30
  matching row. The shared query engine then applies residual predicates, ordering,
29
31
  and limits. A bounded fetch never certifies that the whole object type is loaded.
30
32
 
33
+ Equality, `in`, array `contains`, ranges and missing-value checks are sent as
34
+ exact Foundry filters, and so is a negation of an exact filter, with Foundry's `not`.
35
+ Foundry's `isNull` is also true for an empty array, so on arrays it answers "missing
36
+ or empty" (`length(list) == 0`) exactly, and either alone as a broader candidate.
37
+ Foundry's `wildcard` matches single lowercased tokens and rejects a leading `*`, so
38
+ a `like`/`ilike` pattern that starts with a word is sent as that word's prefix, a
39
+ broader candidate; patterns starting with a wildcard or punctuation stay local. A
40
+ `like` without wildcards is exact equality.
41
+
31
42
  `refetchInterval` supplies a recommended polling interval, in milliseconds. The
32
43
  replica schedules polling; the adapter does not run a separate timer. `false`
33
44
  disables the recommendation, and omission defaults to no polling. An explicit
@@ -1,12 +1,34 @@
1
1
  import { OntologyClient } from "@party-stack/foundry-client";
2
2
  import { Effect } from "effect";
3
3
  import { Actions } from "@osdk/foundry.ontologies";
4
- import { ActionRequest, BackendError, BackendSnapshot, OntologyBackendService } from "@party-stack/ontology-backend";
4
+ import { ActionRequest, BackendError, BackendSnapshot, OntologyBackendService, SubsetWatchEvent } from "@party-stack/ontology-backend";
5
5
  import { OntologyIR } from "@party-stack/ontology-spec";
6
+ import { ObjectSetSubscriptionMessage } from "@party-stack/foundry-object-set-watcher";
6
7
  import { Query } from "@party-stack/ontology-storage";
7
8
  //#region src/adapter/backend.d.ts
9
+ /** Each logical object set has its own acknowledgement. Pump before returning so
10
+ * changes between that acknowledgement and the snapshot read remain observable.
11
+ */
12
+ /** Foundry asked clients to shed subscriptions; do not reconnect for a while. */
13
+ export declare const foundryWatchQosRetryMs: number;
14
+ /** Keep Foundry's reported reason. A rejected object set will not start working on
15
+ * retry, so it is terminal; QoS backs off for minutes; a closure may reopen.
16
+ * Permission rejections are `Forbidden`: the signed-in user's token works, but this
17
+ * application or user may not use Foundry's subscription API. An expired token is
18
+ * `Unauthenticated`, so watches wait for the connection to authenticate again. */
19
+ export declare const subscriptionStateError: (message: Extract<ObjectSetSubscriptionMessage, {
20
+ type: "state";
21
+ }>) => BackendError;
22
+ type ObjectSetChange = Extract<ObjectSetSubscriptionMessage, {
23
+ type: "change";
24
+ }>["updates"][number];
25
+ /** Foundry reports an object entering or changing in the subscribed set with its
26
+ * subscribed properties, and an object leaving it without saying whether it was
27
+ * deleted. Anything else, or anything that cannot be decoded, is only a hint. */
28
+ export declare const foundryWatchChanges: (updates: readonly ObjectSetChange[], objectType: string, primaryKey: string, decodeObject: (objectType: string, value: Record<string, unknown>) => Record<string, unknown>) => SubsetWatchEvent;
8
29
  /** One scoped watcher multiplexes the live object types used by this binding.
9
- * Watch messages invalidate snapshots; they do not pretend to be durable journal cursors.
30
+ * Watch messages report row changes or invalidate snapshots; they do not pretend to
31
+ * be durable journal cursors.
10
32
  */
11
33
  export declare const makeFoundryBackend: (options: {
12
34
  client: OntologyClient;
@@ -32,4 +54,5 @@ export declare const makeFoundryBackend: (options: {
32
54
  decodeObject: (objectType: string, value: Record<string, unknown>) => Record<string, unknown>;
33
55
  }) => Effect.Effect<OntologyBackendService, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, import("effect/Scope").Scope>;
34
56
  //#endregion
57
+ export {};
35
58
  //# sourceMappingURL=backend.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"backend.d.ts","names":[],"sources":["../../src/adapter/backend.ts"],"mappings":";;;;;;;;;;qBAwGa,qBAAkB;EACnB,QAAA;EACJ,IAAA;EACK,SAAA;EACD;EACA;IACJ;IACA,aAAa,OAAO,OAAO,QAAQ,gBAAgB,QAAQ;;EAEjD,eACV,YAAY,eACZ,QAAQ,gBACP;IACD,QAAQ,QAAQ,kBAAkB,QAAQ;MAAyB;;IACnE;MAAiC;MAAiB;;;EAEtC,iBACZ,cACA,YAAY,yBACZ,QAAQ,gBACP;EACS,cAAA;EACF,YAAA;EACE,eAAC,oBAAoB,OAAO,4BAA4B;MAuMxE,OAAA,OAAA,wBAAA,wXAAA"}
1
+ {"version":3,"file":"backend.d.ts","names":[],"sources":["../../src/adapter/backend.ts"],"mappings":";;;;;;;;;;;;qBAqEa;;;;;;qBA8BA,yBAAsB,SACtB,QAAQ;EAAgC;OAClD;KAmCE,kBAAkB,QAAQ;EAAgC;;;;;qBAIlD,sBAAmB,kBACV,mBAAiB,oBACjB,oBACA,eACH,oBAAoB,OAAO,4BAA4B,4BACvE;;;;;qBAoEU,qBAAkB;EACnB,QAAA;EACJ,IAAA;EACK,SAAA;EACD;EACA;IACJ;IACA,aAAa,OAAO,OAAO,QAAQ,gBAAgB,QAAQ;;EAEjD,eACV,YAAY,eACZ,QAAQ,gBACP;IACD,QAAQ,QAAQ,kBAAkB,QAAQ;MAAyB;;IACnE;MAAiC;MAAiB;;;EAEtC,iBACZ,cACA,YAAY,yBACZ,QAAQ,gBACP;EACS,cAAA;EACF,YAAA;EACE,eAAC,oBAAoB,OAAO,4BAA4B;MAoNxE,OAAA,OAAA,wBAAA,wXAAA"}
@@ -1,5 +1,5 @@
1
1
  import { searchFoundryObjects } from "./foundryObjectSearch.js";
2
- import { analyzeSubsetFilter, subsetFilter } from "./subsetFilter.js";
2
+ import { analyzeSubsetFilter, arrayProperties, subsetFilter } from "./subsetFilter.js";
3
3
  import { Deferred, Effect, Queue, Redacted, Schema, Stream } from "effect";
4
4
  import { BackendError, classifyBackendFailure, makeOntologyBackend } from "@party-stack/ontology-backend";
5
5
  import { makeObjectSetWatcher } from "@party-stack/foundry-object-set-watcher";
@@ -45,9 +45,92 @@ const unavailable = (cause) => classifyBackendFailure("foundry.sync", cause);
45
45
  /** Each logical object set has its own acknowledgement. Pump before returning so
46
46
  * changes between that acknowledgement and the snapshot read remain observable.
47
47
  */
48
- const acquireWatch = Effect.fn("Foundry.acquireWatch")(function* (messages) {
48
+ /** Foundry asked clients to shed subscriptions; do not reconnect for a while. */
49
+ const foundryWatchQosRetryMs = 12e4;
50
+ /** Foundry's error code (e.g. `PERMISSION_DENIED`) from a rejected subscription's errors. */
51
+ const subscriptionErrorCode = (detail) => {
52
+ if (!Array.isArray(detail)) return void 0;
53
+ for (const error of detail) {
54
+ const args = error?.args;
55
+ if (!Array.isArray(args)) continue;
56
+ const code = args.find((arg) => arg?.name === "errorCode" && typeof arg.value === "string");
57
+ if (code) return code.value;
58
+ }
59
+ };
60
+ const rejectedKind = (code) => code === "UNAUTHORIZED" ? "Unauthenticated" : code === "PERMISSION_DENIED" ? "Forbidden" : code === "NOT_FOUND" ? "NotFound" : "InvalidRequest";
61
+ /** Keep Foundry's reported reason. A rejected object set will not start working on
62
+ * retry, so it is terminal; QoS backs off for minutes; a closure may reopen.
63
+ * Permission rejections are `Forbidden`: the signed-in user's token works, but this
64
+ * application or user may not use Foundry's subscription API. An expired token is
65
+ * `Unauthenticated`, so watches wait for the connection to authenticate again. */
66
+ const subscriptionStateError = (message) => {
67
+ const reason = message.reason?.message;
68
+ const cause = message.reason?.detail === void 0 ? void 0 : Redacted.make(message.reason.detail);
69
+ switch (message.status) {
70
+ case "error": {
71
+ const code = subscriptionErrorCode(message.reason?.detail);
72
+ const summary = [reason, code].filter(Boolean).join(", ");
73
+ return new BackendError({
74
+ operation: "foundry.watchSubset",
75
+ kind: rejectedKind(code),
76
+ retryable: false,
77
+ message: `Foundry rejected the object-set subscription${summary ? `: ${summary}` : "."}`,
78
+ cause
79
+ });
80
+ }
81
+ case "qos": return new BackendError({
82
+ operation: "foundry.watchSubset",
83
+ kind: "RateLimited",
84
+ retryable: true,
85
+ retryAfterMs: foundryWatchQosRetryMs,
86
+ message: `Foundry asked to reduce object-set subscriptions${reason ? `: ${reason}` : "."}`,
87
+ cause
88
+ });
89
+ default: return new BackendError({
90
+ operation: "foundry.watchSubset",
91
+ kind: "Unavailable",
92
+ retryable: true,
93
+ message: `The Foundry object-set subscription closed${reason ? `: ${reason}` : "."}`,
94
+ cause
95
+ });
96
+ }
97
+ };
98
+ /** Foundry reports an object entering or changing in the subscribed set with its
99
+ * subscribed properties, and an object leaving it without saying whether it was
100
+ * deleted. Anything else, or anything that cannot be decoded, is only a hint. */
101
+ const foundryWatchChanges = (updates, objectType, primaryKey, decodeObject) => {
102
+ const changes = [];
103
+ for (const update of updates) {
104
+ if (update.type !== "object") return void 0;
105
+ const raw = update.object;
106
+ if (raw.__apiName !== void 0 && raw.__apiName !== objectType) return void 0;
107
+ try {
108
+ if (update.state === "ADDED_OR_UPDATED") {
109
+ const value = decodeObject(objectType, raw);
110
+ const key = value[primaryKey];
111
+ if (!Schema.is(KeySchema)(key)) return void 0;
112
+ changes.push({
113
+ kind: "put",
114
+ key,
115
+ value
116
+ });
117
+ } else {
118
+ const key = decodeObject(objectType, { [primaryKey]: raw[primaryKey] ?? raw.__primaryKey })[primaryKey];
119
+ if (!Schema.is(KeySchema)(key)) return void 0;
120
+ changes.push({
121
+ kind: "exit",
122
+ key
123
+ });
124
+ }
125
+ } catch {
126
+ return;
127
+ }
128
+ }
129
+ return changes.length ? { changes } : void 0;
130
+ };
131
+ const acquireWatch = Effect.fn("Foundry.acquireWatch")(function* (messages, decode) {
49
132
  const ready = yield* Deferred.make();
50
- const events = yield* Effect.acquireRelease(Queue.sliding(1), (queue) => Queue.shutdown(queue).pipe(Effect.asVoid));
133
+ const events = yield* Effect.acquireRelease(Queue.unbounded(), (queue) => Queue.shutdown(queue).pipe(Effect.asVoid));
51
134
  const interrupted = () => new BackendError({
52
135
  operation: "foundry.watchSubset",
53
136
  kind: "Unavailable",
@@ -55,15 +138,17 @@ const acquireWatch = Effect.fn("Foundry.acquireWatch")(function* (messages) {
55
138
  message: "The Foundry object-set subscription is no longer active."
56
139
  });
57
140
  const receive = Stream.runForEach(messages, (message) => {
141
+ if (message.type === "change") return Queue.offer(events, decode(message.updates)).pipe(Effect.asVoid);
58
142
  if (message.type !== "state") return Queue.offer(events, void 0).pipe(Effect.asVoid);
59
- return message.status === "open" ? Deferred.succeed(ready, void 0).pipe(Effect.asVoid) : Effect.fail(interrupted());
143
+ return message.status === "open" ? Deferred.succeed(ready, void 0).pipe(Effect.asVoid) : Effect.fail(subscriptionStateError(message));
60
144
  }).pipe(Effect.mapError(unavailable), Effect.andThen(Effect.fail(interrupted())), Effect.catchCause((cause) => Deferred.failCause(ready, cause).pipe(Effect.andThen(Queue.failCause(events, cause)), Effect.asVoid)));
61
145
  yield* Effect.forkScoped(receive, { startImmediately: true });
62
146
  yield* Deferred.await(ready);
63
147
  return Stream.fromQueue(events);
64
148
  });
65
149
  /** One scoped watcher multiplexes the live object types used by this binding.
66
- * Watch messages invalidate snapshots; they do not pretend to be durable journal cursors.
150
+ * Watch messages report row changes or invalidate snapshots; they do not pretend to
151
+ * be durable journal cursors.
67
152
  */
68
153
  const makeFoundryBackend = Effect.fn("FoundryBackend.make")(function* (options) {
69
154
  const watcher = options.watch === false ? void 0 : yield* makeObjectSetWatcher(options.client).pipe(Effect.mapError(unavailable));
@@ -108,7 +193,7 @@ const makeFoundryBackend = Effect.fn("FoundryBackend.make")(function* (options)
108
193
  const predicate = subset.query?.where;
109
194
  const candidates = predicate?.op === "in" && isField(predicate.left) && predicate.left.path.length === 1 && predicate.left.path[0] === definition.primaryKey ? predicate.values : predicate?.op === "eq" && isField(predicate.left) && predicate.left.path.length === 1 && predicate.left.path[0] === definition.primaryKey && !isField(predicate.right) ? [predicate.right] : void 0;
110
195
  const keys = candidates?.every(Schema.is(KeySchema)) ? candidates : void 0;
111
- const plan = analyzeSubsetFilter(predicate);
196
+ const plan = analyzeSubsetFilter(predicate, arrayProperties(options.ir, definition));
112
197
  const pushed = keys ? {
113
198
  type: "in",
114
199
  field: definition.primaryKey,
@@ -189,7 +274,8 @@ const makeFoundryBackend = Effect.fn("FoundryBackend.make")(function* (options)
189
274
  refresh: (subset) => subset.from.source.objectType === options.users?.objectType ? { pollIntervalMs: 6e4 } : void 0,
190
275
  watchSubset: watcher ? (request) => request.from.source.objectType === options.users?.objectType ? void 0 : Effect.gen(function* () {
191
276
  const subset = yield* compileObjectSubset(options.ir, request, options.context);
192
- const filter = subsetFilter(subset.query?.where);
277
+ const definition = options.ir.objectTypes.find((type) => type.name === subset.objectType);
278
+ const filter = subsetFilter(subset.query?.where, arrayProperties(options.ir, definition));
193
279
  return yield* acquireWatch(watcher.subscribe(filter ? {
194
280
  type: "filter",
195
281
  objectSet: {
@@ -200,11 +286,11 @@ const makeFoundryBackend = Effect.fn("FoundryBackend.make")(function* (options)
200
286
  } : {
201
287
  type: "base",
202
288
  objectType: subset.objectType
203
- }));
289
+ }), (updates) => foundryWatchChanges(updates, subset.objectType, definition.primaryKey, options.decodeObject));
204
290
  }) : void 0
205
291
  });
206
292
  });
207
293
  //#endregion
208
- export { makeFoundryBackend };
294
+ export { foundryWatchChanges, foundryWatchQosRetryMs, makeFoundryBackend, subscriptionStateError };
209
295
 
210
296
  //# sourceMappingURL=backend.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"backend.js","names":[],"sources":["../../src/adapter/backend.ts"],"sourcesContent":["import { makeObjectSetWatcher } from \"@party-stack/foundry-object-set-watcher\";\nimport { makeOntologyBackend } from \"@party-stack/ontology-backend\";\nimport { BackendError, classifyBackendFailure } from \"@party-stack/ontology-backend\";\nimport { compileObjectSubset, objectSubset } from \"@party-stack/ontology-backend/subset\";\nimport { QuerySchema } from \"@party-stack/ontology-storage\";\nimport { isField } from \"@party-stack/ontology-storage/tables\";\nimport { Deferred, Effect, Queue, Schema, Stream, Redacted } from \"effect\";\nimport { searchFoundryObjects } from \"./foundryObjectSearch.js\";\nimport { analyzeSubsetFilter, subsetFilter } from \"./subsetFilter.js\";\nimport type { Actions } from \"@osdk/foundry.ontologies\";\nimport type { OntologyClient } from \"@party-stack/foundry-client\";\nimport type { ObjectSetSubscriptionMessage, WatcherError } from \"@party-stack/foundry-object-set-watcher\";\nimport type {\n OntologyBackendService,\n ActionRequest,\n ActionReceipt,\n SourceQueryPlan,\n SubsetWatchEvent,\n} from \"@party-stack/ontology-backend\";\nimport type { BackendSnapshot } from \"@party-stack/ontology-backend\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { Query } from \"@party-stack/ontology-storage\";\n\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nconst ObjectTarget = Schema.Struct({ objectType: Schema.String, primaryKey: Schema.Unknown });\nconst ActionResult = Schema.Struct({\n operationId: Schema.optional(Schema.String),\n edits: Schema.optional(\n Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"largeScaleEdits\"),\n editedObjectTypes: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"edits\"),\n edits: Schema.Array(\n Schema.Union([\n Schema.Struct({\n type: Schema.Literals([\"addObject\", \"modifyObject\", \"deleteObject\"]),\n ...ObjectTarget.fields,\n }),\n Schema.Struct({\n type: Schema.Literals([\"addLink\", \"deleteLink\"]),\n aSideObject: ObjectTarget,\n bSideObject: ObjectTarget,\n }),\n ])\n ),\n }),\n ])\n ),\n});\nconst invalidResponse = (operation: string, cause: unknown) =>\n new BackendError({\n operation,\n kind: \"InvalidResponse\",\n message: \"Foundry returned an invalid response.\",\n retryable: false,\n actionOutcome: \"unknown\",\n cause: Redacted.make(cause),\n });\nconst unavailable = (cause: unknown) => classifyBackendFailure(\"foundry.sync\", cause);\n\n/** Each logical object set has its own acknowledgement. Pump before returning so\n * changes between that acknowledgement and the snapshot read remain observable.\n */\nconst acquireWatch = Effect.fn(\"Foundry.acquireWatch\")(function* (\n messages: Stream.Stream<ObjectSetSubscriptionMessage, WatcherError>\n) {\n const ready = yield* Deferred.make<void, BackendError>();\n const events = yield* Effect.acquireRelease(Queue.sliding<SubsetWatchEvent, BackendError>(1), (queue) =>\n Queue.shutdown(queue).pipe(Effect.asVoid)\n );\n const interrupted = () =>\n new BackendError({\n operation: \"foundry.watchSubset\",\n kind: \"Unavailable\",\n retryable: true,\n message: \"The Foundry object-set subscription is no longer active.\",\n });\n const receive = Stream.runForEach(messages, (message) => {\n if (message.type !== \"state\") return Queue.offer(events, undefined).pipe(Effect.asVoid);\n return message.status === \"open\"\n ? Deferred.succeed(ready, undefined).pipe(Effect.asVoid)\n : Effect.fail(interrupted());\n }).pipe(\n Effect.mapError(unavailable),\n Effect.andThen(Effect.fail(interrupted())),\n Effect.catchCause((cause) =>\n Deferred.failCause(ready, cause).pipe(\n Effect.andThen(Queue.failCause(events, cause)),\n Effect.asVoid\n )\n )\n );\n yield* Effect.forkScoped(receive, { startImmediately: true });\n yield* Deferred.await(ready);\n return Stream.fromQueue(events);\n});\n\n/** One scoped watcher multiplexes the live object types used by this binding.\n * Watch messages invalidate snapshots; they do not pretend to be durable journal cursors.\n */\nexport const makeFoundryBackend = Effect.fn(\"FoundryBackend.make\")(function* (options: {\n client: OntologyClient;\n ir: OntologyIR;\n context: Record<string, unknown>;\n watch?: boolean;\n users?: {\n objectType: string;\n loadSubset: (query: Query, signal: AbortSignal) => Promise<BackendSnapshot>;\n };\n submitAction: (\n invocation: ActionRequest,\n signal: AbortSignal\n ) => Promise<{\n result: Awaited<ReturnType<typeof Actions.applyWithOverrides>> & { operationId?: string };\n attachmentIdMappings: readonly { localId: string; remoteId: string }[];\n }>;\n queryFunction?: (\n name: string,\n parameters: Record<string, unknown>,\n signal: AbortSignal\n ) => Promise<unknown>;\n attachments?: OntologyBackendService[\"attachments\"];\n encrypted?: OntologyBackendService[\"encrypted\"];\n decodeObject: (objectType: string, value: Record<string, unknown>) => Record<string, unknown>;\n}) {\n const watcher =\n options.watch === false\n ? undefined\n : yield* makeObjectSetWatcher(options.client).pipe(Effect.mapError(unavailable));\n return makeOntologyBackend({\n ir: options.ir,\n context: options.context,\n name: \"foundry\",\n sourceId: `foundry:${options.client.baseUrl}:${options.client.ontologyRid}`,\n supportsIdempotency: false,\n queryFunction: (name: string, parameters: Record<string, unknown>) =>\n options.queryFunction\n ? Effect.tryPromise({\n try: (signal) => options.queryFunction!(name, parameters, signal),\n catch: unavailable,\n })\n : Effect.fail(\n new BackendError({\n operation: \"queryFunction\",\n kind: \"NotImplemented\",\n message: \"No Foundry query function implementation.\",\n retryable: false,\n })\n ),\n attachments: options.attachments,\n encrypted: options.encrypted,\n loadSubset: Effect.fn(\"Foundry.loadSubset\")(function* (request: ObjectSubset) {\n const subset = yield* compileObjectSubset(options.ir, request, options.context);\n yield* Effect.annotateCurrentSpan(\"objectType\", subset.objectType);\n yield* Schema.decodeUnknownEffect(QuerySchema)(subset.query ?? {}).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"foundry.loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Invalid subset query.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n );\n if (subset.objectType === options.users?.objectType)\n return yield* Effect.tryPromise({\n try: (signal) => options.users!.loadSubset(subset.query ?? {}, signal),\n catch: unavailable,\n });\n const definition = options.ir.objectTypes.find((type) => type.name === subset.objectType);\n if (!definition)\n return yield* new BackendError({\n operation: \"foundry.loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Unknown Foundry object type.\",\n retryable: false,\n });\n const predicate = subset.query?.where;\n const candidates =\n predicate?.op === \"in\" &&\n isField(predicate.left) &&\n predicate.left.path.length === 1 &&\n predicate.left.path[0] === definition.primaryKey\n ? predicate.values\n : predicate?.op === \"eq\" &&\n isField(predicate.left) &&\n predicate.left.path.length === 1 &&\n predicate.left.path[0] === definition.primaryKey &&\n !isField(predicate.right)\n ? [predicate.right]\n : undefined;\n const keys = candidates?.every(Schema.is(KeySchema))\n ? (candidates as readonly (string | number)[])\n : undefined;\n const plan = analyzeSubsetFilter(predicate);\n const pushed = keys\n ? { type: \"in\" as const, field: definition.primaryKey, value: [...new Set(keys)] }\n : plan.query;\n const values = yield* Effect.tryPromise({\n try: (signal) =>\n searchFoundryObjects(\n options.client,\n subset.objectType,\n definition.properties.map((property) => property.name),\n {\n signal,\n where: pushed,\n },\n (value) => options.decodeObject(subset.objectType, value)\n ),\n catch: unavailable,\n });\n const rows = yield* Effect.forEach(values, (value) =>\n Schema.decodeUnknownEffect(KeySchema)(value[definition.primaryKey]).pipe(\n Effect.map((key) => ({ key, value })),\n Effect.mapError((cause) => invalidResponse(\"foundry.loadSubset\", cause))\n )\n );\n return {\n fulfilledSubset: objectSubset(subset.objectType, { where: subset.query?.where }),\n fetchedRows: values.length,\n pushdown: {\n source: \"Foundry\",\n predicates: plan.predicates.map((predicate) => ({\n ...predicate,\n execution:\n predicate.execution === \"adapter\" ? (\"engine\" as const) : predicate.execution,\n })),\n sorting: subset.query?.orderBy?.length ? \"engine\" : \"none\",\n pagination:\n subset.query?.limit !== undefined ||\n subset.query?.offset !== undefined ||\n subset.query?.after\n ? \"engine\"\n : \"none\",\n rechecksFilter: Boolean(predicate),\n native: {\n language: \"json\",\n text: JSON.stringify(pushed ?? { type: \"and\", value: [] }, null, 2),\n },\n } satisfies SourceQueryPlan,\n rows,\n complete: true,\n };\n }),\n applyAction: Effect.fn(\"Foundry.applyAction\")(function* (invocation: ActionRequest) {\n const { result: rawResult, attachmentIdMappings } = yield* Effect.tryPromise({\n try: (signal) => options.submitAction(invocation, signal),\n catch: (cause) => classifyBackendFailure(\"foundry.applyAction\", cause),\n });\n const result = yield* Schema.decodeUnknownEffect(ActionResult)(rawResult).pipe(\n Effect.mapError((cause) => invalidResponse(\"foundry.applyAction\", cause))\n );\n return yield* Effect.try({\n try: () => {\n const targets = new Map<string, Set<string | number> | undefined>();\n const add = (objectType: string, rawKey?: unknown) => {\n const definition = options.ir.objectTypes.find((type) => type.name === objectType);\n if (!definition || objectType === options.users?.objectType) return;\n const key =\n rawKey === undefined\n ? undefined\n : options.decodeObject(objectType, { [definition.primaryKey]: rawKey })[\n definition.primaryKey\n ];\n if (rawKey === undefined) targets.set(objectType, undefined);\n else if (!Schema.is(KeySchema)(key)) throw new Error(\"Invalid edit identity.\");\n else if (!targets.has(objectType) || targets.get(objectType))\n targets.set(objectType, new Set([...(targets.get(objectType) ?? []), key]));\n };\n if (!result.edits) for (const type of options.ir.objectTypes) add(type.name);\n else if (result.edits.type === \"largeScaleEdits\")\n for (const type of result.edits.editedObjectTypes) add(type);\n else\n for (const edit of result.edits.edits) {\n if (\"aSideObject\" in edit) {\n add(edit.aSideObject.objectType, edit.aSideObject.primaryKey);\n add(edit.bSideObject.objectType, edit.bSideObject.primaryKey);\n } else add(edit.objectType, edit.primaryKey);\n }\n return {\n operationId: invocation.id,\n outcome: \"committed\",\n providerOperationId: result.operationId,\n affected: [...targets].map(([objectType, keys]) => ({\n objectType,\n ...(keys ? { keys: [...keys] } : {}),\n })),\n attachmentIdMappings: attachmentIdMappings.length ? attachmentIdMappings : undefined,\n } satisfies ActionReceipt;\n },\n catch: (cause) => invalidResponse(\"foundry.applyAction\", cause),\n });\n }),\n // Admin users have no ontology websocket feed; the Replica owns this polling lifetime.\n refresh: (subset: ObjectSubset) =>\n subset.from.source.objectType === options.users?.objectType\n ? { pollIntervalMs: 60_000 }\n : undefined,\n watchSubset: watcher\n ? (request: ObjectSubset) =>\n request.from.source.objectType === options.users?.objectType\n ? undefined\n : Effect.gen(function* () {\n const subset = yield* compileObjectSubset(options.ir, request, options.context);\n const filter = subsetFilter(subset.query?.where);\n return yield* acquireWatch(\n watcher.subscribe(\n filter\n ? {\n type: \"filter\",\n objectSet: { type: \"base\", objectType: subset.objectType },\n where: filter,\n }\n : { type: \"base\", objectType: subset.objectType }\n )\n );\n })\n : undefined,\n });\n});\n"],"mappings":";;;;;;;;;AAwBA,MAAM,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAM,eAAe,OAAO,OAAO;CAAE,YAAY,OAAO;CAAQ,YAAY,OAAO;AAAQ,CAAC;AAC5F,MAAM,eAAe,OAAO,OAAO;CAC/B,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,OAAO,OAAO,SACV,OAAO,MAAM,CACT,OAAO,OAAO;EACV,MAAM,OAAO,QAAQ,iBAAiB;EACtC,mBAAmB,OAAO,MAAM,OAAO,MAAM;CACjD,CAAC,GACD,OAAO,OAAO;EACV,MAAM,OAAO,QAAQ,OAAO;EAC5B,OAAO,OAAO,MACV,OAAO,MAAM,CACT,OAAO,OAAO;GACV,MAAM,OAAO,SAAS;IAAC;IAAa;IAAgB;GAAc,CAAC;GACnE,GAAG,aAAa;EACpB,CAAC,GACD,OAAO,OAAO;GACV,MAAM,OAAO,SAAS,CAAC,WAAW,YAAY,CAAC;GAC/C,aAAa;GACb,aAAa;EACjB,CAAC,CACL,CAAC,CACL;CACJ,CAAC,CACL,CAAC,CACL;AACJ,CAAC;AACD,MAAM,mBAAmB,WAAmB,UACxC,IAAI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,"file":"backend.js","names":[],"sources":["../../src/adapter/backend.ts"],"sourcesContent":["import { makeObjectSetWatcher } from \"@party-stack/foundry-object-set-watcher\";\nimport { makeOntologyBackend } from \"@party-stack/ontology-backend\";\nimport { BackendError, classifyBackendFailure } from \"@party-stack/ontology-backend\";\nimport { compileObjectSubset, objectSubset } from \"@party-stack/ontology-backend/subset\";\nimport { QuerySchema } from \"@party-stack/ontology-storage\";\nimport { isField } from \"@party-stack/ontology-storage/tables\";\nimport { Deferred, Effect, Queue, Schema, Stream, Redacted } from \"effect\";\nimport { searchFoundryObjects } from \"./foundryObjectSearch.js\";\nimport { analyzeSubsetFilter, arrayProperties, subsetFilter } from \"./subsetFilter.js\";\nimport type { Actions } from \"@osdk/foundry.ontologies\";\nimport type { OntologyClient } from \"@party-stack/foundry-client\";\nimport type { ObjectSetSubscriptionMessage, WatcherError } from \"@party-stack/foundry-object-set-watcher\";\nimport type {\n OntologyBackendService,\n ActionRequest,\n ActionReceipt,\n SourceQueryPlan,\n SubsetWatchChange,\n SubsetWatchEvent,\n} from \"@party-stack/ontology-backend\";\nimport type { BackendSnapshot } from \"@party-stack/ontology-backend\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { ObjectSubset } from \"@party-stack/ontology-spec/query\";\nimport type { Query } from \"@party-stack/ontology-storage\";\n\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nconst ObjectTarget = Schema.Struct({ objectType: Schema.String, primaryKey: Schema.Unknown });\nconst ActionResult = Schema.Struct({\n operationId: Schema.optional(Schema.String),\n edits: Schema.optional(\n Schema.Union([\n Schema.Struct({\n type: Schema.Literal(\"largeScaleEdits\"),\n editedObjectTypes: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal(\"edits\"),\n edits: Schema.Array(\n Schema.Union([\n Schema.Struct({\n type: Schema.Literals([\"addObject\", \"modifyObject\", \"deleteObject\"]),\n ...ObjectTarget.fields,\n }),\n Schema.Struct({\n type: Schema.Literals([\"addLink\", \"deleteLink\"]),\n aSideObject: ObjectTarget,\n bSideObject: ObjectTarget,\n }),\n ])\n ),\n }),\n ])\n ),\n});\nconst invalidResponse = (operation: string, cause: unknown) =>\n new BackendError({\n operation,\n kind: \"InvalidResponse\",\n message: \"Foundry returned an invalid response.\",\n retryable: false,\n actionOutcome: \"unknown\",\n cause: Redacted.make(cause),\n });\nconst unavailable = (cause: unknown) => classifyBackendFailure(\"foundry.sync\", cause);\n\n/** Each logical object set has its own acknowledgement. Pump before returning so\n * changes between that acknowledgement and the snapshot read remain observable.\n */\n/** Foundry asked clients to shed subscriptions; do not reconnect for a while. */\nexport const foundryWatchQosRetryMs = 2 * 60_000;\n/** Foundry's error code (e.g. `PERMISSION_DENIED`) from a rejected subscription's errors. */\nconst subscriptionErrorCode = (detail: unknown): string | undefined => {\n if (!Array.isArray(detail)) return undefined;\n for (const error of detail) {\n const args = (error as { args?: unknown } | null)?.args;\n if (!Array.isArray(args)) continue;\n const code = args.find(\n (arg): arg is { name: \"errorCode\"; value: string } =>\n (arg as { name?: unknown } | null)?.name === \"errorCode\" &&\n typeof (arg as { value?: unknown }).value === \"string\"\n );\n if (code) return code.value;\n }\n return undefined;\n};\nconst rejectedKind = (code: string | undefined) =>\n code === \"UNAUTHORIZED\"\n ? \"Unauthenticated\"\n : code === \"PERMISSION_DENIED\"\n ? \"Forbidden\"\n : code === \"NOT_FOUND\"\n ? \"NotFound\"\n : \"InvalidRequest\";\n\n/** Keep Foundry's reported reason. A rejected object set will not start working on\n * retry, so it is terminal; QoS backs off for minutes; a closure may reopen.\n * Permission rejections are `Forbidden`: the signed-in user's token works, but this\n * application or user may not use Foundry's subscription API. An expired token is\n * `Unauthenticated`, so watches wait for the connection to authenticate again. */\nexport const subscriptionStateError = (\n message: Extract<ObjectSetSubscriptionMessage, { type: \"state\" }>\n): BackendError => {\n const reason = message.reason?.message;\n const cause = message.reason?.detail === undefined ? undefined : Redacted.make(message.reason.detail);\n switch (message.status) {\n case \"error\": {\n const code = subscriptionErrorCode(message.reason?.detail);\n const summary = [reason, code].filter(Boolean).join(\", \");\n return new BackendError({\n operation: \"foundry.watchSubset\",\n kind: rejectedKind(code),\n retryable: false,\n message: `Foundry rejected the object-set subscription${summary ? `: ${summary}` : \".\"}`,\n cause,\n });\n }\n case \"qos\":\n return new BackendError({\n operation: \"foundry.watchSubset\",\n kind: \"RateLimited\",\n retryable: true,\n retryAfterMs: foundryWatchQosRetryMs,\n message: `Foundry asked to reduce object-set subscriptions${reason ? `: ${reason}` : \".\"}`,\n cause,\n });\n default:\n return new BackendError({\n operation: \"foundry.watchSubset\",\n kind: \"Unavailable\",\n retryable: true,\n message: `The Foundry object-set subscription closed${reason ? `: ${reason}` : \".\"}`,\n cause,\n });\n }\n};\n\ntype ObjectSetChange = Extract<ObjectSetSubscriptionMessage, { type: \"change\" }>[\"updates\"][number];\n/** Foundry reports an object entering or changing in the subscribed set with its\n * subscribed properties, and an object leaving it without saying whether it was\n * deleted. Anything else, or anything that cannot be decoded, is only a hint. */\nexport const foundryWatchChanges = (\n updates: readonly ObjectSetChange[],\n objectType: string,\n primaryKey: string,\n decodeObject: (objectType: string, value: Record<string, unknown>) => Record<string, unknown>\n): SubsetWatchEvent => {\n const changes: SubsetWatchChange[] = [];\n for (const update of updates) {\n if (update.type !== \"object\") return undefined;\n const raw = update.object as Record<string, unknown>;\n if (raw.__apiName !== undefined && raw.__apiName !== objectType) return undefined;\n try {\n if (update.state === \"ADDED_OR_UPDATED\") {\n const value = decodeObject(objectType, raw);\n const key = value[primaryKey];\n if (!Schema.is(KeySchema)(key)) return undefined;\n changes.push({ kind: \"put\", key, value });\n } else {\n const key = decodeObject(objectType, { [primaryKey]: raw[primaryKey] ?? raw.__primaryKey })[\n primaryKey\n ];\n if (!Schema.is(KeySchema)(key)) return undefined;\n changes.push({ kind: \"exit\", key });\n }\n } catch {\n return undefined;\n }\n }\n return changes.length ? { changes } : undefined;\n};\n\nconst acquireWatch = Effect.fn(\"Foundry.acquireWatch\")(function* (\n messages: Stream.Stream<ObjectSetSubscriptionMessage, WatcherError>,\n decode: (updates: readonly ObjectSetChange[]) => SubsetWatchEvent\n) {\n const ready = yield* Deferred.make<void, BackendError>();\n // Row changes cannot be coalesced or dropped; hints can, but keep them in order.\n const events = yield* Effect.acquireRelease(Queue.unbounded<SubsetWatchEvent, BackendError>(), (queue) =>\n Queue.shutdown(queue).pipe(Effect.asVoid)\n );\n const interrupted = () =>\n new BackendError({\n operation: \"foundry.watchSubset\",\n kind: \"Unavailable\",\n retryable: true,\n message: \"The Foundry object-set subscription is no longer active.\",\n });\n const receive = Stream.runForEach(messages, (message) => {\n if (message.type === \"change\")\n return Queue.offer(events, decode(message.updates)).pipe(Effect.asVoid);\n if (message.type !== \"state\") return Queue.offer(events, undefined).pipe(Effect.asVoid);\n return message.status === \"open\"\n ? Deferred.succeed(ready, undefined).pipe(Effect.asVoid)\n : Effect.fail(subscriptionStateError(message));\n }).pipe(\n Effect.mapError(unavailable),\n Effect.andThen(Effect.fail(interrupted())),\n Effect.catchCause((cause) =>\n Deferred.failCause(ready, cause).pipe(\n Effect.andThen(Queue.failCause(events, cause)),\n Effect.asVoid\n )\n )\n );\n yield* Effect.forkScoped(receive, { startImmediately: true });\n yield* Deferred.await(ready);\n return Stream.fromQueue(events);\n});\n\n/** One scoped watcher multiplexes the live object types used by this binding.\n * Watch messages report row changes or invalidate snapshots; they do not pretend to\n * be durable journal cursors.\n */\nexport const makeFoundryBackend = Effect.fn(\"FoundryBackend.make\")(function* (options: {\n client: OntologyClient;\n ir: OntologyIR;\n context: Record<string, unknown>;\n watch?: boolean;\n users?: {\n objectType: string;\n loadSubset: (query: Query, signal: AbortSignal) => Promise<BackendSnapshot>;\n };\n submitAction: (\n invocation: ActionRequest,\n signal: AbortSignal\n ) => Promise<{\n result: Awaited<ReturnType<typeof Actions.applyWithOverrides>> & { operationId?: string };\n attachmentIdMappings: readonly { localId: string; remoteId: string }[];\n }>;\n queryFunction?: (\n name: string,\n parameters: Record<string, unknown>,\n signal: AbortSignal\n ) => Promise<unknown>;\n attachments?: OntologyBackendService[\"attachments\"];\n encrypted?: OntologyBackendService[\"encrypted\"];\n decodeObject: (objectType: string, value: Record<string, unknown>) => Record<string, unknown>;\n}) {\n const watcher =\n options.watch === false\n ? undefined\n : yield* makeObjectSetWatcher(options.client).pipe(Effect.mapError(unavailable));\n return makeOntologyBackend({\n ir: options.ir,\n context: options.context,\n name: \"foundry\",\n sourceId: `foundry:${options.client.baseUrl}:${options.client.ontologyRid}`,\n supportsIdempotency: false,\n queryFunction: (name: string, parameters: Record<string, unknown>) =>\n options.queryFunction\n ? Effect.tryPromise({\n try: (signal) => options.queryFunction!(name, parameters, signal),\n catch: unavailable,\n })\n : Effect.fail(\n new BackendError({\n operation: \"queryFunction\",\n kind: \"NotImplemented\",\n message: \"No Foundry query function implementation.\",\n retryable: false,\n })\n ),\n attachments: options.attachments,\n encrypted: options.encrypted,\n loadSubset: Effect.fn(\"Foundry.loadSubset\")(function* (request: ObjectSubset) {\n const subset = yield* compileObjectSubset(options.ir, request, options.context);\n yield* Effect.annotateCurrentSpan(\"objectType\", subset.objectType);\n yield* Schema.decodeUnknownEffect(QuerySchema)(subset.query ?? {}).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"foundry.loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Invalid subset query.\",\n retryable: false,\n cause: Redacted.make(cause),\n })\n )\n );\n if (subset.objectType === options.users?.objectType)\n return yield* Effect.tryPromise({\n try: (signal) => options.users!.loadSubset(subset.query ?? {}, signal),\n catch: unavailable,\n });\n const definition = options.ir.objectTypes.find((type) => type.name === subset.objectType);\n if (!definition)\n return yield* new BackendError({\n operation: \"foundry.loadSubset\",\n kind: \"InvalidRequest\",\n message: \"Unknown Foundry object type.\",\n retryable: false,\n });\n const predicate = subset.query?.where;\n const candidates =\n predicate?.op === \"in\" &&\n isField(predicate.left) &&\n predicate.left.path.length === 1 &&\n predicate.left.path[0] === definition.primaryKey\n ? predicate.values\n : predicate?.op === \"eq\" &&\n isField(predicate.left) &&\n predicate.left.path.length === 1 &&\n predicate.left.path[0] === definition.primaryKey &&\n !isField(predicate.right)\n ? [predicate.right]\n : undefined;\n const keys = candidates?.every(Schema.is(KeySchema))\n ? (candidates as readonly (string | number)[])\n : undefined;\n const plan = analyzeSubsetFilter(predicate, arrayProperties(options.ir, definition));\n const pushed = keys\n ? { type: \"in\" as const, field: definition.primaryKey, value: [...new Set(keys)] }\n : plan.query;\n const values = yield* Effect.tryPromise({\n try: (signal) =>\n searchFoundryObjects(\n options.client,\n subset.objectType,\n definition.properties.map((property) => property.name),\n {\n signal,\n where: pushed,\n },\n (value) => options.decodeObject(subset.objectType, value)\n ),\n catch: unavailable,\n });\n const rows = yield* Effect.forEach(values, (value) =>\n Schema.decodeUnknownEffect(KeySchema)(value[definition.primaryKey]).pipe(\n Effect.map((key) => ({ key, value })),\n Effect.mapError((cause) => invalidResponse(\"foundry.loadSubset\", cause))\n )\n );\n return {\n fulfilledSubset: objectSubset(subset.objectType, { where: subset.query?.where }),\n fetchedRows: values.length,\n pushdown: {\n source: \"Foundry\",\n predicates: plan.predicates.map((predicate) => ({\n ...predicate,\n execution:\n predicate.execution === \"adapter\" ? (\"engine\" as const) : predicate.execution,\n })),\n sorting: subset.query?.orderBy?.length ? \"engine\" : \"none\",\n pagination:\n subset.query?.limit !== undefined ||\n subset.query?.offset !== undefined ||\n subset.query?.after\n ? \"engine\"\n : \"none\",\n rechecksFilter: Boolean(predicate),\n native: {\n language: \"json\",\n text: JSON.stringify(pushed ?? { type: \"and\", value: [] }, null, 2),\n },\n } satisfies SourceQueryPlan,\n rows,\n complete: true,\n };\n }),\n applyAction: Effect.fn(\"Foundry.applyAction\")(function* (invocation: ActionRequest) {\n const { result: rawResult, attachmentIdMappings } = yield* Effect.tryPromise({\n try: (signal) => options.submitAction(invocation, signal),\n catch: (cause) => classifyBackendFailure(\"foundry.applyAction\", cause),\n });\n const result = yield* Schema.decodeUnknownEffect(ActionResult)(rawResult).pipe(\n Effect.mapError((cause) => invalidResponse(\"foundry.applyAction\", cause))\n );\n return yield* Effect.try({\n try: () => {\n const targets = new Map<string, Set<string | number> | undefined>();\n const add = (objectType: string, rawKey?: unknown) => {\n const definition = options.ir.objectTypes.find((type) => type.name === objectType);\n if (!definition || objectType === options.users?.objectType) return;\n const key =\n rawKey === undefined\n ? undefined\n : options.decodeObject(objectType, { [definition.primaryKey]: rawKey })[\n definition.primaryKey\n ];\n if (rawKey === undefined) targets.set(objectType, undefined);\n else if (!Schema.is(KeySchema)(key)) throw new Error(\"Invalid edit identity.\");\n else if (!targets.has(objectType) || targets.get(objectType))\n targets.set(objectType, new Set([...(targets.get(objectType) ?? []), key]));\n };\n if (!result.edits) for (const type of options.ir.objectTypes) add(type.name);\n else if (result.edits.type === \"largeScaleEdits\")\n for (const type of result.edits.editedObjectTypes) add(type);\n else\n for (const edit of result.edits.edits) {\n if (\"aSideObject\" in edit) {\n add(edit.aSideObject.objectType, edit.aSideObject.primaryKey);\n add(edit.bSideObject.objectType, edit.bSideObject.primaryKey);\n } else add(edit.objectType, edit.primaryKey);\n }\n return {\n operationId: invocation.id,\n outcome: \"committed\",\n providerOperationId: result.operationId,\n affected: [...targets].map(([objectType, keys]) => ({\n objectType,\n ...(keys ? { keys: [...keys] } : {}),\n })),\n attachmentIdMappings: attachmentIdMappings.length ? attachmentIdMappings : undefined,\n } satisfies ActionReceipt;\n },\n catch: (cause) => invalidResponse(\"foundry.applyAction\", cause),\n });\n }),\n // Admin users have no ontology websocket feed; the Replica owns this polling lifetime.\n refresh: (subset: ObjectSubset) =>\n subset.from.source.objectType === options.users?.objectType\n ? { pollIntervalMs: 60_000 }\n : undefined,\n watchSubset: watcher\n ? (request: ObjectSubset) =>\n request.from.source.objectType === options.users?.objectType\n ? undefined\n : Effect.gen(function* () {\n const subset = yield* compileObjectSubset(options.ir, request, options.context);\n const definition = options.ir.objectTypes.find(\n (type) => type.name === subset.objectType\n )!;\n const filter = subsetFilter(\n subset.query?.where,\n arrayProperties(options.ir, definition)\n );\n return yield* acquireWatch(\n watcher.subscribe(\n filter\n ? {\n type: \"filter\",\n objectSet: { type: \"base\", objectType: subset.objectType },\n where: filter,\n }\n : { type: \"base\", objectType: subset.objectType }\n ),\n (updates) =>\n foundryWatchChanges(\n updates,\n subset.objectType,\n definition.primaryKey,\n options.decodeObject\n )\n );\n })\n : undefined,\n });\n});\n"],"mappings":";;;;;;;;;AAyBA,MAAM,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAM,eAAe,OAAO,OAAO;CAAE,YAAY,OAAO;CAAQ,YAAY,OAAO;AAAQ,CAAC;AAC5F,MAAM,eAAe,OAAO,OAAO;CAC/B,aAAa,OAAO,SAAS,OAAO,MAAM;CAC1C,OAAO,OAAO,SACV,OAAO,MAAM,CACT,OAAO,OAAO;EACV,MAAM,OAAO,QAAQ,iBAAiB;EACtC,mBAAmB,OAAO,MAAM,OAAO,MAAM;CACjD,CAAC,GACD,OAAO,OAAO;EACV,MAAM,OAAO,QAAQ,OAAO;EAC5B,OAAO,OAAO,MACV,OAAO,MAAM,CACT,OAAO,OAAO;GACV,MAAM,OAAO,SAAS;IAAC;IAAa;IAAgB;GAAc,CAAC;GACnE,GAAG,aAAa;EACpB,CAAC,GACD,OAAO,OAAO;GACV,MAAM,OAAO,SAAS,CAAC,WAAW,YAAY,CAAC;GAC/C,aAAa;GACb,aAAa;EACjB,CAAC,CACL,CAAC,CACL;CACJ,CAAC,CACL,CAAC,CACL;AACJ,CAAC;AACD,MAAM,mBAAmB,WAAmB,UACxC,IAAI,aAAa;CACb;CACA,MAAM;CACN,SAAS;CACT,WAAW;CACX,eAAe;CACf,OAAO,SAAS,KAAK,KAAK;AAC9B,CAAC;AACL,MAAM,eAAe,UAAmB,uBAAuB,gBAAgB,KAAK;;;;;AAMpF,MAAa,yBAAyB;;AAEtC,MAAM,yBAAyB,WAAwC;CACnE,I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AAqB,SAAS,uBAAuB,KAAA;KAC/E;IACJ;IACA,QAAQ,UAAU,gBAAgB,uBAAuB,KAAK;GAClE,CAAC;EACL,CAAC;EAED,UAAU,WACN,OAAO,KAAK,OAAO,eAAe,QAAQ,OAAO,aAC3C,EAAE,gBAAgB,IAAO,IACzB,KAAA;EACV,aAAa,WACN,YACG,QAAQ,KAAK,OAAO,eAAe,QAAQ,OAAO,aAC5C,KAAA,IACA,OAAO,IAAI,aAAa;GACpB,MAAM,SAAS,OAAO,oBAAoB,QAAQ,IAAI,SAAS,QAAQ,OAAO;GAC9E,MAAM,aAAa,QAAQ,GAAG,YAAY,MACrC,SAAS,KAAK,SAAS,OAAO,UACnC;GACA,MAAM,SAAS,aACX,OAAO,OAAO,OACd,gBAAgB,QAAQ,IAAI,UAAU,CAC1C;GACA,OAAO,OAAO,aACV,QAAQ,UACJ,SACM;IACI,MAAM;IACN,WAAW;KAAE,MAAM;KAAQ,YAAY,OAAO;IAAW;IACzD,OAAO;GACX,IACA;IAAE,MAAM;IAAQ,YAAY,OAAO;GAAW,CACxD,IACC,YACG,oBACI,SACA,OAAO,YACP,WAAW,YACX,QAAQ,YACZ,CACR;EACJ,CAAC,IACX,KAAA;CACV,CAAC;AACL,CAAC"}
@@ -1,9 +1,14 @@
1
1
  import { SearchJsonQueryV2 } from "@osdk/foundry.ontologies";
2
+ import { ObjectTypeDef, OntologyIR } from "@party-stack/ontology-spec";
2
3
  import { Predicate } from "@party-stack/ontology-storage";
3
4
  //#region src/adapter/subsetFilter.d.ts
4
- export declare const subsetFilter: (predicate: Predicate | undefined) => SearchJsonQueryV2 | undefined;
5
+ /** Array properties by name, `true` when the property is required. Foundry's `isNull` is
6
+ * true for an empty array as well as a missing one, so arrays need their own rules. */
7
+ export type ArrayProperties = ReadonlyMap<string, boolean>;
8
+ export declare function arrayProperties(ir: OntologyIR, definition: ObjectTypeDef): ArrayProperties;
9
+ export declare const subsetFilter: (predicate: Predicate | undefined, arrays?: ArrayProperties) => SearchJsonQueryV2 | undefined;
5
10
  /** Report effective placement, including supported OR branches that could not safely be sent. */
6
- export declare function analyzeSubsetFilter(predicate: Predicate | undefined): {
11
+ export declare function analyzeSubsetFilter(predicate: Predicate | undefined, arrays?: ArrayProperties): {
7
12
  query: SearchJsonQueryV2 | undefined;
8
13
  predicates: {
9
14
  readonly path: readonly number[];
@@ -1 +1 @@
1
- {"version":3,"file":"subsetFilter.d.ts","names":[],"sources":["../../src/adapter/subsetFilter.ts"],"mappings":";;;qBAkFa,eAAY,WAAe,0BAAwB;;wBAIhD,oBAAoB,WAAW;SAAA"}
1
+ {"version":3,"file":"subsetFilter.d.ts","names":[],"sources":["../../src/adapter/subsetFilter.ts"],"mappings":";;;;;;YAeY,kBAAkB;wBAEd,gBAAgB,IAAI,YAAY,YAAY,gBAAgB;qBAkJ/D,eAAY,WACV,uBAAqB,SACxB,oBACT;;wBAMa,oBAAoB,WAAW,uBAAuB,SAAQ"}
@@ -1,96 +1,204 @@
1
- import { convertLikeFilter } from "./likeFilter.js";
1
+ import { resolveType } from "@party-stack/ontology-spec/utils";
2
2
  import { isField } from "@party-stack/ontology-storage/tables";
3
3
  //#region src/adapter/subsetFilter.ts
4
+ function arrayProperties(ir, definition) {
5
+ const list = (type, required = true) => {
6
+ const resolved = resolveType(ir, type);
7
+ if (resolved.kind === "optional") return list(resolved.value.type, false);
8
+ return resolved.kind === "list" ? required : void 0;
9
+ };
10
+ const arrays = /* @__PURE__ */ new Map();
11
+ for (const property of definition.properties) {
12
+ const required = list(property.type);
13
+ if (required !== void 0) arrays.set(property.name, required);
14
+ }
15
+ return arrays;
16
+ }
4
17
  const scalar = (value) => value instanceof Date ? value.toISOString() : typeof value === "object" && value !== null && "toString" in value ? value.toString() : value;
5
- /** Conservative candidate filtering shared by HTTP reads and WebSocket watches.
6
- * Unsupported terms broaden membership, including unverified negation semantics.
7
- * Sort/limit/cursors stay local so watches include future window entrants.
18
+ const property = (field) => field.path.length === 1 ? field.path[0] : void 0;
19
+ const propertyIdentifier = (field) => field.path.length === 1 ? {
20
+ type: "property",
21
+ apiName: field.path[0]
22
+ } : field.path.length === 2 ? {
23
+ type: "structField",
24
+ propertyApiName: field.path[0],
25
+ structFieldApiName: field.path[1]
26
+ } : void 0;
27
+ const isNull = (name, value) => ({
28
+ type: "isNull",
29
+ field: name,
30
+ value
31
+ });
32
+ /** `left == undefined` with the field on either side. */
33
+ const missing = (predicate) => {
34
+ if (predicate.op !== "eq") return;
35
+ const [field, other] = isField(predicate.left) ? [predicate.left, predicate.right] : [predicate.right, predicate.left];
36
+ return isField(field) && !isField(other) && other === void 0 ? field : void 0;
37
+ };
38
+ /** Foundry matches `wildcard` against each lowercased token of a string: `*` cannot lead,
39
+ * and a pattern cannot span spaces or punctuation. A LIKE pattern that starts with a word
40
+ * is sent as that word's prefix, which the value's first token must start with. The
41
+ * result is a superset; patterns that start with a wildcard or punctuation stay local. */
42
+ function likeFilter(field, pattern, insensitive) {
43
+ const identifier = propertyIdentifier(field);
44
+ if (!identifier) return;
45
+ const name = property(field);
46
+ if (!insensitive && name && !/[%_]/.test(pattern)) return {
47
+ query: {
48
+ type: "eq",
49
+ field: name,
50
+ value: pattern
51
+ },
52
+ exact: true
53
+ };
54
+ const word = /^[a-z0-9]+/.exec(pattern.toLowerCase())?.[0];
55
+ if (!word) return;
56
+ return {
57
+ query: {
58
+ type: "wildcard",
59
+ propertyIdentifier: identifier,
60
+ value: `${word}*`
61
+ },
62
+ exact: false
63
+ };
64
+ }
65
+ /** Filters Foundry can answer, shared by HTTP reads and WebSocket watches. Unsupported
66
+ * terms broaden membership; sort, limit and cursors stay local so watches include future
67
+ * window entrants. Behaviour was checked against Foundry's search API:
68
+ * - `eq`, `in`, `contains` and ranges compare like storage. Strings compare case-sensitively,
69
+ * and ranges exclude null.
70
+ * - `not` is a plain complement that includes null, as storage's is. It is sent only over an
71
+ * exact filter, since negating a superset would drop rows.
72
+ * - `isNull` is exact for scalars. On arrays it is also true for an empty array, so it
73
+ * answers "missing or empty" exactly, and either alone as a superset.
8
74
  */
9
- function translate(predicate, recurse = translate) {
75
+ function translate(predicate, arrays, recurse) {
76
+ if (predicate.op === "or") {
77
+ const fields = predicate.predicates.map((child) => child.op === "empty" ? child.left : missing(child));
78
+ const name = fields[0] && property(fields[0]);
79
+ if (predicate.predicates.length === 2 && name !== void 0 && arrays.has(name) && fields.every((field) => field && property(field) === name) && predicate.predicates.some((child) => child.op === "empty")) return {
80
+ query: isNull(name, true),
81
+ exact: true
82
+ };
83
+ }
10
84
  if (predicate.op === "and" || predicate.op === "or") {
11
- const children = predicate.predicates.map((child) => recurse(child));
85
+ const children = predicate.predicates.map(recurse);
12
86
  if (predicate.op === "or" && children.some((child) => !child)) return;
13
- const supported = children.filter((child) => child !== void 0);
14
- if (!supported.length) return;
87
+ const sent = children.filter((child) => child !== void 0);
88
+ if (!sent.length) return;
89
+ return {
90
+ query: {
91
+ type: predicate.op,
92
+ value: sent.map((child) => child.query)
93
+ },
94
+ exact: sent.length === children.length && sent.every((child) => child.exact)
95
+ };
96
+ }
97
+ if (predicate.op === "not" || predicate.op === "ne") {
98
+ const inner = recurse(predicate.op === "not" ? predicate.predicate : {
99
+ ...predicate,
100
+ op: "eq"
101
+ });
102
+ return inner?.exact ? {
103
+ query: {
104
+ type: "not",
105
+ value: inner.query
106
+ },
107
+ exact: true
108
+ } : void 0;
109
+ }
110
+ if (predicate.op === "empty") {
111
+ const name = property(predicate.left);
112
+ return name && arrays.has(name) ? {
113
+ query: isNull(name, true),
114
+ exact: arrays.get(name)
115
+ } : void 0;
116
+ }
117
+ const absent = missing(predicate);
118
+ if (absent) {
119
+ const name = property(absent);
120
+ if (!name) return;
15
121
  return {
16
- type: predicate.op,
17
- value: supported
122
+ query: isNull(name, true),
123
+ exact: !arrays.has(name)
18
124
  };
19
125
  }
20
- if (predicate.op === "not" || predicate.op === "ne") return;
21
126
  if (predicate.op === "like" || predicate.op === "ilike") {
22
- if (!isField(predicate.left) || predicate.left.path.length !== 1 || typeof predicate.right !== "string") return;
23
- return convertLikeFilter([...predicate.left.path], predicate.right, true).query;
127
+ if (!isField(predicate.left) || typeof predicate.right !== "string") return;
128
+ return likeFilter(predicate.left, predicate.right, predicate.op === "ilike");
24
129
  }
25
130
  if (predicate.op === "contains") {
26
- if (predicate.left.path.length !== 1 || isField(predicate.right) || predicate.right == null || typeof predicate.right === "bigint") return;
131
+ const name = property(predicate.left);
132
+ if (!name || isField(predicate.right) || predicate.right == null || typeof predicate.right === "bigint") return;
27
133
  return {
28
- type: "contains",
29
- field: predicate.left.path[0],
30
- value: scalar(predicate.right)
134
+ query: {
135
+ type: "contains",
136
+ field: name,
137
+ value: scalar(predicate.right)
138
+ },
139
+ exact: true
31
140
  };
32
141
  }
33
- let left = predicate.left;
34
142
  if (predicate.op === "in") {
35
- if (!isField(left) || left.path.length !== 1 || predicate.values.some((value) => value == null || typeof value === "bigint")) return;
143
+ const name = isField(predicate.left) ? property(predicate.left) : void 0;
144
+ if (!name || predicate.values.some((value) => value == null || typeof value === "bigint")) return;
36
145
  return {
37
- type: "in",
38
- field: left.path[0],
39
- value: predicate.values.map(scalar)
146
+ query: {
147
+ type: "in",
148
+ field: name,
149
+ value: predicate.values.map(scalar)
150
+ },
151
+ exact: true
40
152
  };
41
153
  }
42
- let right = predicate.right;
43
- let operation = predicate.op;
154
+ let { left, right, op } = predicate;
44
155
  if (isField(right) && !isField(left)) {
45
156
  [left, right] = [right, left];
46
- operation = {
157
+ op = {
47
158
  eq: "eq",
48
159
  gt: "lt",
49
160
  gte: "lte",
50
161
  lt: "gt",
51
162
  lte: "gte"
52
- }[operation];
163
+ }[op];
53
164
  }
54
- if (!isField(left) || isField(right) || left.path.length !== 1 || right == null || typeof right === "bigint") return;
165
+ const name = isField(left) ? property(left) : void 0;
166
+ if (!name || arrays.has(name) || isField(right) || right == null || typeof right === "bigint") return;
55
167
  const query = {
56
- type: operation,
57
- field: left.path[0],
168
+ type: op,
169
+ field: name,
58
170
  value: scalar(right)
59
171
  };
60
- return operation === "eq" ? query : {
61
- type: "or",
62
- value: [query, {
63
- type: "isNull",
64
- field: left.path[0],
65
- value: true
66
- }]
172
+ return {
173
+ query: op === "lt" || op === "lte" ? {
174
+ type: "or",
175
+ value: [query, isNull(name, true)]
176
+ } : query,
177
+ exact: true
67
178
  };
68
179
  }
69
- const subsetFilter = (predicate) => predicate ? translate(predicate) : void 0;
180
+ const subsetFilter = (predicate, arrays = /* @__PURE__ */ new Map()) => {
181
+ const recurse = (child) => translate(child, arrays, recurse);
182
+ return predicate ? recurse(predicate)?.query : void 0;
183
+ };
70
184
  /** Report effective placement, including supported OR branches that could not safely be sent. */
71
- function analyzeSubsetFilter(predicate) {
185
+ function analyzeSubsetFilter(predicate, arrays = /* @__PURE__ */ new Map()) {
72
186
  const translated = /* @__PURE__ */ new Map();
73
187
  const visit = (predicate) => {
74
- const query = translate(predicate, visit);
75
- translated.set(predicate, query);
76
- return query;
188
+ const result = translate(predicate, arrays, visit);
189
+ translated.set(predicate, result);
190
+ return result;
77
191
  };
78
- const query = predicate ? visit(predicate) : void 0;
192
+ const query = predicate ? visit(predicate)?.query : void 0;
79
193
  const predicates = [];
80
- const report = (predicate, path, allowed) => {
81
- const sent = allowed && translated.get(predicate) !== void 0;
82
- if (predicate.op === "and" || predicate.op === "or") predicate.predicates.forEach((child, index) => report(child, [...path, index], sent));
83
- else if (predicate.op === "not") report(predicate.predicate, [...path, 0], false);
194
+ const report = (predicate, path, allowed, exact = false) => {
195
+ const result = allowed ? translated.get(predicate) : void 0;
196
+ const whole = exact || result?.exact === true;
197
+ if (predicate.op === "and" || predicate.op === "or") predicate.predicates.forEach((child, index) => report(child, [...path, index], result !== void 0, whole));
198
+ else if (predicate.op === "not") report(predicate.predicate, [...path, 0], result !== void 0, whole);
84
199
  else predicates.push({
85
200
  path,
86
- execution: !sent ? "adapter" : [
87
- "like",
88
- "ilike",
89
- "gt",
90
- "gte",
91
- "lt",
92
- "lte"
93
- ].includes(predicate.op) ? "candidate" : "source"
201
+ execution: whole ? "source" : result ? "candidate" : "adapter"
94
202
  });
95
203
  };
96
204
  if (predicate) report(predicate, [], true);
@@ -100,6 +208,6 @@ function analyzeSubsetFilter(predicate) {
100
208
  };
101
209
  }
102
210
  //#endregion
103
- export { analyzeSubsetFilter, subsetFilter };
211
+ export { analyzeSubsetFilter, arrayProperties, subsetFilter };
104
212
 
105
213
  //# sourceMappingURL=subsetFilter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"subsetFilter.js","names":[],"sources":["../../src/adapter/subsetFilter.ts"],"sourcesContent":["import { isField } from \"@party-stack/ontology-storage/tables\";\nimport { convertLikeFilter } from \"./likeFilter.js\";\nimport type { SearchJsonQueryV2 } from \"@osdk/foundry.ontologies\";\nimport type { SourceQueryPlan } from \"@party-stack/ontology-backend\";\nimport type { Predicate, Scalar } from \"@party-stack/ontology-storage\";\n\nconst scalar = (value: Scalar): unknown =>\n value instanceof Date\n ? value.toISOString()\n : typeof value === \"object\" && value !== null && \"toString\" in value\n ? value.toString()\n : value;\n\n/** Conservative candidate filtering shared by HTTP reads and WebSocket watches.\n * Unsupported terms broaden membership, including unverified negation semantics.\n * Sort/limit/cursors stay local so watches include future window entrants.\n */\nfunction translate(\n predicate: Predicate,\n recurse: (predicate: Predicate) => SearchJsonQueryV2 | undefined = translate\n): SearchJsonQueryV2 | undefined {\n if (predicate.op === \"and\" || predicate.op === \"or\") {\n const children = predicate.predicates.map((child) => recurse(child));\n if (predicate.op === \"or\" && children.some((child) => !child)) return;\n const supported = children.filter((child): child is SearchJsonQueryV2 => child !== undefined);\n if (!supported.length) return;\n return { type: predicate.op, value: supported };\n }\n if (predicate.op === \"not\" || predicate.op === \"ne\") return;\n if (predicate.op === \"like\" || predicate.op === \"ilike\") {\n if (\n !isField(predicate.left) ||\n predicate.left.path.length !== 1 ||\n typeof predicate.right !== \"string\"\n )\n return;\n // Portable LIKE follows TanStack's literal-backslash semantics. Foundry\n // may overfetch; exact storage evaluation still precedes pagination.\n return convertLikeFilter([...predicate.left.path], predicate.right, true).query;\n }\n if (predicate.op === \"contains\") {\n if (\n predicate.left.path.length !== 1 ||\n isField(predicate.right) ||\n predicate.right == null ||\n typeof predicate.right === \"bigint\"\n )\n return;\n return { type: \"contains\", field: predicate.left.path[0]!, value: scalar(predicate.right) };\n }\n let left = predicate.left;\n if (predicate.op === \"in\") {\n if (\n !isField(left) ||\n left.path.length !== 1 ||\n predicate.values.some((value) => value == null || typeof value === \"bigint\")\n )\n return;\n return { type: \"in\", field: left.path[0]!, value: predicate.values.map(scalar) };\n }\n let right = predicate.right;\n let operation = predicate.op;\n if (isField(right) && !isField(left)) {\n [left, right] = [right, left];\n operation = { eq: \"eq\", gt: \"lt\", gte: \"lte\", lt: \"gt\", lte: \"gte\" }[operation] as typeof operation;\n }\n if (\n !isField(left) ||\n isField(right) ||\n left.path.length !== 1 ||\n right == null ||\n typeof right === \"bigint\"\n )\n return;\n const query: SearchJsonQueryV2 = { type: operation, field: left.path[0]!, value: scalar(right) };\n // Storage has an explicit ordering for missing/nullish values; provider range\n // filters need not share it. Including nulls preserves a candidate superset.\n return operation === \"eq\"\n ? query\n : { type: \"or\", value: [query, { type: \"isNull\", field: left.path[0]!, value: true }] };\n}\n\nexport const subsetFilter = (predicate: Predicate | undefined): SearchJsonQueryV2 | undefined =>\n predicate ? translate(predicate) : undefined;\n\n/** Report effective placement, including supported OR branches that could not safely be sent. */\nexport function analyzeSubsetFilter(predicate: Predicate | undefined) {\n const translated = new Map<Predicate, SearchJsonQueryV2 | undefined>();\n const visit = (predicate: Predicate): SearchJsonQueryV2 | undefined => {\n const query = translate(predicate, visit);\n translated.set(predicate, query);\n return query;\n };\n const query = predicate ? visit(predicate) : undefined;\n const predicates: SourceQueryPlan[\"predicates\"][number][] = [];\n const report = (predicate: Predicate, path: readonly number[], allowed: boolean): void => {\n const sent = allowed && translated.get(predicate) !== undefined;\n if (predicate.op === \"and\" || predicate.op === \"or\") {\n predicate.predicates.forEach((child, index) => report(child, [...path, index], sent));\n } else if (predicate.op === \"not\") {\n report(predicate.predicate, [...path, 0], false);\n } else {\n predicates.push({\n path,\n execution: !sent\n ? \"adapter\"\n : [\"like\", \"ilike\", \"gt\", \"gte\", \"lt\", \"lte\"].includes(predicate.op)\n ? \"candidate\"\n : \"source\",\n });\n }\n };\n if (predicate) report(predicate, [], true);\n return { query, predicates };\n}\n"],"mappings":";;;AAMA,MAAM,UAAU,UACZ,iBAAiB,OACX,MAAM,YAAY,IAClB,OAAO,UAAU,YAAY,UAAU,QAAQ,cAAc,QAC3D,MAAM,SAAS,IACf;;;;;AAMZ,SAAS,UACL,WACA,UAAmE,WACtC;CAC7B,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAAM;EACjD,MAAM,WAAW,UAAU,WAAW,KAAK,UAAU,QAAQ,KAAK,CAAC;EACnE,IAAI,UAAU,OAAO,QAAQ,SAAS,MAAM,UAAU,CAAC,KAAK,GAAG;EAC/D,MAAM,YAAY,SAAS,QAAQ,UAAsC,UAAU,KAAA,CAAS;EAC5F,IAAI,CAAC,UAAU,QAAQ;EACvB,OAAO;GAAE,MAAM,UAAU;GAAI,OAAO;EAAU;CAClD;CACA,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAAM;CACrD,IAAI,UAAU,OAAO,UAAU,UAAU,OAAO,SAAS;EACrD,IACI,CAAC,QAAQ,UAAU,IAAI,KACvB,UAAU,KAAK,KAAK,WAAW,KAC/B,OAAO,UAAU,UAAU,UAE3B;EAGJ,OAAO,kBAAkB,CAAC,GAAG,UAAU,KAAK,IAAI,GAAG,UAAU,OAAO,IAAI,CAAC,CAAC;CAC9E;CACA,IAAI,UAAU,OAAO,YAAY;EAC7B,IACI,UAAU,KAAK,KAAK,WAAW,KAC/B,QAAQ,UAAU,KAAK,KACvB,UAAU,SAAS,QACnB,OAAO,UAAU,UAAU,UAE3B;EACJ,OAAO;GAAE,MAAM;GAAY,OAAO,UAAU,KAAK,KAAK;GAAK,OAAO,OAAO,UA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W,WAAW,IAAI,SAAS,MAAM,KAAA;EACtD,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAC3C,UAAU,WAAW,SAAS,OAAO,UAAU,OAAO,OAAO,CAAC,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC;OACjF,IAAI,UAAU,OAAO,OACxB,OAAO,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC,GAAG,KAAK;OAE/C,WAAW,KAAK;GACZ;GACA,WAAW,CAAC,OACN,YACA;IAAC;IAAQ;IAAS;IAAM;IAAO;IAAM;GAAK,CAAC,CAAC,SAAS,UAAU,EAAE,IAC/D,cACA;EACZ,CAAC;CAET;CACA,IAAI,WAAW,OAAO,WAAW,CAAC,GAAG,IAAI;CACzC,OAAO;EAAE;EAAO;CAAW;AAC/B"}
1
+ {"version":3,"file":"subsetFilter.js","names":[],"sources":["../../src/adapter/subsetFilter.ts"],"sourcesContent":["import { resolveType } from \"@party-stack/ontology-spec/utils\";\nimport { isField } from \"@party-stack/ontology-storage/tables\";\nimport type { PropertyIdentifier, SearchJsonQueryV2 } from \"@osdk/foundry.ontologies\";\nimport type { SourceQueryPlan } from \"@party-stack/ontology-backend\";\nimport type { ObjectTypeDef, OntologyIR, TypeDef } from \"@party-stack/ontology-spec\";\nimport type { Field, Predicate, Scalar } from \"@party-stack/ontology-storage\";\n\n/** A Foundry filter, and whether it returns exactly the matching rows rather than a superset. */\ninterface Translation {\n readonly query: SearchJsonQueryV2;\n readonly exact: boolean;\n}\n\n/** Array properties by name, `true` when the property is required. Foundry's `isNull` is\n * true for an empty array as well as a missing one, so arrays need their own rules. */\nexport type ArrayProperties = ReadonlyMap<string, boolean>;\n\nexport function arrayProperties(ir: OntologyIR, definition: ObjectTypeDef): ArrayProperties {\n const list = (type: TypeDef, required = true): boolean | undefined => {\n const resolved = resolveType(ir, type);\n if (resolved.kind === \"optional\") return list(resolved.value.type, false);\n return resolved.kind === \"list\" ? required : undefined;\n };\n const arrays = new Map<string, boolean>();\n for (const property of definition.properties) {\n const required = list(property.type);\n if (required !== undefined) arrays.set(property.name, required);\n }\n return arrays;\n}\n\nconst scalar = (value: Scalar): unknown =>\n value instanceof Date\n ? value.toISOString()\n : typeof value === \"object\" && value !== null && \"toString\" in value\n ? value.toString()\n : value;\n\nconst property = (field: Field): string | undefined => (field.path.length === 1 ? field.path[0] : undefined);\nconst propertyIdentifier = (field: Field): PropertyIdentifier | undefined =>\n field.path.length === 1\n ? { type: \"property\", apiName: field.path[0]! }\n : field.path.length === 2\n ? { type: \"structField\", propertyApiName: field.path[0]!, structFieldApiName: field.path[1]! }\n : undefined;\nconst isNull = (name: string, value: boolean): SearchJsonQueryV2 => ({ type: \"isNull\", field: name, value });\n\n/** `left == undefined` with the field on either side. */\nconst missing = (predicate: Predicate): Field | undefined => {\n if (predicate.op !== \"eq\") return;\n const [field, other] = isField(predicate.left)\n ? [predicate.left, predicate.right]\n : [predicate.right, predicate.left];\n return isField(field) && !isField(other) && other === undefined ? field : undefined;\n};\n\n/** Foundry matches `wildcard` against each lowercased token of a string: `*` cannot lead,\n * and a pattern cannot span spaces or punctuation. A LIKE pattern that starts with a word\n * is sent as that word's prefix, which the value's first token must start with. The\n * result is a superset; patterns that start with a wildcard or punctuation stay local. */\nfunction likeFilter(field: Field, pattern: string, insensitive: boolean): Translation | undefined {\n const identifier = propertyIdentifier(field);\n if (!identifier) return;\n const name = property(field);\n if (!insensitive && name && !/[%_]/.test(pattern))\n return { query: { type: \"eq\", field: name, value: pattern }, exact: true };\n const word = /^[a-z0-9]+/.exec(pattern.toLowerCase())?.[0];\n if (!word) return;\n return { query: { type: \"wildcard\", propertyIdentifier: identifier, value: `${word}*` }, exact: false };\n}\n\n/** Filters Foundry can answer, shared by HTTP reads and WebSocket watches. Unsupported\n * terms broaden membership; sort, limit and cursors stay local so watches include future\n * window entrants. Behaviour was checked against Foundry's search API:\n * - `eq`, `in`, `contains` and ranges compare like storage. Strings compare case-sensitively,\n * and ranges exclude null.\n * - `not` is a plain complement that includes null, as storage's is. It is sent only over an\n * exact filter, since negating a superset would drop rows.\n * - `isNull` is exact for scalars. On arrays it is also true for an empty array, so it\n * answers \"missing or empty\" exactly, and either alone as a superset.\n */\nfunction translate(\n predicate: Predicate,\n arrays: ArrayProperties,\n recurse: (predicate: Predicate) => Translation | undefined\n): Translation | undefined {\n if (predicate.op === \"or\") {\n // Missing or empty, the lowering of `length(list) == 0`.\n const fields = predicate.predicates.map((child) =>\n child.op === \"empty\" ? child.left : missing(child)\n );\n const name = fields[0] && property(fields[0]);\n if (\n predicate.predicates.length === 2 &&\n name !== undefined &&\n arrays.has(name) &&\n fields.every((field) => field && property(field) === name) &&\n predicate.predicates.some((child) => child.op === \"empty\")\n )\n return { query: isNull(name, true), exact: true };\n }\n if (predicate.op === \"and\" || predicate.op === \"or\") {\n const children = predicate.predicates.map(recurse);\n if (predicate.op === \"or\" && children.some((child) => !child)) return;\n const sent = children.filter((child): child is Translation => child !== undefined);\n if (!sent.length) return;\n return {\n query: { type: predicate.op, value: sent.map((child) => child.query) },\n exact: sent.length === children.length && sent.every((child) => child.exact),\n };\n }\n if (predicate.op === \"not\" || predicate.op === \"ne\") {\n const inner = recurse(\n predicate.op === \"not\" ? predicate.predicate : { ...predicate, op: \"eq\" as const }\n );\n return inner?.exact ? { query: { type: \"not\", value: inner.query }, exact: true } : undefined;\n }\n if (predicate.op === \"empty\") {\n const name = property(predicate.left);\n // A required array is never missing, so `isNull` is exactly \"empty\".\n return name && arrays.has(name) ? { query: isNull(name, true), exact: arrays.get(name)! } : undefined;\n }\n const absent = missing(predicate);\n if (absent) {\n const name = property(absent);\n if (!name) return;\n return { query: isNull(name, true), exact: !arrays.has(name) };\n }\n if (predicate.op === \"like\" || predicate.op === \"ilike\") {\n if (!isField(predicate.left) || typeof predicate.right !== \"string\") return;\n return likeFilter(predicate.left, predicate.right, predicate.op === \"ilike\");\n }\n if (predicate.op === \"contains\") {\n const name = property(predicate.left);\n if (\n !name ||\n isField(predicate.right) ||\n predicate.right == null ||\n typeof predicate.right === \"bigint\"\n )\n return;\n return { query: { type: \"contains\", field: name, value: scalar(predicate.right) }, exact: true };\n }\n if (predicate.op === \"in\") {\n const name = isField(predicate.left) ? property(predicate.left) : undefined;\n if (!name || predicate.values.some((value) => value == null || typeof value === \"bigint\")) return;\n return { query: { type: \"in\", field: name, value: predicate.values.map(scalar) }, exact: true };\n }\n let { left, right, op } = predicate;\n if (isField(right) && !isField(left)) {\n [left, right] = [right, left];\n op = ({ eq: \"eq\", gt: \"lt\", gte: \"lte\", lt: \"gt\", lte: \"gte\" } as const)[op];\n }\n const name = isField(left) ? property(left) : undefined;\n if (!name || arrays.has(name) || isField(right) || right == null || typeof right === \"bigint\") return;\n const query: SearchJsonQueryV2 = { type: op, field: name, value: scalar(right) };\n // Storage orders a missing value before every other value; Foundry's ranges exclude null.\n return {\n query: op === \"lt\" || op === \"lte\" ? { type: \"or\", value: [query, isNull(name, true)] } : query,\n exact: true,\n };\n}\n\nexport const subsetFilter = (\n predicate: Predicate | undefined,\n arrays: ArrayProperties = new Map()\n): SearchJsonQueryV2 | undefined => {\n const recurse = (child: Predicate): Translation | undefined => translate(child, arrays, recurse);\n return predicate ? recurse(predicate)?.query : undefined;\n};\n\n/** Report effective placement, including supported OR branches that could not safely be sent. */\nexport function analyzeSubsetFilter(predicate: Predicate | undefined, arrays: ArrayProperties = new Map()) {\n const translated = new Map<Predicate, Translation | undefined>();\n const visit = (predicate: Predicate): Translation | undefined => {\n const result = translate(predicate, arrays, visit);\n translated.set(predicate, result);\n return result;\n };\n const query = predicate ? visit(predicate)?.query : undefined;\n const predicates: SourceQueryPlan[\"predicates\"][number][] = [];\n const report = (predicate: Predicate, path: readonly number[], allowed: boolean, exact = false): void => {\n const result = allowed ? translated.get(predicate) : undefined;\n // Everything under an exact filter is answered by Foundry, including terms\n // translated together rather than one by one.\n const whole = exact || result?.exact === true;\n if (predicate.op === \"and\" || predicate.op === \"or\")\n predicate.predicates.forEach((child, index) =>\n report(child, [...path, index], result !== undefined, whole)\n );\n else if (predicate.op === \"not\")\n report(predicate.predicate, [...path, 0], result !== undefined, whole);\n else\n predicates.push({\n path,\n execution: whole ? \"source\" : result ? \"candidate\" : \"adapter\",\n });\n };\n if (predicate) report(predicate, [], true);\n return { query, predicates };\n}\n"],"mappings":";;;AAiBA,SAAgB,gBAAgB,IAAgB,YAA4C;CACxF,MAAM,QAAQ,MAAe,WAAW,SAA8B;EAClE,MAAM,WAAW,YAAY,IAAI,IAAI;EACrC,IAAI,SAAS,SAAS,YAAY,OAAO,KAAK,SAAS,MAAM,MAAM,KAAK;EACxE,OAAO,SAAS,SAAS,SAAS,WAAW,KAAA;CACjD;CACA,MAAM,yBAAS,IAAI,IAAqB;CACxC,KAAK,MAAM,YAAY,WAAW,YAAY;EAC1C,MAAM,WAAW,KAAK,SAAS,IAAI;EACnC,IAAI,aAAa,KAAA,GAAW,OAAO,IAAI,SAAS,MAAM,QAAQ;CAClE;CACA,OAAO;AACX;AAEA,MAAM,UAAU,UACZ,iBAAiB,OACX,MAAM,YAAY,IAClB,OAAO,UAAU,YAAY,UAAU,QAAQ,cAAc,QAC3D,MAAM,SAAS,IACf;AAEZ,MAAM,YAAY,UAAsC,MAAM,KAAK,WAAW,IAAI,MAAM,KAAK,KAAK,KAAA;AAClG,MAAM,sBAAsB,UACxB,MAAM,KAAK,WAAW,IAChB;CAAE,MAAM;CAAY,SAAS,MAAM,KAAK;AAAI,IAC5C,MAAM,KAAK,WAAW,IACpB;CAAE,MAAM;CAAe,iBAAiB,MAAM,KAAK;CAAK,oBAAoB,MAAM,KAAK;AAAI,IAC3F,KAAA;AACZ,MAAM,UAAU,MAAc,WAAuC;CAAE,MAAM;CAAU,OAAO;CAAM;AAAM;;AAG1G,MAAM,WAAW,cAA4C;CACzD,IAAI,UAAU,OAAO,MAAM;CAC3B,MAAM,CAAC,OAAO,SAAS,QAAQ,UAAU,IAAI,IACvC,CAAC,UAAU,MAAM,UAAU,KAAK,IAChC,CAAC,UAAU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CAC/D,MAAM,SAAS,cAAkD;EAC7D,MAAM,SAAS,UAAU,WAAW,QAAQ,KAAK;EACjD,WAAW,IAAI,WAAW,MAAM;EAChC,OAAO;CACX;CACA,MAAM,QAAQ,YAAY,MAAM,SAAS,CAAC,EAAE,QAAQ,KAAA;CACpD,MAAM,aAAsD,CAAC;CAC7D,MAAM,UAAU,WAAsB,MAAyB,SAAkB,QAAQ,UAAgB;EACrG,MAAM,SAAS,UAAU,WAAW,IAAI,SAAS,IAAI,KAAA;EAGrD,MAAM,QAAQ,SAAS,QAAQ,UAAU;EACzC,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAC3C,UAAU,WAAW,SAAS,OAAO,UACjC,OAAO,OAAO,CAAC,GAAG,MAAM,KAAK,GAAG,WAAW,KAAA,GAAW,KAAK,CAC/D;OACC,IAAI,UAAU,OAAO,OACtB,OAAO,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC,GAAG,WAAW,KAAA,GAAW,KAAK;OAErE,WAAW,KAAK;GACZ;GACA,WAAW,QAAQ,WAAW,SAAS,cAAc;EACzD,CAAC;CACT;CACA,IAAI,WAAW,OAAO,WAAW,CAAC,GAAG,IAAI;CACzC,OAAO;EAAE;EAAO;CAAW;AAC/B"}
@@ -1,6 +1,6 @@
1
1
  import { fromPagination, toArray } from "../utils/AsyncIterable.js";
2
- import { foundryUserProfilePictureAttachment } from "./foundryUser.js";
3
2
  import { chunk } from "../utils/chunk.js";
3
+ import { foundryUserProfilePictureAttachment } from "./foundryUser.js";
4
4
  import { Redacted, Schema } from "effect";
5
5
  import { BackendError } from "@party-stack/ontology-backend";
6
6
  import { applyLensToObject, mapTargetPathToSourceWithLens } from "@party-stack/ontology-spec";
@@ -47,7 +47,7 @@ function select(predicate, lens, path = []) {
47
47
  };
48
48
  return;
49
49
  }
50
- if (predicate.op === "not") return;
50
+ if (predicate.op === "not" || predicate.op === "empty") return;
51
51
  const left = predicate.op === "eq" && !isField(predicate.left) && isField(predicate.right) ? predicate.right : predicate.left;
52
52
  const right = predicate.op === "eq" && left === predicate.right ? predicate.left : predicate.op !== "in" ? predicate.right : void 0;
53
53
  if (!isField(left)) return;
@@ -1 +1 @@
1
- {"version":3,"file":"loadUserSubset.js","names":["AsyncIterable.toArray","AsyncIterable.fromPagination"],"sources":["../../src/users/loadUserSubset.ts"],"sourcesContent":["import { Users, type User } from \"@osdk/foundry.admin\";\nimport { BackendError } from \"@party-stack/ontology-backend\";\nimport { objectSubset } from \"@party-stack/ontology-backend/subset\";\nimport { applyLensToObject, mapTargetPathToSourceWithLens, type Lens } from \"@party-stack/ontology-spec\";\nimport { evaluateQuery, type Predicate, type Query } from \"@party-stack/ontology-storage\";\nimport { isField } from \"@party-stack/ontology-storage/tables\";\nimport { Schema, Redacted } from \"effect\";\nimport * as AsyncIterable from \"../utils/AsyncIterable.js\";\nimport { chunk } from \"../utils/chunk.js\";\nimport { foundryUserProfilePictureAttachment } from \"./foundryUser.js\";\nimport type { Client } from \"@party-stack/foundry-client\";\nimport type { BackendSnapshot, SourceQueryPlan } from \"@party-stack/ontology-backend\";\n\nconst UserIdentity = Schema.Struct({ id: Schema.String });\nconst UserPage = Schema.Struct({\n data: Schema.Array(UserIdentity),\n nextPageToken: Schema.optional(Schema.String),\n});\nconst UserBatch = Schema.Struct({ data: Schema.Record(Schema.String, UserIdentity) });\nfunction checked<A>(schema: Schema.Decoder<unknown>, value: A): A {\n try {\n Schema.decodeUnknownSync(schema)(value);\n return value;\n } catch (cause) {\n throw new BackendError({\n operation: \"foundry.users.loadSubset\",\n kind: \"InvalidResponse\",\n message: \"Foundry returned an invalid user response.\",\n retryable: false,\n cause: Redacted.make(cause),\n });\n }\n}\n\ntype Selection =\n | { type: \"getBatch\"; ids: string[]; paths: number[][] }\n | { type: \"search\"; term: string; paths: number[][] };\n\n/** Choose only a safe candidate set. Every response is checked against the full query. */\nfunction select(predicate: Predicate, lens: Lens, path: number[] = []): Selection | undefined {\n if (predicate.op === \"and\" || predicate.op === \"or\") {\n const children = predicate.predicates.map((child, index) => select(child, lens, [...path, index]));\n if (predicate.op === \"and\")\n return children.find((child) => child?.type === \"getBatch\") ?? children.find(Boolean);\n if (children.some((child) => !child)) return;\n if (children.every((child) => child?.type === \"getBatch\"))\n return {\n type: \"getBatch\",\n ids: [...new Set(children.flatMap((child) => child.ids))],\n paths: children.flatMap((child) => child.paths),\n };\n const first = children[0];\n if (\n first?.type === \"search\" &&\n children.every((child) => child?.type === \"search\" && child.term === first.term)\n )\n return { ...first, paths: children.flatMap((child) => child!.paths) };\n return;\n }\n if (predicate.op === \"not\") return;\n const left =\n predicate.op === \"eq\" && !isField(predicate.left) && isField(predicate.right)\n ? predicate.right\n : predicate.left;\n const right =\n predicate.op === \"eq\" && left === predicate.right\n ? predicate.left\n : predicate.op !== \"in\"\n ? predicate.right\n : undefined;\n if (!isField(left)) return;\n const source = mapTargetPathToSourceWithLens(left.path, lens).join(\".\");\n if (source === \"id\") {\n if (predicate.op === \"eq\" && typeof right === \"string\")\n return { type: \"getBatch\", ids: [right], paths: [path] };\n if (predicate.op === \"in\" && predicate.values.every((value) => typeof value === \"string\"))\n return { type: \"getBatch\", ids: [...new Set(predicate.values)], paths: [path] };\n }\n if (\n (predicate.op === \"like\" || predicate.op === \"ilike\") &&\n typeof right === \"string\" &&\n [\"username\", \"givenName\", \"familyName\"].includes(source)\n ) {\n // Admin search is case-insensitive prefix matching across all name fields.\n // Complex patterns must not become a narrower, incorrect search term.\n const term = right.slice(0, -1);\n if (right.endsWith(\"%\") && term.length > 0 && !/[%_\\\\]/.test(term))\n return { type: \"search\", term, paths: [path] };\n }\n}\n\nfunction placements(\n predicate: Predicate | undefined,\n selection: Selection | undefined\n): SourceQueryPlan[\"predicates\"] {\n const selected = new Set(selection?.paths.map((path) => JSON.stringify(path)));\n const result: SourceQueryPlan[\"predicates\"][number][] = [];\n const visit = (predicate: Predicate, path: number[]) => {\n if (predicate.op === \"and\" || predicate.op === \"or\")\n predicate.predicates.forEach((child, index) => visit(child, [...path, index]));\n else if (predicate.op === \"not\") visit(predicate.predicate, [...path, 0]);\n else\n result.push({\n path,\n execution: selected.has(JSON.stringify(path))\n ? selection?.type === \"getBatch\"\n ? \"source\"\n : \"candidate\"\n : \"engine\",\n });\n };\n if (predicate) visit(predicate, []);\n return result;\n}\n\nexport async function loadUserSubset(\n client: Client,\n objectType: string,\n lens: Lens,\n query: Query,\n signal: AbortSignal\n): Promise<BackendSnapshot> {\n signal.throwIfAborted();\n evaluateQuery([], query);\n if (query.limit === 0) return { rows: [], complete: true, fetchedRows: 0 };\n const requestClient = {\n ...client,\n fetch: (input: RequestInfo | URL, init?: RequestInit) =>\n client.fetch(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal,\n }),\n };\n const selection = query.where ? select(query.where, lens) : undefined;\n const users: User[] = [];\n const batches = selection?.type === \"getBatch\" ? chunk(selection.ids, 500) : undefined;\n if (batches) {\n for (const ids of batches) {\n signal.throwIfAborted();\n const response = await Users.getBatch(\n requestClient,\n ids.map((userId) => ({ userId }))\n );\n checked(UserBatch, response);\n users.push(...Object.values(response.data));\n }\n } else {\n users.push(\n ...(await AsyncIterable.toArray(\n AsyncIterable.fromPagination(\n async (_pageSize, pageToken: string | undefined) => {\n signal.throwIfAborted();\n const page =\n selection?.type === \"search\"\n ? await Users.search(requestClient, {\n where: { type: \"queryString\", value: selection.term },\n pageToken,\n })\n : await Users.list(requestClient, { pageToken });\n return checked(UserPage, page);\n },\n (page) => page.nextPageToken,\n (page) => page.data,\n 500\n )\n ))\n );\n }\n signal.throwIfAborted();\n const rows = users.map((user) => ({\n key: user.id,\n value: applyLensToObject(\n { ...user, profilePicture: foundryUserProfilePictureAttachment(user.id) },\n lens\n ),\n }));\n return {\n rows,\n fulfilledSubset: objectSubset(objectType, selection ? { where: query.where } : {}),\n complete: true,\n fetchedRows: users.length,\n pushdown: {\n source: \"Foundry users\",\n predicates: placements(query.where, selection),\n sorting: query.orderBy?.length ? \"engine\" : \"none\",\n pagination:\n query.limit !== undefined || query.offset !== undefined || query.after ? \"engine\" : \"none\",\n rechecksFilter: Boolean(query.where),\n native: {\n language: \"json\",\n text: JSON.stringify(\n batches\n ? {\n operation: \"Users.getBatch\",\n batches: batches.map((ids) => ids.map((userId) => ({ userId }))),\n }\n : selection?.type === \"search\"\n ? {\n operation: \"Users.search\",\n where: { type: \"queryString\", value: selection.term },\n }\n : { operation: \"Users.list\" },\n null,\n 2\n ),\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,eAAe,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC;AACxD,MAAM,WAAW,OAAO,OAAO;CAC3B,MAAM,OAAO,MAAM,YAAY;CAC/B,eAAe,OAAO,SAAS,OAAO,MAAM;AAChD,CAAC;AACD,MAAM,YAAY,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,EAAE,CAAC;AACpF,SAAS,QAAW,QAAiC,OAAa;CAC9D,IAAI;EACA,OAAO,kBAAkB,MAAM,CAAC,CAAC,KAAK;EACtC,OAAO;CACX,SAAS,OAAO;EACZ,MAAM,IAAI,aAAa;GACnB,WAAW;GACX,MAAM;GACN,SAAS;GACT,WAAW;GACX,OAAO,SAAS,KAAK,KAAK;EAC9B,CAAC;CACL;AACJ;;AAOA,SAAS,OAAO,WAAsB,MAAY,OAAiB,CAAC,GAA0B;CAC1F,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAAM;EACjD,MAAM,WAAW,UAAU,WAAW,KAAK,OAAO,UAAU,OAAO,OAAO,MAAM,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC;EACjG,IAAI,UAAU,OAAO,OACjB,OAAO,SAAS,MAAM,UAAU,OAAO,SAAS,UAAU,KAAK,SAAS,KAAK,OAAO;EACxF,IAAI,SAAS,MAAM,UAAU,CAAC,KAAK,GAAG;EACtC,IAAI,SAAS,OAAO,UAAU,OAAO,SAAS,UAAU,GACpD,OAAO;GACH,MAAM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EAAE,WAAW,aAAa,GAClC,MACA,CACJ;GACJ;EACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"loadUserSubset.js","names":["AsyncIterable.toArray","AsyncIterable.fromPagination"],"sources":["../../src/users/loadUserSubset.ts"],"sourcesContent":["import { Users, type User } from \"@osdk/foundry.admin\";\nimport { BackendError } from \"@party-stack/ontology-backend\";\nimport { objectSubset } from \"@party-stack/ontology-backend/subset\";\nimport { applyLensToObject, mapTargetPathToSourceWithLens, type Lens } from \"@party-stack/ontology-spec\";\nimport { evaluateQuery, type Predicate, type Query } from \"@party-stack/ontology-storage\";\nimport { isField } from \"@party-stack/ontology-storage/tables\";\nimport { Schema, Redacted } from \"effect\";\nimport * as AsyncIterable from \"../utils/AsyncIterable.js\";\nimport { chunk } from \"../utils/chunk.js\";\nimport { foundryUserProfilePictureAttachment } from \"./foundryUser.js\";\nimport type { Client } from \"@party-stack/foundry-client\";\nimport type { BackendSnapshot, SourceQueryPlan } from \"@party-stack/ontology-backend\";\n\nconst UserIdentity = Schema.Struct({ id: Schema.String });\nconst UserPage = Schema.Struct({\n data: Schema.Array(UserIdentity),\n nextPageToken: Schema.optional(Schema.String),\n});\nconst UserBatch = Schema.Struct({ data: Schema.Record(Schema.String, UserIdentity) });\nfunction checked<A>(schema: Schema.Decoder<unknown>, value: A): A {\n try {\n Schema.decodeUnknownSync(schema)(value);\n return value;\n } catch (cause) {\n throw new BackendError({\n operation: \"foundry.users.loadSubset\",\n kind: \"InvalidResponse\",\n message: \"Foundry returned an invalid user response.\",\n retryable: false,\n cause: Redacted.make(cause),\n });\n }\n}\n\ntype Selection =\n | { type: \"getBatch\"; ids: string[]; paths: number[][] }\n | { type: \"search\"; term: string; paths: number[][] };\n\n/** Choose only a safe candidate set. Every response is checked against the full query. */\nfunction select(predicate: Predicate, lens: Lens, path: number[] = []): Selection | undefined {\n if (predicate.op === \"and\" || predicate.op === \"or\") {\n const children = predicate.predicates.map((child, index) => select(child, lens, [...path, index]));\n if (predicate.op === \"and\")\n return children.find((child) => child?.type === \"getBatch\") ?? children.find(Boolean);\n if (children.some((child) => !child)) return;\n if (children.every((child) => child?.type === \"getBatch\"))\n return {\n type: \"getBatch\",\n ids: [...new Set(children.flatMap((child) => child.ids))],\n paths: children.flatMap((child) => child.paths),\n };\n const first = children[0];\n if (\n first?.type === \"search\" &&\n children.every((child) => child?.type === \"search\" && child.term === first.term)\n )\n return { ...first, paths: children.flatMap((child) => child!.paths) };\n return;\n }\n if (predicate.op === \"not\" || predicate.op === \"empty\") return;\n const left =\n predicate.op === \"eq\" && !isField(predicate.left) && isField(predicate.right)\n ? predicate.right\n : predicate.left;\n const right =\n predicate.op === \"eq\" && left === predicate.right\n ? predicate.left\n : predicate.op !== \"in\"\n ? predicate.right\n : undefined;\n if (!isField(left)) return;\n const source = mapTargetPathToSourceWithLens(left.path, lens).join(\".\");\n if (source === \"id\") {\n if (predicate.op === \"eq\" && typeof right === \"string\")\n return { type: \"getBatch\", ids: [right], paths: [path] };\n if (predicate.op === \"in\" && predicate.values.every((value) => typeof value === \"string\"))\n return { type: \"getBatch\", ids: [...new Set(predicate.values)], paths: [path] };\n }\n if (\n (predicate.op === \"like\" || predicate.op === \"ilike\") &&\n typeof right === \"string\" &&\n [\"username\", \"givenName\", \"familyName\"].includes(source)\n ) {\n // Admin search is case-insensitive prefix matching across all name fields.\n // Complex patterns must not become a narrower, incorrect search term.\n const term = right.slice(0, -1);\n if (right.endsWith(\"%\") && term.length > 0 && !/[%_\\\\]/.test(term))\n return { type: \"search\", term, paths: [path] };\n }\n}\n\nfunction placements(\n predicate: Predicate | undefined,\n selection: Selection | undefined\n): SourceQueryPlan[\"predicates\"] {\n const selected = new Set(selection?.paths.map((path) => JSON.stringify(path)));\n const result: SourceQueryPlan[\"predicates\"][number][] = [];\n const visit = (predicate: Predicate, path: number[]) => {\n if (predicate.op === \"and\" || predicate.op === \"or\")\n predicate.predicates.forEach((child, index) => visit(child, [...path, index]));\n else if (predicate.op === \"not\") visit(predicate.predicate, [...path, 0]);\n else\n result.push({\n path,\n execution: selected.has(JSON.stringify(path))\n ? selection?.type === \"getBatch\"\n ? \"source\"\n : \"candidate\"\n : \"engine\",\n });\n };\n if (predicate) visit(predicate, []);\n return result;\n}\n\nexport async function loadUserSubset(\n client: Client,\n objectType: string,\n lens: Lens,\n query: Query,\n signal: AbortSignal\n): Promise<BackendSnapshot> {\n signal.throwIfAborted();\n evaluateQuery([], query);\n if (query.limit === 0) return { rows: [], complete: true, fetchedRows: 0 };\n const requestClient = {\n ...client,\n fetch: (input: RequestInfo | URL, init?: RequestInit) =>\n client.fetch(input, {\n ...init,\n signal: init?.signal ? AbortSignal.any([signal, init.signal]) : signal,\n }),\n };\n const selection = query.where ? select(query.where, lens) : undefined;\n const users: User[] = [];\n const batches = selection?.type === \"getBatch\" ? chunk(selection.ids, 500) : undefined;\n if (batches) {\n for (const ids of batches) {\n signal.throwIfAborted();\n const response = await Users.getBatch(\n requestClient,\n ids.map((userId) => ({ userId }))\n );\n checked(UserBatch, response);\n users.push(...Object.values(response.data));\n }\n } else {\n users.push(\n ...(await AsyncIterable.toArray(\n AsyncIterable.fromPagination(\n async (_pageSize, pageToken: string | undefined) => {\n signal.throwIfAborted();\n const page =\n selection?.type === \"search\"\n ? await Users.search(requestClient, {\n where: { type: \"queryString\", value: selection.term },\n pageToken,\n })\n : await Users.list(requestClient, { pageToken });\n return checked(UserPage, page);\n },\n (page) => page.nextPageToken,\n (page) => page.data,\n 500\n )\n ))\n );\n }\n signal.throwIfAborted();\n const rows = users.map((user) => ({\n key: user.id,\n value: applyLensToObject(\n { ...user, profilePicture: foundryUserProfilePictureAttachment(user.id) },\n lens\n ),\n }));\n return {\n rows,\n fulfilledSubset: objectSubset(objectType, selection ? { where: query.where } : {}),\n complete: true,\n fetchedRows: users.length,\n pushdown: {\n source: \"Foundry users\",\n predicates: placements(query.where, selection),\n sorting: query.orderBy?.length ? \"engine\" : \"none\",\n pagination:\n query.limit !== undefined || query.offset !== undefined || query.after ? \"engine\" : \"none\",\n rechecksFilter: Boolean(query.where),\n native: {\n language: \"json\",\n text: JSON.stringify(\n batches\n ? {\n operation: \"Users.getBatch\",\n batches: batches.map((ids) => ids.map((userId) => ({ userId }))),\n }\n : selection?.type === \"search\"\n ? {\n operation: \"Users.search\",\n where: { type: \"queryString\", value: selection.term },\n }\n : { operation: \"Users.list\" },\n null,\n 2\n ),\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,eAAe,OAAO,OAAO,EAAE,IAAI,OAAO,OAAO,CAAC;AACxD,MAAM,WAAW,OAAO,OAAO;CAC3B,MAAM,OAAO,MAAM,YAAY;CAC/B,eAAe,OAAO,SAAS,OAAO,MAAM;AAChD,CAAC;AACD,MAAM,YAAY,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,OAAO,QAAQ,YAAY,EAAE,CAAC;AACpF,SAAS,QAAW,QAAiC,OAAa;CAC9D,IAAI;EACA,OAAO,kBAAkB,MAAM,CAAC,CAAC,KAAK;EACtC,OAAO;CACX,SAAS,OAAO;EACZ,MAAM,IAAI,aAAa;GACnB,WAAW;GACX,MAAM;GACN,SAAS;GACT,WAAW;GACX,OAAO,SAAS,KAAK,KAAK;EAC9B,CAAC;CACL;AACJ;;AAOA,SAAS,OAAO,WAAsB,MAAY,OAAiB,CAAC,GAA0B;CAC1F,IAAI,UAAU,OAAO,SAAS,UAAU,OAAO,MAAM;EACjD,MAAM,WAAW,UAAU,WAAW,KAAK,OAAO,UAAU,OAAO,OAAO,MAAM,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC;EACjG,IAAI,UAAU,OAAO,OACjB,OAAO,SAAS,MAAM,UAAU,OAAO,SAAS,UAAU,KAAK,SAAS,KAAK,OAAO;EACxF,IAAI,SAAS,MAAM,UAAU,CAAC,KAAK,GAAG;EACtC,IAAI,SAAS,OAAO,UAAU,OAAO,SAAS,UAAU,GACpD,OAAO;GACH,MAAM;GACN,KAAK,CAAC,GAAG,IAAI,IAAI,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AClC,MACA,CACJ;GACJ;EACJ;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@party-stack/foundry-ontology",
3
- "version": "0.20.1",
3
+ "version": "0.20.3",
4
4
  "files": [
5
5
  "lib"
6
6
  ],
@@ -39,15 +39,15 @@
39
39
  "effect": "^4.0.5",
40
40
  "temporal-polyfill": "^0.3.0",
41
41
  "zod": "^4.4.3",
42
- "@party-stack/connect": "0.2.1",
42
+ "@party-stack/connect": "0.3.0",
43
43
  "@party-stack/foundry-client": "0.3.1",
44
- "@party-stack/foundry-object-set-watcher": "0.6.0",
44
+ "@party-stack/foundry-object-set-watcher": "0.6.1",
45
45
  "@party-stack/icons-blueprint": "0.2.1",
46
- "@party-stack/ontology": "0.22.0",
47
- "@party-stack/ontology-backend": "0.2.1",
48
- "@party-stack/ontology-spec": "0.3.0",
49
- "@party-stack/ontology-storage": "0.2.1",
50
- "@party-stack/runtime": "0.5.1"
46
+ "@party-stack/ontology": "0.22.2",
47
+ "@party-stack/ontology-backend": "0.2.2",
48
+ "@party-stack/ontology-spec": "0.3.1",
49
+ "@party-stack/ontology-storage": "0.2.2",
50
+ "@party-stack/runtime": "0.6.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@tanstack/db": "1.0.0-rc.1.4",