@noy-db/hub 0.4.0-pre.2 → 0.4.0-pre.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/dist/aggregate/index.js +1 -1
- package/dist/blobs/index.js.map +1 -1
- package/dist/broker/index.js +3 -3
- package/dist/broker/index.js.map +1 -1
- package/dist/cargo/index.js +5 -5
- package/dist/{chunk-OGY4ELVE.js → chunk-3XVOLB75.js} +2 -2
- package/dist/{chunk-Y5E6CH6S.js → chunk-EW4HFWGJ.js} +2 -2
- package/dist/{chunk-OTU5ZI3U.js → chunk-GU5AYA2Q.js} +2 -2
- package/dist/{chunk-S3OYXPSE.js → chunk-HKR25MGX.js} +2 -2
- package/dist/{chunk-RI3OKC3Y.js → chunk-JIMEB4C6.js} +1 -1
- package/dist/chunk-JIMEB4C6.js.map +1 -0
- package/dist/{chunk-VZELV7ZJ.js → chunk-LUH2MPEF.js} +37 -92
- package/dist/chunk-LUH2MPEF.js.map +1 -0
- package/dist/{chunk-IU22SQGU.js → chunk-N4A3DCBT.js} +1 -1
- package/dist/{chunk-IU22SQGU.js.map → chunk-N4A3DCBT.js.map} +1 -1
- package/dist/{chunk-PWZKD4HW.js → chunk-OWLPX2GI.js} +3 -3
- package/dist/{chunk-TYBXP6WE.js → chunk-QYJIOWKN.js} +2 -2
- package/dist/{chunk-A64XXIIB.js → chunk-SN75YVM5.js} +3 -3
- package/dist/{chunk-4JYYIFHW.js → chunk-UBF7HTOR.js} +2 -2
- package/dist/{chunk-RGL53NXZ.js → chunk-WEC3JGBA.js} +2 -2
- package/dist/{chunk-HVZT5T22.js → chunk-WJDYZP3U.js} +1 -1
- package/dist/chunk-WJDYZP3U.js.map +1 -0
- package/dist/{executor-UF7LTX6O.js → executor-YORMIBWV.js} +3 -3
- package/dist/index.d.ts +5 -0
- package/dist/index.js +13 -13
- package/dist/kernel/enclave/index.d.ts +1 -1
- package/dist/kernel/noydb.d.ts +13 -1
- package/dist/{liberate-W5MDWYOV.js → liberate-FK7JI2QX.js} +3 -3
- package/dist/materialized-views/index.js +3 -3
- package/dist/{noydb-U63S3Z7F.js → noydb-KUX2TJMX.js} +9 -9
- package/dist/query/index.js +2 -2
- package/dist/{seed-6GTDHL4E.js → seed-EKF4DIBB.js} +2 -2
- package/dist/{stale-NB5BGRVU.js → stale-4UNPHWOU.js} +2 -2
- package/dist/team/index.js +3 -3
- package/dist/tiers/index.js +1 -1
- package/dist/via/blob/active.d.ts +2 -1
- package/dist/with/index.js +2 -2
- package/dist/with-audit/forget/index.d.ts +2 -1
- package/dist/with-audit/tiers/index.d.ts +1 -0
- package/dist/with-cargo/index.d.ts +2 -0
- package/dist/with-formula/derivations/index.d.ts +2 -0
- package/dist/with-formula/materialized-views/index.d.ts +1 -0
- package/dist/with-lookup/aggregate/reducers.d.ts +1 -2
- package/dist/with-party/broker/index.d.ts +1 -0
- package/dist/with-party/team/keyring.d.ts +2 -2
- package/package.json +5 -4
- package/dist/chunk-HVZT5T22.js.map +0 -1
- package/dist/chunk-RI3OKC3Y.js.map +0 -1
- package/dist/chunk-VZELV7ZJ.js.map +0 -1
- /package/dist/{chunk-OGY4ELVE.js.map → chunk-3XVOLB75.js.map} +0 -0
- /package/dist/{chunk-Y5E6CH6S.js.map → chunk-EW4HFWGJ.js.map} +0 -0
- /package/dist/{chunk-OTU5ZI3U.js.map → chunk-GU5AYA2Q.js.map} +0 -0
- /package/dist/{chunk-S3OYXPSE.js.map → chunk-HKR25MGX.js.map} +0 -0
- /package/dist/{chunk-PWZKD4HW.js.map → chunk-OWLPX2GI.js.map} +0 -0
- /package/dist/{chunk-TYBXP6WE.js.map → chunk-QYJIOWKN.js.map} +0 -0
- /package/dist/{chunk-A64XXIIB.js.map → chunk-SN75YVM5.js.map} +0 -0
- /package/dist/{chunk-4JYYIFHW.js.map → chunk-UBF7HTOR.js.map} +0 -0
- /package/dist/{chunk-RGL53NXZ.js.map → chunk-WEC3JGBA.js.map} +0 -0
- /package/dist/{executor-UF7LTX6O.js.map → executor-YORMIBWV.js.map} +0 -0
- /package/dist/{liberate-W5MDWYOV.js.map → liberate-FK7JI2QX.js.map} +0 -0
- /package/dist/{noydb-U63S3Z7F.js.map → noydb-KUX2TJMX.js.map} +0 -0
- /package/dist/{seed-6GTDHL4E.js.map → seed-EKF4DIBB.js.map} +0 -0
- /package/dist/{stale-NB5BGRVU.js.map → stale-4UNPHWOU.js.map} +0 -0
package/dist/aggregate/index.js
CHANGED
package/dist/blobs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/via/blob/active.ts"],"sourcesContent":["/**\n * Active blob strategy factory. Calling `blobs()` returns a\n * `BlobStrategy` whose `openSlot` constructs a real `BlobSet` bound\n * to the caller's record. The returned strategy is passed into\n * `createNoydb({ blobStrategy: blobs() })` to light up the\n * `collection.blob(id)` path.\n *\n * This module is only reachable through the `@noy-db/hub/blobs`\n * subpath — a consumer that never imports the subpath ships none of\n * this (ESM tree-shaking + hub's `\"sideEffects\": false`).\n */\n\nimport { BlobSet } from '../../with-shape/blobs/blob-set.js'\nimport type { BlobStrategy } from '../../port/with/blob-strategy.js'\nimport { createBlobPinCache } from '../../with-shape/blobs/blob-pinning.js'\nimport type { BlobPinStore, BlobCacheStats } from '../../with-shape/blobs/blob-pinning.js'\n\n/** Options for {@link withBlobs} (#808). */\nexport interface WithBlobsOptions {\n /**\n * Device-local backend for the offline-pin registry + external side-cache\n * (`collection.blob(id).pin()`, the `cacheBudget` LRU stamps). Default:\n * in-memory — pins then last one app session. Supply a durable,\n * DEVICE-LOCAL store (IndexedDB-backed on the web; it must never sync) to\n * keep pins across restarts. See `BlobPinStore`'s doc for the posture.\n */\n readonly pinStore?: BlobPinStore\n}\n\n/**\n * The strategy `withBlobs()` returns — a `BlobStrategy` plus the device-local\n * blob-cache KPI surface (#808).\n */\nexport interface BlobsService extends BlobStrategy {\n /**\n * Snapshot of this device's blob-cache KPI counters: local-read hits,\n * network misses, and total bytes downloaded from the object store.\n */\n cacheStats(): BlobCacheStats\n}\n\n/**\n * Build a default `BlobStrategy` ready to pass into `createNoydb`.\n *\n * Named `withBlobs` (plugin-pattern canonical) rather than `blobs` to\n * avoid shadowing the very common local idiom\n * `const blobs = invoices.blob(id)` in user code.\n *\n * One `withBlobs()` instance owns one device-local pin registry + KPI\n * counter set (#808) — treat it as \"this device's\" blob service.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { withBlobs } from '@noy-db/hub/blobs'\n *\n * const db = await createNoydb({\n * store, user, secret,\n * blobStrategy: withBlobs(),\n * })\n *\n * // Now live — delegates to BlobSet.\n * await db.
|
|
1
|
+
{"version":3,"sources":["../../src/via/blob/active.ts"],"sourcesContent":["/**\n * Active blob strategy factory. Calling `blobs()` returns a\n * `BlobStrategy` whose `openSlot` constructs a real `BlobSet` bound\n * to the caller's record. The returned strategy is passed into\n * `createNoydb({ blobStrategy: blobs() })` to light up the\n * `collection.blob(id)` path.\n *\n * This module is only reachable through the `@noy-db/hub/blobs`\n * subpath — a consumer that never imports the subpath ships none of\n * this (ESM tree-shaking + hub's `\"sideEffects\": false`).\n */\n\nimport { BlobSet } from '../../with-shape/blobs/blob-set.js'\nimport type { BlobStrategy } from '../../port/with/blob-strategy.js'\nimport { createBlobPinCache } from '../../with-shape/blobs/blob-pinning.js'\nimport type { BlobPinStore, BlobCacheStats } from '../../with-shape/blobs/blob-pinning.js'\n\n/** Options for {@link withBlobs} (#808). */\nexport interface WithBlobsOptions {\n /**\n * Device-local backend for the offline-pin registry + external side-cache\n * (`collection.blob(id).pin()`, the `cacheBudget` LRU stamps). Default:\n * in-memory — pins then last one app session. Supply a durable,\n * DEVICE-LOCAL store (IndexedDB-backed on the web; it must never sync) to\n * keep pins across restarts. See `BlobPinStore`'s doc for the posture.\n */\n readonly pinStore?: BlobPinStore\n}\n\n/**\n * The strategy `withBlobs()` returns — a `BlobStrategy` plus the device-local\n * blob-cache KPI surface (#808).\n */\nexport interface BlobsService extends BlobStrategy {\n /**\n * Snapshot of this device's blob-cache KPI counters: local-read hits,\n * network misses, and total bytes downloaded from the object store.\n */\n cacheStats(): BlobCacheStats\n}\n\n/**\n * Build a default `BlobStrategy` ready to pass into `createNoydb`.\n *\n * Named `withBlobs` (plugin-pattern canonical) rather than `blobs` to\n * avoid shadowing the very common local idiom\n * `const blobs = invoices.blob(id)` in user code.\n *\n * One `withBlobs()` instance owns one device-local pin registry + KPI\n * counter set (#808) — treat it as \"this device's\" blob service.\n *\n * @example\n * ```ts\n * import { createNoydb } from '@noy-db/hub'\n * import { withBlobs } from '@noy-db/hub/blobs'\n *\n * const db = await createNoydb({\n * store, user, secret,\n * blobStrategy: withBlobs(),\n * })\n *\n * // Now live — delegates to BlobSet.\n * const vault = await db.openVault('acme')\n * await vault.collection('invoices').blob('inv-1').put('receipt.pdf', bytes)\n * ```\n */\nexport function withBlobs(options: WithBlobsOptions = {}): BlobsService {\n const pinCache = createBlobPinCache(options.pinStore)\n return {\n openSlot(args) {\n return new BlobSet({ ...args, pinCache })\n },\n cacheStats() {\n return { ...pinCache.stats }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEO,SAAS,UAAU,UAA4B,CAAC,GAAiB;AACtE,QAAM,WAAW,mBAAmB,QAAQ,QAAQ;AACpD,SAAO;AAAA,IACL,SAAS,MAAM;AACb,aAAO,IAAI,QAAQ,EAAE,GAAG,MAAM,SAAS,CAAC;AAAA,IAC1C;AAAA,IACA,aAAa;AACX,aAAO,EAAE,GAAG,SAAS,MAAM;AAAA,IAC7B;AAAA,EACF;AACF;","names":[]}
|
package/dist/broker/index.js
CHANGED
|
@@ -30,7 +30,7 @@ function withBroker(config) {
|
|
|
30
30
|
const cache = /* @__PURE__ */ new Map();
|
|
31
31
|
return {
|
|
32
32
|
async enroll(ctx) {
|
|
33
|
-
const { enrollSeed } = await import("../seed-
|
|
33
|
+
const { enrollSeed } = await import("../seed-EKF4DIBB.js");
|
|
34
34
|
return enrollSeed({ ...ctx, config });
|
|
35
35
|
},
|
|
36
36
|
async rotate(ctx) {
|
|
@@ -39,7 +39,7 @@ function withBroker(config) {
|
|
|
39
39
|
const inFlight = scoped.map(([, e]) => e.inFlight).filter((p) => p !== void 0);
|
|
40
40
|
await Promise.allSettled(inFlight);
|
|
41
41
|
for (const [key] of scoped) cache.delete(key);
|
|
42
|
-
const { rotateSeed } = await import("../seed-
|
|
42
|
+
const { rotateSeed } = await import("../seed-EKF4DIBB.js");
|
|
43
43
|
return rotateSeed({ ...ctx, config });
|
|
44
44
|
},
|
|
45
45
|
credentialSource(ctx, profile) {
|
|
@@ -56,7 +56,7 @@ function withBroker(config) {
|
|
|
56
56
|
const skewMs = config.skewMs ?? DEFAULT_SKEW_MS;
|
|
57
57
|
const capturedEntry = entry;
|
|
58
58
|
const inFlight = (async () => {
|
|
59
|
-
const { mintStoreCredentials } = await import("../seed-
|
|
59
|
+
const { mintStoreCredentials } = await import("../seed-EKF4DIBB.js");
|
|
60
60
|
const creds = await mintStoreCredentials({ ...ctx, config }, profile);
|
|
61
61
|
capturedEntry.cached = { creds, validUntil: cacheFloor(creds, skewMs) };
|
|
62
62
|
return creds;
|
package/dist/broker/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/with-party/broker/active.ts","../../src/with-party/broker/index.ts"],"sourcesContent":["/**\n * Enable the credential-broker capability (#479, spec §5).\n *\n * Pass to `createNoydb({ brokerStrategy: withBroker(config) })` to make\n * `vault.broker()` live. Each method dynamic-imports the seed lifecycle\n * engine (`./seed.js`) — mirroring `via/classified/active.ts`'s per-method\n * dynamic-import seam — so `with-party/broker/seed.ts` (the heavy module:\n * the CAS enrol, quiesce-then-swap rotate, and the challenge/response round\n * trip) is reachable only through the `@noy-db/hub/broker` subpath and\n * never enters the single-user floor bundle.\n *\n * The single-flight, per-vault-per-profile refresh cache (H-6/I6) lives\n * HERE, in this factory's closure — shared across every `credentialSource(profile)`\n * call for this one broker instance (in turn shared across every vault of a\n * `createNoydb()` instance — `vault.broker()` passes the SAME `BrokerStrategy`\n * for all of them), so `rotate()` can quiesce it (await any in-flight\n * round-trip, then drop it) before the seed swap. The cache key is\n * `${vault}\\0${profile}` — keyed by vault FIRST, or two vaults sharing this\n * one strategy would collide and hand vault-B a cached credential minted\n * (and STS-scoped) for vault-A.\n */\nimport type { BrokerStrategy, BrokerConfig, BrokerCtx } from '../../port/with/broker-strategy.js'\nimport type { StoreCredentials, StoreCredentialSource } from '../../kernel/types.js'\n\nconst DEFAULT_SKEW_MS = 60_000\n/** Floor under the skew-adjusted boundary so a sub-skew credential TTL\n * doesn't collapse to \"already expired\" and thrash re-proving every call (I6b). */\nconst MIN_CACHE_MS = 1_000\n\ninterface CacheEntry {\n cached?: { creds: StoreCredentials; validUntil: number } | undefined\n inFlight?: Promise<StoreCredentials> | undefined\n}\n\nfunction cacheFloor(creds: StoreCredentials, skewMs: number): number {\n const expiresAtMs = creds.expiresAt ? Date.parse(creds.expiresAt) : Date.now() + skewMs * 2\n return Math.max(expiresAtMs - skewMs, Date.now() + MIN_CACHE_MS)\n}\n\nexport function withBroker(config: BrokerConfig): BrokerStrategy {\n const cache = new Map<string, CacheEntry>()\n\n return {\n async enroll(ctx) {\n const { enrollSeed } = await import('./seed.js')\n return enrollSeed({ ...ctx, config })\n },\n async rotate(ctx) {\n // Quiesce (I5): let any in-flight round-trip finish (it may still be\n // proving under the pre-rotation seed) before the local record is\n // overwritten, then drop the cache — scoped to THIS vault's entries\n // only (`${ctx.vault}\\0`-prefixed keys). A global cache.clear() here\n // would blow away every OTHER vault's cache on this shared strategy\n // too — same root cause as the cross-vault read collision this fixes.\n const vaultPrefix = `${ctx.vault}\\0`\n const scoped = [...cache.entries()].filter(([key]) => key.startsWith(vaultPrefix))\n const inFlight = scoped.map(([, e]) => e.inFlight).filter((p): p is Promise<StoreCredentials> => p !== undefined)\n await Promise.allSettled(inFlight)\n for (const [key] of scoped) cache.delete(key)\n const { rotateSeed } = await import('./seed.js')\n return rotateSeed({ ...ctx, config })\n },\n credentialSource(ctx: BrokerCtx, profile?: string): StoreCredentialSource {\n const key = `${ctx.vault}\\0${profile ?? ''}`\n return async () => {\n let entry = cache.get(key)\n if (!entry) {\n entry = {}\n cache.set(key, entry)\n }\n const now = Date.now()\n if (entry.cached && now < entry.cached.validUntil) return entry.cached.creds\n if (entry.inFlight) return entry.inFlight\n\n const skewMs = config.skewMs ?? DEFAULT_SKEW_MS\n const capturedEntry = entry\n const inFlight = (async () => {\n const { mintStoreCredentials } = await import('./seed.js')\n const creds = await mintStoreCredentials({ ...ctx, config }, profile)\n capturedEntry.cached = { creds, validUntil: cacheFloor(creds, skewMs) }\n return creds\n })()\n entry.inFlight = inFlight\n try {\n return await inFlight\n } finally {\n // Clear-on-settle (I6a): a rejected in-flight promise must never\n // stay pinned in the cache, or every subsequent call would wedge\n // on the same rejection instead of retrying.\n capturedEntry.inFlight = undefined\n }\n }\n },\n }\n}\n","/**\n * `@noy-db/hub/broker` — subpath export for the credential-broker capability\n * (#479, credential-broker spec). Apps that never call `vault.broker()` can\n * exclude this subpath entirely: the floor default `NO_BROKER` throws, and\n * this module's real engine (`with-party/broker/{seed,active}.ts`) is only\n * ever reached through `withBroker()`'s dynamic imports, so it never enters\n * a floor bundle.\n *\n * Also re-exports the host-side helpers (`issueChallenge`, `verifyBrokerProof`)\n * from the enclave barrel, so a Lambda/Worker implementing the reference\n * broker host can import just this one subpath and get everything it\n * needs, `crypto.subtle`-only.\n */\n\n// ─── Capability opt-in seam ──────────────────────────────────\nexport { withBroker } from './active.js'\nexport {\n NO_BROKER,\n type BrokerStrategy,\n type BrokerCtx,\n type BrokerConfig,\n type CredentialBrokerHandle,\n} from '../../port/with/broker-strategy.js'\nexport { BrokerNotEnabledError, BrokerEnrolmentError, BrokerProofError } from '../../kernel/errors.js'\n\n// ─── Host helpers (verify side — for a reference broker host) ───\nimport { issueChallenge as issueChallengeRaw, verifyBrokerProof } from '../../kernel/enclave/index.js'\nimport type { IssuedChallenge, VerifyBrokerProofArgs } from '../../kernel/enclave/index.js'\n\n/**\n * Floor — a challenge TTL must survive network latency + clock drift\n * between host and client. The enclave's `issueChallenge` is deliberately\n * unclamped (a mechanical primitive, not a policy); this floor is host\n * POLICY, so it lives here in the party layer, not\n * `kernel/enclave/broker/proof.ts` (carried forward from Task 2's review,\n * I6b).\n */\nconst MIN_CHALLENGE_TTL_MS = 10_000\n/** Ceiling — spec §2 step 2: \"TTL ≤ 60 s\". */\nconst MAX_CHALLENGE_TTL_MS = 60_000\n\n/**\n * {@link issueChallengeRaw} (the enclave's mechanical primitive) with a\n * `[10s, 60s]` TTL clamp applied, so a reference host built on this barrel\n * gets a safe challenge TTL without having to know the bounds itself.\n */\nexport function issueChallenge(opts?: { ttlMs?: number }): IssuedChallenge {\n const requested = opts?.ttlMs ?? MAX_CHALLENGE_TTL_MS\n const clamped = Math.min(Math.max(requested, MIN_CHALLENGE_TTL_MS), MAX_CHALLENGE_TTL_MS)\n return issueChallengeRaw({ ttlMs: clamped })\n}\nexport { verifyBrokerProof }\nexport type { VerifyBrokerProofArgs }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,kBAAkB;AAGxB,IAAM,eAAe;AAOrB,SAAS,WAAW,OAAyB,QAAwB;AACnE,QAAM,cAAc,MAAM,YAAY,KAAK,MAAM,MAAM,SAAS,IAAI,KAAK,IAAI,IAAI,SAAS;AAC1F,SAAO,KAAK,IAAI,cAAc,QAAQ,KAAK,IAAI,IAAI,YAAY;AACjE;AAEO,SAAS,WAAW,QAAsC;AAC/D,QAAM,QAAQ,oBAAI,IAAwB;AAE1C,SAAO;AAAA,IACL,MAAM,OAAO,KAAK;AAChB,YAAM,EAAE,WAAW,IAAI,MAAM,OAAO,qBAAW;AAC/C,aAAO,WAAW,EAAE,GAAG,KAAK,OAAO,CAAC;AAAA,IACtC;AAAA,IACA,MAAM,OAAO,KAAK;AA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,EACF;AACF;;;ACzDA,IAAM,uBAAuB;AAE7B,IAAM,uBAAuB;AAOtB,SAASA,gBAAe,MAA4C;AACzE,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,UAAU,KAAK,IAAI,KAAK,IAAI,WAAW,oBAAoB,GAAG,oBAAoB;AACxF,SAAO,eAAkB,EAAE,OAAO,QAAQ,CAAC;AAC7C;","names":["issueChallenge"]}
|
|
1
|
+
{"version":3,"sources":["../../src/with-party/broker/active.ts","../../src/with-party/broker/index.ts"],"sourcesContent":["/**\n * Enable the credential-broker capability (#479, spec §5).\n *\n * Pass to `createNoydb({ brokerStrategy: withBroker(config) })` to make\n * `vault.broker()` live. Each method dynamic-imports the seed lifecycle\n * engine (`./seed.js`) — mirroring `via/classified/active.ts`'s per-method\n * dynamic-import seam — so `with-party/broker/seed.ts` (the heavy module:\n * the CAS enrol, quiesce-then-swap rotate, and the challenge/response round\n * trip) is reachable only through the `@noy-db/hub/broker` subpath and\n * never enters the single-user floor bundle.\n *\n * The single-flight, per-vault-per-profile refresh cache (H-6/I6) lives\n * HERE, in this factory's closure — shared across every `credentialSource(profile)`\n * call for this one broker instance (in turn shared across every vault of a\n * `createNoydb()` instance — `vault.broker()` passes the SAME `BrokerStrategy`\n * for all of them), so `rotate()` can quiesce it (await any in-flight\n * round-trip, then drop it) before the seed swap. The cache key is\n * `${vault}\\0${profile}` — keyed by vault FIRST, or two vaults sharing this\n * one strategy would collide and hand vault-B a cached credential minted\n * (and STS-scoped) for vault-A.\n */\nimport type { BrokerStrategy, BrokerConfig, BrokerCtx } from '../../port/with/broker-strategy.js'\nimport type { StoreCredentials, StoreCredentialSource } from '../../kernel/types.js'\n\nconst DEFAULT_SKEW_MS = 60_000\n/** Floor under the skew-adjusted boundary so a sub-skew credential TTL\n * doesn't collapse to \"already expired\" and thrash re-proving every call (I6b). */\nconst MIN_CACHE_MS = 1_000\n\ninterface CacheEntry {\n cached?: { creds: StoreCredentials; validUntil: number } | undefined\n inFlight?: Promise<StoreCredentials> | undefined\n}\n\nfunction cacheFloor(creds: StoreCredentials, skewMs: number): number {\n const expiresAtMs = creds.expiresAt ? Date.parse(creds.expiresAt) : Date.now() + skewMs * 2\n return Math.max(expiresAtMs - skewMs, Date.now() + MIN_CACHE_MS)\n}\n\nexport function withBroker(config: BrokerConfig): BrokerStrategy {\n const cache = new Map<string, CacheEntry>()\n\n return {\n async enroll(ctx) {\n const { enrollSeed } = await import('./seed.js')\n return enrollSeed({ ...ctx, config })\n },\n async rotate(ctx) {\n // Quiesce (I5): let any in-flight round-trip finish (it may still be\n // proving under the pre-rotation seed) before the local record is\n // overwritten, then drop the cache — scoped to THIS vault's entries\n // only (`${ctx.vault}\\0`-prefixed keys). A global cache.clear() here\n // would blow away every OTHER vault's cache on this shared strategy\n // too — same root cause as the cross-vault read collision this fixes.\n const vaultPrefix = `${ctx.vault}\\0`\n const scoped = [...cache.entries()].filter(([key]) => key.startsWith(vaultPrefix))\n const inFlight = scoped.map(([, e]) => e.inFlight).filter((p): p is Promise<StoreCredentials> => p !== undefined)\n await Promise.allSettled(inFlight)\n for (const [key] of scoped) cache.delete(key)\n const { rotateSeed } = await import('./seed.js')\n return rotateSeed({ ...ctx, config })\n },\n credentialSource(ctx: BrokerCtx, profile?: string): StoreCredentialSource {\n const key = `${ctx.vault}\\0${profile ?? ''}`\n return async () => {\n let entry = cache.get(key)\n if (!entry) {\n entry = {}\n cache.set(key, entry)\n }\n const now = Date.now()\n if (entry.cached && now < entry.cached.validUntil) return entry.cached.creds\n if (entry.inFlight) return entry.inFlight\n\n const skewMs = config.skewMs ?? DEFAULT_SKEW_MS\n const capturedEntry = entry\n const inFlight = (async () => {\n const { mintStoreCredentials } = await import('./seed.js')\n const creds = await mintStoreCredentials({ ...ctx, config }, profile)\n capturedEntry.cached = { creds, validUntil: cacheFloor(creds, skewMs) }\n return creds\n })()\n entry.inFlight = inFlight\n try {\n return await inFlight\n } finally {\n // Clear-on-settle (I6a): a rejected in-flight promise must never\n // stay pinned in the cache, or every subsequent call would wedge\n // on the same rejection instead of retrying.\n capturedEntry.inFlight = undefined\n }\n }\n },\n }\n}\n","/**\n * `@noy-db/hub/broker` — subpath export for the credential-broker capability\n * (#479, credential-broker spec). Apps that never call `vault.broker()` can\n * exclude this subpath entirely: the floor default `NO_BROKER` throws, and\n * this module's real engine (`with-party/broker/{seed,active}.ts`) is only\n * ever reached through `withBroker()`'s dynamic imports, so it never enters\n * a floor bundle.\n *\n * Also re-exports the host-side helpers (`issueChallenge`, `verifyBrokerProof`)\n * from the enclave barrel, so a Lambda/Worker implementing the reference\n * broker host can import just this one subpath and get everything it\n * needs, `crypto.subtle`-only.\n */\n\n// ─── Capability opt-in seam ──────────────────────────────────\nexport { withBroker } from './active.js'\nexport {\n NO_BROKER,\n type BrokerStrategy,\n type BrokerCtx,\n type BrokerConfig,\n type CredentialBrokerHandle,\n} from '../../port/with/broker-strategy.js'\nexport { BrokerNotEnabledError, BrokerEnrolmentError, BrokerProofError } from '../../kernel/errors.js'\n\n// ─── Host helpers (verify side — for a reference broker host) ───\nimport { issueChallenge as issueChallengeRaw, verifyBrokerProof } from '../../kernel/enclave/index.js'\nimport type { IssuedChallenge, VerifyBrokerProofArgs } from '../../kernel/enclave/index.js'\n\n/**\n * Floor — a challenge TTL must survive network latency + clock drift\n * between host and client. The enclave's `issueChallenge` is deliberately\n * unclamped (a mechanical primitive, not a policy); this floor is host\n * POLICY, so it lives here in the party layer, not\n * `kernel/enclave/broker/proof.ts` (carried forward from Task 2's review,\n * I6b).\n */\nconst MIN_CHALLENGE_TTL_MS = 10_000\n/** Ceiling — spec §2 step 2: \"TTL ≤ 60 s\". */\nconst MAX_CHALLENGE_TTL_MS = 60_000\n\n/**\n * {@link issueChallengeRaw} (the enclave's mechanical primitive) with a\n * `[10s, 60s]` TTL clamp applied, so a reference host built on this barrel\n * gets a safe challenge TTL without having to know the bounds itself.\n */\nexport function issueChallenge(opts?: { ttlMs?: number }): IssuedChallenge {\n const requested = opts?.ttlMs ?? MAX_CHALLENGE_TTL_MS\n const clamped = Math.min(Math.max(requested, MIN_CHALLENGE_TTL_MS), MAX_CHALLENGE_TTL_MS)\n return issueChallengeRaw({ ttlMs: clamped })\n}\nexport { verifyBrokerProof }\nexport type { VerifyBrokerProofArgs }\n\n// #837 — issueChallenge's return type must be nameable from this entry.\nexport type { IssuedChallenge } from '../../kernel/enclave/index.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,kBAAkB;AAGxB,IAAM,eAAe;AAOrB,SAAS,WAAW,OAAyB,QAAwB;AACnE,QAAM,cAAc,MAAM,YAAY,KAAK,MAAM,MAAM,SAAS,IAAI,KAAK,IAAI,IAAI,SAAS;AAC1F,SAAO,KAAK,IAAI,cAAc,QAAQ,KAAK,IAAI,IAAI,YAAY;AACjE;AAEO,SAAS,WAAW,QAAsC;AAC/D,QAAM,QAAQ,oBAAI,IAAwB;AAE1C,SAAO;AAAA,IACL,MAAM,OAAO,KAAK;AAChB,YAAM,EAAE,WAAW,IAAI,MAAM,OAAO,qBAAW;AAC/C,aAAO,WAAW,EAAE,GAAG,KAAK,OAAO,CAAC;AAAA,IACtC;AAAA,IACA,MAAM,OAAO,KAAK;AAOhB,YAAM,cAAc,GAAG,IAAI,KAAK;AAChC,YAAM,SAAS,CAAC,GAAG,MAAM,QAAQ,CAAC,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,IAAI,WAAW,WAAW,CAAC;AACjF,YAAM,WAAW,OAAO,IAAI,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,MAAsC,MAAM,MAAS;AAChH,YAAM,QAAQ,WAAW,QAAQ;AACjC,iBAAW,CAAC,GAAG,KAAK,OAAQ,OAAM,OAAO,GAAG;AAC5C,YAAM,EAAE,WAAW,IAAI,MAAM,OAAO,qBAAW;AAC/C,aAAO,WAAW,EAAE,GAAG,KAAK,OAAO,CAAC;AAAA,IACtC;AAAA,IACA,iBAAiB,KAAgB,SAAyC;AACxE,YAAM,MAAM,GAAG,IAAI,KAAK,KAAK,WAAW,EAAE;AAC1C,aAAO,YAAY;AACjB,YAAI,QAAQ,MAAM,IAAI,GAAG;AACzB,YAAI,CAAC,OAAO;AACV,kBAAQ,CAAC;AACT,gBAAM,IAAI,KAAK,KAAK;AAAA,QACtB;AACA,cAAM,MAAM,KAAK,IAAI;AACrB,YAAI,MAAM,UAAU,MAAM,MAAM,OAAO,WAAY,QAAO,MAAM,OAAO;AACvE,YAAI,MAAM,SAAU,QAAO,MAAM;AAEjC,cAAM,SAAS,OAAO,UAAU;AAChC,cAAM,gBAAgB;AACtB,cAAM,YAAY,YAAY;AAC5B,gBAAM,EAAE,qBAAqB,IAAI,MAAM,OAAO,qBAAW;AACzD,gBAAM,QAAQ,MAAM,qBAAqB,EAAE,GAAG,KAAK,OAAO,GAAG,OAAO;AACpE,wBAAc,SAAS,EAAE,OAAO,YAAY,WAAW,OAAO,MAAM,EAAE;AACtE,iBAAO;AAAA,QACT,GAAG;AACH,cAAM,WAAW;AACjB,YAAI;AACF,iBAAO,MAAM;AAAA,QACf,UAAE;AAIA,wBAAc,WAAW;AAAA,QAC3B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;ACzDA,IAAM,uBAAuB;AAE7B,IAAM,uBAAuB;AAOtB,SAASA,gBAAe,MAA4C;AACzE,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,UAAU,KAAK,IAAI,KAAK,IAAI,WAAW,oBAAoB,GAAG,oBAAoB;AACxF,SAAO,eAAkB,EAAE,OAAO,QAAQ,CAAC;AAC7C;","names":["issueChallenge"]}
|
package/dist/cargo/index.js
CHANGED
|
@@ -5,11 +5,11 @@ import {
|
|
|
5
5
|
describeExtraction,
|
|
6
6
|
unsealDeks,
|
|
7
7
|
withCargo
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-OWLPX2GI.js";
|
|
9
9
|
import {
|
|
10
10
|
CustodyApi,
|
|
11
11
|
NO_CARGO
|
|
12
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-SN75YVM5.js";
|
|
13
13
|
import {
|
|
14
14
|
extractPartition,
|
|
15
15
|
walkClosure
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
isDeedVault,
|
|
20
20
|
liberateVault,
|
|
21
21
|
loadDeedMarker
|
|
22
|
-
} from "../chunk-
|
|
22
|
+
} from "../chunk-HKR25MGX.js";
|
|
23
23
|
import "../chunk-BCOKZC4B.js";
|
|
24
24
|
import {
|
|
25
25
|
fuseRetrieval
|
|
@@ -38,7 +38,7 @@ import "../chunk-YGBIBOCR.js";
|
|
|
38
38
|
import {
|
|
39
39
|
groupAndReduce,
|
|
40
40
|
reduceRecords
|
|
41
|
-
} from "../chunk-
|
|
41
|
+
} from "../chunk-JIMEB4C6.js";
|
|
42
42
|
import {
|
|
43
43
|
readPath
|
|
44
44
|
} from "../chunk-IGJCYUT5.js";
|
|
@@ -46,7 +46,7 @@ import "../chunk-MEKAMERX.js";
|
|
|
46
46
|
import "../chunk-BVZGNMVM.js";
|
|
47
47
|
import "../chunk-XGVDLQJE.js";
|
|
48
48
|
import "../chunk-STR7WBOB.js";
|
|
49
|
-
import "../chunk-
|
|
49
|
+
import "../chunk-WJDYZP3U.js";
|
|
50
50
|
import "../chunk-7B4GPCX7.js";
|
|
51
51
|
import "../chunk-MSO2C3KG.js";
|
|
52
52
|
import {
|
|
@@ -100,7 +100,7 @@ async function resolveStaleMVOnRead(accessor, outputCollection, dispatchCtx) {
|
|
|
100
100
|
continue;
|
|
101
101
|
}
|
|
102
102
|
if (executor === null) {
|
|
103
|
-
({ MaterializedViewExecutor: executor } = await import("./executor-
|
|
103
|
+
({ MaterializedViewExecutor: executor } = await import("./executor-YORMIBWV.js"));
|
|
104
104
|
}
|
|
105
105
|
for (const dep of reg.dependencies) {
|
|
106
106
|
await accessor.getCollection(dep).ensureHydrated();
|
|
@@ -132,4 +132,4 @@ export {
|
|
|
132
132
|
clearMVStale,
|
|
133
133
|
clearMVStaleFully
|
|
134
134
|
};
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
135
|
+
//# sourceMappingURL=chunk-3XVOLB75.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
grant,
|
|
5
5
|
revoke,
|
|
6
6
|
rotateKeys
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-WJDYZP3U.js";
|
|
8
8
|
import {
|
|
9
9
|
openEnvelopeJson
|
|
10
10
|
} from "./chunk-PEY6ZTCF.js";
|
|
@@ -96,4 +96,4 @@ export {
|
|
|
96
96
|
listCredentials,
|
|
97
97
|
credentialStatus
|
|
98
98
|
};
|
|
99
|
-
//# sourceMappingURL=chunk-
|
|
99
|
+
//# sourceMappingURL=chunk-EW4HFWGJ.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-OGFPMCSP.js";
|
|
4
4
|
import {
|
|
5
5
|
reducerBuilder
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-JIMEB4C6.js";
|
|
7
7
|
import {
|
|
8
8
|
evaluateClause,
|
|
9
9
|
hasFnClause,
|
|
@@ -1534,4 +1534,4 @@ export {
|
|
|
1534
1534
|
executePlan,
|
|
1535
1535
|
ScanBuilder
|
|
1536
1536
|
};
|
|
1537
|
-
//# sourceMappingURL=chunk-
|
|
1537
|
+
//# sourceMappingURL=chunk-GU5AYA2Q.js.map
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
} from "./chunk-XULHFSHO.js";
|
|
7
7
|
import {
|
|
8
8
|
createOwnerKeyring
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-WJDYZP3U.js";
|
|
10
10
|
import {
|
|
11
11
|
wrapKey
|
|
12
12
|
} from "./chunk-5P5AAXYA.js";
|
|
@@ -132,4 +132,4 @@ export {
|
|
|
132
132
|
isDeedVault,
|
|
133
133
|
liberateVault
|
|
134
134
|
};
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
135
|
+
//# sourceMappingURL=chunk-HKR25MGX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-lookup/aggregate/reducers.ts","../src/with-lookup/aggregate/aggregation.ts","../src/with-lookup/aggregate/canonical-key.ts","../src/with-lookup/aggregate/groupby.ts"],"sourcesContent":["/**\n * Aggregation reducers for the query DSL.\n *\n * the reducer protocol plus five built-in factories\n * (`count`, `sum`, `avg`, `min`, `max`) consumed by `Query.aggregate()`\n * and, in the future, `Scan.aggregate()`. Every factory accepts\n * an optional `{ seed }` parameter that is plumbed through the\n * protocol but unused by the executor — that's the load-bearing\n * half of constraint #2. When partition-aware aggregation\n * lands, the seed carries the previous partition's running total into\n * the next partition without requiring a protocol change.\n *\n * Reducers are intentionally generic over their internal state type\n * `S` so compound reducers (avg keeps `{sum, count}`, min/max keep a\n * value bag) can model internal bookkeeping without leaking the\n * implementation through the accumulator's public shape. `finalize`\n * collapses `S` back into the user-visible `R`.\n *\n * Reducers are pure data — `init` / `step` / `finalize` / optional\n * `remove` are stateless functions that receive and return `S`. This\n * is the shape that admits O(1) incremental maintenance in a future\n * optimization (delta-aware `LiveAggregation` applies `step` or\n * `remove` per delta), without blocking the simpler \"full re-run on\n * source change\" that ships.\n */\n\nimport { readPath } from '../../kernel/query/predicate.js'\nimport type { MoneyString } from '../../via/money/branded.js'\nimport type { QueryField } from '../../kernel/types.js'\n\n/**\n * A single reducer: factory-produced, ready to plug into an\n * `.aggregate()` spec.\n *\n * Type parameters:\n * - `R` — user-visible result type (what the aggregation returns\n * for this slot, e.g. `number` for `sum()`)\n * - `S` — internal state type, defaults to `R` for simple reducers\n * that don't need compound bookkeeping\n *\n * A reducer is stateless: every method is pure over `S`. `init()` is\n * called once per aggregation run to build the initial state; `step()`\n * folds a record into the state; `remove()` (optional) un-folds a\n * record, enabling incremental live maintenance; `finalize()` reads\n * the final answer out of the state at the end of the run.\n */\nexport interface Reducer<R, S = R> {\n /** Build the initial state for a fresh aggregation run. */\n init(): S\n /** Fold a record into the state. Returns the new state. */\n step(state: S, record: unknown): S\n /**\n * Un-fold a record from the state. Returns the new state.\n *\n * Optional — reducers without `remove` cannot be maintained\n * incrementally and must be re-run from scratch when the underlying\n * record set changes. `sum`, `count`, `avg` implement `remove` in\n * O(1); `min` and `max` implement it in O(N) worst case (when the\n * extremum itself is removed and the next extremum must be\n * recomputed from the remaining contributing values).\n */\n remove?(state: S, record: unknown): S\n /** Collapse the internal state into the user-visible result. */\n finalize(state: S): R\n /**\n * Combine two independent partial states into one (then `finalize` once).\n * Optional. MUST be associative + commutative with `init()` as identity.\n * Never merge finalized results — only states. Enables parallel /\n * hierarchical aggregation (e.g. cross-shard or advisor→firm rollup).\n */\n merge?(a: S, b: S): S\n /**\n * Identifying operation tag stamped by each built-in factory.\n * Used by `summariseAggregateOp` in the introspection walker to\n * render human-readable aggregate descriptors in `dumpSchema()`.\n * Optional so third-party custom reducers are unaffected.\n */\n readonly op?: 'count' | 'sum' | 'avg' | 'min' | 'max'\n /**\n * Field name for field-based reducers (`sum`, `avg`, `min`, `max`).\n * Absent on `count` which aggregates over record count, not a field.\n */\n readonly field?: string\n /**\n * Money-only: target currency for `sum` over a multi-currency money\n * field. Consumed by `wrapMoneyReducers` to convert per-currency\n * subtotals to one figure. Ignored for non-money fields.\n */\n readonly convertTo?: string\n /**\n * Money-only: FX rate map (`'USD->EUR' → rate`) used with `convertTo`.\n */\n readonly fx?: Record<string, number | string>\n}\n\n/**\n * Common options accepted by every reducer factory.\n *\n * `seed` — optional initial value for the internal state. **Unused by\n * the executor**, plumbed through the protocol for constraint\n * #2 (partition-aware aggregation seam). In, partitioned\n * aggregations will pass the previous partition's carry as `seed` so\n * a long time series can be rolled forward one partition at a time\n * without re-aggregating closed partitions.\n *\n * always uses `init()` with the factory's zero value, regardless\n * of whether `seed` was passed. Do not remove the parameter — that's\n * the whole point of having it exist now.\n */\nexport interface ReducerOptions<TSeed = unknown> {\n /** constraint #2 — seed is plumbed through but unused in. */\n readonly seed?: TSeed\n /**\n * Money-only (honored by `sum` over a multi-currency money field):\n * convert per-currency subtotals to this currency for a single figure.\n */\n readonly convertTo?: string\n /** Money-only: FX rate map (`'USD->EUR' → rate`) used with `convertTo`. */\n readonly fx?: Record<string, number | string>\n}\n\n// ---------------------------------------------------------------------------\n// Factories\n// ---------------------------------------------------------------------------\n\n/**\n * Count the number of records that match the query. Ignores field\n * values entirely — the count is over the number of records, not over\n * the number of non-null field values in any column.\n */\nexport function count(opts?: ReducerOptions<number>): Reducer<number> {\n // Seed captured on the closure but unused at execution time in\n //. The reference in _seed keeps lint happy.\n const _seed = opts?.seed\n void _seed\n return {\n op: 'count',\n init: () => 0,\n step: (state) => state + 1,\n remove: (state) => state - 1,\n finalize: (state) => state,\n merge: (a, b) => a + b,\n }\n}\n\n/**\n * Sum a numeric field across all matching records. Non-number values\n * at the field path are coerced to 0 — consumers who want a different\n * behavior (throw, skip, treat as NaN) should filter upstream via\n * `.where()` or write a custom reducer.\n *\n * KNOWN LIMITATION (type imprecision): the declared result type is `number`,\n * but when `field` is a **money** field the runtime returns a decimal *string*\n * (e.g. `'0.30'`, or `{ EUR: '0.30' }` in multi-currency mode) — money sums are\n * BigInt-exact in scaled space and never collapse to a float. The `number` type\n * is therefore a lie for money fields; narrow the result yourself at the call\n * site. A precise fix requires threading money-field declarations into the type\n * system (tracked separately).\n */\nexport function sum(\n field: string,\n opts?: ReducerOptions<number>,\n): Reducer<number> {\n const _seed = opts?.seed\n void _seed\n return {\n op: 'sum',\n field,\n // Money-only metadata, read by `wrapMoneyReducers`. No effect on a\n // generic numeric sum.\n ...(opts?.convertTo !== undefined ? { convertTo: opts.convertTo } : {}),\n ...(opts?.fx !== undefined ? { fx: opts.fx } : {}),\n init: () => 0,\n step: (state, record) => state + readNumber(record, field),\n remove: (state, record) => state - readNumber(record, field),\n finalize: (state) => state,\n merge: (a, b) => a + b,\n }\n}\n\n/**\n * Arithmetic mean of a numeric field across all matching records.\n *\n * Returns `null` for an empty result set (zero records is not a\n * well-defined denominator — returning NaN would poison downstream\n * arithmetic, and throwing would force every consumer to wrap in\n * try/catch just to handle \"no matches\"). Consumers who want an\n * explicit zero should coalesce with `?? 0`.\n *\n * Internal state is `{sum, count}` so the running average can be\n * maintained incrementally — on each delta, both fields update in\n * O(1) and `finalize` divides. Directly storing `avg` as state would\n * not admit incremental removal without also tracking count.\n */\nexport function avg(\n field: string,\n opts?: ReducerOptions<{ sum: number; count: number }>,\n): Reducer<number | null, { sum: number; count: number }> {\n const _seed = opts?.seed\n void _seed\n return {\n op: 'avg',\n field,\n init: () => ({ sum: 0, count: 0 }),\n step: (state, record) => ({\n sum: state.sum + readNumber(record, field),\n count: state.count + 1,\n }),\n remove: (state, record) => ({\n sum: state.sum - readNumber(record, field),\n count: state.count - 1,\n }),\n finalize: (state) => (state.count === 0 ? null : state.sum / state.count),\n merge: (a, b) => ({ sum: a.sum + b.sum, count: a.count + b.count }),\n }\n}\n\nexport interface MinMaxState {\n /**\n * Multiset of contributing field values. Stored as a plain array\n * because we need to support `remove` and a plain array gives us\n * O(1) push + O(N) worst-case removal — which matches the\n * documented min/max removal complexity. A sorted structure would\n * let us drop the O(N) rescan but adds complexity that doesn't\n * need; consumers hitting the O(N) ceiling should file an issue.\n */\n readonly values: number[]\n}\n\nfunction pushValue(state: MinMaxState, value: number): MinMaxState {\n return { values: [...state.values, value] }\n}\n\nfunction removeValue(state: MinMaxState, value: number): MinMaxState {\n // Remove the first matching value — duplicates are fine, we only\n // need to drop one instance per `remove()` call so the multiset\n // count stays consistent with the record count.\n const idx = state.values.indexOf(value)\n if (idx < 0) return state\n const next = state.values.slice()\n next.splice(idx, 1)\n return { values: next }\n}\n\n/**\n * Smallest numeric value of a field across all matching records.\n * Returns `null` for an empty result set. See `avg()` for the\n * reasoning on `null` vs NaN vs throwing.\n *\n * Incremental complexity: O(1) for `step`, O(N) worst case for\n * `remove` when the current minimum is removed (the state holds the\n * full multiset of contributing values and `finalize` scans for the\n * new minimum). Consumers with very large result sets and frequent\n * removals of the current extremum should either accept the cost or\n * wait for a future optimization.\n */\nexport function min(\n field: string,\n opts?: ReducerOptions<number>,\n): Reducer<number | null, MinMaxState> {\n const _seed = opts?.seed\n void _seed\n return {\n op: 'min',\n field,\n init: () => ({ values: [] }),\n step: (state, record) => pushValue(state, readNumber(record, field)),\n remove: (state, record) => removeValue(state, readNumber(record, field)),\n finalize: (state) => {\n if (state.values.length === 0) return null\n let out = state.values[0]!\n for (let i = 1; i < state.values.length; i++) {\n const v = state.values[i]!\n if (v < out) out = v\n }\n return out\n },\n merge: (a, b) => ({ values: [...a.values, ...b.values] }),\n }\n}\n\n/**\n * Largest numeric value of a field across all matching records.\n * Mirror of `min()` — see that doc for semantics, null-on-empty\n * behavior, and the O(N) removal caveat.\n */\nexport function max(\n field: string,\n opts?: ReducerOptions<number>,\n): Reducer<number | null, MinMaxState> {\n const _seed = opts?.seed\n void _seed\n return {\n op: 'max',\n field,\n init: () => ({ values: [] }),\n step: (state, record) => pushValue(state, readNumber(record, field)),\n remove: (state, record) => removeValue(state, readNumber(record, field)),\n finalize: (state) => {\n if (state.values.length === 0) return null\n let out = state.values[0]!\n for (let i = 1; i < state.values.length; i++) {\n const v = state.values[i]!\n if (v > out) out = v\n }\n return out\n },\n merge: (a, b) => ({ values: [...a.values, ...b.values] }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Money-typed reducer constructors\n// ---------------------------------------------------------------------------\n\n/**\n * `sum()` for a **declared money field**, typed to match the runtime.\n *\n * `sum()` returns `Reducer<number>`, but `wrapMoneyReducers` (applied at\n * `query.aggregate()` time, once `moneyFields` is known) rewrites any\n * `sum`/`min`/`max` over a money field to a money reducer that finalizes to a\n * `MoneyString` decimal — so the `number` type is a lie for money fields and\n * consumers need a cast at every read site. `moneySum` is the same reducer with\n * the correct `Reducer<MoneyString>` return type, so no read-site cast is\n * needed. It is the caller's assertion that `field` is a money field; use plain\n * `sum()` for non-money fields. (For a multi-currency money field WITHOUT\n * `convertTo`, the runtime returns a per-currency `Record<string, MoneyString>`\n * rather than a single `MoneyString` — pass `convertTo` to collapse to one\n * currency, or read the map at the boundary.)\n */\nexport function moneySum(field: string, opts?: ReducerOptions<number>): Reducer<MoneyString> {\n // The constructed reducer is the plain numeric `sum`; `wrapMoneyReducers`\n // swaps in the MoneyString-producing money reducer at aggregate() time.\n return sum(field, opts) as unknown as Reducer<MoneyString>\n}\n\n/**\n * `min()` for a declared money field, typed `Reducer<MoneyString | null>`\n * (null on an empty result set in fixed-currency mode, mirroring `min()`). See\n * {@link moneySum} for the late-binding rewrite. Note: `convertTo`/`fx` on\n * `opts` have no effect on min/max (cross-currency min/max is unsupported — use\n * {@link moneySum} for currency conversion). In multi-currency mode the runtime\n * returns a per-currency map and an empty result is `{}` rather than `null`.\n */\nexport function moneyMin(field: string, opts?: ReducerOptions<number>): Reducer<MoneyString | null> {\n return min(field, opts) as unknown as Reducer<MoneyString | null>\n}\n\n/**\n * `max()` for a declared money field, typed `Reducer<MoneyString | null>`\n * (null on an empty result set in fixed-currency mode, mirroring `max()`). See\n * {@link moneyMin} for the `convertTo`/`fx` and multi-currency caveats.\n */\nexport function moneyMax(field: string, opts?: ReducerOptions<number>): Reducer<MoneyString | null> {\n return max(field, opts) as unknown as Reducer<MoneyString | null>\n}\n\n// ---------------------------------------------------------------------------\n// Builder (typed spec-builder for aggregate())\n// ---------------------------------------------------------------------------\n\n/**\n * Typed builder passed to the `aggregate(b => spec)` overload.\n *\n * Each field-taking method narrows `field` to `QueryField<T, S>`, which\n * excludes any field listed in the collection's `sensitive` option at\n * compile time. `count()` carries no field argument and is always allowed.\n *\n * The type parameters match the `Query<T, S>` they come from:\n * - `T` — the record type of the collection\n * - `S` — the union of sensitive field keys (defaults to `never`)\n *\n * ONE shared runtime instance (`reducerBuilder`) serves all `T`/`S`\n * combinations — the field narrowing is type-only; the methods delegate\n * directly to the standalone factories.\n */\nexport interface ReducerBuilder<T, S extends keyof T = never, M extends keyof T & string = never> {\n count(opts?: ReducerOptions<number>): Reducer<number>\n sum<F extends QueryField<T, S>>(field: F, opts?: ReducerOptions<number>): [F] extends [M] ? Reducer<MoneyString> : Reducer<number>\n avg(field: QueryField<T, S>, opts?: ReducerOptions<{ sum: number; count: number }>): ReturnType<typeof avg>\n min<F extends QueryField<T, S>>(field: F, opts?: ReducerOptions<number>): [F] extends [M] ? Reducer<MoneyString | null> : ReturnType<typeof min>\n max<F extends QueryField<T, S>>(field: F, opts?: ReducerOptions<number>): [F] extends [M] ? Reducer<MoneyString | null> : ReturnType<typeof max>\n moneySum(field: QueryField<T, S>, opts?: ReducerOptions<number>): Reducer<MoneyString>\n moneyMin(field: QueryField<T, S>, opts?: ReducerOptions<number>): Reducer<MoneyString | null>\n moneyMax(field: QueryField<T, S>, opts?: ReducerOptions<number>): Reducer<MoneyString | null>\n}\n\n/**\n * Shared runtime instance for the `aggregate(b => spec)` builder form.\n *\n * The field-narrowing to `QueryField<T, S>` is type-only — each method\n * delegates directly to its standalone factory. A `(field: string) => R`\n * factory is assignable to a `(field: QueryField<T,S>) => R` method by\n * parameter-contravariance, so this single instance works for all `T`/`S`.\n */\nexport const reducerBuilder: ReducerBuilder<Record<string, unknown>> = {\n count,\n // The generic F parameter on sum/min/max in the interface is type-only; the\n // standalone factories are plain `(field: string)` functions. With M=never the\n // conditional return collapses to the numeric branch, matching the factories'\n // return type, but TypeScript cannot verify that collapse for a generic method\n // signature — so each factory is cast directly to the method's type.\n sum: sum as ReducerBuilder<Record<string, unknown>>['sum'],\n avg,\n min: min as ReducerBuilder<Record<string, unknown>>['min'],\n max: max as ReducerBuilder<Record<string, unknown>>['max'],\n moneySum, moneyMin, moneyMax,\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Read a numeric field from a record. Non-number values (null,\n * undefined, strings, objects) coerce to 0 so sum/avg/min/max don't\n * produce NaN on one bad row. Consumers who want strict typing should\n * validate upstream with Standard Schema, which NOYDB already runs on\n * every `put()`.\n */\nfunction readNumber(record: unknown, field: string): number {\n const value = readPath(record, field)\n // Defensive: a `{ amount, currency }` value means a multi-currency\n // money field reached a generic numeric reducer instead of being\n // rewritten by `wrapMoneyReducers` — that would silently produce a\n // wrong total. Surface it loudly rather than coercing to 0.\n if (\n typeof value === 'object' &&\n value !== null &&\n 'amount' in value &&\n 'currency' in value\n ) {\n throw new Error(\n `aggregate: field \"${field}\" holds a money value but was not money-aware — ` +\n `declare it in the collection's moneyFields so sum/min/max stay exact`,\n )\n }\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n","/**\n * Aggregate execution — the runtime behind `Query.aggregate()`.\n *\n * takes an `AggregateSpec` (a record of named reducers\n * built from `reducers.ts`) and runs every reducer over the records\n * produced by the underlying query. Two terminal surfaces:\n *\n * - `.run(): R` — synchronous one-shot reduction. Matches the\n * existing `Query.toArray()` / `.first()` / `.count()` style.\n * - `.live(): LiveAggregation<R>` — reactive primitive that\n * re-runs the reduction whenever the query's source notifies of\n * a change. uses naive full re-run; incremental delta\n * maintenance is admitted by the reducer protocol (`remove()`)\n * but not wired to the executor yet — a follow-up optimization\n * can switch from full re-run to delta-based without breaking\n * the public API. Consumers get correct, reactive values today.\n *\n * The `Aggregation<R>` wrapper is deliberately tiny — it exists so\n * `.aggregate(spec)` can be chained with either `.run()` or `.live()`\n * without the builder needing two separate terminal methods. It\n * holds the closure over the query execution (produces the current\n * matching record set) and the spec, and stitches them together in\n * either mode.\n *\n * This file depends ONLY on `reducers.ts` — it has no knowledge of\n * the `Query` class. Tests can therefore exercise the reduction\n * surface with plain record arrays, without spinning up a Collection.\n */\n\nimport type { Reducer } from './reducers.js'\n\n/**\n * A named set of reducers, keyed by output field name. Each key\n * becomes a field on the aggregated result.\n *\n * ```ts\n * const spec = {\n * total: sum('amount'),\n * n: count(),\n * avgAmount: avg('amount'),\n * }\n * ```\n */\nexport type AggregateSpec = Readonly<Record<string, Reducer<unknown, unknown>>>\n\n/**\n * Map an `AggregateSpec` to its reduced result shape — each key\n * carries the finalized result type from its reducer. A spec built\n * from `{ total: sum('amount'), n: count() }` yields a result of\n * `{ total: number, n: number }`.\n *\n * This uses a mapped type with a conditional to extract `R` from\n * each `Reducer<R, _>`. The `infer` captures the user-visible result\n * type, discarding the internal state type `S`.\n */\nexport type AggregateResult<Spec extends AggregateSpec> = {\n [K in keyof Spec]: Spec[K] extends Reducer<infer R, unknown> ? R : never\n}\n\n/**\n * Pure reduction over a record array. Runs every reducer's\n * `init → step* → finalize` pipeline exactly once over the records.\n *\n * Called by `Aggregation.run()` and by the live-mode refresh path.\n * Exported for tests and for future `scan().aggregate()` reuse\n * — the streaming path will call the same reducer protocol with a\n * per-page loop instead of a single array.\n */\nexport function reduceRecords<Spec extends AggregateSpec>(\n records: readonly unknown[],\n spec: Spec,\n): AggregateResult<Spec> {\n // Per-slot state, keyed by the spec's output field name.\n const state: Record<string, unknown> = {}\n for (const key of Object.keys(spec)) {\n state[key] = spec[key]!.init()\n }\n for (const record of records) {\n for (const key of Object.keys(spec)) {\n state[key] = spec[key]!.step(state[key], record)\n }\n }\n const result: Record<string, unknown> = {}\n for (const key of Object.keys(spec)) {\n result[key] = spec[key]!.finalize(state[key])\n }\n return result as AggregateResult<Spec>\n}\n\n/**\n * A minimal reactive primitive for aggregation results.\n *\n * Same spirit as the `LiveQuery` in : frame-agnostic, a plain\n * object with `value` / `error` fields and a `subscribe(cb)`\n * notification channel that Vue / React / Solid adapters wrap in\n * their own primitive. Intentionally NOT a Promise — aggregations\n * have a well-defined \"current value\" at every instant, and the\n * reactive consumer wants to read that value synchronously.\n *\n * Error semantics mirror `LiveQuery`: if a re-run throws, the\n * previous successful `value` is preserved and the error is stored\n * in `error` so consumers can render an error state without losing\n * the last-known-good result. The throw does NOT propagate out of\n * the source's change handler (which would tear down the upstream\n * emitter).\n *\n * `stop()` tears down the upstream subscription. It is idempotent —\n * calling it multiple times is safe — and subscribe calls after\n * stop are no-ops (they immediately return a no-op unsubscribe).\n * Always call `stop()` when done; Vue's `onUnmounted` is the\n * canonical place. Raw consumers must do it themselves.\n */\nexport interface LiveAggregation<R> {\n /** Current reduced value. Undefined only if the first compute threw. */\n readonly value: R | undefined\n /** Last execution error, if any. Cleared on the next successful run. */\n readonly error: unknown\n /** Notify on every recomputation (success or error). Returns unsubscribe. */\n subscribe(cb: () => void): () => void\n /** Tear down the upstream subscription. Idempotent. */\n stop(): void\n}\n\n/**\n * Upstream change-notification hook for live aggregation.\n *\n * Matches the shape that `QuerySource.subscribe` already uses — a\n * single method that accepts a callback and returns an unsubscribe\n * function. The `Aggregation` wrapper collects upstreams from the\n * query's source and wires them into a single re-run trigger.\n */\nexport interface AggregationUpstream {\n subscribe(cb: () => void): () => void\n}\n\n/**\n * Internal implementation of `LiveAggregation`. Not exported —\n * consumers get the interface only. The class wraps a `recompute`\n * closure (which runs the full reduction and returns the new value)\n * and a list of upstreams (sources whose changes should trigger a\n * re-run).\n *\n * Error isolation: if an individual listener callback throws, the\n * other listeners still fire and the error is logged to the warn\n * channel. This matches `LiveQuery` from and keeps one misbehaving\n * consumer from tearing down the whole live aggregation.\n */\nclass LiveAggregationImpl<R> implements LiveAggregation<R> {\n public value: R | undefined\n public error: unknown\n private readonly listeners = new Set<() => void>()\n private readonly unsubscribes: Array<() => void> = []\n private stopped = false\n\n constructor(\n private readonly recompute: () => R,\n upstreams: readonly AggregationUpstream[],\n ) {\n // Initial computation — surface any error through the `error`\n // field rather than letting the constructor throw, so consumers\n // can always construct a LiveAggregation and check its state\n // afterwards. Throwing from a constructor would force every\n // caller to wrap in try/catch, which is the opposite of the\n // \"reactive value with error state\" ergonomics we want.\n try {\n this.value = recompute()\n this.error = undefined\n } catch (err) {\n this.value = undefined\n this.error = err\n }\n\n // Wire up upstream subscriptions. Each one triggers a full\n // recomputation; we don't attempt incremental updates in.\n for (const upstream of upstreams) {\n const unsub = upstream.subscribe(() => this.refresh())\n this.unsubscribes.push(unsub)\n }\n }\n\n private refresh(): void {\n if (this.stopped) return\n try {\n this.value = this.recompute()\n this.error = undefined\n } catch (err) {\n // Preserve the previous successful value — consumers render an\n // error state using `error` without losing the last-known-good\n // number. This matches LiveQuery's error-preservation contract.\n this.error = err\n }\n for (const listener of this.listeners) {\n try {\n listener()\n } catch (err) {\n // Isolate listener errors so one bad consumer can't tear\n // down every other subscriber on the same aggregation.\n console.warn('[noy-db] LiveAggregation listener threw:', err)\n }\n }\n }\n\n subscribe(cb: () => void): () => void {\n if (this.stopped) {\n // No-op after stop. Returning a harmless unsubscribe lets\n // consumers use the same teardown pattern unconditionally.\n return () => {}\n }\n this.listeners.add(cb)\n return () => {\n this.listeners.delete(cb)\n }\n }\n\n stop(): void {\n if (this.stopped) return\n this.stopped = true\n for (const unsub of this.unsubscribes) {\n try {\n unsub()\n } catch (err) {\n console.warn('[noy-db] LiveAggregation upstream unsubscribe threw:', err)\n }\n }\n this.unsubscribes.length = 0\n this.listeners.clear()\n }\n}\n\n/**\n * Chainable wrapper returned by `Query.aggregate(spec)`. Holds the\n * execute-records closure and the spec; terminal methods (`run`,\n * `live`) stitch them together in either mode.\n *\n * Why a wrapper instead of two terminal methods on `Query` directly?\n *\n * The `.aggregate(spec)` call is where the spec is bound — both\n * `.run()` and `.live()` need the same spec, and the consumer's\n * fluent style is `query.where(...).aggregate(spec).run()` or\n * `.aggregate(spec).live()`. Wrapping lets the spec be named once\n * and reused for either terminal, and keeps the `Query` class\n * from growing a pair of near-duplicate method overloads\n * (`aggregateRun` / `aggregateLive`) that would be harder to\n * discover.\n */\nexport class Aggregation<R> {\n constructor(\n private readonly executeRecords: () => readonly unknown[],\n private readonly spec: AggregateSpec,\n private readonly upstreams: readonly AggregationUpstream[],\n ) {}\n\n /**\n * Execute the query and reduce the results synchronously.\n * Returns the reduced shape matching the spec — e.g. a spec of\n * `{ total: sum('amount'), n: count() }` returns\n * `{ total: number, n: number }`.\n */\n run(): R {\n return reduceRecords(this.executeRecords(), this.spec) as unknown as R\n }\n\n /**\n * Build a reactive `LiveAggregation<R>` that re-runs the reduction\n * whenever any upstream source notifies of a change. The initial\n * value is computed eagerly in the constructor, so consumers can\n * read `live.value` immediately after calling `.live()`.\n *\n * Always call `live.stop()` when finished — it tears down the\n * upstream subscriptions. Vue's `onUnmounted` is the canonical\n * place.\n *\n * **Implementation note:** every upstream change triggers a full\n * re-reduction. Incremental maintenance (O(1) per delta for\n * sum/count/avg via the reducer protocol's `remove()` method) is a\n * planned follow-up optimization — the protocol already supports\n * it, but the executor doesn't drive it yet. Consumers get\n * correct, reactive values today; future PRs can switch to\n * delta-based maintenance without changing this API.\n */\n live(): LiveAggregation<R> {\n const recompute = (): R =>\n reduceRecords(this.executeRecords(), this.spec) as unknown as R\n return new LiveAggregationImpl<R>(recompute, this.upstreams)\n }\n}\n\n/**\n * Build a `LiveAggregation<V>` from a recompute closure and a list\n * of upstreams. Exposed so sibling files in the query DSL\n * (currently `groupby.ts`) can reuse the reactive primitive\n * without reaching into `LiveAggregationImpl` directly. This keeps\n * the implementation class private while still allowing planned\n * composition with `.groupBy().aggregate().live()`.\n */\nexport function buildLiveAggregation<V>(\n recompute: () => V,\n upstreams: readonly AggregationUpstream[],\n): LiveAggregation<V> {\n return new LiveAggregationImpl<V>(recompute, upstreams)\n}\n","/**\n * Canonicalise a group-key tuple to a stable string for dedup hashing.\n *\n * Sorts field names lexicographically before serialising, so that\n * `.groupBy('a', 'b')` and `.groupBy('b', 'a')` produce identical\n * keys for the same logical group. Values are JSON-stringified;\n * `undefined` and `null` are distinguished (matching the Map-key\n * semantics in `groupAndReduce`).\n *\n * NOT part of the public API. Used by:\n * - `groupAndReduce` for the dedup Map's key\n * - `materialized-views/query-hash` for UNION MV cross-arm row-key dedup (PR 2)\n *\n * Pure: same input → same output, no side effects.\n */\nexport function canonicalGroupKey(\n fields: readonly string[],\n row: Record<string, unknown>,\n): string {\n const sorted = [...fields].sort()\n const parts: string[] = []\n for (const name of sorted) {\n const v = row[name]\n const serialised =\n v === undefined ? 'undefined' : JSON.stringify(v)\n parts.push(`${name}=${serialised}`)\n }\n return parts.join('|')\n}\n","/**\n * Query DSL `.groupBy()` —.\n *\n * Chains after `.where()` / `.filter()` / `.or()` / `.and()` on a\n * Query and before a reducer spec, so consumers can compute\n * per-bucket aggregates without folding in userland:\n *\n * ```ts\n * const byClient = invoices.query()\n * .where('status', '==', 'open')\n * .groupBy('clientId')\n * .aggregate({ total: sum('amount'), n: count() })\n * .run()\n * // → [ { clientId: 'c1', total: 5250, n: 3 }, … ]\n * ```\n *\n * Execution pipeline:\n *\n * 1. Run the query's where/filter clauses (same candidate /\n * filter pipeline as `.aggregate()` directly on Query).\n * 2. Partition the matching records into buckets keyed by\n * `readPath(record, field)`. JS `Map` preserves insertion\n * order, so the first-seen key for a bucket determines its\n * position in the result array — consumers who want a\n * specific ordering should `.sort()` downstream.\n * 3. Enforce cardinality: warn once per field at 10% of the cap\n * (10_000 buckets), throw `GroupCardinalityError` at 100% of\n * the cap (100_000 buckets).\n * 4. For each bucket, build a per-group reducer state and\n * step every record in the bucket through it.\n * 5. Emit one result row per bucket, shaped as\n * `{ [field]: key, ...reduced }`.\n *\n * **Null / undefined keys:** `Map` distinguishes `null` from\n * `undefined`, so records with a missing group field get their own\n * bucket, and records with an explicit `null` value get a separate\n * bucket from that. Consumers who want them merged can coalesce\n * upstream with `.filter()`.\n *\n * **Live mode:** `.groupBy().aggregate().live()` re-runs the full\n * grouping pipeline on every source change. Per-bucket incremental\n * delta maintenance is a future optimization — the reducer\n * protocol's `remove()` hook admits it, but ships naive\n * re-grouping for simplicity.\n *\n * **Type-level stable-key narrowing:** when\n * `dictKey` lands, `groupBy<DictField>()` will narrow the group key\n * type to the stable dictionary key rather than the resolved locale\n * label. That prevents grouping by the locale-resolved label,\n * which would produce different buckets per reader. types the\n * key as `unknown` at the result shape; the dictKey narrowing\n * layers on top without an API break.\n *\n * Partition-awareness seam: when partitioned collections land,\n * per-partition grouping will need to merge sub-results across\n * partitions. The reducer protocol's `{ seed }` parameter\n * (already plumbed through in `reducers.ts`) is the mechanism —\n * groupBy doesn't need its own seam for the moment, because it\n * delegates to the reducer protocol for all per-bucket state.\n */\n\nimport { readPath } from '../../kernel/query/predicate.js'\nimport type {\n AggregateSpec,\n AggregateResult,\n AggregationUpstream,\n LiveAggregation,\n} from './aggregation.js'\nimport { buildLiveAggregation } from './aggregation.js'\nimport type { ReducerBuilder } from './reducers.js'\nimport { reducerBuilder } from './reducers.js'\nimport { canonicalGroupKey } from './canonical-key.js'\nimport { GroupCardinalityError } from '../../kernel/errors.js'\nimport type { MoneyDescriptor } from '../../via/money/descriptor.js'\nimport type { ViaPipeline } from '../../kernel/via/pipeline.js'\nimport { viaBinder } from '../../kernel/via/index.js'\nimport { applyI18nLocale, type I18nTextDescriptor } from '../../via/i18n/core.js'\n\n/**\n * Cardinality thresholds for `.groupBy()`. The warn threshold gives\n * consumers a heads-up before the hard error; the cap is a fixed\n * constant in (not overridable). A `{ maxGroups }` override\n * can be added later without a break if a real consumer asks.\n */\nexport const GROUPBY_WARN_CARDINALITY = 10_000\nexport const GROUPBY_MAX_CARDINALITY = 100_000\n\n/**\n * One-shot warning dedup per-field-set — reactive dashboards\n * re-executing the same grouped query should produce the warning\n * once, not once per re-fire. Keyed on the sorted JSON of grouping\n * field names so `.groupBy('a', 'b')` and `.groupBy('b', 'a')`\n * share the same dedup slot (their result tuples are isomorphic).\n */\nconst warnedCardinalityFields = new Set<string>()\nfunction warnCardinalityApproaching(\n fields: readonly string[],\n observed: number,\n): void {\n const key = JSON.stringify([...fields].sort())\n if (warnedCardinalityFields.has(key)) return\n warnedCardinalityFields.add(key)\n const label = `[${fields.join(', ')}]`\n console.warn(\n `[noy-db] .groupBy(${label}) produced ${observed} distinct groups, ` +\n `${Math.round((observed / GROUPBY_MAX_CARDINALITY) * 100)}% of the ` +\n `${GROUPBY_MAX_CARDINALITY}-group ceiling. Narrow the query with ` +\n `.where() before grouping, or switch to a lower-cardinality field.`,\n )\n}\n\n/**\n * Test-only: clear the per-field cardinality warning dedup between\n * tests. Production code never calls this — matching the\n * `resetJoinWarnings` pattern in `join.ts`.\n */\nexport function resetGroupByWarnings(): void {\n warnedCardinalityFields.clear()\n}\n\n/**\n * Result row shape for a grouped aggregation. Each row carries the\n * group key value under the grouping field name plus every reducer\n * output from the spec.\n *\n * types the group key as `unknown` at the result shape — the\n * runtime read via `readPath` can return any value, and narrowing\n * to a specific type would require the caller to assert at the\n * call site. `dictKey` narrowing layers on top of this by\n * adding an overload that constrains `F` when the grouping field\n * is a `dictKey`.\n */\nexport type GroupedRow<F extends string, R> = { [K in F]: unknown } & R\n\n/**\n * Multi-key variant — result-row shape for variadic\n * `.groupBy(...fields)`. Every grouped field name appears on the row\n * (typed as `unknown` for the same reason as `GroupedRow`), plus the\n * reducer outputs from the spec.\n */\nexport type GroupedRowN<F extends readonly string[], R> =\n { [K in F[number]]: unknown } & R\n\n/**\n * Shared base class for the chainable grouped-query wrappers. Holds\n * the constructor + protected fields that both single-key\n * `GroupedQuery<T, F>` and variadic `GroupedQueryN<T, F>` need; each\n * subclass only overrides `aggregate()` with its own result-row\n * generic.\n *\n * Not exported — implementation detail. Adding `.having()` /\n * `.live()` / `.orderByGroup()` etc. in the future lands here once\n * and both subclasses pick it up automatically.\n *\n * @internal\n */\nabstract class GroupedQueryBase {\n /**\n * Field set this grouped query buckets on. Stored in declaration\n * order — the same order is preserved on every result row by\n * `groupAndReduce`. For the single-field constructor, this is\n * `[field]`.\n */\n protected readonly fields: readonly string[]\n\n constructor(\n protected readonly executeRecords: () => readonly unknown[],\n fieldOrFields: string | readonly string[],\n protected readonly upstreams: readonly AggregationUpstream[],\n /**\n * Optional dict label resolver attached by the query builder when\n * the grouping field is a dictKey. Variadic groupings always pass\n * `undefined` — `<field>Label` projection has no meaningful shape\n * for composite keys.\n */\n protected readonly dictLabelResolver?: (\n key: string,\n locale: string,\n fallback?: string | readonly string[],\n ) => Promise<string | undefined>,\n /**\n * The backing collection's compiled Via pipeline — used to rewrite\n * `sum`/`min`/`max` over Via-covered fields (e.g. money) into exact\n * BigInt reducers when `.aggregate(spec)` is terminated.\n */\n protected readonly via?: ViaPipeline,\n ) {\n this.fields =\n typeof fieldOrFields === 'string' ? [fieldOrFields] : [...fieldOrFields]\n }\n\n /** Apply Via-aware reducer rewriting (e.g. money) when the source declares one. */\n protected wrapSpec<Spec extends AggregateSpec>(spec: Spec): Spec {\n return this.via ? this.via.wrapReducers(spec) : spec\n }\n}\n\n/**\n * Chainable wrapper returned by `Query.groupBy(field)`. Terminates\n * with `.aggregate(spec)` which returns a `GroupedAggregation`.\n *\n * Kept minimal — the only operation on a grouped query is\n * aggregation. Ordering, limiting, and further filtering belong on\n * the underlying `Query` before `.groupBy()` is called; applying\n * them post-group would be a different operation (`having` /\n * `groupOrderBy`), out of scope for.\n */\nexport class GroupedQuery<T, F extends string, S extends keyof T = never, M extends keyof T & string = never> extends GroupedQueryBase {\n /**\n * Build a grouped aggregation. Returns a `GroupedAggregation`\n * with `.run()`, `.runAsync()`, and `.live()` terminals — same shape\n * as the non-grouped `.aggregate()` wrapper, just with an array\n * result (one row per bucket) instead of a single reduced object.\n *\n * The builder overload `aggregate(b => spec)` types `b` as\n * `ReducerBuilder<T, S, M>`, so field-taking reducers (`sum`, `avg`,\n * `min`, `max`) refuse any field listed in the collection's\n * `sensitive` option at compile time, and `sum`/`min`/`max` over a\n * declared `moneyFields` (`M`) member return a `MoneyString`. The\n * bare-spec overload is preserved for backward compatibility.\n */\n aggregate<Spec extends AggregateSpec>(spec: Spec): GroupedAggregation<GroupedRow<F, AggregateResult<Spec>>>\n aggregate<Spec extends AggregateSpec>(build: (b: ReducerBuilder<T, S, M>) => Spec): GroupedAggregation<GroupedRow<F, AggregateResult<Spec>>>\n aggregate<Spec extends AggregateSpec>(\n specOrBuild: Spec | ((b: ReducerBuilder<T, S, M>) => Spec),\n ): GroupedAggregation<GroupedRow<F, AggregateResult<Spec>>> {\n const spec: Spec = typeof specOrBuild === 'function'\n ? (specOrBuild as (b: ReducerBuilder<T, S, M>) => Spec)(reducerBuilder as unknown as ReducerBuilder<T, S, M>)\n : specOrBuild\n // T is phantom on the wrapper so consumers can still see the\n // source row type on hover. Reference it to keep lint quiet.\n void undefined as T | undefined\n return new GroupedAggregation<GroupedRow<F, AggregateResult<Spec>>>(\n this.executeRecords,\n this.fields,\n this.wrapSpec(spec),\n this.upstreams,\n this.dictLabelResolver,\n )\n }\n}\n\n/**\n * Variadic-keyed sibling of `GroupedQuery<T, F>`. Constructed by the\n * multi-arg `Query.groupBy(...fields)` overload. The runtime shape is\n * identical — only the type-level result-row narrowing differs.\n */\nexport class GroupedQueryN<T, F extends readonly string[], S extends keyof T = never, M extends keyof T & string = never> extends GroupedQueryBase {\n aggregate<Spec extends AggregateSpec>(spec: Spec): GroupedAggregation<GroupedRowN<F, AggregateResult<Spec>>>\n aggregate<Spec extends AggregateSpec>(build: (b: ReducerBuilder<T, S, M>) => Spec): GroupedAggregation<GroupedRowN<F, AggregateResult<Spec>>>\n aggregate<Spec extends AggregateSpec>(\n specOrBuild: Spec | ((b: ReducerBuilder<T, S, M>) => Spec),\n ): GroupedAggregation<GroupedRowN<F, AggregateResult<Spec>>> {\n const spec: Spec = typeof specOrBuild === 'function'\n ? (specOrBuild as (b: ReducerBuilder<T, S, M>) => Spec)(reducerBuilder as unknown as ReducerBuilder<T, S, M>)\n : specOrBuild\n void undefined as T | undefined\n return new GroupedAggregation<GroupedRowN<F, AggregateResult<Spec>>>(\n this.executeRecords,\n this.fields,\n this.wrapSpec(spec),\n this.upstreams,\n this.dictLabelResolver,\n )\n }\n}\n\n/**\n * Execute the group-and-reduce pipeline. Pure function over a\n * record array and a spec — shared by `GroupedAggregation.run()`\n * and the live-mode refresh path. Exported for tests and for any\n * future `scan().groupBy().aggregate()` reuse.\n *\n * Enforces the cardinality cap incrementally during the partition\n * loop, so a runaway grouping throws at the moment the 100_001st\n * bucket would be created — the consumer doesn't have to wait for\n * the full partition to materialize before the error fires.\n */\nexport function groupAndReduce<R>(\n records: readonly unknown[],\n fieldOrFields: string | readonly string[],\n spec: AggregateSpec,\n moneyFields?: Record<string, MoneyDescriptor>,\n): R[] {\n const fields: readonly string[] =\n typeof fieldOrFields === 'string' ? [fieldOrFields] : fieldOrFields\n if (fields.length === 0) {\n throw new Error('.groupBy() requires at least one field')\n }\n\n // Money-aware aggregation: when the caller declares money descriptors\n // for output/intermediate fields, rewrite any `sum`/`min`/`max` over\n // them into exact BigInt reducers before bucketing. Omitted → spec\n // passes through unchanged (backward compatible). The chainable\n // `GroupedQuery` path already wraps upstream via `wrapSpec`; this\n // covers direct `groupAndReduce` callers (UNION-form MVs) that have\n // no Query wrapper to do it. Builds a transient money binding via the\n // kernel's Via port rather than a Query-attached pipeline — `moneyFields`\n // here is the MV spec's OWN descriptor map, not a collection's.\n if (moneyFields) {\n spec = viaBinder('money')({ moneyFields }).wrapReducers!(spec) as AggregateSpec\n }\n\n // Bucket value is { keyValues, records } so the output row can stamp\n // every grouped field in DECLARATION ORDER. Map preserves insertion\n // order natively (ES2015), so first-seen keys determine ordering.\n interface Bucket {\n keyValues: Record<string, unknown>\n records: unknown[]\n }\n const buckets = new Map<string, Bucket>()\n // Field-label string for error messages — matches the variadic\n // surface (`[a, b]` for multi-key, `\"k\"` for single-key back-compat).\n const fieldLabel = fields.length === 1 ? fields[0]! : `[${fields.join(', ')}]`\n\n for (const record of records) {\n // Read each field's value into a row object, then canonicalise.\n const keyValues: Record<string, unknown> = {}\n for (const f of fields) {\n keyValues[f] = readPath(record, f)\n }\n const dedupKey = canonicalGroupKey(fields, keyValues)\n let bucket = buckets.get(dedupKey)\n if (bucket === undefined) {\n if (buckets.size >= GROUPBY_MAX_CARDINALITY) {\n throw new GroupCardinalityError(\n fieldLabel,\n buckets.size + 1,\n GROUPBY_MAX_CARDINALITY,\n )\n }\n bucket = { keyValues, records: [] }\n buckets.set(dedupKey, bucket)\n }\n bucket.records.push(record)\n }\n\n if (buckets.size >= GROUPBY_WARN_CARDINALITY) {\n warnCardinalityApproaching(fields, buckets.size)\n }\n\n // Reduce each bucket through the spec. Same init/step/finalize\n // pipeline as `reduceRecords` in aggregate.ts, but one state per\n // bucket. Inlining the loop here keeps the per-bucket path tight\n // — calling `reduceRecords` per bucket would recompute\n // `Object.keys(spec)` once per bucket unnecessarily.\n const reducerKeys = Object.keys(spec)\n const out: R[] = []\n for (const bucket of buckets.values()) {\n const state: Record<string, unknown> = {}\n for (const rk of reducerKeys) {\n state[rk] = spec[rk]!.init()\n }\n for (const record of bucket.records) {\n for (const rk of reducerKeys) {\n state[rk] = spec[rk]!.step(state[rk], record)\n }\n }\n // Stamp grouped fields FIRST, in declaration order — this is\n // tested via `Object.keys(row).slice(0, fields.length)`.\n const row: Record<string, unknown> = {}\n for (const f of fields) {\n row[f] = bucket.keyValues[f]\n }\n for (const rk of reducerKeys) {\n row[rk] = spec[rk]!.finalize(state[rk])\n }\n out.push(row as unknown as R)\n }\n return out\n}\n\n/**\n * Grouped aggregation wrapper — the `.groupBy(field).aggregate(spec)`\n * terminal. Shape mirrors `Aggregation<R>` from aggregate.ts: two\n * terminals (`.run()` and `.live()`), spec bound at construction\n * time, upstreams collected for live mode.\n *\n * The generic `R` is the per-row result shape (i.e. a single\n * grouped row), and the terminals return `R[]` — one row per\n * bucket.\n */\nexport class GroupedAggregation<R> {\n private readonly fields: readonly string[]\n\n constructor(\n private readonly executeRecords: () => readonly unknown[],\n fields: string | readonly string[],\n private readonly spec: AggregateSpec,\n private readonly upstreams: readonly AggregationUpstream[],\n /**\n * Optional dict label resolver for `<field>Label` projection\n *. Present when the grouping field is a dictKey.\n */\n private readonly dictLabelResolver?: (\n key: string,\n locale: string,\n fallback?: string | readonly string[],\n ) => Promise<string | undefined>,\n ) {\n this.fields = typeof fields === 'string' ? [fields] : [...fields]\n }\n\n /**\n * Execute the query, group, reduce, and return an array of rows.\n *\n * `opts` (query-form MV grouping): when a `locale` + `i18nFields` are\n * given, the declared group-key `i18nText` fields are resolved to that locale\n * at the `mv` layer BEFORE bucketing — so an i18n group key is a stable string\n * instead of a raw `{locale}` map. The MV executor passes the MV's\n * `i18nLocale`/`i18nFields`; ordinary `.run()` callers pass nothing and are\n * unaffected.\n */\n run(opts?: { locale?: string; i18nFields?: Record<string, I18nTextDescriptor> }): R[] {\n let records = this.executeRecords()\n if (opts?.locale !== undefined && opts.i18nFields !== undefined) {\n const groupI18n: Record<string, I18nTextDescriptor> = {}\n for (const f of this.fields) {\n const d = opts.i18nFields[f]\n if (d !== undefined) groupI18n[f] = d\n }\n if (Object.keys(groupI18n).length > 0) {\n records = records.map((r) => applyI18nLocale(r as Record<string, unknown>, groupI18n, opts.locale!, undefined, 'mv'))\n }\n }\n return groupAndReduce<R>(records, this.fields, this.spec)\n }\n\n /**\n * Execute the query, group, reduce, and resolve `<field>Label` for\n * each result row when the grouping field is a `dictKey` and a\n * `locale` is provided. Returns `R[]` synchronously when\n * no locale is specified (identical to `.run()`).\n *\n * The `<field>Label` field is appended to each row. Rows whose group\n * key has no dictionary entry get `<field>Label: undefined`.\n *\n * Dict-label resolution is single-field only — multi-key groupings\n * do not produce a `<field>Label`. The resolver is only attached\n * by the builder when `fields.length === 1`.\n */\n async runAsync(opts?: {\n locale?: string\n fallback?: string | readonly string[]\n }): Promise<R[]> {\n const rows = groupAndReduce<R>(this.executeRecords(), this.fields, this.spec)\n if (!opts?.locale || !this.dictLabelResolver || this.fields.length !== 1) return rows\n\n const resolve = this.dictLabelResolver\n const locale = opts.locale\n const fallback = opts.fallback\n const field = this.fields[0]!\n const labelKey = `${field}Label`\n\n return Promise.all(\n rows.map(async (row) => {\n const key = (row as Record<string, unknown>)[field]\n if (typeof key !== 'string') return row\n const label = await resolve(key, locale, fallback)\n return { ...(row as Record<string, unknown>), [labelKey]: label } as unknown as R\n }),\n )\n }\n\n /**\n * Build a reactive `LiveAggregation<R[]>` that re-runs the full\n * group-and-reduce pipeline whenever any upstream source notifies\n * of a change. Same error-isolation and idempotent-stop contract\n * as `Aggregation.live()` — the implementation delegates to the\n * same `LiveAggregationImpl` class by threading a fresh\n * recompute closure through the existing constructor.\n *\n * uses naive full re-run on every change. Incremental\n * per-bucket maintenance (apply `step` on inserted records,\n * `remove` on deleted records, route by bucket key) is a future\n * optimization — the reducer protocol admits it, but wiring\n * delta-aware source subscriptions is a separate PR.\n *\n * Always call `live.stop()` when finished.\n */\n live(): LiveAggregation<R[]> {\n const recompute = (): R[] =>\n groupAndReduce<R>(this.executeRecords(), this.fields, this.spec)\n return buildLiveAggregation<R[]>(recompute, this.upstreams)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkIO,SAAS,MAAM,MAAgD;AAGpE,QAAM,QAAQ,MAAM;AACpB,OAAK;AACL,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM,MAAM;AAAA,IACZ,MAAM,CAAC,UAAU,QAAQ;AAAA,IACzB,QAAQ,CAAC,UAAU,QAAQ;AAAA,IAC3B,UAAU,CAAC,UAAU;AAAA,IACrB,OAAO,CAAC,GAAG,MAAM,IAAI;AAAA,EACvB;AACF;AAgBO,SAAS,IACd,OACA,MACiB;AACjB,QAAM,QAAQ,MAAM;AACpB,OAAK;AACL,SAAO;AAAA,IACL,IAAI;AAAA,IACJ;AAAA;AAAA;AAAA,IAGA,GAAI,MAAM,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,IACrE,GAAI,MAAM,OAAO,SAAY,EAAE,IAAI,KAAK,GAAG,IAAI,CAAC;AAAA,IAChD,MAAM,MAAM;AAAA,IACZ,MAAM,CAAC,OAAO,WAAW,QAAQ,WAAW,QAAQ,KAAK;AAAA,IACzD,QAAQ,CAAC,OAAO,WAAW,QAAQ,WAAW,QAAQ,KAAK;AAAA,IAC3D,UAAU,CAAC,UAAU;AAAA,IACrB,OAAO,CAAC,GAAG,MAAM,IAAI;AAAA,EACvB;AACF;AAgBO,SAAS,IACd,OACA,MACwD;AACxD,QAAM,QAAQ,MAAM;AACpB,OAAK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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,OAA6B;AAC3B,UAAM,YAAY,MAChB,eAAkB,KAAK,eAAe,GAAG,KAAK,QAAQ,KAAK,IAAI;AACjE,WAAO,qBAA0B,WAAW,KAAK,SAAS;AAAA,EAC5D;AACF;","names":[]}
|
|
@@ -44,7 +44,7 @@ import {
|
|
|
44
44
|
CustodyApi,
|
|
45
45
|
NO_CARGO,
|
|
46
46
|
NO_CUSTODY
|
|
47
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-SN75YVM5.js";
|
|
48
48
|
import {
|
|
49
49
|
resolveManagedSecret,
|
|
50
50
|
saveSealedPassphrase
|
|
@@ -56,7 +56,7 @@ import {
|
|
|
56
56
|
assertCanImport,
|
|
57
57
|
canExport,
|
|
58
58
|
canImport
|
|
59
|
-
} from "./chunk-
|
|
59
|
+
} from "./chunk-WEC3JGBA.js";
|
|
60
60
|
import {
|
|
61
61
|
runDrainBarrier
|
|
62
62
|
} from "./chunk-KMONEHDJ.js";
|
|
@@ -72,7 +72,7 @@ import {
|
|
|
72
72
|
NO_TIERS,
|
|
73
73
|
classifySealedShred,
|
|
74
74
|
syncDerivedOutputs
|
|
75
|
-
} from "./chunk-
|
|
75
|
+
} from "./chunk-N4A3DCBT.js";
|
|
76
76
|
import {
|
|
77
77
|
NO_PORTABILITY
|
|
78
78
|
} from "./chunk-GYB2QK5H.js";
|
|
@@ -115,7 +115,7 @@ import {
|
|
|
115
115
|
NO_AGGREGATE,
|
|
116
116
|
Query,
|
|
117
117
|
ScanBuilder
|
|
118
|
-
} from "./chunk-
|
|
118
|
+
} from "./chunk-GU5AYA2Q.js";
|
|
119
119
|
import {
|
|
120
120
|
EXPORT_AUDIT_COLLECTION,
|
|
121
121
|
createExportBlobsHandle,
|
|
@@ -133,7 +133,7 @@ import {
|
|
|
133
133
|
} from "./chunk-NO272T7Q.js";
|
|
134
134
|
import {
|
|
135
135
|
canonicalGroupKey
|
|
136
|
-
} from "./chunk-
|
|
136
|
+
} from "./chunk-JIMEB4C6.js";
|
|
137
137
|
import {
|
|
138
138
|
readPath
|
|
139
139
|
} from "./chunk-IGJCYUT5.js";
|
|
@@ -163,7 +163,7 @@ import {
|
|
|
163
163
|
rotatePassphrase,
|
|
164
164
|
updateAuthenticator,
|
|
165
165
|
writeMagicLinkGrant
|
|
166
|
-
} from "./chunk-
|
|
166
|
+
} from "./chunk-UBF7HTOR.js";
|
|
167
167
|
import {
|
|
168
168
|
assertKeyringOpenAllowed,
|
|
169
169
|
buildRecipientKeyringFile,
|
|
@@ -176,7 +176,7 @@ import {
|
|
|
176
176
|
listUsers,
|
|
177
177
|
loadKeyring,
|
|
178
178
|
updateKeyringIdentity
|
|
179
|
-
} from "./chunk-
|
|
179
|
+
} from "./chunk-WJDYZP3U.js";
|
|
180
180
|
import {
|
|
181
181
|
persistDirectoryConfig,
|
|
182
182
|
readDirectoryConfig
|
|
@@ -2056,6 +2056,11 @@ function resolveCollectionConfig(opts) {
|
|
|
2056
2056
|
`Collection "${opts.name}": embeddings are not supported on CRDT collections (L2). Use a non-CRDT collection for semantic search.`
|
|
2057
2057
|
);
|
|
2058
2058
|
}
|
|
2059
|
+
if (opts.sensitive && opts.sensitive.length > 0 && opts.crdt) {
|
|
2060
|
+
throw new Error(
|
|
2061
|
+
`Collection "${opts.name}": sensitive (structural group-encryption) is not supported on CRDT collections \u2014 the CRDT write path bypasses per-field sealing, so the fields would be stored in the ordinary encrypted body with no \`_sealed\` slot and no per-field key. Use a non-CRDT collection for sealed fields.`
|
|
2062
|
+
);
|
|
2063
|
+
}
|
|
2059
2064
|
if (opts.tiers && opts.tiers.length > 0 && opts.blobFields !== void 0 && Object.keys(opts.blobFields).length > 0 && opts.perRecordKeys !== true) {
|
|
2060
2065
|
throw new UnsupportedTierCompositionError(
|
|
2061
2066
|
"blobs",
|
|
@@ -3258,7 +3263,7 @@ var Collection = class {
|
|
|
3258
3263
|
}
|
|
3259
3264
|
}
|
|
3260
3265
|
if (this.materializedViewSource !== void 0) {
|
|
3261
|
-
const { resolveStaleMVOnRead } = await import("./stale-
|
|
3266
|
+
const { resolveStaleMVOnRead } = await import("./stale-4UNPHWOU.js");
|
|
3262
3267
|
await resolveStaleMVOnRead(this.materializedViewSource, this.name, this.#dispatchCtx({ collection: this.name, id: "resolve-on-read" }));
|
|
3263
3268
|
}
|
|
3264
3269
|
let record;
|
|
@@ -3727,7 +3732,7 @@ var Collection = class {
|
|
|
3727
3732
|
if (wave?.seen(`mv\0${reg.spec.name}`)) continue;
|
|
3728
3733
|
if (executor === null) {
|
|
3729
3734
|
;
|
|
3730
|
-
({ MaterializedViewExecutor: executor } = await import("./executor-
|
|
3735
|
+
({ MaterializedViewExecutor: executor } = await import("./executor-YORMIBWV.js"));
|
|
3731
3736
|
}
|
|
3732
3737
|
await executor.refresh(reg, {
|
|
3733
3738
|
getCollection: (name) => this.materializedViewSource.getCollection(name),
|
|
@@ -3737,7 +3742,7 @@ var Collection = class {
|
|
|
3737
3742
|
});
|
|
3738
3743
|
} else if (mode === "lazy") {
|
|
3739
3744
|
if (staleHelpers === null) {
|
|
3740
|
-
staleHelpers = await import("./stale-
|
|
3745
|
+
staleHelpers = await import("./stale-4UNPHWOU.js");
|
|
3741
3746
|
}
|
|
3742
3747
|
staleHelpers.markMVStale(registry, reg.spec.name);
|
|
3743
3748
|
}
|
|
@@ -4356,7 +4361,7 @@ var Collection = class {
|
|
|
4356
4361
|
if (mode === "eager") {
|
|
4357
4362
|
if (executor === null) {
|
|
4358
4363
|
;
|
|
4359
|
-
({ MaterializedViewExecutor: executor } = await import("./executor-
|
|
4364
|
+
({ MaterializedViewExecutor: executor } = await import("./executor-YORMIBWV.js"));
|
|
4360
4365
|
}
|
|
4361
4366
|
const rr = await executor.refresh(reg, {
|
|
4362
4367
|
getCollection: (name) => this.materializedViewSource.getCollection(name),
|
|
@@ -4369,7 +4374,7 @@ var Collection = class {
|
|
|
4369
4374
|
residueDeclined.push(...rr.residueDeclined);
|
|
4370
4375
|
} else {
|
|
4371
4376
|
if (staleHelpers === null) {
|
|
4372
|
-
staleHelpers = await import("./stale-
|
|
4377
|
+
staleHelpers = await import("./stale-4UNPHWOU.js");
|
|
4373
4378
|
}
|
|
4374
4379
|
const inv = await staleHelpers.invalidateMVAtRest(this.materializedViewSource, reg, mode);
|
|
4375
4380
|
deleted += inv.deleted;
|
|
@@ -4396,7 +4401,7 @@ var Collection = class {
|
|
|
4396
4401
|
);
|
|
4397
4402
|
}
|
|
4398
4403
|
if (this.materializedViewSource !== void 0) {
|
|
4399
|
-
const { resolveStaleMVOnRead } = await import("./stale-
|
|
4404
|
+
const { resolveStaleMVOnRead } = await import("./stale-4UNPHWOU.js");
|
|
4400
4405
|
await resolveStaleMVOnRead(this.materializedViewSource, this.name, this.#dispatchCtx({ collection: this.name, id: "resolve-on-read" }));
|
|
4401
4406
|
}
|
|
4402
4407
|
await this.ensureHydrated();
|
|
@@ -10005,14 +10010,14 @@ var Vault = class {
|
|
|
10005
10010
|
if (!reg) {
|
|
10006
10011
|
throw new Error(`refreshView: no MV registered with name "${name}"`);
|
|
10007
10012
|
}
|
|
10008
|
-
const { MaterializedViewExecutor } = await import("./executor-
|
|
10013
|
+
const { MaterializedViewExecutor } = await import("./executor-YORMIBWV.js");
|
|
10009
10014
|
const result = await MaterializedViewExecutor.refresh(reg, {
|
|
10010
10015
|
getCollection: (n) => this.collection(n),
|
|
10011
10016
|
getActiveTxContext: () => this.noydb._activeTxContextOrNull,
|
|
10012
10017
|
getQueryContext: () => this,
|
|
10013
10018
|
dispatchCtx: this._dispatchCtx({ collection: name, id: "refreshView" })
|
|
10014
10019
|
});
|
|
10015
|
-
const { clearMVStaleFully } = await import("./stale-
|
|
10020
|
+
const { clearMVStaleFully } = await import("./stale-4UNPHWOU.js");
|
|
10016
10021
|
await clearMVStaleFully(this.adapter, this.name, registry, name);
|
|
10017
10022
|
return result;
|
|
10018
10023
|
}
|
|
@@ -13105,85 +13110,25 @@ var Noydb = class {
|
|
|
13105
13110
|
this.vaultCache.set(name, comp);
|
|
13106
13111
|
return comp;
|
|
13107
13112
|
}
|
|
13108
|
-
/**
|
|
13113
|
+
/**
|
|
13114
|
+
* Synchronous access to an ALREADY-OPEN vault.
|
|
13115
|
+
*
|
|
13116
|
+
* Returns the instance `openVault()` produced, or throws — it never
|
|
13117
|
+
* constructs. It used to fall back to building a Vault itself (once for
|
|
13118
|
+
* plaintext, once for encrypted-with-cached-keyring), and those copies
|
|
13119
|
+
* drifted from the real open path: the encrypted one silently omitted six
|
|
13120
|
+
* strategies, so a vault reached this way threw `*NotEnabledError` for
|
|
13121
|
+
* services the caller had configured (#834). Both fallbacks also skipped
|
|
13122
|
+
* the async registry init and schema-fence snapshot that `openVault`
|
|
13123
|
+
* performs, which a synchronous method cannot await. One construction
|
|
13124
|
+
* path is the only way that divergence stays fixed.
|
|
13125
|
+
*/
|
|
13109
13126
|
vault(name) {
|
|
13110
13127
|
const cached = this.vaultCache.get(name);
|
|
13111
13128
|
if (cached) return cached;
|
|
13112
|
-
|
|
13113
|
-
|
|
13114
|
-
|
|
13115
|
-
adapter: this.options.store,
|
|
13116
|
-
name,
|
|
13117
|
-
noydb: this,
|
|
13118
|
-
keyring: keyring2,
|
|
13119
|
-
encrypted: false,
|
|
13120
|
-
emitter: this.emitter,
|
|
13121
|
-
historyConfig: this.options.history,
|
|
13122
|
-
...this.options.blobStrategy !== void 0 ? { blobStrategy: this.options.blobStrategy } : {},
|
|
13123
|
-
...this.options.objectStore !== void 0 ? { objectStore: this.options.objectStore } : {},
|
|
13124
|
-
...this.options.archiveStrategy !== void 0 ? { archiveStrategy: this.options.archiveStrategy } : {},
|
|
13125
|
-
...this.options.indexStrategy !== void 0 ? { indexStrategy: this.options.indexStrategy } : {},
|
|
13126
|
-
...this.options.lazyStrategy !== void 0 ? { lazyStrategy: this.options.lazyStrategy } : {},
|
|
13127
|
-
...this.options.aggregateStrategy !== void 0 ? { aggregateStrategy: this.options.aggregateStrategy } : {},
|
|
13128
|
-
...this.options.crdtStrategy !== void 0 ? { crdtStrategy: this.options.crdtStrategy } : {},
|
|
13129
|
-
...this.options.tiersStrategy !== void 0 ? { tiersStrategy: this.options.tiersStrategy } : {},
|
|
13130
|
-
...this.options.searchStrategy !== void 0 ? { searchStrategy: this.options.searchStrategy } : {},
|
|
13131
|
-
...this.options.cargoStrategy !== void 0 ? { cargoStrategy: this.options.cargoStrategy } : {},
|
|
13132
|
-
...this.options.brokerStrategy !== void 0 ? { brokerStrategy: this.options.brokerStrategy } : {},
|
|
13133
|
-
...this.options.consentStrategy !== void 0 ? { consentStrategy: this.options.consentStrategy } : {},
|
|
13134
|
-
...this.options.periodsStrategy !== void 0 ? { periodsStrategy: this.options.periodsStrategy } : {},
|
|
13135
|
-
...this.options.shadowStrategy !== void 0 ? { shadowStrategy: this.options.shadowStrategy } : {},
|
|
13136
|
-
...this.options.historyStrategy !== void 0 ? { historyStrategy: this.options.historyStrategy } : {},
|
|
13137
|
-
...this.options.i18nStrategy !== void 0 ? { i18nStrategy: this.options.i18nStrategy } : {},
|
|
13138
|
-
...this.options.syncStrategy !== void 0 ? { syncStrategy: this.options.syncStrategy } : {},
|
|
13139
|
-
...this.options.guardStrategies !== void 0 ? { guardStrategies: this.options.guardStrategies } : {},
|
|
13140
|
-
...this.options.numbering !== void 0 ? { numberingConfigs: this.options.numbering } : {},
|
|
13141
|
-
forgetStrategy: this.forgetStrategy,
|
|
13142
|
-
...this.options.attestationStrategy !== void 0 ? { attestationStrategy: this.options.attestationStrategy } : {},
|
|
13143
|
-
...this.options.classifiedStrategy !== void 0 ? { classifiedStrategy: this.options.classifiedStrategy } : {},
|
|
13144
|
-
...this.options.sealedRecordStrategy !== void 0 ? { sealedRecordStrategy: this.options.sealedRecordStrategy } : {},
|
|
13145
|
-
...this.options.portabilityStrategy !== void 0 ? { portabilityStrategy: this.options.portabilityStrategy } : {},
|
|
13146
|
-
...this.options.sequenceStrategy !== void 0 ? { sequenceStrategy: this.options.sequenceStrategy } : {}
|
|
13147
|
-
});
|
|
13148
|
-
this.vaultCache.set(name, comp2);
|
|
13149
|
-
return comp2;
|
|
13150
|
-
}
|
|
13151
|
-
const keyring = this.keyringCache.get(name);
|
|
13152
|
-
if (!keyring) {
|
|
13153
|
-
throw new ValidationError(
|
|
13154
|
-
`Vault "${name}" not opened. Use await db.openVault("${name}") first.`
|
|
13155
|
-
);
|
|
13156
|
-
}
|
|
13157
|
-
const comp = new Vault({
|
|
13158
|
-
adapter: this.options.store,
|
|
13159
|
-
name,
|
|
13160
|
-
noydb: this,
|
|
13161
|
-
keyring,
|
|
13162
|
-
encrypted: true,
|
|
13163
|
-
historyConfig: this.options.history,
|
|
13164
|
-
...this.options.blobStrategy !== void 0 ? { blobStrategy: this.options.blobStrategy } : {},
|
|
13165
|
-
...this.options.objectStore !== void 0 ? { objectStore: this.options.objectStore } : {},
|
|
13166
|
-
...this.options.archiveStrategy !== void 0 ? { archiveStrategy: this.options.archiveStrategy } : {},
|
|
13167
|
-
...this.options.indexStrategy !== void 0 ? { indexStrategy: this.options.indexStrategy } : {},
|
|
13168
|
-
...this.options.lazyStrategy !== void 0 ? { lazyStrategy: this.options.lazyStrategy } : {},
|
|
13169
|
-
...this.options.aggregateStrategy !== void 0 ? { aggregateStrategy: this.options.aggregateStrategy } : {},
|
|
13170
|
-
...this.options.crdtStrategy !== void 0 ? { crdtStrategy: this.options.crdtStrategy } : {},
|
|
13171
|
-
...this.options.tiersStrategy !== void 0 ? { tiersStrategy: this.options.tiersStrategy } : {},
|
|
13172
|
-
...this.options.searchStrategy !== void 0 ? { searchStrategy: this.options.searchStrategy } : {},
|
|
13173
|
-
...this.options.cargoStrategy !== void 0 ? { cargoStrategy: this.options.cargoStrategy } : {},
|
|
13174
|
-
...this.options.brokerStrategy !== void 0 ? { brokerStrategy: this.options.brokerStrategy } : {},
|
|
13175
|
-
...this.options.consentStrategy !== void 0 ? { consentStrategy: this.options.consentStrategy } : {},
|
|
13176
|
-
...this.options.periodsStrategy !== void 0 ? { periodsStrategy: this.options.periodsStrategy } : {},
|
|
13177
|
-
...this.options.shadowStrategy !== void 0 ? { shadowStrategy: this.options.shadowStrategy } : {},
|
|
13178
|
-
...this.options.historyStrategy !== void 0 ? { historyStrategy: this.options.historyStrategy } : {},
|
|
13179
|
-
...this.options.i18nStrategy !== void 0 ? { i18nStrategy: this.options.i18nStrategy } : {},
|
|
13180
|
-
...this.options.syncStrategy !== void 0 ? { syncStrategy: this.options.syncStrategy } : {},
|
|
13181
|
-
...this.options.guardStrategies !== void 0 ? { guardStrategies: this.options.guardStrategies } : {},
|
|
13182
|
-
...this.options.numbering !== void 0 ? { numberingConfigs: this.options.numbering } : {},
|
|
13183
|
-
emitter: this.emitter
|
|
13184
|
-
});
|
|
13185
|
-
this.vaultCache.set(name, comp);
|
|
13186
|
-
return comp;
|
|
13129
|
+
throw new ValidationError(
|
|
13130
|
+
`Vault "${name}" is not open. Call \`await db.openVault("${name}")\` first \u2014 vault() only returns an already-open vault, because opening involves async work (registry init, schema fence) that a sync accessor cannot do.`
|
|
13131
|
+
);
|
|
13187
13132
|
}
|
|
13188
13133
|
/**
|
|
13189
13134
|
* Grant access to a user for a vault.
|
|
@@ -14419,4 +14364,4 @@ export {
|
|
|
14419
14364
|
Noydb,
|
|
14420
14365
|
createNoydb
|
|
14421
14366
|
};
|
|
14422
|
-
//# sourceMappingURL=chunk-
|
|
14367
|
+
//# sourceMappingURL=chunk-LUH2MPEF.js.map
|