@spacelr/sdk 0.10.10 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +94 -6
- package/dist/index.d.ts +94 -6
- package/dist/index.js +457 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +457 -24
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -171,17 +171,27 @@ var HttpClient = class {
|
|
|
171
171
|
* caller should retry with a refreshed token. 403 is never routed here —
|
|
172
172
|
* it means "forbidden for this action" and must not trigger logout.
|
|
173
173
|
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
174
|
+
* Auth-loss ownership (#759 review):
|
|
175
|
+
* - When a refresh WAS possible (a refresh token existed), `doRefresh` owns
|
|
176
|
+
* the outcome: it clears + emits on a server-confirmed rejection, and stays
|
|
177
|
+
* silent on a transient transport failure. We must not second-guess it, so
|
|
178
|
+
* we do NOT emit here — that avoids a double clear/emit and stops a transient
|
|
179
|
+
* blip during a 401 retry from ejecting the user.
|
|
180
|
+
* - When no refresh was possible (no refresh token), this 401 IS the confirmed
|
|
181
|
+
* loss and we own it: `notifyAuthLost` clears the dead session then emits.
|
|
182
|
+
* The single clear always runs before any listener, so a listener that
|
|
183
|
+
* re-logs-in via `setTokens()` can never have its fresh session erased.
|
|
176
184
|
*/
|
|
177
185
|
async recoverFromAuthFailure(isRetry) {
|
|
178
186
|
if (isRetry) {
|
|
179
|
-
this.tokenManager.
|
|
187
|
+
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
180
188
|
return false;
|
|
181
189
|
}
|
|
190
|
+
const hadRefreshToken = await this.tokenManager.hasRefreshToken();
|
|
182
191
|
const refreshed = await this.tokenManager.forceRefresh();
|
|
183
192
|
if (refreshed) return true;
|
|
184
|
-
|
|
193
|
+
if (hadRefreshToken) return false;
|
|
194
|
+
await this.tokenManager.notifyAuthLost("unauthorized");
|
|
185
195
|
return false;
|
|
186
196
|
}
|
|
187
197
|
async uploadFormOnce(url, headers, formData, timeoutMs) {
|
|
@@ -413,6 +423,11 @@ var TokenManager = class {
|
|
|
413
423
|
// that hits `/auth/logout` with a dead token) don't re-emit and loop.
|
|
414
424
|
// Cleared by setTokens() / clearTokens() to re-arm for the next session.
|
|
415
425
|
this.authLostEmitted = false;
|
|
426
|
+
// The in-flight auth-loss storage wipe, if any. `setTokens` awaits it before
|
|
427
|
+
// writing so a re-login that lands DURING the wipe (e.g. an external
|
|
428
|
+
// auth-components bridge calling setTokens concurrently with a background
|
|
429
|
+
// refresh failure) is applied AFTER the wipe and never erased (#759 review).
|
|
430
|
+
this.pendingClear = null;
|
|
416
431
|
this.storage = storage ?? new MemoryTokenStorage();
|
|
417
432
|
this.refreshBufferSeconds = refreshBufferSeconds;
|
|
418
433
|
this.refreshLockName = refreshLockName;
|
|
@@ -434,6 +449,7 @@ var TokenManager = class {
|
|
|
434
449
|
return tokens.accessToken;
|
|
435
450
|
}
|
|
436
451
|
async setTokens(tokens) {
|
|
452
|
+
if (this.pendingClear) await this.pendingClear;
|
|
437
453
|
const needsDefault = tokens.expiresAt === void 0 && !!tokens.refreshToken;
|
|
438
454
|
const normalised = needsDefault ? { ...tokens, expiresAt: Math.floor(Date.now() / 1e3) } : tokens;
|
|
439
455
|
await this.storage.setTokens(normalised);
|
|
@@ -466,6 +482,16 @@ var TokenManager = class {
|
|
|
466
482
|
const refreshed = await this.tryRefresh(tokens);
|
|
467
483
|
return refreshed?.accessToken ?? null;
|
|
468
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* Whether the stored session currently carries a refresh token. Used by the
|
|
487
|
+
* 401-recovery path to decide whether a refresh was even possible, so it can
|
|
488
|
+
* let `doRefresh` own the auth-loss classification instead of second-guessing
|
|
489
|
+
* it. A rejecting storage backend reads as "no refresh token".
|
|
490
|
+
*/
|
|
491
|
+
async hasRefreshToken() {
|
|
492
|
+
const tokens = await this.safeGetTokens();
|
|
493
|
+
return !!tokens?.refreshToken;
|
|
494
|
+
}
|
|
469
495
|
onTokenRefreshed(listener) {
|
|
470
496
|
this.tokenRefreshedListeners.add(listener);
|
|
471
497
|
return () => this.tokenRefreshedListeners.delete(listener);
|
|
@@ -477,6 +503,9 @@ var TokenManager = class {
|
|
|
477
503
|
emitAuthLost(reason) {
|
|
478
504
|
if (this.authLostEmitted) return;
|
|
479
505
|
this.authLostEmitted = true;
|
|
506
|
+
this.dispatchAuthLost(reason);
|
|
507
|
+
}
|
|
508
|
+
dispatchAuthLost(reason) {
|
|
480
509
|
for (const listener of this.authLostListeners) {
|
|
481
510
|
try {
|
|
482
511
|
listener(reason);
|
|
@@ -484,6 +513,57 @@ var TokenManager = class {
|
|
|
484
513
|
}
|
|
485
514
|
}
|
|
486
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Handle a server-confirmed auth loss: drop the dead session, THEN notify.
|
|
518
|
+
*
|
|
519
|
+
* The stored tokens are cleared **before** listeners run (#759) so that a
|
|
520
|
+
* reload lands on the login screen and `hasStoredSession()` reads false — and,
|
|
521
|
+
* critically, so a listener that re-logs-in via `setTokens()` (synchronously
|
|
522
|
+
* OR after an await) writes its new session strictly AFTER the clear and can
|
|
523
|
+
* never be erased by it. The clear is a storage-only wipe: we do NOT reset
|
|
524
|
+
* `authLostEmitted` (as `clearTokens()` would), so the emit stays deduped for
|
|
525
|
+
* this lost session. A rejecting storage backend is swallowed — best-effort,
|
|
526
|
+
* the consumer is routed to logout regardless. `refreshPromise` is left to
|
|
527
|
+
* `doRefresh`'s own `finally`; nulling it here could clobber a newer in-flight
|
|
528
|
+
* refresh.
|
|
529
|
+
*
|
|
530
|
+
* The token-clearing auth-loss path. Called from `doRefresh` (single-flighted
|
|
531
|
+
* via `refreshPromise`) on a server-confirmed refresh rejection, and from
|
|
532
|
+
* `HttpClient` only when a 401 could not be refreshed AND no refresh was even
|
|
533
|
+
* attempted (no refresh token) — these are mutually exclusive, so there is
|
|
534
|
+
* exactly one clear per loss and it runs BEFORE any listener. A re-login a
|
|
535
|
+
* listener performs is therefore never erased.
|
|
536
|
+
*/
|
|
537
|
+
async notifyAuthLost(reason) {
|
|
538
|
+
if (this.authLostEmitted) return;
|
|
539
|
+
this.authLostEmitted = true;
|
|
540
|
+
this.pendingClear = this.storage.clearTokens().catch(() => {
|
|
541
|
+
});
|
|
542
|
+
await this.pendingClear;
|
|
543
|
+
this.pendingClear = null;
|
|
544
|
+
this.dispatchAuthLost(reason);
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* A refresh failure that is transient (retryable), not a server-confirmed auth
|
|
548
|
+
* loss — so it must NOT eject a local-first app; the next request retries.
|
|
549
|
+
* Covers:
|
|
550
|
+
* - a transport failure (offline, tunnel, captive portal, unreachable
|
|
551
|
+
* gateway) surfaced as `SpacelrNetworkError`/`SpacelrTimeoutError` (#759);
|
|
552
|
+
* - a 5xx server response — e.g. a 503 the gateway returns when oauth-service
|
|
553
|
+
* is momentarily down (#760/#762) — which is retryable infrastructure, not
|
|
554
|
+
* a token rejection.
|
|
555
|
+
* A real auth rejection (401/invalid_grant) or any other non-5xx server error
|
|
556
|
+
* is NOT transient and is treated as a server-confirmed loss.
|
|
557
|
+
*/
|
|
558
|
+
isTransientTransportError(error) {
|
|
559
|
+
if (error instanceof SpacelrNetworkError || error instanceof SpacelrTimeoutError) {
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
if (error instanceof SpacelrError && typeof error.statusCode === "number") {
|
|
563
|
+
return error.statusCode >= 500 && error.statusCode <= 599;
|
|
564
|
+
}
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
487
567
|
isTokenExpired(tokens) {
|
|
488
568
|
if (!tokens.expiresAt) return false;
|
|
489
569
|
return Date.now() >= tokens.expiresAt * 1e3;
|
|
@@ -522,15 +602,18 @@ var TokenManager = class {
|
|
|
522
602
|
return current;
|
|
523
603
|
}
|
|
524
604
|
const activeRefreshToken = current?.refreshToken || refreshToken;
|
|
605
|
+
let newTokens;
|
|
525
606
|
try {
|
|
526
|
-
|
|
527
|
-
await this.storage.setTokens(newTokens);
|
|
528
|
-
this.emitTokenRefreshed(newTokens);
|
|
529
|
-
return newTokens;
|
|
607
|
+
newTokens = await callback(activeRefreshToken);
|
|
530
608
|
} catch (error) {
|
|
531
|
-
this.
|
|
609
|
+
if (!this.isTransientTransportError(error)) {
|
|
610
|
+
await this.notifyAuthLost("refresh-failed");
|
|
611
|
+
}
|
|
532
612
|
throw error;
|
|
533
613
|
}
|
|
614
|
+
await this.storage.setTokens(newTokens);
|
|
615
|
+
this.emitTokenRefreshed(newTokens);
|
|
616
|
+
return newTokens;
|
|
534
617
|
}
|
|
535
618
|
async safeGetTokens() {
|
|
536
619
|
try {
|
|
@@ -684,6 +767,33 @@ function whereValueMatches(actual, expected) {
|
|
|
684
767
|
if (Array.isArray(actual)) return actual.includes(expected);
|
|
685
768
|
return actual === expected;
|
|
686
769
|
}
|
|
770
|
+
var TYPED_EQUALITY_MAX_COMPARAND_LENGTH = 64;
|
|
771
|
+
var TYPED_EQUALITY_RFC3339_WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
772
|
+
var TYPED_EQUALITY_OBJECT_ID_HEX = /^[0-9a-f]{24}$/i;
|
|
773
|
+
var NEVER_TYPED_FIELD = "_id";
|
|
774
|
+
function resolveFieldTypeTag(t, key) {
|
|
775
|
+
if (key === NEVER_TYPED_FIELD) return void 0;
|
|
776
|
+
if (!t || t.incomplete) return void 0;
|
|
777
|
+
const tag = t.fields?.[key];
|
|
778
|
+
return tag === "date" || tag === "objectId" ? tag : void 0;
|
|
779
|
+
}
|
|
780
|
+
function whereValueMatchesTyped(actual, expected, fieldType) {
|
|
781
|
+
if (fieldType === "date" && typeof actual === "string" && typeof expected === "string") {
|
|
782
|
+
if (actual.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && expected.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && TYPED_EQUALITY_RFC3339_WITH_OFFSET.test(actual) && TYPED_EQUALITY_RFC3339_WITH_OFFSET.test(expected)) {
|
|
783
|
+
const a = Date.parse(actual);
|
|
784
|
+
const e = Date.parse(expected);
|
|
785
|
+
if (!Number.isNaN(a) && !Number.isNaN(e)) return a === e;
|
|
786
|
+
}
|
|
787
|
+
return whereValueMatches(actual, expected);
|
|
788
|
+
}
|
|
789
|
+
if (fieldType === "objectId" && typeof actual === "string" && typeof expected === "string") {
|
|
790
|
+
if (actual.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && expected.length <= TYPED_EQUALITY_MAX_COMPARAND_LENGTH && TYPED_EQUALITY_OBJECT_ID_HEX.test(actual) && TYPED_EQUALITY_OBJECT_ID_HEX.test(expected)) {
|
|
791
|
+
return actual.toLowerCase() === expected.toLowerCase();
|
|
792
|
+
}
|
|
793
|
+
return whereValueMatches(actual, expected);
|
|
794
|
+
}
|
|
795
|
+
return whereValueMatches(actual, expected);
|
|
796
|
+
}
|
|
687
797
|
function isFiniteScalar(v) {
|
|
688
798
|
const t = typeof v;
|
|
689
799
|
if (t === "string" || t === "boolean") return true;
|
|
@@ -1069,7 +1179,8 @@ var RealtimeClient = class {
|
|
|
1069
1179
|
if (!where || Object.keys(where).length === 0) return true;
|
|
1070
1180
|
if (!event.document) return true;
|
|
1071
1181
|
for (const [key, value] of Object.entries(where)) {
|
|
1072
|
-
|
|
1182
|
+
const fieldType = resolveFieldTypeTag(event.__t, key);
|
|
1183
|
+
if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
|
|
1073
1184
|
return false;
|
|
1074
1185
|
}
|
|
1075
1186
|
}
|
|
@@ -1235,7 +1346,8 @@ var RealtimeClient = class {
|
|
|
1235
1346
|
if (!where) return false;
|
|
1236
1347
|
if (!event.document) return false;
|
|
1237
1348
|
for (const [key, value] of Object.entries(where)) {
|
|
1238
|
-
|
|
1349
|
+
const fieldType = resolveFieldTypeTag(event.__t, key);
|
|
1350
|
+
if (!whereValueMatchesTyped(resolveWherePath(event.document, key), value, fieldType)) {
|
|
1239
1351
|
return false;
|
|
1240
1352
|
}
|
|
1241
1353
|
}
|
|
@@ -2348,6 +2460,262 @@ function isTimelineSourceStats(value) {
|
|
|
2348
2460
|
return true;
|
|
2349
2461
|
}
|
|
2350
2462
|
|
|
2463
|
+
// libs/sdk/src/core/typed-matcher.ts
|
|
2464
|
+
var MAX_WHERE_DEPTH2 = 10;
|
|
2465
|
+
var RESERVED_FIELD_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
2466
|
+
var SCALAR_OPS = ["$eq", "$ne", "$gt", "$gte", "$lt", "$lte"];
|
|
2467
|
+
var ARRAY_ELEMENT_OPS = ["$in", "$nin"];
|
|
2468
|
+
function isScalarOp(op) {
|
|
2469
|
+
return SCALAR_OPS.includes(op);
|
|
2470
|
+
}
|
|
2471
|
+
function isArrayElementOp(op) {
|
|
2472
|
+
return ARRAY_ELEMENT_OPS.includes(op);
|
|
2473
|
+
}
|
|
2474
|
+
function isPlainObject(value) {
|
|
2475
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2476
|
+
}
|
|
2477
|
+
function isSafeComparableNumber(n) {
|
|
2478
|
+
return Number.isFinite(n) && Math.abs(n) <= Number.MAX_SAFE_INTEGER;
|
|
2479
|
+
}
|
|
2480
|
+
function compileComparand(leaf, rawValue, allowScalar) {
|
|
2481
|
+
if (leaf?.kind === "date") return { kind: "date", epochMs: leaf.epochMs };
|
|
2482
|
+
if (leaf?.kind === "objectId") return { kind: "objectId", hex: leaf.hex };
|
|
2483
|
+
if (leaf?.kind === "raw") return null;
|
|
2484
|
+
if (typeof rawValue === "number" && isSafeComparableNumber(rawValue)) return { kind: "number", value: rawValue };
|
|
2485
|
+
if (allowScalar && (typeof rawValue === "string" || typeof rawValue === "boolean")) {
|
|
2486
|
+
return { kind: "scalar", value: rawValue };
|
|
2487
|
+
}
|
|
2488
|
+
return null;
|
|
2489
|
+
}
|
|
2490
|
+
function comparableValue(comparand) {
|
|
2491
|
+
switch (comparand.kind) {
|
|
2492
|
+
case "date":
|
|
2493
|
+
return comparand.epochMs;
|
|
2494
|
+
case "objectId":
|
|
2495
|
+
return comparand.hex;
|
|
2496
|
+
case "number":
|
|
2497
|
+
return comparand.value;
|
|
2498
|
+
case "scalar":
|
|
2499
|
+
return comparand.value;
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
function scalarActualKind(raw, tag, untrusted) {
|
|
2503
|
+
if (untrusted) return "unknown";
|
|
2504
|
+
if (tag === "date") return "date";
|
|
2505
|
+
if (tag === "objectId") return "objectId";
|
|
2506
|
+
if (typeof raw === "number") return isSafeComparableNumber(raw) ? "number" : "unknown";
|
|
2507
|
+
if (typeof raw === "string" || typeof raw === "boolean") return "scalar";
|
|
2508
|
+
return "unknown";
|
|
2509
|
+
}
|
|
2510
|
+
function comparandNeedsTag(comparand) {
|
|
2511
|
+
return comparand.kind === "date" || comparand.kind === "objectId";
|
|
2512
|
+
}
|
|
2513
|
+
function isUntrusted(t, comparand) {
|
|
2514
|
+
if (t?.incomplete === true) return true;
|
|
2515
|
+
return comparandNeedsTag(comparand) && t?.fields === void 0;
|
|
2516
|
+
}
|
|
2517
|
+
function toEpochMs(raw) {
|
|
2518
|
+
if (typeof raw === "string") {
|
|
2519
|
+
const parsed = Date.parse(raw);
|
|
2520
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
2521
|
+
}
|
|
2522
|
+
if (typeof raw === "number" && Number.isFinite(raw)) return raw;
|
|
2523
|
+
return void 0;
|
|
2524
|
+
}
|
|
2525
|
+
function resolveScalar(comparand, present, raw, actualKind) {
|
|
2526
|
+
if (!present) return { status: "absent" };
|
|
2527
|
+
if (actualKind === "unknown") return { status: "unknown" };
|
|
2528
|
+
if (comparand.kind === "date") {
|
|
2529
|
+
if (actualKind !== "date") return { status: "cross" };
|
|
2530
|
+
const epoch = toEpochMs(raw);
|
|
2531
|
+
if (epoch === void 0) return { status: "unknown" };
|
|
2532
|
+
return { status: "ok", value: epoch };
|
|
2533
|
+
}
|
|
2534
|
+
if (comparand.kind === "objectId") {
|
|
2535
|
+
if (actualKind !== "objectId") return { status: "cross" };
|
|
2536
|
+
if (typeof raw !== "string") return { status: "unknown" };
|
|
2537
|
+
return { status: "ok", value: raw.toLowerCase() };
|
|
2538
|
+
}
|
|
2539
|
+
if (actualKind === "date" || actualKind === "objectId") return { status: "unknown" };
|
|
2540
|
+
if (comparand.kind === "number") {
|
|
2541
|
+
if (actualKind !== "number") return { status: "cross" };
|
|
2542
|
+
return { status: "ok", value: raw };
|
|
2543
|
+
}
|
|
2544
|
+
if (actualKind !== "scalar" || typeof raw !== typeof comparand.value) return { status: "cross" };
|
|
2545
|
+
return { status: "ok", value: raw };
|
|
2546
|
+
}
|
|
2547
|
+
function confirmedEqual(resolved, comparand) {
|
|
2548
|
+
return resolved.status === "ok" && resolved.value === comparableValue(comparand);
|
|
2549
|
+
}
|
|
2550
|
+
function maybeEqual(resolved, comparand) {
|
|
2551
|
+
return resolved.status === "unknown" || confirmedEqual(resolved, comparand);
|
|
2552
|
+
}
|
|
2553
|
+
function compareOrder(a, b) {
|
|
2554
|
+
if (a === b) return 0;
|
|
2555
|
+
return a < b ? -1 : 1;
|
|
2556
|
+
}
|
|
2557
|
+
function satisfiesRange(op, cmp) {
|
|
2558
|
+
switch (op) {
|
|
2559
|
+
case "$gt":
|
|
2560
|
+
return cmp > 0;
|
|
2561
|
+
case "$gte":
|
|
2562
|
+
return cmp >= 0;
|
|
2563
|
+
case "$lt":
|
|
2564
|
+
return cmp < 0;
|
|
2565
|
+
case "$lte":
|
|
2566
|
+
return cmp <= 0;
|
|
2567
|
+
default:
|
|
2568
|
+
return false;
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
function maybeSatisfiesRange(resolved, comparand, op) {
|
|
2572
|
+
if (resolved.status === "unknown") return true;
|
|
2573
|
+
if (resolved.status !== "ok") return false;
|
|
2574
|
+
return satisfiesRange(op, compareOrder(resolved.value, comparableValue(comparand)));
|
|
2575
|
+
}
|
|
2576
|
+
function fieldPresent(document2, field) {
|
|
2577
|
+
return Object.prototype.hasOwnProperty.call(document2, field);
|
|
2578
|
+
}
|
|
2579
|
+
function fieldTag(t, field) {
|
|
2580
|
+
return t?.fields?.[field];
|
|
2581
|
+
}
|
|
2582
|
+
function isArrayTag(tag) {
|
|
2583
|
+
return typeof tag === "object" && tag !== null && "array" in tag;
|
|
2584
|
+
}
|
|
2585
|
+
function evalScalarLeaf(field, op, comparand) {
|
|
2586
|
+
return (document2, t) => {
|
|
2587
|
+
const present = fieldPresent(document2, field);
|
|
2588
|
+
const raw = present ? document2[field] : void 0;
|
|
2589
|
+
const untrusted = isUntrusted(t, comparand);
|
|
2590
|
+
const tag = fieldTag(t, field);
|
|
2591
|
+
if (present && Array.isArray(raw)) {
|
|
2592
|
+
const arrayTag = isArrayTag(tag) ? tag.array : void 0;
|
|
2593
|
+
return evalArrayLeaf(raw, arrayTag, untrusted, op, comparand);
|
|
2594
|
+
}
|
|
2595
|
+
const scalarTag = isArrayTag(tag) ? void 0 : tag;
|
|
2596
|
+
const actualKind = scalarActualKind(raw, scalarTag, untrusted);
|
|
2597
|
+
const resolved = resolveScalar(comparand, present, raw, actualKind);
|
|
2598
|
+
if (op === "$ne") return !confirmedEqual(resolved, comparand);
|
|
2599
|
+
if (op === "$eq") return maybeEqual(resolved, comparand);
|
|
2600
|
+
return maybeSatisfiesRange(resolved, comparand, op);
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
function evalArrayLeaf(raw, arrayTag, untrusted, op, comparand) {
|
|
2604
|
+
const resolvedElements = raw.map((el, i) => {
|
|
2605
|
+
const tag = arrayTag?.[i];
|
|
2606
|
+
const scalarTag = tag === "date" || tag === "objectId" ? tag : void 0;
|
|
2607
|
+
const actualKind = scalarActualKind(el, scalarTag, untrusted);
|
|
2608
|
+
return resolveScalar(comparand, true, el, actualKind);
|
|
2609
|
+
});
|
|
2610
|
+
if (op === "$ne") {
|
|
2611
|
+
return !resolvedElements.some((r) => confirmedEqual(r, comparand));
|
|
2612
|
+
}
|
|
2613
|
+
if (op === "$eq") {
|
|
2614
|
+
return resolvedElements.some((r) => maybeEqual(r, comparand));
|
|
2615
|
+
}
|
|
2616
|
+
return resolvedElements.some((r) => maybeSatisfiesRange(r, comparand, op));
|
|
2617
|
+
}
|
|
2618
|
+
function evalArrayElementOpLeaf(field, op, comparands) {
|
|
2619
|
+
return (document2, t) => {
|
|
2620
|
+
const present = fieldPresent(document2, field);
|
|
2621
|
+
const raw = present ? document2[field] : void 0;
|
|
2622
|
+
const tag = fieldTag(t, field);
|
|
2623
|
+
const evalOne = (comparand) => {
|
|
2624
|
+
const untrusted = isUntrusted(t, comparand);
|
|
2625
|
+
if (present && Array.isArray(raw)) {
|
|
2626
|
+
const arrayTag = isArrayTag(tag) ? tag.array : void 0;
|
|
2627
|
+
const resolvedElements = raw.map((el, i) => {
|
|
2628
|
+
const elTag = arrayTag?.[i];
|
|
2629
|
+
const scalarTag2 = elTag === "date" || elTag === "objectId" ? elTag : void 0;
|
|
2630
|
+
const actualKind2 = scalarActualKind(el, scalarTag2, untrusted);
|
|
2631
|
+
return resolveScalar(comparand, true, el, actualKind2);
|
|
2632
|
+
});
|
|
2633
|
+
return {
|
|
2634
|
+
any: resolvedElements.some((r) => maybeEqual(r, comparand)),
|
|
2635
|
+
confirmed: resolvedElements.some((r) => confirmedEqual(r, comparand))
|
|
2636
|
+
};
|
|
2637
|
+
}
|
|
2638
|
+
const scalarTag = isArrayTag(tag) ? void 0 : tag;
|
|
2639
|
+
const actualKind = scalarActualKind(raw, scalarTag, untrusted);
|
|
2640
|
+
const resolved = resolveScalar(comparand, present, raw, actualKind);
|
|
2641
|
+
return { any: maybeEqual(resolved, comparand), confirmed: confirmedEqual(resolved, comparand) };
|
|
2642
|
+
};
|
|
2643
|
+
const perCandidate = comparands.map(evalOne);
|
|
2644
|
+
const inMatch = perCandidate.some((r) => r.any);
|
|
2645
|
+
const confirmedAny = perCandidate.some((r) => r.confirmed);
|
|
2646
|
+
return op === "$in" ? inMatch : !confirmedAny;
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
function compileFieldClause(field, value, plan, pathPrefix) {
|
|
2650
|
+
if (field.includes(".") || RESERVED_FIELD_NAMES.has(field) || field.startsWith("$")) return null;
|
|
2651
|
+
const planPath = `${pathPrefix}${field}`;
|
|
2652
|
+
if (!isPlainObject(value)) {
|
|
2653
|
+
const comparand = compileComparand(plan[planPath], value, true);
|
|
2654
|
+
if (!comparand) return null;
|
|
2655
|
+
return evalScalarLeaf(field, "$eq", comparand);
|
|
2656
|
+
}
|
|
2657
|
+
const entries = Object.entries(value);
|
|
2658
|
+
const predicates = [];
|
|
2659
|
+
for (const [op, opValue] of entries) {
|
|
2660
|
+
if (!op.startsWith("$")) return null;
|
|
2661
|
+
if (isScalarOp(op)) {
|
|
2662
|
+
const leaf = plan[`${planPath}.${op}`];
|
|
2663
|
+
const allowScalar = op === "$eq";
|
|
2664
|
+
const comparand = compileComparand(leaf, opValue, allowScalar);
|
|
2665
|
+
if (!comparand) return null;
|
|
2666
|
+
predicates.push(evalScalarLeaf(field, op, comparand));
|
|
2667
|
+
continue;
|
|
2668
|
+
}
|
|
2669
|
+
if (isArrayElementOp(op)) {
|
|
2670
|
+
if (!Array.isArray(opValue) || opValue.length === 0) return null;
|
|
2671
|
+
const allowScalar = op === "$in";
|
|
2672
|
+
const comparands = [];
|
|
2673
|
+
for (let i = 0; i < opValue.length; i += 1) {
|
|
2674
|
+
const leaf = plan[`${planPath}.${op}.${i}`];
|
|
2675
|
+
const comparand = compileComparand(leaf, opValue[i], allowScalar);
|
|
2676
|
+
if (!comparand) return null;
|
|
2677
|
+
comparands.push(comparand);
|
|
2678
|
+
}
|
|
2679
|
+
predicates.push(evalArrayElementOpLeaf(field, op, comparands));
|
|
2680
|
+
continue;
|
|
2681
|
+
}
|
|
2682
|
+
return null;
|
|
2683
|
+
}
|
|
2684
|
+
if (predicates.length === 0) return null;
|
|
2685
|
+
return (document2, t) => predicates.every((p) => p(document2, t));
|
|
2686
|
+
}
|
|
2687
|
+
function compileWhereObject(where, plan, depth, pathPrefix) {
|
|
2688
|
+
if (depth > MAX_WHERE_DEPTH2) return null;
|
|
2689
|
+
const predicates = [];
|
|
2690
|
+
for (const [key, value] of Object.entries(where)) {
|
|
2691
|
+
if (key === "$and" || key === "$or") {
|
|
2692
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
2693
|
+
const subPredicates = [];
|
|
2694
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
2695
|
+
const clause = value[i];
|
|
2696
|
+
if (!isPlainObject(clause)) return null;
|
|
2697
|
+
const compiled2 = compileWhereObject(clause, plan, depth + 1, `${pathPrefix}${key}.${i}.`);
|
|
2698
|
+
if (!compiled2) return null;
|
|
2699
|
+
subPredicates.push(compiled2);
|
|
2700
|
+
}
|
|
2701
|
+
predicates.push(
|
|
2702
|
+
key === "$and" ? (document2, t) => subPredicates.every((p) => p(document2, t)) : (document2, t) => subPredicates.some((p) => p(document2, t))
|
|
2703
|
+
);
|
|
2704
|
+
continue;
|
|
2705
|
+
}
|
|
2706
|
+
if (key.startsWith("$")) return null;
|
|
2707
|
+
const compiled = compileFieldClause(key, value, plan, pathPrefix);
|
|
2708
|
+
if (!compiled) return null;
|
|
2709
|
+
predicates.push(compiled);
|
|
2710
|
+
}
|
|
2711
|
+
return (document2, t) => predicates.every((p) => p(document2, t));
|
|
2712
|
+
}
|
|
2713
|
+
function compileMatcher(where, plan) {
|
|
2714
|
+
const compiled = compileWhereObject(where, plan, 0, "");
|
|
2715
|
+
if (!compiled) return null;
|
|
2716
|
+
return { matches: (document2, t) => compiled(document2, t) };
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2351
2719
|
// libs/sdk/src/modules/database.module.ts
|
|
2352
2720
|
var DEFAULT_CATCHUP_MAX_PAGES = 1e3;
|
|
2353
2721
|
var DEFAULT_CATCHUP_MAX_DOCS = 5e4;
|
|
@@ -2414,6 +2782,10 @@ var Paginator = class {
|
|
|
2414
2782
|
return { documents: result.documents, hasMore };
|
|
2415
2783
|
}
|
|
2416
2784
|
};
|
|
2785
|
+
var typedWhereV1Flags = /* @__PURE__ */ new WeakMap();
|
|
2786
|
+
function enableTypedWhereV1(builder) {
|
|
2787
|
+
typedWhereV1Flags.set(builder, true);
|
|
2788
|
+
}
|
|
2417
2789
|
var QueryBuilder = class {
|
|
2418
2790
|
constructor(http, basePath, filter) {
|
|
2419
2791
|
this.http = http;
|
|
@@ -2496,6 +2868,7 @@ var QueryBuilder = class {
|
|
|
2496
2868
|
if (this._before !== void 0) query["before"] = this._before;
|
|
2497
2869
|
if (this._after !== void 0) query["after"] = this._after;
|
|
2498
2870
|
if (this._fields) query["fields"] = this._fields.join(",");
|
|
2871
|
+
if (typedWhereV1Flags.get(this)) query["typedWhereV1"] = "true";
|
|
2499
2872
|
if (this._populate.length) {
|
|
2500
2873
|
query["populate"] = this._populate.map(
|
|
2501
2874
|
(p) => p.foreignField ? `${p.field}:${p.collection}:${p.foreignField}` : `${p.field}:${p.collection}`
|
|
@@ -2805,8 +3178,9 @@ var CollectionRef = class {
|
|
|
2805
3178
|
if (opts.sort) builder.sort(opts.sort);
|
|
2806
3179
|
if (opts.limit !== void 0) builder.limit(opts.limit);
|
|
2807
3180
|
if (opts.select) builder.select(opts.select);
|
|
3181
|
+
enableTypedWhereV1(builder);
|
|
2808
3182
|
const result = await builder.execute(signal);
|
|
2809
|
-
return result.documents;
|
|
3183
|
+
return { documents: result.documents, coercionPlan: result.coercionPlan };
|
|
2810
3184
|
}
|
|
2811
3185
|
const asCap = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : def;
|
|
2812
3186
|
const asPageSize = (v, def) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : def;
|
|
@@ -2815,10 +3189,21 @@ var CollectionRef = class {
|
|
|
2815
3189
|
const pageSize = asPageSize(opts.limit, DEFAULT_CATCHUP_PAGE_SIZE);
|
|
2816
3190
|
const all = [];
|
|
2817
3191
|
let cursor;
|
|
3192
|
+
let coercionPlan;
|
|
3193
|
+
let coercionPlanCaptured = false;
|
|
3194
|
+
let coercionPlanMismatch = false;
|
|
2818
3195
|
for (let page = 0; page < maxPages && all.length < maxDocs; page++) {
|
|
2819
3196
|
const builder = this.find(opts.where).sort({ _id: 1 }).limit(pageSize);
|
|
2820
3197
|
if (opts.select) builder.select(opts.select);
|
|
3198
|
+
enableTypedWhereV1(builder);
|
|
2821
3199
|
const result = cursor === void 0 ? await builder.execute(signal) : await builder.after(cursor).execute(signal);
|
|
3200
|
+
if (!coercionPlanCaptured) {
|
|
3201
|
+
coercionPlan = result.coercionPlan;
|
|
3202
|
+
coercionPlanCaptured = true;
|
|
3203
|
+
} else if (!coercionPlanMismatch && JSON.stringify(result.coercionPlan) !== JSON.stringify(coercionPlan)) {
|
|
3204
|
+
coercionPlanMismatch = true;
|
|
3205
|
+
coercionPlan = void 0;
|
|
3206
|
+
}
|
|
2822
3207
|
const docs = result.documents;
|
|
2823
3208
|
if (docs.length === 0) break;
|
|
2824
3209
|
const room = maxDocs - all.length;
|
|
@@ -2835,7 +3220,7 @@ var CollectionRef = class {
|
|
|
2835
3220
|
}
|
|
2836
3221
|
cursor = nextCursor;
|
|
2837
3222
|
}
|
|
2838
|
-
return all;
|
|
3223
|
+
return { documents: all, coercionPlan };
|
|
2839
3224
|
}
|
|
2840
3225
|
async subscribeWithSnapshot(opts) {
|
|
2841
3226
|
if (!this.realtime) {
|
|
@@ -2850,7 +3235,7 @@ var CollectionRef = class {
|
|
|
2850
3235
|
if (!opts.where) return void 0;
|
|
2851
3236
|
const out = {};
|
|
2852
3237
|
for (const [k, v] of Object.entries(opts.where)) {
|
|
2853
|
-
if (typeof v === "
|
|
3238
|
+
if (typeof v === "number" || typeof v === "boolean" || typeof v === "string") {
|
|
2854
3239
|
out[k] = v;
|
|
2855
3240
|
}
|
|
2856
3241
|
}
|
|
@@ -2858,11 +3243,39 @@ var CollectionRef = class {
|
|
|
2858
3243
|
})();
|
|
2859
3244
|
const postFilterWhere = opts.where && Object.keys(opts.where).length > 0 && isMongoWhereFullySupported(opts.where) ? opts.where : void 0;
|
|
2860
3245
|
const postFilter = postFilterWhere !== void 0;
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
);
|
|
2865
|
-
|
|
3246
|
+
let typedMatcherPlan = null;
|
|
3247
|
+
let planCoercedSomething = false;
|
|
3248
|
+
const recomputeTypedMatcherPlan = (coercionPlan) => {
|
|
3249
|
+
planCoercedSomething = coercionPlan ? Object.values(coercionPlan).some((leaf) => leaf.kind !== "raw") : false;
|
|
3250
|
+
typedMatcherPlan = opts.where && Object.keys(opts.where).length > 0 && coercionPlan ? compileMatcher(opts.where, coercionPlan) : null;
|
|
3251
|
+
};
|
|
3252
|
+
const passesLiveGate = (event) => {
|
|
3253
|
+
if (typedMatcherPlan) {
|
|
3254
|
+
return !!event.document && typedMatcherPlan.matches(event.document, event.__t);
|
|
3255
|
+
}
|
|
3256
|
+
if (planCoercedSomething) {
|
|
3257
|
+
return true;
|
|
3258
|
+
}
|
|
3259
|
+
if (postFilterWhere) {
|
|
3260
|
+
return !!event.document && matchesMongoWhere(event.document, postFilterWhere);
|
|
3261
|
+
}
|
|
3262
|
+
return true;
|
|
3263
|
+
};
|
|
3264
|
+
let warnedAboutFallback = false;
|
|
3265
|
+
const warnIfNoGateAvailable = () => {
|
|
3266
|
+
if (warnedAboutFallback) return;
|
|
3267
|
+
if (opts.where && Object.keys(opts.where).length > 0 && !typedMatcherPlan && // No usable gate: either the #719 subset check failed, OR the snapshot
|
|
3268
|
+
// coerced a leaf but no typed matcher compiled (#725 C-1) — in the
|
|
3269
|
+
// latter case `passesLiveGate` deliberately over-delivers, which is
|
|
3270
|
+
// exactly the "onChange volume higher than expected" the warning
|
|
3271
|
+
// exists to explain.
|
|
3272
|
+
(!postFilter || planCoercedSomething)) {
|
|
3273
|
+
warnedAboutFallback = true;
|
|
3274
|
+
console.warn(
|
|
3275
|
+
`[spacelr] subscribeWithSnapshot on ${this.projectId}:${this.collectionName}: 'where' filter contains clauses (e.g. $gt, $ne, Date, dotted paths) that may not be enforced on the live stream. onChange may receive events beyond the filter; snapshot is still fully filtered.`
|
|
3276
|
+
);
|
|
3277
|
+
}
|
|
3278
|
+
};
|
|
2866
3279
|
const runRecovery = async () => {
|
|
2867
3280
|
currentUnsubscribe?.();
|
|
2868
3281
|
currentUnsubscribe = null;
|
|
@@ -2870,6 +3283,7 @@ var CollectionRef = class {
|
|
|
2870
3283
|
let recoveryAckResolved = false;
|
|
2871
3284
|
let recoverySnapshotDelivered = false;
|
|
2872
3285
|
const pendingRecoveryEvents = [];
|
|
3286
|
+
let freshRecoveryPlanReady = false;
|
|
2873
3287
|
let next;
|
|
2874
3288
|
try {
|
|
2875
3289
|
next = await realtime.subscribeWithCursorWithMeta({
|
|
@@ -2879,8 +3293,8 @@ var CollectionRef = class {
|
|
|
2879
3293
|
where: streamWhere,
|
|
2880
3294
|
onEvent: async ({ event }) => {
|
|
2881
3295
|
if (!isActive) return;
|
|
2882
|
-
if (
|
|
2883
|
-
return;
|
|
3296
|
+
if (freshRecoveryPlanReady) {
|
|
3297
|
+
if (!passesLiveGate(event)) return;
|
|
2884
3298
|
}
|
|
2885
3299
|
if (!recoverySnapshotDelivered) {
|
|
2886
3300
|
pendingRecoveryEvents.push(event);
|
|
@@ -2913,7 +3327,16 @@ var CollectionRef = class {
|
|
|
2913
3327
|
snapshotAbort = new AbortController();
|
|
2914
3328
|
let recoveryDocs;
|
|
2915
3329
|
try {
|
|
2916
|
-
|
|
3330
|
+
const recoveryResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
|
|
3331
|
+
recoveryDocs = recoveryResult.documents;
|
|
3332
|
+
recomputeTypedMatcherPlan(recoveryResult.coercionPlan);
|
|
3333
|
+
warnIfNoGateAvailable();
|
|
3334
|
+
freshRecoveryPlanReady = true;
|
|
3335
|
+
for (let i = pendingRecoveryEvents.length - 1; i >= 0; i--) {
|
|
3336
|
+
if (!passesLiveGate(pendingRecoveryEvents[i])) {
|
|
3337
|
+
pendingRecoveryEvents.splice(i, 1);
|
|
3338
|
+
}
|
|
3339
|
+
}
|
|
2917
3340
|
} catch (err) {
|
|
2918
3341
|
if (!isActive) return;
|
|
2919
3342
|
if (err instanceof DOMException && err.name === "AbortError") return;
|
|
@@ -3004,6 +3427,7 @@ var CollectionRef = class {
|
|
|
3004
3427
|
let subscribeAckResolved = false;
|
|
3005
3428
|
let initialSnapshotDelivered = false;
|
|
3006
3429
|
const pendingInitialEvents = [];
|
|
3430
|
+
let initialPlanReady = false;
|
|
3007
3431
|
let initial;
|
|
3008
3432
|
try {
|
|
3009
3433
|
initial = await realtime.subscribeWithCursorWithMeta({
|
|
@@ -3013,7 +3437,7 @@ var CollectionRef = class {
|
|
|
3013
3437
|
where: streamWhere,
|
|
3014
3438
|
onEvent: async ({ event }) => {
|
|
3015
3439
|
if (!isActive) return;
|
|
3016
|
-
if (
|
|
3440
|
+
if (initialPlanReady && !passesLiveGate(event)) {
|
|
3017
3441
|
return;
|
|
3018
3442
|
}
|
|
3019
3443
|
if (!initialSnapshotDelivered) {
|
|
@@ -3060,7 +3484,16 @@ var CollectionRef = class {
|
|
|
3060
3484
|
currentUnsubscribe = initial.unsubscribe;
|
|
3061
3485
|
let snapshotDocs;
|
|
3062
3486
|
try {
|
|
3063
|
-
|
|
3487
|
+
const snapshotResult = await this.resolveSnapshotDocs(opts, snapshotAbort.signal);
|
|
3488
|
+
snapshotDocs = snapshotResult.documents;
|
|
3489
|
+
recomputeTypedMatcherPlan(snapshotResult.coercionPlan);
|
|
3490
|
+
initialPlanReady = true;
|
|
3491
|
+
for (let i = pendingInitialEvents.length - 1; i >= 0; i--) {
|
|
3492
|
+
if (!passesLiveGate(pendingInitialEvents[i])) {
|
|
3493
|
+
pendingInitialEvents.splice(i, 1);
|
|
3494
|
+
}
|
|
3495
|
+
}
|
|
3496
|
+
warnIfNoGateAvailable();
|
|
3064
3497
|
} catch (err) {
|
|
3065
3498
|
currentUnsubscribe?.();
|
|
3066
3499
|
isActive = false;
|