@spotto/semantic-query 1.0.70-alpha.38 → 1.0.70-alpha.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/evaluate.js CHANGED
@@ -1,587 +1,588 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evaluateSemanticQuery = exports.semanticPredicate = void 0;
4
- // Workspace Dependencies
5
- const contract_1 = require("@spotto/contract");
6
- // Project Dependencies
7
- const dates_1 = require("./dates");
8
- const resolve_name_1 = require("./resolve-name");
9
- const validate_1 = require("./validate");
10
- const SLOT = {
11
- STRING: 'valueString',
12
- INTEGER: 'valueInteger',
13
- DECIMAL: 'valueDecimal',
14
- BOOLEAN: 'valueBoolean',
15
- DATE: 'valueDate',
16
- };
17
- function get(doc, path) {
18
- return path.split('.').reduce((a, k) => (a == null ? undefined : a[k]), doc);
19
- }
20
- function cmp(actual, op, target) {
21
- if (actual === undefined || actual === null)
22
- return false;
23
- switch (op) {
24
- case 'eq':
25
- return actual === target;
26
- case 'ne':
27
- return actual !== target;
28
- case 'gt':
29
- return actual > target;
30
- case 'gte':
31
- return actual >= target;
32
- case 'lt':
33
- return actual < target;
34
- case 'lte':
35
- return actual <= target;
36
- default:
37
- return false;
38
- }
39
- }
40
- /**
41
- * The query as a predicate, with the context built ONCE. A caller that asks
42
- * the same question of many documents one at a time (the group rules module
43
- * on every row of a CSV export, or on every asset a list shows) goes through
44
- * this; `evaluateSemanticQuery` is the same thing over an array.
45
- */
46
- function semanticPredicate(query, schema, opts = {}) {
47
- var _a, _b, _c;
48
- const ctx = {
49
- schema,
50
- now: (_a = opts.now) !== null && _a !== void 0 ? _a : new Date(),
51
- tz: (_b = opts.timeZone) !== null && _b !== void 0 ? _b : 'UTC',
52
- fieldByName: new Map(schema.fields.map((f) => [f.name.toLowerCase(), f])),
53
- typeById: new Map(schema.types.map((t) => [t.id, t])),
54
- entityType: (_c = opts.entityType) !== null && _c !== void 0 ? _c : 'asset',
55
- };
56
- return (doc) => query.conditions.every((c) => match(doc, c, ctx));
57
- }
58
- exports.semanticPredicate = semanticPredicate;
59
- function evaluateSemanticQuery(query, docs, schema, opts = {}) {
60
- return docs.filter(semanticPredicate(query, schema, opts));
61
- }
62
- exports.evaluateSemanticQuery = evaluateSemanticQuery;
63
- /**
64
- * Grouping is shared — it is structure, not subject matter — and everything
65
- * else dispatches to the entity's own matcher, mirroring the Mongo compiler so
66
- * the two engines are organised the same way and can be read side by side.
67
- */
68
- function match(doc, cond, ctx) {
69
- if (cond.type === 'and')
70
- return cond.conditions.every((c) => match(doc, c, ctx));
71
- if (cond.type === 'or')
72
- return cond.conditions.some((c) => match(doc, c, ctx));
73
- if (ctx.entityType === 'location') {
74
- return matchLocation(doc, cond, ctx);
75
- }
76
- if (ctx.entityType === 'event') {
77
- return matchEvent(doc, cond, ctx);
78
- }
79
- if (ctx.entityType === 'snapshot') {
80
- return matchSnapshot(doc, cond, ctx);
81
- }
82
- if (ctx.entityType === 'reader') {
83
- return matchReader(doc, cond);
84
- }
85
- return matchAsset(doc, cond, ctx);
86
- }
87
- /**
88
- * Reads the SERVER event document. Events are never evaluated in the browser —
89
- * the client caches query RESULTS, not events, so there is no corpus to run
90
- * over. This matcher exists as the ORACLE: the acceptance property
91
- * `evaluate(q, docs) === find(compile(q))` is what catches an encoding mistake
92
- * in the Mongo compiler, and an entity with no second implementation has
93
- * nothing checking it but the person who wrote it.
94
- *
95
- * The three name-resolved words compare against the ids VALIDATION already
96
- * resolved, from the same catalogue the compiler uses — so the two engines
97
- * cannot disagree about who "Sarah" is.
98
- */
99
- function matchEvent(doc, cond, ctx) {
100
- var _a, _b, _c, _d, _e;
101
- switch (cond.type) {
102
- case 'occurred':
103
- return cmpTimestamp(get(doc, 'timestamp'), cond.operator, cond.value, ctx);
104
- case 'eventType':
105
- return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).includes(get(doc, 'type'));
106
- case 'assetType': {
107
- // BOTH halves, exactly as `action` below and exactly as the compiler:
108
- // `thing` is a full asset only on the CRUD events, so the type scope is
109
- // part of the condition rather than something a caller must remember.
110
- // Checked FIRST — a movement event has no `thing.typePath` at all, and
111
- // reading one would only ever produce a confusing miss.
112
- if (!contract_1.ASSET_CRUD_EVENT_TYPES.includes(String(get(doc, 'type')))) {
113
- return false;
114
- }
115
- const actual = String((_b = get(doc, 'thing.typePath')) !== null && _b !== void 0 ? _b : '');
116
- return cond.includeSubtypes !== false
117
- ? actual.startsWith(cond.path)
118
- : actual === cond.path;
119
- }
120
- case 'location': {
121
- // The stored pipe path, exactly as a location document keeps it — events
122
- // embed it under `location.name`.
123
- const actual = String((_c = get(doc, 'location.name')) !== null && _c !== void 0 ? _c : '');
124
- const path = cond.path; // optional on the type: the asset word also takes hasAny
125
- if (path === undefined)
126
- return false;
127
- return cond.includeSublocations !== false
128
- ? actual.startsWith(path)
129
- : actual === path;
130
- }
131
- case 'reader':
132
- return idIn(get(doc, 'reader._id'), resolvedIds(ctx.schema.readers, cond.name));
133
- case 'user':
134
- // A resolved user id inherently excludes system-generated events — Slate
135
- // movements carry no user at all, and must never answer "what did X do".
136
- return idIn(get(doc, 'user._id'), resolvedIds(ctx.schema.users, cond.name));
137
- case 'action': {
138
- // An action implies a submission, so both halves are checked — matching
139
- // the compiler, which constrains the type for the same reason.
140
- // Both submission types — see the compiler's note.
141
- if (!SUBMISSION_EVENT_TYPES.includes(String(get(doc, 'type'))))
142
- return false;
143
- // Resolve ONCE — resolving inside the predicate re-ran it per action.
144
- const ids = resolvedIds(ctx.schema.actions, cond.name);
145
- const names = ((_d = ctx.schema.actions) !== null && _d !== void 0 ? _d : [])
146
- .filter((a) => ids.includes(a.id))
147
- .map((a) => a.name);
148
- return names.includes(String((_e = get(doc, 'submission.actionName')) !== null && _e !== void 0 ? _e : ''));
149
- }
150
- default:
151
- // LOUD, not false. This function is the ORACLE the Mongo compiler is
152
- // checked against, and an oracle that silently matches nothing AGREES
153
- // with a compiler that returns nothing — so a word added to the
154
- // vocabulary and the compiler but forgotten here would let the
155
- // differential check pass by both engines being wrong together.
156
- throw new Error(`semantic-query evaluator has no arm for event condition ` +
157
- `'${cond.type}'`);
158
- }
159
- }
160
- /**
161
- * Reads the SERVER snapshot document.
162
- *
163
- * Unlike the event matcher, this one is NOT only an oracle — it is the
164
- * production path. Snapshots are cached whole and the list filters them in the
165
- * browser (`useSnapshotList` → `db.snapshots.toArray()`), so a mistake here is
166
- * a wrong answer a user sees, not a test that fails. The Mongo compiler still
167
- * has to agree with it for saved queries and widgets.
168
- *
169
- * Two arms below are not the obvious reading of the field, and both are
170
- * copied from the flat filter (`snapshots/filters.ts`) rather than invented,
171
- * because chip and query must return the same rows.
172
- */
173
- function matchSnapshot(doc, cond, ctx) {
174
- var _a, _b, _c;
175
- switch (cond.type) {
176
- case 'occurred':
177
- // `submitted`, not `created` — the flat time filter's field. It is
178
- // optional, so an unsubmitted snapshot matches no bound; `cmpTimestamp`
179
- // returns false for an absent value, which is the same answer the flat
180
- // filter's range gives.
181
- return cmpTimestamp(get(doc, 'submitted'), cond.operator, cond.value, ctx);
182
- case 'snapshotType': {
183
- const type = get(doc, 'type');
184
- const hasManifest = get(doc, 'manifest') != null;
185
- return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).some((wanted) => {
186
- const rule = contract_1.SNAPSHOT_TYPE_RULES[wanted];
187
- if (!rule)
188
- return false;
189
- if (type === rule.explicit)
190
- return true;
191
- // Legacy: no `type` at all, classified by the manifest's presence.
192
- // Without this arm every pre-`type` snapshot silently disappears from
193
- // a kind filter that the chip beside it still returns.
194
- return (type == null &&
195
- rule.legacyHasManifest !== undefined &&
196
- hasManifest === rule.legacyHasManifest);
197
- });
198
- }
199
- case 'asset':
200
- // The snapshot's SUBJECT asset, not its contents — see the contract.
201
- return idIn(get(doc, 'asset._id'), [cond.assetId]);
202
- case 'assetType': {
203
- const actual = String((_b = get(doc, 'asset.typePath')) !== null && _b !== void 0 ? _b : '');
204
- return cond.includeSubtypes !== false
205
- ? actual.startsWith(cond.path)
206
- : actual === cond.path;
207
- }
208
- case 'location': {
209
- // `location.path` here, NOT `location.name` as events use. Absent on
210
- // legacy snapshots, which therefore match no path condition — the same
211
- // acceptance record scope already makes (usergroups S7).
212
- const actual = String((_c = get(doc, 'location.path')) !== null && _c !== void 0 ? _c : '');
213
- const path = cond.path; // optional on the type: the asset word also takes hasAny
214
- if (!actual || path === undefined)
215
- return false;
216
- return cond.includeSublocations !== false
217
- ? actual.startsWith(path)
218
- : actual === path;
219
- }
220
- case 'manifest': {
221
- // Mirrors the compiler byte-for-byte: `satisfied` is an exact match on
222
- // the frozen `c_satisfiesManifest` annotation — a snapshot that never
223
- // stamped a verdict carries no flag and matches NEITHER polarity. Both
224
- // keys AND together when present; the validator guarantees at least
225
- // one, so reaching the end means every present key matched.
226
- if (cond.manifestId !== undefined &&
227
- !idIn(get(doc, 'manifest._id'), [cond.manifestId])) {
228
- return false;
229
- }
230
- if (cond.satisfied !== undefined &&
231
- get(doc, 'c_satisfiesManifest') !== cond.satisfied) {
232
- return false;
233
- }
234
- return true;
235
- }
236
- case 'user':
237
- return idIn(get(doc, 'user._id'), resolvedIds(ctx.schema.users, cond.name));
238
- case 'reader':
239
- return idIn(get(doc, 'reader._id'), resolvedIds(ctx.schema.readers, cond.name));
240
- default:
241
- // LOUD, for the reason the event matcher gives — and more so here, since
242
- // this arm running in the browser is what the user actually sees.
243
- throw new Error(`semantic-query evaluator has no arm for snapshot condition ` +
244
- `'${cond.type}'`);
245
- }
246
- }
247
- /**
248
- * Reads the SERVER reader document — and, like the snapshot matcher, this is
249
- * PRODUCTION code: `useReaderList` holds the whole set and the list filters it
250
- * in memory.
251
- *
252
- * No `ctx`: every reader condition is a plain field comparison. Nothing here
253
- * resolves a name or a date, which is the whole reason this vocabulary is the
254
- * least treacherous of the four.
255
- */
256
- function matchReader(doc, cond) {
257
- var _a, _b, _c;
258
- switch (cond.type) {
259
- case 'deviceType':
260
- return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).includes(get(doc, 'deviceType'));
261
- case 'readerType':
262
- return ((_b = cond.values) !== null && _b !== void 0 ? _b : []).includes(get(doc, 'type'));
263
- case 'location': {
264
- // `locationName` holds the FULL pipe path (`readers/helpers.ts` copies
265
- // `location.name`, which is a location document's path). A reader with
266
- // no location matches nothing rather than everything.
267
- const actual = String((_c = get(doc, 'locationName')) !== null && _c !== void 0 ? _c : '');
268
- const path = cond.path; // optional on the type: the asset word also takes hasAny
269
- if (!actual || path === undefined)
270
- return false;
271
- return cond.includeSublocations !== false
272
- ? actual.startsWith(path)
273
- : actual === path;
274
- }
275
- case 'attachedAsset':
276
- return idIn(get(doc, 'asset'), [cond.assetId]);
277
- case 'online':
278
- // Strict equality against the stored boolean. A reader that has never
279
- // reported has no `state` at all, so it is neither online nor offline —
280
- // `hasReported` is the word for that, and conflating the two is exactly
281
- // what the prototype did.
282
- return get(doc, 'state.online') === cond.value;
283
- case 'hasReported':
284
- // `state.onlineTransTime` is the marker the flat filter uses, not
285
- // `state` itself.
286
- return (get(doc, 'state.onlineTransTime') !== undefined) === cond.value;
287
- case 'hasGeolocation':
288
- return (get(doc, 'state.geolocation') != null) === cond.value;
289
- default:
290
- throw new Error(`semantic-query evaluator has no arm for reader condition ` +
291
- `'${cond.type}'`);
292
- }
293
- }
294
- /**
295
- * An event's ONE timestamp against a boundary. No `includeNeverSet` branch:
296
- * every event has a timestamp by construction, so there is no absent case to
297
- * decide a polarity for.
298
- */
299
- function cmpTimestamp(actual, operator, value, ctx) {
300
- if (actual === undefined || actual === null)
301
- return false;
302
- const ms = (0, dates_1.semanticDateBoundaryMs)(value, operator, ctx.now, ctx.tz);
303
- return cmp(actual, operator, ms);
304
- }
305
- /** The event types that carry `submission.actionName`. */
306
- const SUBMISSION_EVENT_TYPES = ['FormSubmitted', 'FormSubmissionVoided'];
307
- /** Ids a name resolves to; empty when it does not resolve (validation refused it first). */
308
- function resolvedIds(catalogue, name) {
309
- return (0, resolve_name_1.resolveName)(catalogue, name, { path: '', noun: '' }).ids;
310
- }
311
- function idIn(actual, ids) {
312
- // Case-insensitive: `String(ObjectId)` is lowercase hex, but a caller-built
313
- // catalogue may carry uppercase (the wire's own id check accepts either).
314
- // Comparing raw would make the ORACLE miss rows the compiler matches — and
315
- // an oracle that under-matches agrees with a broken compiler.
316
- if (actual == null)
317
- return false;
318
- const a = String(actual).toLowerCase();
319
- return ids.some((id) => id.toLowerCase() === a);
320
- }
321
- /**
322
- * Reads the SERVER document shape, as the asset matcher does — a client
323
- * caching parsed responses maps into it first (`evaluable-*`).
324
- *
325
- * Two words differ from their asset namesakes and both would fail silently:
326
- * the pipe path lives in `name` (a location document has no `path` field), and
327
- * `geolocation` is the CONFIGURED position at the top level, not the observed
328
- * `state.geolocation` an asset's condition reads.
329
- */
330
- function matchLocation(doc, cond, ctx) {
331
- var _a, _b;
332
- switch (cond.type) {
333
- case 'path':
334
- return prefixMatch(String((_a = get(doc, 'name')) !== null && _a !== void 0 ? _a : ''), cond.path, cond.includeSublocations !== false);
335
- case 'locationType':
336
- return ((_b = cond.values) !== null && _b !== void 0 ? _b : []).includes(get(doc, 'type'));
337
- case 'hasReaders': {
338
- const readers = get(doc, 'readers');
339
- return (Array.isArray(readers) && readers.length > 0) === cond.value;
340
- }
341
- case 'geofence': {
342
- // `!= null` is deliberate (missing OR explicit null), matching the
343
- // compiler's `{geofence: null}` partition exactly. `!== undefined` alone
344
- // would put a null geofence on the opposite side from Mongo.
345
- const v = get(doc, 'geofence');
346
- return cond.exists ? v != null : v == null;
347
- }
348
- case 'manifest': {
349
- const ids = get(doc, 'manifestIds');
350
- return Array.isArray(ids) && ids.some((id) => String(id) === cond.manifestId);
351
- }
352
- case 'geolocation': {
353
- const v = get(doc, 'geolocation');
354
- return cond.exists !== false ? v !== undefined : v === undefined;
355
- }
356
- case 'tags':
357
- return matchTags(doc, cond);
358
- // No lastSeen / firstSeen / telemetry — see the vocabulary in the contract.
359
- case 'createdDate':
360
- case 'lastUpdated':
361
- case 'lastChanged':
362
- return matchTimestamp(doc, cond, ctx);
363
- default:
364
- return false;
365
- }
366
- }
367
- function matchTags(doc, cond) {
368
- var _a, _b;
369
- const tags = ((_a = doc.tagIds) !== null && _a !== void 0 ? _a : []).map(String);
370
- const want = ((_b = cond.values) !== null && _b !== void 0 ? _b : []).map(String);
371
- return cond.operator === 'all'
372
- ? want.every((t) => tags.includes(t))
373
- : want.some((t) => tags.includes(t));
374
- }
375
- function matchAsset(doc, cond, ctx) {
376
- var _a, _b, _c, _d, _e;
377
- switch (cond.type) {
378
- case 'and':
379
- return cond.conditions.every((c) => match(doc, c, ctx));
380
- case 'or':
381
- return cond.conditions.some((c) => match(doc, c, ctx));
382
- case 'assetType':
383
- return prefixMatch(String((_a = get(doc, 'typePath')) !== null && _a !== void 0 ? _a : ''), cond.path, cond.includeSubtypes !== false);
384
- case 'location': {
385
- // Mirrors the compiler: `hasAny` reads the stored PATH, and "none" is
386
- // null or empty — the location tally reads an empty path as no path.
387
- const actual = String((_b = get(doc, 'state.locationName')) !== null && _b !== void 0 ? _b : '');
388
- if (cond.hasAny !== undefined)
389
- return (actual !== '') === cond.hasAny;
390
- const path = cond.path; // optional on the type: the asset word also takes hasAny
391
- if (path === undefined)
392
- return false;
393
- return prefixMatch(actual, path, cond.includeSublocations !== false);
394
- }
395
- case 'homeLocation': {
396
- const path = cond.path; // optional on the type: the asset word also takes hasAny
397
- if (path === undefined)
398
- return false;
399
- return prefixMatch(String((_c = get(doc, 'homeLocationPath')) !== null && _c !== void 0 ? _c : ''), path, cond.includeSublocations !== false);
400
- }
401
- case 'withAsset': {
402
- const v = get(doc, 'state.locationWithId');
403
- if (cond.hasAny !== undefined)
404
- return (v !== undefined && v !== null) === cond.hasAny;
405
- return v != null && String(v) === cond.assetId;
406
- }
407
- case 'geolocation': {
408
- const v = get(doc, 'state.geolocation');
409
- return cond.exists !== false ? v !== undefined : v === undefined;
410
- }
411
- case 'tags':
412
- return matchTags(doc, cond);
413
- case 'telemetry':
414
- return cmp(get(doc, `telemetry.${cond.field}`), cond.operator, cond.value);
415
- case 'readiness': {
416
- const levels = (_d = cond.levels) !== null && _d !== void 0 ? _d : (cond.level === undefined ? [] : [cond.level]);
417
- // Missing readiness ≡ green (0).
418
- const actual = get(doc, 'readiness.ready');
419
- const effective = typeof actual === 'number' ? actual : 0;
420
- return levels.includes(effective);
421
- }
422
- case 'kit': {
423
- if (cond.parentAssetId !== undefined) {
424
- const p = get(doc, 'groupParentId');
425
- return p != null && String(p) === cond.parentAssetId;
426
- }
427
- if (cond.isKit !== undefined)
428
- return (doc.typeKit === true) === cond.isKit;
429
- if (cond.isMember !== undefined)
430
- return (doc.groupMember === true) === cond.isMember;
431
- // The 4-state manifest-check status, mirroring the Mongo compile
432
- // exactly — `neverChecked` carries the same typeKit self-scope, and
433
- // every state requires `hasManifest` (a stored status outlives a
434
- // manifest detach as inert history; the gate keeps the filter agreeing
435
- // with the display).
436
- if (cond.manifest !== undefined) {
437
- if (doc.hasManifest !== true)
438
- return false;
439
- const status = doc.groupSatisfiesManifest;
440
- switch (cond.manifest) {
441
- case 'satisfied':
442
- return status === 0;
443
- case 'needsRecheck':
444
- return status === 1;
445
- case 'notSatisfied':
446
- return status === 2;
447
- case 'neverChecked':
448
- return doc.typeKit === true && status === undefined;
449
- }
450
- }
451
- // Legacy `satisfied` boolean over the 4-state `groupSatisfiesManifest`
452
- // (0 satisfied · 1 needs-recheck · 2 not satisfied · absent never
453
- // checked): true → 0, false → 2, exactly mirroring the Mongo compile —
454
- // including its `hasManifest` gate. Exact value matches — absent means
455
- // no manifest check has ever stamped the field, so it is neither
456
- // satisfied NOR unsatisfied.
457
- return (doc.hasManifest === true &&
458
- doc.groupSatisfiesManifest === (cond.satisfied ? 0 : 2));
459
- }
460
- case 'seenWithoutLocation': {
461
- // Mirrors the compiler: the stored path is null or empty, and the
462
- // status is one the location system only writes when it places the
463
- // asset (the enum minus NEVERSEEN). Read off the status, never the
464
- // state object — a kit's state holds only `supportsWith` and is never
465
- // seen.
466
- const path = String((_e = get(doc, 'state.locationName')) !== null && _e !== void 0 ? _e : '');
467
- const status = get(doc, 'state.locationStatus');
468
- const seen = typeof status === 'string' && contract_1.SEEN_LOCATION_STATUSES.includes(status);
469
- return (path === '' && seen) === cond.value;
470
- }
471
- case 'locationStatus': {
472
- const status = get(doc, 'state.locationStatus');
473
- if (typeof status === 'string' && cond.values.includes(status))
474
- return true;
475
- // NEVERSEEN also means "no status": no state at all, or a state the
476
- // location system wrote without ever locating the asset. Mirrors the
477
- // compiler's `$in [..., null]`, which matches a missing key either way.
478
- return cond.values.includes('NEVERSEEN') && (status === undefined || status === null);
479
- }
480
- case 'createdDate':
481
- case 'lastUpdated':
482
- case 'lastChanged':
483
- case 'lastSeen':
484
- case 'firstSeen':
485
- return matchTimestamp(doc, cond, ctx);
486
- case 'customField':
487
- return matchCustomField(doc, cond, ctx);
488
- default:
489
- return false;
490
- }
491
- }
492
- function prefixMatch(actual, path, includeDescendants) {
493
- return includeDescendants ? actual.startsWith(path) : actual === path;
494
- }
495
- const TIMESTAMP_FIELD = {
496
- lastUpdated: 'lastUpdated',
497
- lastChanged: 'lastChanged',
498
- lastSeen: 'state.lastSeen',
499
- firstSeen: 'state.firstSeen',
500
- };
501
- function matchTimestamp(doc, cond, ctx) {
502
- const ms = (0, dates_1.semanticDateBoundaryMs)(cond.value, cond.operator, ctx.now, ctx.tz);
503
- if (cond.type === 'createdDate') {
504
- // The ObjectId's first 4 bytes are the creation time in SECONDS. The
505
- // compiler steps `lte`/`gt` to the next second (a zero-tail boundary id
506
- // sorts before every real id in the same second); mirror that exactly,
507
- // or documents created within the boundary second classify differently.
508
- const created = parseInt(String(doc._id).slice(0, 8), 16);
509
- const second = Math.floor(ms / 1000);
510
- switch (cond.operator) {
511
- case 'gte':
512
- return created >= second;
513
- case 'lt':
514
- return created < second;
515
- case 'lte':
516
- return created < second + 1;
517
- default: // gt
518
- return created >= second + 1;
519
- }
520
- }
521
- const actual = get(doc, TIMESTAMP_FIELD[cond.type]);
522
- const neverSet = actual === undefined || actual === null;
523
- if (neverSet) {
524
- return ((cond.operator === 'lt' || cond.operator === 'lte') &&
525
- cond.includeNeverSet !== false);
526
- }
527
- return cmp(actual, cond.operator, ms);
528
- }
529
- // ---------------------------------------------------------------------------
530
- // Custom fields — mirror of the compiler's two-container conjunct
531
- // ---------------------------------------------------------------------------
532
- /**
533
- * Every value the field holds in this container.
534
- *
535
- * Matched by field `_id` ONLY — the compiler's `$elemMatch: {_id: …}` cannot
536
- * match a name — and ALL matching entries are returned, because `$elemMatch`
537
- * is existential: a duplicated field where one entry is null and another
538
- * holds the value must match, so inspecting only the first entry would
539
- * disagree with Mongo.
540
- */
541
- function valuesFor(entries, fdef, slot) {
542
- return (entries !== null && entries !== void 0 ? entries : [])
543
- .filter((e) => (e === null || e === void 0 ? void 0 : e._id) !== undefined && String(e._id) === fdef.id)
544
- .map((e) => e[slot]);
545
- }
546
- function isPresent(v) {
547
- return v !== undefined && v !== null && v !== '';
548
- }
549
- function matchCustomField(doc, cond, ctx) {
550
- var _a;
551
- const fdef = ctx.fieldByName.get(String(cond.fieldName).toLowerCase());
552
- if (!fdef)
553
- return false;
554
- const slot = SLOT[fdef.dataType];
555
- // The in-memory equivalent of the joinedType $lookup: the asset's own
556
- // fieldValues entries, and its type's inheritance-resolved entries.
557
- const type = ctx.typeById.get(String(doc.typeId));
558
- const values = [
559
- ...valuesFor(doc.fieldValues, fdef, slot),
560
- ...valuesFor(type === null || type === void 0 ? void 0 : type.typeFieldValuesAll, fdef, slot),
561
- ];
562
- const anyPresent = values.some(isPresent);
563
- switch (cond.operator) {
564
- case 'exists':
565
- return anyPresent;
566
- case 'notExists':
567
- return !anyPresent;
568
- case 'contains': {
569
- const term = String((_a = cond.value) !== null && _a !== void 0 ? _a : '').toLowerCase();
570
- return values.some((v) => isPresent(v) && String(v).toLowerCase().includes(term));
571
- }
572
- default:
573
- break;
574
- }
575
- // The SAME coercion the Mongo compiler applies — shared, not mirrored.
576
- // A numeric literal for a text field, or a relative date for a DATE field,
577
- // has to become one concrete value; two copies of this rule would classify
578
- // the same document differently.
579
- const target = (0, validate_1.coerceSemanticValue)(cond.value, fdef.dataType, ctx.now, ctx.tz);
580
- if (cond.operator === 'ne') {
581
- // Present-and-different at either level; default also counts fully unset.
582
- const strict = values.some((v) => isPresent(v) && v !== target);
583
- return cond.includeUnset === false ? strict : strict || !anyPresent;
584
- }
585
- return values.some((v) => cmp(v, cond.operator, target));
586
- }
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.evaluateSemanticQuery = exports.semanticPredicate = void 0;
4
+ // Workspace Dependencies
5
+ const contract_1 = require("@spotto/contract");
6
+ // Project Dependencies
7
+ const dates_1 = require("./dates");
8
+ const resolve_name_1 = require("./resolve-name");
9
+ const validate_1 = require("./validate");
10
+ const SLOT = {
11
+ STRING: 'valueString',
12
+ INTEGER: 'valueInteger',
13
+ DECIMAL: 'valueDecimal',
14
+ BOOLEAN: 'valueBoolean',
15
+ DATE: 'valueDate',
16
+ };
17
+ function get(doc, path) {
18
+ return path.split('.').reduce((a, k) => (a == null ? undefined : a[k]), doc);
19
+ }
20
+ function cmp(actual, op, target) {
21
+ if (actual === undefined || actual === null)
22
+ return false;
23
+ switch (op) {
24
+ case 'eq':
25
+ return actual === target;
26
+ case 'ne':
27
+ return actual !== target;
28
+ case 'gt':
29
+ return actual > target;
30
+ case 'gte':
31
+ return actual >= target;
32
+ case 'lt':
33
+ return actual < target;
34
+ case 'lte':
35
+ return actual <= target;
36
+ default:
37
+ return false;
38
+ }
39
+ }
40
+ /**
41
+ * The query as a predicate, with the context built ONCE. A caller that asks
42
+ * the same question of many documents one at a time (the group rules module
43
+ * on every row of a CSV export, or on every asset a list shows) goes through
44
+ * this; `evaluateSemanticQuery` is the same thing over an array.
45
+ */
46
+ function semanticPredicate(query, schema, opts = {}) {
47
+ var _a, _b, _c;
48
+ const ctx = {
49
+ schema,
50
+ now: (_a = opts.now) !== null && _a !== void 0 ? _a : new Date(),
51
+ tz: (_b = opts.timeZone) !== null && _b !== void 0 ? _b : 'UTC',
52
+ fieldByName: new Map(schema.fields.map((f) => [f.name.toLowerCase(), f])),
53
+ typeById: new Map(schema.types.map((t) => [t.id, t])),
54
+ entityType: (_c = opts.entityType) !== null && _c !== void 0 ? _c : 'asset',
55
+ };
56
+ return (doc) => query.conditions.every((c) => match(doc, c, ctx));
57
+ }
58
+ exports.semanticPredicate = semanticPredicate;
59
+ function evaluateSemanticQuery(query, docs, schema, opts = {}) {
60
+ return docs.filter(semanticPredicate(query, schema, opts));
61
+ }
62
+ exports.evaluateSemanticQuery = evaluateSemanticQuery;
63
+ /**
64
+ * Grouping is shared — it is structure, not subject matter — and everything
65
+ * else dispatches to the entity's own matcher, mirroring the Mongo compiler so
66
+ * the two engines are organised the same way and can be read side by side.
67
+ */
68
+ function match(doc, cond, ctx) {
69
+ if (cond.type === 'and')
70
+ return cond.conditions.every((c) => match(doc, c, ctx));
71
+ if (cond.type === 'or')
72
+ return cond.conditions.some((c) => match(doc, c, ctx));
73
+ if (ctx.entityType === 'location') {
74
+ return matchLocation(doc, cond, ctx);
75
+ }
76
+ if (ctx.entityType === 'event') {
77
+ return matchEvent(doc, cond, ctx);
78
+ }
79
+ if (ctx.entityType === 'snapshot') {
80
+ return matchSnapshot(doc, cond, ctx);
81
+ }
82
+ if (ctx.entityType === 'reader') {
83
+ return matchReader(doc, cond);
84
+ }
85
+ return matchAsset(doc, cond, ctx);
86
+ }
87
+ /**
88
+ * Reads the SERVER event document. Events are never evaluated in the browser —
89
+ * the client caches query RESULTS, not events, so there is no corpus to run
90
+ * over. This matcher exists as the ORACLE: the acceptance property
91
+ * `evaluate(q, docs) === find(compile(q))` is what catches an encoding mistake
92
+ * in the Mongo compiler, and an entity with no second implementation has
93
+ * nothing checking it but the person who wrote it.
94
+ *
95
+ * The three name-resolved words compare against the ids VALIDATION already
96
+ * resolved, from the same catalogue the compiler uses — so the two engines
97
+ * cannot disagree about who "Sarah" is.
98
+ */
99
+ function matchEvent(doc, cond, ctx) {
100
+ var _a, _b, _c, _d, _e;
101
+ switch (cond.type) {
102
+ case 'occurred':
103
+ return cmpTimestamp(get(doc, 'timestamp'), cond.operator, cond.value, ctx);
104
+ case 'eventType':
105
+ return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).includes(get(doc, 'type'));
106
+ case 'assetType': {
107
+ // BOTH halves, exactly as `action` below and exactly as the compiler:
108
+ // `thing` records a type path only on the CRUD events and the readiness
109
+ // transition, so the type scope is part of the condition rather than
110
+ // something a caller must remember. Checked FIRST — a movement event has
111
+ // no `thing.typePath` at all, and reading one would only ever produce a
112
+ // confusing miss.
113
+ if (!contract_1.TYPED_ASSET_EVENT_TYPES.includes(String(get(doc, 'type')))) {
114
+ return false;
115
+ }
116
+ const actual = String((_b = get(doc, 'thing.typePath')) !== null && _b !== void 0 ? _b : '');
117
+ return cond.includeSubtypes !== false
118
+ ? actual.startsWith(cond.path)
119
+ : actual === cond.path;
120
+ }
121
+ case 'location': {
122
+ // The stored pipe path, exactly as a location document keeps it — events
123
+ // embed it under `location.name`.
124
+ const actual = String((_c = get(doc, 'location.name')) !== null && _c !== void 0 ? _c : '');
125
+ const path = cond.path; // optional on the type: the asset word also takes hasAny
126
+ if (path === undefined)
127
+ return false;
128
+ return cond.includeSublocations !== false
129
+ ? actual.startsWith(path)
130
+ : actual === path;
131
+ }
132
+ case 'reader':
133
+ return idIn(get(doc, 'reader._id'), resolvedIds(ctx.schema.readers, cond.name));
134
+ case 'user':
135
+ // A resolved user id inherently excludes system-generated events — Slate
136
+ // movements carry no user at all, and must never answer "what did X do".
137
+ return idIn(get(doc, 'user._id'), resolvedIds(ctx.schema.users, cond.name));
138
+ case 'action': {
139
+ // An action implies a submission, so both halves are checked — matching
140
+ // the compiler, which constrains the type for the same reason.
141
+ // Both submission types — see the compiler's note.
142
+ if (!SUBMISSION_EVENT_TYPES.includes(String(get(doc, 'type'))))
143
+ return false;
144
+ // Resolve ONCE — resolving inside the predicate re-ran it per action.
145
+ const ids = resolvedIds(ctx.schema.actions, cond.name);
146
+ const names = ((_d = ctx.schema.actions) !== null && _d !== void 0 ? _d : [])
147
+ .filter((a) => ids.includes(a.id))
148
+ .map((a) => a.name);
149
+ return names.includes(String((_e = get(doc, 'submission.actionName')) !== null && _e !== void 0 ? _e : ''));
150
+ }
151
+ default:
152
+ // LOUD, not false. This function is the ORACLE the Mongo compiler is
153
+ // checked against, and an oracle that silently matches nothing AGREES
154
+ // with a compiler that returns nothing — so a word added to the
155
+ // vocabulary and the compiler but forgotten here would let the
156
+ // differential check pass by both engines being wrong together.
157
+ throw new Error(`semantic-query evaluator has no arm for event condition ` +
158
+ `'${cond.type}'`);
159
+ }
160
+ }
161
+ /**
162
+ * Reads the SERVER snapshot document.
163
+ *
164
+ * Unlike the event matcher, this one is NOT only an oracle — it is the
165
+ * production path. Snapshots are cached whole and the list filters them in the
166
+ * browser (`useSnapshotList` → `db.snapshots.toArray()`), so a mistake here is
167
+ * a wrong answer a user sees, not a test that fails. The Mongo compiler still
168
+ * has to agree with it for saved queries and widgets.
169
+ *
170
+ * Two arms below are not the obvious reading of the field, and both are
171
+ * copied from the flat filter (`snapshots/filters.ts`) rather than invented,
172
+ * because chip and query must return the same rows.
173
+ */
174
+ function matchSnapshot(doc, cond, ctx) {
175
+ var _a, _b, _c;
176
+ switch (cond.type) {
177
+ case 'occurred':
178
+ // `submitted`, not `created` — the flat time filter's field. It is
179
+ // optional, so an unsubmitted snapshot matches no bound; `cmpTimestamp`
180
+ // returns false for an absent value, which is the same answer the flat
181
+ // filter's range gives.
182
+ return cmpTimestamp(get(doc, 'submitted'), cond.operator, cond.value, ctx);
183
+ case 'snapshotType': {
184
+ const type = get(doc, 'type');
185
+ const hasManifest = get(doc, 'manifest') != null;
186
+ return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).some((wanted) => {
187
+ const rule = contract_1.SNAPSHOT_TYPE_RULES[wanted];
188
+ if (!rule)
189
+ return false;
190
+ if (type === rule.explicit)
191
+ return true;
192
+ // Legacy: no `type` at all, classified by the manifest's presence.
193
+ // Without this arm every pre-`type` snapshot silently disappears from
194
+ // a kind filter that the chip beside it still returns.
195
+ return (type == null &&
196
+ rule.legacyHasManifest !== undefined &&
197
+ hasManifest === rule.legacyHasManifest);
198
+ });
199
+ }
200
+ case 'asset':
201
+ // The snapshot's SUBJECT asset, not its contents — see the contract.
202
+ return idIn(get(doc, 'asset._id'), [cond.assetId]);
203
+ case 'assetType': {
204
+ const actual = String((_b = get(doc, 'asset.typePath')) !== null && _b !== void 0 ? _b : '');
205
+ return cond.includeSubtypes !== false
206
+ ? actual.startsWith(cond.path)
207
+ : actual === cond.path;
208
+ }
209
+ case 'location': {
210
+ // `location.path` here, NOT `location.name` as events use. Absent on
211
+ // legacy snapshots, which therefore match no path condition — the same
212
+ // acceptance record scope already makes (usergroups S7).
213
+ const actual = String((_c = get(doc, 'location.path')) !== null && _c !== void 0 ? _c : '');
214
+ const path = cond.path; // optional on the type: the asset word also takes hasAny
215
+ if (!actual || path === undefined)
216
+ return false;
217
+ return cond.includeSublocations !== false
218
+ ? actual.startsWith(path)
219
+ : actual === path;
220
+ }
221
+ case 'manifest': {
222
+ // Mirrors the compiler byte-for-byte: `satisfied` is an exact match on
223
+ // the frozen `c_satisfiesManifest` annotation — a snapshot that never
224
+ // stamped a verdict carries no flag and matches NEITHER polarity. Both
225
+ // keys AND together when present; the validator guarantees at least
226
+ // one, so reaching the end means every present key matched.
227
+ if (cond.manifestId !== undefined &&
228
+ !idIn(get(doc, 'manifest._id'), [cond.manifestId])) {
229
+ return false;
230
+ }
231
+ if (cond.satisfied !== undefined &&
232
+ get(doc, 'c_satisfiesManifest') !== cond.satisfied) {
233
+ return false;
234
+ }
235
+ return true;
236
+ }
237
+ case 'user':
238
+ return idIn(get(doc, 'user._id'), resolvedIds(ctx.schema.users, cond.name));
239
+ case 'reader':
240
+ return idIn(get(doc, 'reader._id'), resolvedIds(ctx.schema.readers, cond.name));
241
+ default:
242
+ // LOUD, for the reason the event matcher gives — and more so here, since
243
+ // this arm running in the browser is what the user actually sees.
244
+ throw new Error(`semantic-query evaluator has no arm for snapshot condition ` +
245
+ `'${cond.type}'`);
246
+ }
247
+ }
248
+ /**
249
+ * Reads the SERVER reader document — and, like the snapshot matcher, this is
250
+ * PRODUCTION code: `useReaderList` holds the whole set and the list filters it
251
+ * in memory.
252
+ *
253
+ * No `ctx`: every reader condition is a plain field comparison. Nothing here
254
+ * resolves a name or a date, which is the whole reason this vocabulary is the
255
+ * least treacherous of the four.
256
+ */
257
+ function matchReader(doc, cond) {
258
+ var _a, _b, _c;
259
+ switch (cond.type) {
260
+ case 'deviceType':
261
+ return ((_a = cond.values) !== null && _a !== void 0 ? _a : []).includes(get(doc, 'deviceType'));
262
+ case 'readerType':
263
+ return ((_b = cond.values) !== null && _b !== void 0 ? _b : []).includes(get(doc, 'type'));
264
+ case 'location': {
265
+ // `locationName` holds the FULL pipe path (`readers/helpers.ts` copies
266
+ // `location.name`, which is a location document's path). A reader with
267
+ // no location matches nothing rather than everything.
268
+ const actual = String((_c = get(doc, 'locationName')) !== null && _c !== void 0 ? _c : '');
269
+ const path = cond.path; // optional on the type: the asset word also takes hasAny
270
+ if (!actual || path === undefined)
271
+ return false;
272
+ return cond.includeSublocations !== false
273
+ ? actual.startsWith(path)
274
+ : actual === path;
275
+ }
276
+ case 'attachedAsset':
277
+ return idIn(get(doc, 'asset'), [cond.assetId]);
278
+ case 'online':
279
+ // Strict equality against the stored boolean. A reader that has never
280
+ // reported has no `state` at all, so it is neither online nor offline —
281
+ // `hasReported` is the word for that, and conflating the two is exactly
282
+ // what the prototype did.
283
+ return get(doc, 'state.online') === cond.value;
284
+ case 'hasReported':
285
+ // `state.onlineTransTime` is the marker the flat filter uses, not
286
+ // `state` itself.
287
+ return (get(doc, 'state.onlineTransTime') !== undefined) === cond.value;
288
+ case 'hasGeolocation':
289
+ return (get(doc, 'state.geolocation') != null) === cond.value;
290
+ default:
291
+ throw new Error(`semantic-query evaluator has no arm for reader condition ` +
292
+ `'${cond.type}'`);
293
+ }
294
+ }
295
+ /**
296
+ * An event's ONE timestamp against a boundary. No `includeNeverSet` branch:
297
+ * every event has a timestamp by construction, so there is no absent case to
298
+ * decide a polarity for.
299
+ */
300
+ function cmpTimestamp(actual, operator, value, ctx) {
301
+ if (actual === undefined || actual === null)
302
+ return false;
303
+ const ms = (0, dates_1.semanticDateBoundaryMs)(value, operator, ctx.now, ctx.tz);
304
+ return cmp(actual, operator, ms);
305
+ }
306
+ /** The event types that carry `submission.actionName`. */
307
+ const SUBMISSION_EVENT_TYPES = ['FormSubmitted', 'FormSubmissionVoided'];
308
+ /** Ids a name resolves to; empty when it does not resolve (validation refused it first). */
309
+ function resolvedIds(catalogue, name) {
310
+ return (0, resolve_name_1.resolveName)(catalogue, name, { path: '', noun: '' }).ids;
311
+ }
312
+ function idIn(actual, ids) {
313
+ // Case-insensitive: `String(ObjectId)` is lowercase hex, but a caller-built
314
+ // catalogue may carry uppercase (the wire's own id check accepts either).
315
+ // Comparing raw would make the ORACLE miss rows the compiler matches — and
316
+ // an oracle that under-matches agrees with a broken compiler.
317
+ if (actual == null)
318
+ return false;
319
+ const a = String(actual).toLowerCase();
320
+ return ids.some((id) => id.toLowerCase() === a);
321
+ }
322
+ /**
323
+ * Reads the SERVER document shape, as the asset matcher does — a client
324
+ * caching parsed responses maps into it first (`evaluable-*`).
325
+ *
326
+ * Two words differ from their asset namesakes and both would fail silently:
327
+ * the pipe path lives in `name` (a location document has no `path` field), and
328
+ * `geolocation` is the CONFIGURED position at the top level, not the observed
329
+ * `state.geolocation` an asset's condition reads.
330
+ */
331
+ function matchLocation(doc, cond, ctx) {
332
+ var _a, _b;
333
+ switch (cond.type) {
334
+ case 'path':
335
+ return prefixMatch(String((_a = get(doc, 'name')) !== null && _a !== void 0 ? _a : ''), cond.path, cond.includeSublocations !== false);
336
+ case 'locationType':
337
+ return ((_b = cond.values) !== null && _b !== void 0 ? _b : []).includes(get(doc, 'type'));
338
+ case 'hasReaders': {
339
+ const readers = get(doc, 'readers');
340
+ return (Array.isArray(readers) && readers.length > 0) === cond.value;
341
+ }
342
+ case 'geofence': {
343
+ // `!= null` is deliberate (missing OR explicit null), matching the
344
+ // compiler's `{geofence: null}` partition exactly. `!== undefined` alone
345
+ // would put a null geofence on the opposite side from Mongo.
346
+ const v = get(doc, 'geofence');
347
+ return cond.exists ? v != null : v == null;
348
+ }
349
+ case 'manifest': {
350
+ const ids = get(doc, 'manifestIds');
351
+ return Array.isArray(ids) && ids.some((id) => String(id) === cond.manifestId);
352
+ }
353
+ case 'geolocation': {
354
+ const v = get(doc, 'geolocation');
355
+ return cond.exists !== false ? v !== undefined : v === undefined;
356
+ }
357
+ case 'tags':
358
+ return matchTags(doc, cond);
359
+ // No lastSeen / firstSeen / telemetry — see the vocabulary in the contract.
360
+ case 'createdDate':
361
+ case 'lastUpdated':
362
+ case 'lastChanged':
363
+ return matchTimestamp(doc, cond, ctx);
364
+ default:
365
+ return false;
366
+ }
367
+ }
368
+ function matchTags(doc, cond) {
369
+ var _a, _b;
370
+ const tags = ((_a = doc.tagIds) !== null && _a !== void 0 ? _a : []).map(String);
371
+ const want = ((_b = cond.values) !== null && _b !== void 0 ? _b : []).map(String);
372
+ return cond.operator === 'all'
373
+ ? want.every((t) => tags.includes(t))
374
+ : want.some((t) => tags.includes(t));
375
+ }
376
+ function matchAsset(doc, cond, ctx) {
377
+ var _a, _b, _c, _d, _e;
378
+ switch (cond.type) {
379
+ case 'and':
380
+ return cond.conditions.every((c) => match(doc, c, ctx));
381
+ case 'or':
382
+ return cond.conditions.some((c) => match(doc, c, ctx));
383
+ case 'assetType':
384
+ return prefixMatch(String((_a = get(doc, 'typePath')) !== null && _a !== void 0 ? _a : ''), cond.path, cond.includeSubtypes !== false);
385
+ case 'location': {
386
+ // Mirrors the compiler: `hasAny` reads the stored PATH, and "none" is
387
+ // null or empty — the location tally reads an empty path as no path.
388
+ const actual = String((_b = get(doc, 'state.locationName')) !== null && _b !== void 0 ? _b : '');
389
+ if (cond.hasAny !== undefined)
390
+ return (actual !== '') === cond.hasAny;
391
+ const path = cond.path; // optional on the type: the asset word also takes hasAny
392
+ if (path === undefined)
393
+ return false;
394
+ return prefixMatch(actual, path, cond.includeSublocations !== false);
395
+ }
396
+ case 'homeLocation': {
397
+ const path = cond.path; // optional on the type: the asset word also takes hasAny
398
+ if (path === undefined)
399
+ return false;
400
+ return prefixMatch(String((_c = get(doc, 'homeLocationPath')) !== null && _c !== void 0 ? _c : ''), path, cond.includeSublocations !== false);
401
+ }
402
+ case 'withAsset': {
403
+ const v = get(doc, 'state.locationWithId');
404
+ if (cond.hasAny !== undefined)
405
+ return (v !== undefined && v !== null) === cond.hasAny;
406
+ return v != null && String(v) === cond.assetId;
407
+ }
408
+ case 'geolocation': {
409
+ const v = get(doc, 'state.geolocation');
410
+ return cond.exists !== false ? v !== undefined : v === undefined;
411
+ }
412
+ case 'tags':
413
+ return matchTags(doc, cond);
414
+ case 'telemetry':
415
+ return cmp(get(doc, `telemetry.${cond.field}`), cond.operator, cond.value);
416
+ case 'readiness': {
417
+ const levels = (_d = cond.levels) !== null && _d !== void 0 ? _d : (cond.level === undefined ? [] : [cond.level]);
418
+ // Missing readiness ≡ green (0).
419
+ const actual = get(doc, 'readiness.ready');
420
+ const effective = typeof actual === 'number' ? actual : 0;
421
+ return levels.includes(effective);
422
+ }
423
+ case 'kit': {
424
+ if (cond.parentAssetId !== undefined) {
425
+ const p = get(doc, 'groupParentId');
426
+ return p != null && String(p) === cond.parentAssetId;
427
+ }
428
+ if (cond.isKit !== undefined)
429
+ return (doc.typeKit === true) === cond.isKit;
430
+ if (cond.isMember !== undefined)
431
+ return (doc.groupMember === true) === cond.isMember;
432
+ // The 4-state manifest-check status, mirroring the Mongo compile
433
+ // exactly — `neverChecked` carries the same typeKit self-scope, and
434
+ // every state requires `hasManifest` (a stored status outlives a
435
+ // manifest detach as inert history; the gate keeps the filter agreeing
436
+ // with the display).
437
+ if (cond.manifest !== undefined) {
438
+ if (doc.hasManifest !== true)
439
+ return false;
440
+ const status = doc.groupSatisfiesManifest;
441
+ switch (cond.manifest) {
442
+ case 'satisfied':
443
+ return status === 0;
444
+ case 'needsRecheck':
445
+ return status === 1;
446
+ case 'notSatisfied':
447
+ return status === 2;
448
+ case 'neverChecked':
449
+ return doc.typeKit === true && status === undefined;
450
+ }
451
+ }
452
+ // Legacy `satisfied` boolean over the 4-state `groupSatisfiesManifest`
453
+ // (0 satisfied · 1 needs-recheck · 2 not satisfied · absent never
454
+ // checked): true → 0, false → 2, exactly mirroring the Mongo compile —
455
+ // including its `hasManifest` gate. Exact value matches — absent means
456
+ // no manifest check has ever stamped the field, so it is neither
457
+ // satisfied NOR unsatisfied.
458
+ return (doc.hasManifest === true &&
459
+ doc.groupSatisfiesManifest === (cond.satisfied ? 0 : 2));
460
+ }
461
+ case 'seenWithoutLocation': {
462
+ // Mirrors the compiler: the stored path is null or empty, and the
463
+ // status is one the location system only writes when it places the
464
+ // asset (the enum minus NEVERSEEN). Read off the status, never the
465
+ // state object — a kit's state holds only `supportsWith` and is never
466
+ // seen.
467
+ const path = String((_e = get(doc, 'state.locationName')) !== null && _e !== void 0 ? _e : '');
468
+ const status = get(doc, 'state.locationStatus');
469
+ const seen = typeof status === 'string' && contract_1.SEEN_LOCATION_STATUSES.includes(status);
470
+ return (path === '' && seen) === cond.value;
471
+ }
472
+ case 'locationStatus': {
473
+ const status = get(doc, 'state.locationStatus');
474
+ if (typeof status === 'string' && cond.values.includes(status))
475
+ return true;
476
+ // NEVERSEEN also means "no status": no state at all, or a state the
477
+ // location system wrote without ever locating the asset. Mirrors the
478
+ // compiler's `$in [..., null]`, which matches a missing key either way.
479
+ return cond.values.includes('NEVERSEEN') && (status === undefined || status === null);
480
+ }
481
+ case 'createdDate':
482
+ case 'lastUpdated':
483
+ case 'lastChanged':
484
+ case 'lastSeen':
485
+ case 'firstSeen':
486
+ return matchTimestamp(doc, cond, ctx);
487
+ case 'customField':
488
+ return matchCustomField(doc, cond, ctx);
489
+ default:
490
+ return false;
491
+ }
492
+ }
493
+ function prefixMatch(actual, path, includeDescendants) {
494
+ return includeDescendants ? actual.startsWith(path) : actual === path;
495
+ }
496
+ const TIMESTAMP_FIELD = {
497
+ lastUpdated: 'lastUpdated',
498
+ lastChanged: 'lastChanged',
499
+ lastSeen: 'state.lastSeen',
500
+ firstSeen: 'state.firstSeen',
501
+ };
502
+ function matchTimestamp(doc, cond, ctx) {
503
+ const ms = (0, dates_1.semanticDateBoundaryMs)(cond.value, cond.operator, ctx.now, ctx.tz);
504
+ if (cond.type === 'createdDate') {
505
+ // The ObjectId's first 4 bytes are the creation time in SECONDS. The
506
+ // compiler steps `lte`/`gt` to the next second (a zero-tail boundary id
507
+ // sorts before every real id in the same second); mirror that exactly,
508
+ // or documents created within the boundary second classify differently.
509
+ const created = parseInt(String(doc._id).slice(0, 8), 16);
510
+ const second = Math.floor(ms / 1000);
511
+ switch (cond.operator) {
512
+ case 'gte':
513
+ return created >= second;
514
+ case 'lt':
515
+ return created < second;
516
+ case 'lte':
517
+ return created < second + 1;
518
+ default: // gt
519
+ return created >= second + 1;
520
+ }
521
+ }
522
+ const actual = get(doc, TIMESTAMP_FIELD[cond.type]);
523
+ const neverSet = actual === undefined || actual === null;
524
+ if (neverSet) {
525
+ return ((cond.operator === 'lt' || cond.operator === 'lte') &&
526
+ cond.includeNeverSet !== false);
527
+ }
528
+ return cmp(actual, cond.operator, ms);
529
+ }
530
+ // ---------------------------------------------------------------------------
531
+ // Custom fields — mirror of the compiler's two-container conjunct
532
+ // ---------------------------------------------------------------------------
533
+ /**
534
+ * Every value the field holds in this container.
535
+ *
536
+ * Matched by field `_id` ONLY — the compiler's `$elemMatch: {_id: …}` cannot
537
+ * match a name — and ALL matching entries are returned, because `$elemMatch`
538
+ * is existential: a duplicated field where one entry is null and another
539
+ * holds the value must match, so inspecting only the first entry would
540
+ * disagree with Mongo.
541
+ */
542
+ function valuesFor(entries, fdef, slot) {
543
+ return (entries !== null && entries !== void 0 ? entries : [])
544
+ .filter((e) => (e === null || e === void 0 ? void 0 : e._id) !== undefined && String(e._id) === fdef.id)
545
+ .map((e) => e[slot]);
546
+ }
547
+ function isPresent(v) {
548
+ return v !== undefined && v !== null && v !== '';
549
+ }
550
+ function matchCustomField(doc, cond, ctx) {
551
+ var _a;
552
+ const fdef = ctx.fieldByName.get(String(cond.fieldName).toLowerCase());
553
+ if (!fdef)
554
+ return false;
555
+ const slot = SLOT[fdef.dataType];
556
+ // The in-memory equivalent of the joinedType $lookup: the asset's own
557
+ // fieldValues entries, and its type's inheritance-resolved entries.
558
+ const type = ctx.typeById.get(String(doc.typeId));
559
+ const values = [
560
+ ...valuesFor(doc.fieldValues, fdef, slot),
561
+ ...valuesFor(type === null || type === void 0 ? void 0 : type.typeFieldValuesAll, fdef, slot),
562
+ ];
563
+ const anyPresent = values.some(isPresent);
564
+ switch (cond.operator) {
565
+ case 'exists':
566
+ return anyPresent;
567
+ case 'notExists':
568
+ return !anyPresent;
569
+ case 'contains': {
570
+ const term = String((_a = cond.value) !== null && _a !== void 0 ? _a : '').toLowerCase();
571
+ return values.some((v) => isPresent(v) && String(v).toLowerCase().includes(term));
572
+ }
573
+ default:
574
+ break;
575
+ }
576
+ // The SAME coercion the Mongo compiler applies — shared, not mirrored.
577
+ // A numeric literal for a text field, or a relative date for a DATE field,
578
+ // has to become one concrete value; two copies of this rule would classify
579
+ // the same document differently.
580
+ const target = (0, validate_1.coerceSemanticValue)(cond.value, fdef.dataType, ctx.now, ctx.tz);
581
+ if (cond.operator === 'ne') {
582
+ // Present-and-different at either level; default also counts fully unset.
583
+ const strict = values.some((v) => isPresent(v) && v !== target);
584
+ return cond.includeUnset === false ? strict : strict || !anyPresent;
585
+ }
586
+ return values.some((v) => cmp(v, cond.operator, target));
587
+ }
587
588
  //# sourceMappingURL=evaluate.js.map