@noy-db/hub 0.1.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/LICENSE +21 -0
- package/README.md +197 -0
- package/dist/aggregate/index.cjs +476 -0
- package/dist/aggregate/index.cjs.map +1 -0
- package/dist/aggregate/index.d.cts +38 -0
- package/dist/aggregate/index.d.ts +38 -0
- package/dist/aggregate/index.js +53 -0
- package/dist/aggregate/index.js.map +1 -0
- package/dist/blobs/index.cjs +1480 -0
- package/dist/blobs/index.cjs.map +1 -0
- package/dist/blobs/index.d.cts +45 -0
- package/dist/blobs/index.d.ts +45 -0
- package/dist/blobs/index.js +48 -0
- package/dist/blobs/index.js.map +1 -0
- package/dist/bundle/index.cjs +436 -0
- package/dist/bundle/index.cjs.map +1 -0
- package/dist/bundle/index.d.cts +7 -0
- package/dist/bundle/index.d.ts +7 -0
- package/dist/bundle/index.js +40 -0
- package/dist/bundle/index.js.map +1 -0
- package/dist/chunk-2QR2PQTT.js +217 -0
- package/dist/chunk-2QR2PQTT.js.map +1 -0
- package/dist/chunk-4OWFYIDQ.js +79 -0
- package/dist/chunk-4OWFYIDQ.js.map +1 -0
- package/dist/chunk-5AATM2M2.js +90 -0
- package/dist/chunk-5AATM2M2.js.map +1 -0
- package/dist/chunk-ACLDOTNQ.js +543 -0
- package/dist/chunk-ACLDOTNQ.js.map +1 -0
- package/dist/chunk-BTDCBVJW.js +160 -0
- package/dist/chunk-BTDCBVJW.js.map +1 -0
- package/dist/chunk-CIMZBAZB.js +72 -0
- package/dist/chunk-CIMZBAZB.js.map +1 -0
- package/dist/chunk-E445ICYI.js +365 -0
- package/dist/chunk-E445ICYI.js.map +1 -0
- package/dist/chunk-EXQRC2L4.js +722 -0
- package/dist/chunk-EXQRC2L4.js.map +1 -0
- package/dist/chunk-FZU343FL.js +32 -0
- package/dist/chunk-FZU343FL.js.map +1 -0
- package/dist/chunk-GJILMRPO.js +354 -0
- package/dist/chunk-GJILMRPO.js.map +1 -0
- package/dist/chunk-GOUT6DND.js +1285 -0
- package/dist/chunk-GOUT6DND.js.map +1 -0
- package/dist/chunk-J66GRPNH.js +111 -0
- package/dist/chunk-J66GRPNH.js.map +1 -0
- package/dist/chunk-M2F2JAWB.js +464 -0
- package/dist/chunk-M2F2JAWB.js.map +1 -0
- package/dist/chunk-M5INGEFC.js +84 -0
- package/dist/chunk-M5INGEFC.js.map +1 -0
- package/dist/chunk-M62XNWRA.js +72 -0
- package/dist/chunk-M62XNWRA.js.map +1 -0
- package/dist/chunk-MR4424N3.js +275 -0
- package/dist/chunk-MR4424N3.js.map +1 -0
- package/dist/chunk-NPC4LFV5.js +132 -0
- package/dist/chunk-NPC4LFV5.js.map +1 -0
- package/dist/chunk-NXFEYLVG.js +311 -0
- package/dist/chunk-NXFEYLVG.js.map +1 -0
- package/dist/chunk-R36SIKES.js +79 -0
- package/dist/chunk-R36SIKES.js.map +1 -0
- package/dist/chunk-TDR6T5CJ.js +381 -0
- package/dist/chunk-TDR6T5CJ.js.map +1 -0
- package/dist/chunk-UF3BUNQZ.js +1 -0
- package/dist/chunk-UF3BUNQZ.js.map +1 -0
- package/dist/chunk-UQFSPSWG.js +1109 -0
- package/dist/chunk-UQFSPSWG.js.map +1 -0
- package/dist/chunk-USKYUS74.js +793 -0
- package/dist/chunk-USKYUS74.js.map +1 -0
- package/dist/chunk-XCL3WP6J.js +121 -0
- package/dist/chunk-XCL3WP6J.js.map +1 -0
- package/dist/chunk-XHFOENR2.js +680 -0
- package/dist/chunk-XHFOENR2.js.map +1 -0
- package/dist/chunk-ZFKD4QMV.js +430 -0
- package/dist/chunk-ZFKD4QMV.js.map +1 -0
- package/dist/chunk-ZLMV3TUA.js +490 -0
- package/dist/chunk-ZLMV3TUA.js.map +1 -0
- package/dist/chunk-ZRG4V3F5.js +17 -0
- package/dist/chunk-ZRG4V3F5.js.map +1 -0
- package/dist/consent/index.cjs +204 -0
- package/dist/consent/index.cjs.map +1 -0
- package/dist/consent/index.d.cts +24 -0
- package/dist/consent/index.d.ts +24 -0
- package/dist/consent/index.js +23 -0
- package/dist/consent/index.js.map +1 -0
- package/dist/crdt/index.cjs +152 -0
- package/dist/crdt/index.cjs.map +1 -0
- package/dist/crdt/index.d.cts +30 -0
- package/dist/crdt/index.d.ts +30 -0
- package/dist/crdt/index.js +24 -0
- package/dist/crdt/index.js.map +1 -0
- package/dist/crypto-IVKU7YTT.js +44 -0
- package/dist/crypto-IVKU7YTT.js.map +1 -0
- package/dist/delegation-XDJCBTI2.js +16 -0
- package/dist/delegation-XDJCBTI2.js.map +1 -0
- package/dist/dev-unlock-CeXic1xC.d.cts +263 -0
- package/dist/dev-unlock-KrKkcqD3.d.ts +263 -0
- package/dist/hash-9KO1BGxh.d.cts +63 -0
- package/dist/hash-ChfJjRjQ.d.ts +63 -0
- package/dist/history/index.cjs +1215 -0
- package/dist/history/index.cjs.map +1 -0
- package/dist/history/index.d.cts +62 -0
- package/dist/history/index.d.ts +62 -0
- package/dist/history/index.js +79 -0
- package/dist/history/index.js.map +1 -0
- package/dist/i18n/index.cjs +746 -0
- package/dist/i18n/index.cjs.map +1 -0
- package/dist/i18n/index.d.cts +38 -0
- package/dist/i18n/index.d.ts +38 -0
- package/dist/i18n/index.js +55 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/index-BRHBCmLt.d.ts +1940 -0
- package/dist/index-C8kQtmOk.d.ts +380 -0
- package/dist/index-DN-J-5wT.d.cts +1940 -0
- package/dist/index-DhjMjz7L.d.cts +380 -0
- package/dist/index.cjs +14756 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +269 -0
- package/dist/index.d.ts +269 -0
- package/dist/index.js +6085 -0
- package/dist/index.js.map +1 -0
- package/dist/indexing/index.cjs +736 -0
- package/dist/indexing/index.cjs.map +1 -0
- package/dist/indexing/index.d.cts +36 -0
- package/dist/indexing/index.d.ts +36 -0
- package/dist/indexing/index.js +77 -0
- package/dist/indexing/index.js.map +1 -0
- package/dist/lazy-builder-BwEoBQZ9.d.ts +304 -0
- package/dist/lazy-builder-CZVLKh0Z.d.cts +304 -0
- package/dist/ledger-2NX4L7PN.js +33 -0
- package/dist/ledger-2NX4L7PN.js.map +1 -0
- package/dist/mime-magic-CBBSOkjm.d.cts +50 -0
- package/dist/mime-magic-CBBSOkjm.d.ts +50 -0
- package/dist/periods/index.cjs +1035 -0
- package/dist/periods/index.cjs.map +1 -0
- package/dist/periods/index.d.cts +21 -0
- package/dist/periods/index.d.ts +21 -0
- package/dist/periods/index.js +25 -0
- package/dist/periods/index.js.map +1 -0
- package/dist/predicate-SBHmi6D0.d.cts +161 -0
- package/dist/predicate-SBHmi6D0.d.ts +161 -0
- package/dist/query/index.cjs +1957 -0
- package/dist/query/index.cjs.map +1 -0
- package/dist/query/index.d.cts +3 -0
- package/dist/query/index.d.ts +3 -0
- package/dist/query/index.js +62 -0
- package/dist/query/index.js.map +1 -0
- package/dist/session/index.cjs +487 -0
- package/dist/session/index.cjs.map +1 -0
- package/dist/session/index.d.cts +45 -0
- package/dist/session/index.d.ts +45 -0
- package/dist/session/index.js +44 -0
- package/dist/session/index.js.map +1 -0
- package/dist/shadow/index.cjs +133 -0
- package/dist/shadow/index.cjs.map +1 -0
- package/dist/shadow/index.d.cts +16 -0
- package/dist/shadow/index.d.ts +16 -0
- package/dist/shadow/index.js +20 -0
- package/dist/shadow/index.js.map +1 -0
- package/dist/store/index.cjs +1069 -0
- package/dist/store/index.cjs.map +1 -0
- package/dist/store/index.d.cts +491 -0
- package/dist/store/index.d.ts +491 -0
- package/dist/store/index.js +34 -0
- package/dist/store/index.js.map +1 -0
- package/dist/strategy-BSxFXGzb.d.cts +110 -0
- package/dist/strategy-BSxFXGzb.d.ts +110 -0
- package/dist/strategy-D-SrOLCl.d.cts +548 -0
- package/dist/strategy-D-SrOLCl.d.ts +548 -0
- package/dist/sync/index.cjs +1062 -0
- package/dist/sync/index.cjs.map +1 -0
- package/dist/sync/index.d.cts +42 -0
- package/dist/sync/index.d.ts +42 -0
- package/dist/sync/index.js +28 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/team/index.cjs +1233 -0
- package/dist/team/index.cjs.map +1 -0
- package/dist/team/index.d.cts +117 -0
- package/dist/team/index.d.ts +117 -0
- package/dist/team/index.js +39 -0
- package/dist/team/index.js.map +1 -0
- package/dist/tx/index.cjs +212 -0
- package/dist/tx/index.cjs.map +1 -0
- package/dist/tx/index.d.cts +20 -0
- package/dist/tx/index.d.ts +20 -0
- package/dist/tx/index.js +20 -0
- package/dist/tx/index.js.map +1 -0
- package/dist/types-BZpCZB8N.d.ts +7526 -0
- package/dist/types-Bfs0qr5F.d.cts +7526 -0
- package/dist/ulid-COREQ2RQ.js +9 -0
- package/dist/ulid-COREQ2RQ.js.map +1 -0
- package/dist/util/index.cjs +230 -0
- package/dist/util/index.cjs.map +1 -0
- package/dist/util/index.d.cts +77 -0
- package/dist/util/index.d.ts +77 -0
- package/dist/util/index.js +190 -0
- package/dist/util/index.js.map +1 -0
- package/package.json +244 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { at as NoydbStore, ar as UnlockedKeyring } from '../types-Bfs0qr5F.cjs';
|
|
2
|
+
export { bK as PresenceHandle, c6 as SyncEngine, ce as SyncTransaction, cq as evaluateExportCapability, cr as evaluateImportCapability, cs as hasExportCapability, ct as hasImportCapability } from '../types-Bfs0qr5F.cjs';
|
|
3
|
+
import '../lazy-builder-CZVLKh0Z.cjs';
|
|
4
|
+
import '../predicate-SBHmi6D0.cjs';
|
|
5
|
+
import '../strategy-D-SrOLCl.cjs';
|
|
6
|
+
import '../strategy-BSxFXGzb.cjs';
|
|
7
|
+
import '../index-DN-J-5wT.cjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* _sync_credentials reserved collection —
|
|
11
|
+
*
|
|
12
|
+
* Stores per-adapter OAuth tokens (and any other long-lived sync secrets) as
|
|
13
|
+
* encrypted records inside the vault itself. Tokens are wrapped with the
|
|
14
|
+
* compartment's own DEK, live on disk as ciphertext like any other record, and
|
|
15
|
+
* are accessed only through the dedicated API in this module — never via
|
|
16
|
+
* `vault.collection('_sync_credentials')`.
|
|
17
|
+
*
|
|
18
|
+
* Design decisions
|
|
19
|
+
* ────────────────
|
|
20
|
+
*
|
|
21
|
+
* **Why a reserved collection, not a separate store?**
|
|
22
|
+
* The compartment's existing encryption stack (AES-256-GCM + collection DEK)
|
|
23
|
+
* is exactly the right primitive for protecting OAuth tokens at rest. Using a
|
|
24
|
+
* separate store would require a new encryption surface, new adapter calls,
|
|
25
|
+
* and a new backup/restore path — all of which already exist for collections.
|
|
26
|
+
*
|
|
27
|
+
* **Why not exposed as a regular collection?**
|
|
28
|
+
* The same reason `_keyring` and `_ledger` aren't: they have invariants that
|
|
29
|
+
* must be enforced (naming scheme, no cross-user leakage, no schema
|
|
30
|
+
* validation, no history/ledger writes for privacy). Routing through a
|
|
31
|
+
* dedicated API enforces those invariants.
|
|
32
|
+
*
|
|
33
|
+
* **Token lifecycle:**
|
|
34
|
+
* - `putCredential(vault, adapterId, token)` — store or overwrite
|
|
35
|
+
* - `getCredential(vault, adapterId)` — load and decrypt
|
|
36
|
+
* - `deleteCredential(vault, adapterId)` — remove
|
|
37
|
+
* - `listCredentials(vault)` — enumerate adapter IDs (not tokens)
|
|
38
|
+
*
|
|
39
|
+
* The `adapterId` is the record ID within the `_sync_credentials` collection.
|
|
40
|
+
* It should be a stable, human-readable identifier for the adapter instance
|
|
41
|
+
* (e.g. `'google-drive'`, `'dropbox'`, `'s3-prod'`).
|
|
42
|
+
*
|
|
43
|
+
* **ACL:** only `owner` and `admin` roles can read/write sync credentials.
|
|
44
|
+
* Operators, viewers, and clients cannot call this API. The check is made
|
|
45
|
+
* against the caller's keyring role at call time.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/** The reserved collection name. Never collides with user collections. */
|
|
49
|
+
declare const SYNC_CREDENTIALS_COLLECTION = "_sync_credentials";
|
|
50
|
+
/**
|
|
51
|
+
* An OAuth/auth token stored in `_sync_credentials`.
|
|
52
|
+
*
|
|
53
|
+
* Fields mirror the OAuth2 token response shape. `customData` is an escape
|
|
54
|
+
* hatch for adapter-specific secrets (API keys, connection strings, etc.)
|
|
55
|
+
* that don't fit the OAuth2 shape.
|
|
56
|
+
*/
|
|
57
|
+
interface SyncCredential {
|
|
58
|
+
/** Stable identifier for the adapter instance (e.g. 'google-drive'). */
|
|
59
|
+
readonly adapterId: string;
|
|
60
|
+
/** OAuth token type, usually 'Bearer'. */
|
|
61
|
+
readonly tokenType: string;
|
|
62
|
+
/** The access token. Expires at `expiresAt` if set. */
|
|
63
|
+
readonly accessToken: string;
|
|
64
|
+
/** Long-lived refresh token for renewing the access token. */
|
|
65
|
+
readonly refreshToken?: string;
|
|
66
|
+
/** ISO timestamp when `accessToken` expires. Absent means "no expiry". */
|
|
67
|
+
readonly expiresAt?: string;
|
|
68
|
+
/** Space-separated OAuth scopes. */
|
|
69
|
+
readonly scopes?: string;
|
|
70
|
+
/** Adapter-specific opaque data (API keys, endpoints, etc.). */
|
|
71
|
+
readonly customData?: Record<string, string>;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Store or overwrite a sync credential for the given adapter.
|
|
75
|
+
*
|
|
76
|
+
* The credential is encrypted with the `_sync_credentials` collection DEK
|
|
77
|
+
* (auto-generated on first use). The record ID is the `adapterId`.
|
|
78
|
+
*
|
|
79
|
+
* Requires owner or admin role.
|
|
80
|
+
*/
|
|
81
|
+
declare function putCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, credential: SyncCredential): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Load and decrypt a sync credential for the given adapter ID.
|
|
84
|
+
*
|
|
85
|
+
* Returns `null` if no credential exists for this adapter.
|
|
86
|
+
* Requires owner or admin role.
|
|
87
|
+
*/
|
|
88
|
+
declare function getCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<SyncCredential | null>;
|
|
89
|
+
/**
|
|
90
|
+
* Delete a sync credential by adapter ID.
|
|
91
|
+
*
|
|
92
|
+
* No-op if the credential doesn't exist. Requires owner or admin role.
|
|
93
|
+
*/
|
|
94
|
+
declare function deleteCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* List all adapter IDs that have stored credentials.
|
|
97
|
+
*
|
|
98
|
+
* Returns only the IDs, never the credential payloads. Useful for
|
|
99
|
+
* displaying "connected adapters" in UI without decrypting tokens.
|
|
100
|
+
* Requires owner or admin role.
|
|
101
|
+
*/
|
|
102
|
+
declare function listCredentials(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring): Promise<string[]>;
|
|
103
|
+
/**
|
|
104
|
+
* Check whether a credential exists and whether its access token has expired.
|
|
105
|
+
*
|
|
106
|
+
* Returns `{ exists: false }` if no credential is stored, or
|
|
107
|
+
* `{ exists: true, expired: boolean }` based on the `expiresAt` field.
|
|
108
|
+
* Requires owner or admin role.
|
|
109
|
+
*/
|
|
110
|
+
declare function credentialStatus(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<{
|
|
111
|
+
exists: false;
|
|
112
|
+
} | {
|
|
113
|
+
exists: true;
|
|
114
|
+
expired: boolean;
|
|
115
|
+
}>;
|
|
116
|
+
|
|
117
|
+
export { SYNC_CREDENTIALS_COLLECTION, type SyncCredential, UnlockedKeyring, credentialStatus, deleteCredential, getCredential, listCredentials, putCredential };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { at as NoydbStore, ar as UnlockedKeyring } from '../types-BZpCZB8N.js';
|
|
2
|
+
export { bK as PresenceHandle, c6 as SyncEngine, ce as SyncTransaction, cq as evaluateExportCapability, cr as evaluateImportCapability, cs as hasExportCapability, ct as hasImportCapability } from '../types-BZpCZB8N.js';
|
|
3
|
+
import '../lazy-builder-BwEoBQZ9.js';
|
|
4
|
+
import '../predicate-SBHmi6D0.js';
|
|
5
|
+
import '../strategy-D-SrOLCl.js';
|
|
6
|
+
import '../strategy-BSxFXGzb.js';
|
|
7
|
+
import '../index-BRHBCmLt.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* _sync_credentials reserved collection —
|
|
11
|
+
*
|
|
12
|
+
* Stores per-adapter OAuth tokens (and any other long-lived sync secrets) as
|
|
13
|
+
* encrypted records inside the vault itself. Tokens are wrapped with the
|
|
14
|
+
* compartment's own DEK, live on disk as ciphertext like any other record, and
|
|
15
|
+
* are accessed only through the dedicated API in this module — never via
|
|
16
|
+
* `vault.collection('_sync_credentials')`.
|
|
17
|
+
*
|
|
18
|
+
* Design decisions
|
|
19
|
+
* ────────────────
|
|
20
|
+
*
|
|
21
|
+
* **Why a reserved collection, not a separate store?**
|
|
22
|
+
* The compartment's existing encryption stack (AES-256-GCM + collection DEK)
|
|
23
|
+
* is exactly the right primitive for protecting OAuth tokens at rest. Using a
|
|
24
|
+
* separate store would require a new encryption surface, new adapter calls,
|
|
25
|
+
* and a new backup/restore path — all of which already exist for collections.
|
|
26
|
+
*
|
|
27
|
+
* **Why not exposed as a regular collection?**
|
|
28
|
+
* The same reason `_keyring` and `_ledger` aren't: they have invariants that
|
|
29
|
+
* must be enforced (naming scheme, no cross-user leakage, no schema
|
|
30
|
+
* validation, no history/ledger writes for privacy). Routing through a
|
|
31
|
+
* dedicated API enforces those invariants.
|
|
32
|
+
*
|
|
33
|
+
* **Token lifecycle:**
|
|
34
|
+
* - `putCredential(vault, adapterId, token)` — store or overwrite
|
|
35
|
+
* - `getCredential(vault, adapterId)` — load and decrypt
|
|
36
|
+
* - `deleteCredential(vault, adapterId)` — remove
|
|
37
|
+
* - `listCredentials(vault)` — enumerate adapter IDs (not tokens)
|
|
38
|
+
*
|
|
39
|
+
* The `adapterId` is the record ID within the `_sync_credentials` collection.
|
|
40
|
+
* It should be a stable, human-readable identifier for the adapter instance
|
|
41
|
+
* (e.g. `'google-drive'`, `'dropbox'`, `'s3-prod'`).
|
|
42
|
+
*
|
|
43
|
+
* **ACL:** only `owner` and `admin` roles can read/write sync credentials.
|
|
44
|
+
* Operators, viewers, and clients cannot call this API. The check is made
|
|
45
|
+
* against the caller's keyring role at call time.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
/** The reserved collection name. Never collides with user collections. */
|
|
49
|
+
declare const SYNC_CREDENTIALS_COLLECTION = "_sync_credentials";
|
|
50
|
+
/**
|
|
51
|
+
* An OAuth/auth token stored in `_sync_credentials`.
|
|
52
|
+
*
|
|
53
|
+
* Fields mirror the OAuth2 token response shape. `customData` is an escape
|
|
54
|
+
* hatch for adapter-specific secrets (API keys, connection strings, etc.)
|
|
55
|
+
* that don't fit the OAuth2 shape.
|
|
56
|
+
*/
|
|
57
|
+
interface SyncCredential {
|
|
58
|
+
/** Stable identifier for the adapter instance (e.g. 'google-drive'). */
|
|
59
|
+
readonly adapterId: string;
|
|
60
|
+
/** OAuth token type, usually 'Bearer'. */
|
|
61
|
+
readonly tokenType: string;
|
|
62
|
+
/** The access token. Expires at `expiresAt` if set. */
|
|
63
|
+
readonly accessToken: string;
|
|
64
|
+
/** Long-lived refresh token for renewing the access token. */
|
|
65
|
+
readonly refreshToken?: string;
|
|
66
|
+
/** ISO timestamp when `accessToken` expires. Absent means "no expiry". */
|
|
67
|
+
readonly expiresAt?: string;
|
|
68
|
+
/** Space-separated OAuth scopes. */
|
|
69
|
+
readonly scopes?: string;
|
|
70
|
+
/** Adapter-specific opaque data (API keys, endpoints, etc.). */
|
|
71
|
+
readonly customData?: Record<string, string>;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Store or overwrite a sync credential for the given adapter.
|
|
75
|
+
*
|
|
76
|
+
* The credential is encrypted with the `_sync_credentials` collection DEK
|
|
77
|
+
* (auto-generated on first use). The record ID is the `adapterId`.
|
|
78
|
+
*
|
|
79
|
+
* Requires owner or admin role.
|
|
80
|
+
*/
|
|
81
|
+
declare function putCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, credential: SyncCredential): Promise<void>;
|
|
82
|
+
/**
|
|
83
|
+
* Load and decrypt a sync credential for the given adapter ID.
|
|
84
|
+
*
|
|
85
|
+
* Returns `null` if no credential exists for this adapter.
|
|
86
|
+
* Requires owner or admin role.
|
|
87
|
+
*/
|
|
88
|
+
declare function getCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<SyncCredential | null>;
|
|
89
|
+
/**
|
|
90
|
+
* Delete a sync credential by adapter ID.
|
|
91
|
+
*
|
|
92
|
+
* No-op if the credential doesn't exist. Requires owner or admin role.
|
|
93
|
+
*/
|
|
94
|
+
declare function deleteCredential(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* List all adapter IDs that have stored credentials.
|
|
97
|
+
*
|
|
98
|
+
* Returns only the IDs, never the credential payloads. Useful for
|
|
99
|
+
* displaying "connected adapters" in UI without decrypting tokens.
|
|
100
|
+
* Requires owner or admin role.
|
|
101
|
+
*/
|
|
102
|
+
declare function listCredentials(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring): Promise<string[]>;
|
|
103
|
+
/**
|
|
104
|
+
* Check whether a credential exists and whether its access token has expired.
|
|
105
|
+
*
|
|
106
|
+
* Returns `{ exists: false }` if no credential is stored, or
|
|
107
|
+
* `{ exists: true, expired: boolean }` based on the `expiresAt` field.
|
|
108
|
+
* Requires owner or admin role.
|
|
109
|
+
*/
|
|
110
|
+
declare function credentialStatus(adapter: NoydbStore, vault: string, keyring: UnlockedKeyring, adapterId: string): Promise<{
|
|
111
|
+
exists: false;
|
|
112
|
+
} | {
|
|
113
|
+
exists: true;
|
|
114
|
+
expired: boolean;
|
|
115
|
+
}>;
|
|
116
|
+
|
|
117
|
+
export { SYNC_CREDENTIALS_COLLECTION, type SyncCredential, UnlockedKeyring, credentialStatus, deleteCredential, getCredential, listCredentials, putCredential };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SYNC_CREDENTIALS_COLLECTION,
|
|
3
|
+
credentialStatus,
|
|
4
|
+
deleteCredential,
|
|
5
|
+
getCredential,
|
|
6
|
+
listCredentials,
|
|
7
|
+
putCredential
|
|
8
|
+
} from "../chunk-4OWFYIDQ.js";
|
|
9
|
+
import {
|
|
10
|
+
PresenceHandle,
|
|
11
|
+
SyncEngine,
|
|
12
|
+
SyncTransaction
|
|
13
|
+
} from "../chunk-EXQRC2L4.js";
|
|
14
|
+
import {
|
|
15
|
+
evaluateExportCapability,
|
|
16
|
+
evaluateImportCapability,
|
|
17
|
+
hasExportCapability,
|
|
18
|
+
hasImportCapability
|
|
19
|
+
} from "../chunk-M2F2JAWB.js";
|
|
20
|
+
import "../chunk-2QR2PQTT.js";
|
|
21
|
+
import "../chunk-ZRG4V3F5.js";
|
|
22
|
+
import "../chunk-MR4424N3.js";
|
|
23
|
+
import "../chunk-ACLDOTNQ.js";
|
|
24
|
+
export {
|
|
25
|
+
PresenceHandle,
|
|
26
|
+
SYNC_CREDENTIALS_COLLECTION,
|
|
27
|
+
SyncEngine,
|
|
28
|
+
SyncTransaction,
|
|
29
|
+
credentialStatus,
|
|
30
|
+
deleteCredential,
|
|
31
|
+
evaluateExportCapability,
|
|
32
|
+
evaluateImportCapability,
|
|
33
|
+
getCredential,
|
|
34
|
+
hasExportCapability,
|
|
35
|
+
hasImportCapability,
|
|
36
|
+
listCredentials,
|
|
37
|
+
putCredential
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/tx/index.ts
|
|
21
|
+
var tx_exports = {};
|
|
22
|
+
__export(tx_exports, {
|
|
23
|
+
TxCollection: () => TxCollection,
|
|
24
|
+
TxContext: () => TxContext,
|
|
25
|
+
TxVault: () => TxVault,
|
|
26
|
+
runTransaction: () => runTransaction,
|
|
27
|
+
withTransactions: () => withTransactions
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(tx_exports);
|
|
30
|
+
|
|
31
|
+
// src/errors.ts
|
|
32
|
+
var NoydbError = class extends Error {
|
|
33
|
+
/** Machine-readable error code. Stable across library versions. */
|
|
34
|
+
code;
|
|
35
|
+
constructor(code, message) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "NoydbError";
|
|
38
|
+
this.code = code;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var ConflictError = class extends NoydbError {
|
|
42
|
+
/** The actual stored version at the time of conflict. */
|
|
43
|
+
version;
|
|
44
|
+
constructor(version, message = "Version conflict") {
|
|
45
|
+
super("CONFLICT", message);
|
|
46
|
+
this.name = "ConflictError";
|
|
47
|
+
this.version = version;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// src/tx/transaction.ts
|
|
52
|
+
var TxContext = class {
|
|
53
|
+
/** @internal */
|
|
54
|
+
_ops = [];
|
|
55
|
+
/** @internal */
|
|
56
|
+
_db;
|
|
57
|
+
/** @internal */
|
|
58
|
+
constructor(db) {
|
|
59
|
+
this._db = db;
|
|
60
|
+
}
|
|
61
|
+
/** Scope subsequent `collection()` calls to the named vault. */
|
|
62
|
+
vault(name) {
|
|
63
|
+
const v = this._db.vault(name);
|
|
64
|
+
return new TxVault(this, v);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var TxVault = class {
|
|
68
|
+
/** @internal */
|
|
69
|
+
_ctx;
|
|
70
|
+
/** @internal */
|
|
71
|
+
_vault;
|
|
72
|
+
/** @internal */
|
|
73
|
+
constructor(ctx, vault) {
|
|
74
|
+
this._ctx = ctx;
|
|
75
|
+
this._vault = vault;
|
|
76
|
+
}
|
|
77
|
+
/** Scope subsequent op calls to the named collection. */
|
|
78
|
+
collection(name) {
|
|
79
|
+
const c = this._vault.collection(name);
|
|
80
|
+
return new TxCollection(this._ctx, this._vault, c, name);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
var TxCollection = class {
|
|
84
|
+
/** @internal */
|
|
85
|
+
_ctx;
|
|
86
|
+
/** @internal */
|
|
87
|
+
_vault;
|
|
88
|
+
/** @internal */
|
|
89
|
+
_coll;
|
|
90
|
+
/** @internal */
|
|
91
|
+
_name;
|
|
92
|
+
/** @internal */
|
|
93
|
+
constructor(ctx, vault, coll, name) {
|
|
94
|
+
this._ctx = ctx;
|
|
95
|
+
this._vault = vault;
|
|
96
|
+
this._coll = coll;
|
|
97
|
+
this._name = name;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Read the current committed value, or the most-recently-staged
|
|
101
|
+
* value from the same transaction if one exists.
|
|
102
|
+
*/
|
|
103
|
+
async get(id) {
|
|
104
|
+
for (let i = this._ctx._ops.length - 1; i >= 0; i--) {
|
|
105
|
+
const op = this._ctx._ops[i];
|
|
106
|
+
if (op.vaultName === this._vault.name && op.collectionName === this._name && op.id === id) {
|
|
107
|
+
if (op.type === "delete") return null;
|
|
108
|
+
return op.record;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return this._coll.get(id);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Stage a put. Does not write until the transaction body returns.
|
|
115
|
+
* Supply `{ expectedVersion }` to enforce optimistic concurrency
|
|
116
|
+
* during the commit pre-flight.
|
|
117
|
+
*/
|
|
118
|
+
put(id, record, options) {
|
|
119
|
+
const op = {
|
|
120
|
+
type: "put",
|
|
121
|
+
vaultName: this._vault.name,
|
|
122
|
+
collectionName: this._name,
|
|
123
|
+
id,
|
|
124
|
+
record
|
|
125
|
+
};
|
|
126
|
+
if (options?.expectedVersion !== void 0) op.expectedVersion = options.expectedVersion;
|
|
127
|
+
this._ctx._ops.push(op);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Stage a delete. Does not write until the transaction body returns.
|
|
131
|
+
* Supply `{ expectedVersion }` to enforce optimistic concurrency
|
|
132
|
+
* during the commit pre-flight.
|
|
133
|
+
*/
|
|
134
|
+
delete(id, options) {
|
|
135
|
+
const op = {
|
|
136
|
+
type: "delete",
|
|
137
|
+
vaultName: this._vault.name,
|
|
138
|
+
collectionName: this._name,
|
|
139
|
+
id
|
|
140
|
+
};
|
|
141
|
+
if (options?.expectedVersion !== void 0) op.expectedVersion = options.expectedVersion;
|
|
142
|
+
this._ctx._ops.push(op);
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
async function runTransaction(db, fn) {
|
|
146
|
+
const ctx = new TxContext(db);
|
|
147
|
+
const bodyResult = await fn(ctx);
|
|
148
|
+
if (ctx._ops.length === 0) return bodyResult;
|
|
149
|
+
const priorEnvelopes = /* @__PURE__ */ new Map();
|
|
150
|
+
const store = db._store;
|
|
151
|
+
for (const op of ctx._ops) {
|
|
152
|
+
const key = keyOf(op);
|
|
153
|
+
if (!priorEnvelopes.has(key)) {
|
|
154
|
+
const env = await store.get(op.vaultName, op.collectionName, op.id);
|
|
155
|
+
priorEnvelopes.set(key, env);
|
|
156
|
+
}
|
|
157
|
+
if (op.expectedVersion !== void 0) {
|
|
158
|
+
const env = priorEnvelopes.get(key) ?? null;
|
|
159
|
+
const actual = env?._v ?? 0;
|
|
160
|
+
if (actual !== op.expectedVersion) {
|
|
161
|
+
throw new ConflictError(
|
|
162
|
+
actual,
|
|
163
|
+
`Transaction pre-flight: ${op.vaultName}/${op.collectionName}/${op.id} expected v${op.expectedVersion}, found v${actual}`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const executed = [];
|
|
169
|
+
try {
|
|
170
|
+
for (const op of ctx._ops) {
|
|
171
|
+
const coll = db.vault(op.vaultName).collection(op.collectionName);
|
|
172
|
+
const key = keyOf(op);
|
|
173
|
+
const prior = priorEnvelopes.get(key) ?? null;
|
|
174
|
+
if (op.type === "put") {
|
|
175
|
+
await coll.put(op.id, op.record);
|
|
176
|
+
} else {
|
|
177
|
+
await coll.delete(op.id);
|
|
178
|
+
}
|
|
179
|
+
executed.push({ op, priorEnvelope: prior });
|
|
180
|
+
}
|
|
181
|
+
return bodyResult;
|
|
182
|
+
} catch (err) {
|
|
183
|
+
for (const { op, priorEnvelope } of executed.slice().reverse()) {
|
|
184
|
+
try {
|
|
185
|
+
if (priorEnvelope) {
|
|
186
|
+
await store.put(op.vaultName, op.collectionName, op.id, priorEnvelope);
|
|
187
|
+
} else {
|
|
188
|
+
await store.delete(op.vaultName, op.collectionName, op.id);
|
|
189
|
+
}
|
|
190
|
+
} catch {
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
throw err;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function keyOf(op) {
|
|
197
|
+
return `${op.vaultName}\0${op.collectionName}\0${op.id}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// src/tx/active.ts
|
|
201
|
+
function withTransactions() {
|
|
202
|
+
return { runTransaction };
|
|
203
|
+
}
|
|
204
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
205
|
+
0 && (module.exports = {
|
|
206
|
+
TxCollection,
|
|
207
|
+
TxContext,
|
|
208
|
+
TxVault,
|
|
209
|
+
runTransaction,
|
|
210
|
+
withTransactions
|
|
211
|
+
});
|
|
212
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/tx/index.ts","../../src/errors.ts","../../src/tx/transaction.ts","../../src/tx/active.ts"],"sourcesContent":["/**\n * Multi-record transactions subpath barrel.\n *\n * Public entry point is `db.transaction(fn)`; these types are exported\n * so consumers can annotate transaction-body signatures in their own\n * code.\n */\nexport { withTransactions } from './active.js'\nexport type { TxStrategy } from './strategy.js'\n\nexport { TxContext, TxVault, TxCollection, runTransaction } from './transaction.js'\n","/**\n * All NOYDB error classes — a single import surface for `catch` blocks and\n * `instanceof` checks.\n *\n * ## Class hierarchy\n *\n * ```\n * Error\n * └─ NoydbError (code: string)\n * ├─ Crypto errors\n * │ ├─ DecryptionError — AES-GCM tag failure\n * │ ├─ TamperedError — ciphertext modified after write\n * │ └─ InvalidKeyError — wrong passphrase / corrupt keyring\n * ├─ Access errors\n * │ ├─ NoAccessError — no DEK for this collection\n * │ ├─ ReadOnlyError — ro permission, write attempted\n * │ ├─ PermissionDeniedError — role too low for operation\n * │ ├─ PrivilegeEscalationError — grant wider than grantor holds\n * │ └─ StoreCapabilityError — optional store method missing\n * ├─ Sync errors\n * │ ├─ ConflictError — optimistic-lock version mismatch\n * │ ├─ BundleVersionConflictError — bundle push rejected by remote\n * │ └─ NetworkError — push/pull network failure\n * ├─ Data errors\n * │ ├─ NotFoundError — get(id) on missing record\n * │ ├─ ValidationError — application-level guard failed\n * │ └─ SchemaValidationError — Standard Schema v1 rejection\n * ├─ Query errors\n * │ ├─ JoinTooLargeError — join row ceiling exceeded\n * │ ├─ DanglingReferenceError — strict ref() points at nothing\n * │ ├─ GroupCardinalityError — groupBy bucket cap exceeded\n * │ ├─ IndexRequiredError — lazy-mode query touches unindexed field\n * │ └─ IndexWriteFailureError — index side-car put/delete failed post-main\n * ├─ i18n / Dictionary errors\n * │ ├─ ReservedCollectionNameError\n * │ ├─ DictKeyMissingError\n * │ ├─ DictKeyInUseError\n * │ ├─ MissingTranslationError\n * │ ├─ LocaleNotSpecifiedError\n * │ └─ TranslatorNotConfiguredError\n * ├─ Backup errors\n * │ ├─ BackupLedgerError — hash-chain verification failed\n * │ └─ BackupCorruptedError — envelope hash mismatch in dump\n * ├─ Bundle errors\n * │ └─ BundleIntegrityError — .noydb body sha256 mismatch\n * └─ Session errors\n * ├─ SessionExpiredError\n * ├─ SessionNotFoundError\n * └─ SessionPolicyError\n * ```\n *\n * ## Catching all NOYDB errors\n *\n * ```ts\n * import { NoydbError, InvalidKeyError, ConflictError } from '@noy-db/hub'\n *\n * try {\n * await vault.unlock(passphrase)\n * } catch (e) {\n * if (e instanceof InvalidKeyError) { showBadPassphraseUI(); return }\n * if (e instanceof NoydbError) { logToSentry(e.code, e); return }\n * throw e // unexpected — re-throw\n * }\n * ```\n *\n * @module\n */\n\n/**\n * Base class for all NOYDB errors.\n *\n * Every error thrown by `@noy-db/hub` extends this class, so consumers can\n * catch all NOYDB errors in a single `catch (e) { if (e instanceof NoydbError) ... }`\n * block. The `code` field is a machine-readable string (e.g. `'DECRYPTION_FAILED'`)\n * suitable for `switch` statements and logging pipelines.\n */\nexport class NoydbError extends Error {\n /** Machine-readable error code. Stable across library versions. */\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = 'NoydbError'\n this.code = code\n }\n}\n\n// ─── Crypto Errors ─────────────────────────────────────────────────────\n\n/**\n * Thrown when AES-GCM decryption fails.\n *\n * The most common cause is a wrong passphrase or a corrupted ciphertext.\n * A `DecryptionError` at the wrong passphrase level is caught internally\n * and re-thrown as `InvalidKeyError` — so in practice this surfaces for\n * per-record corruption rather than authentication failures.\n */\nexport class DecryptionError extends NoydbError {\n constructor(message = 'Decryption failed') {\n super('DECRYPTION_FAILED', message)\n this.name = 'DecryptionError'\n }\n}\n\n/**\n * Thrown when GCM tag verification fails, indicating the ciphertext was\n * modified after encryption.\n *\n * AES-256-GCM is authenticated encryption — the tag over the ciphertext\n * is checked on every decrypt. If any byte was flipped (accidental\n * corruption or deliberate tampering), decryption throws this error.\n * Treat it as a security alert: the stored bytes are not what NOYDB wrote.\n */\nexport class TamperedError extends NoydbError {\n constructor(message = 'Data integrity check failed — record may have been tampered with') {\n super('TAMPERED', message)\n this.name = 'TamperedError'\n }\n}\n\n/**\n * Thrown when key unwrapping fails, typically because the passphrase is wrong\n * or the keyring file is corrupted.\n *\n * NOYDB uses AES-KW (RFC 3394) to wrap DEKs with the KEK. If AES-KW\n * unwrapping fails, it means either the KEK was derived from the wrong\n * passphrase (PBKDF2 with 600K iterations) or the keyring bytes are\n * corrupted. This is the error shown to the user on a failed unlock attempt.\n */\nexport class InvalidKeyError extends NoydbError {\n constructor(message = 'Invalid key — wrong passphrase or corrupted keyring') {\n super('INVALID_KEY', message)\n this.name = 'InvalidKeyError'\n }\n}\n\n// ─── Access Errors ─────────────────────────────────────────────────────\n\n/**\n * Thrown when the authenticated user does not have a DEK for the requested\n * collection — i.e. the collection is not in their keyring at all.\n *\n * This is the \"no key for this door\" error. It is different from\n * `ReadOnlyError` (user has a key but it only grants ro) and from\n * `PermissionDeniedError` (user's role doesn't allow the operation).\n */\nexport class NoAccessError extends NoydbError {\n constructor(message = 'No access — user does not have a key for this collection') {\n super('NO_ACCESS', message)\n this.name = 'NoAccessError'\n }\n}\n\n/**\n * Thrown when a user with read-only (`ro`) permission attempts a write\n * operation (`put` or `delete`) on a collection.\n *\n * The user has a DEK for the collection (they can decrypt and read), but\n * their keyring grants only `ro`. To fix: re-grant the user with `rw`\n * permission, or do not attempt writes as a viewer/client role.\n */\nexport class ReadOnlyError extends NoydbError {\n constructor(message = 'Read-only — user has ro permission on this collection') {\n super('READ_ONLY', message)\n this.name = 'ReadOnlyError'\n }\n}\n\n/**\n * Thrown when a write is attempted against a historical view produced\n * by `vault.at(timestamp)`. Time-machine views are read-only by\n * contract — mutating the past would require either the shadow-vault\n * mechanism or a ledger-history rewrite (which breaks\n * the tamper-evidence guarantee).\n *\n * Distinct from {@link ReadOnlyError} (keyring-level) and\n * {@link PermissionDeniedError} (role-level): this error is about the\n * *view* being historical, independent of the caller's permissions.\n */\nexport class ReadOnlyAtInstantError extends NoydbError {\n constructor(operation: string, timestamp: string) {\n super(\n 'READ_ONLY_AT_INSTANT',\n `Cannot ${operation}() on a vault view anchored at ${timestamp} — time-machine views are read-only`,\n )\n this.name = 'ReadOnlyAtInstantError'\n }\n}\n\n/**\n * Thrown when a write is attempted against a shadow-vault frame\n * produced by `vault.frame()`. Frames are read-only by contract —\n * the use case is screen-sharing / demos / compliance review where\n * the operator wants to prevent accidental edits.\n *\n * Behavioural enforcement only — the underlying keyring still holds\n * write-capable DEKs. See {@link VaultFrame} for the full caveat.\n */\nexport class ReadOnlyFrameError extends NoydbError {\n constructor(operation: string) {\n super(\n 'READ_ONLY_FRAME',\n `Cannot ${operation}() on a vault frame — frames are read-only presentations of the current vault`,\n )\n this.name = 'ReadOnlyFrameError'\n }\n}\n\n/**\n * Thrown when the authenticated user's role does not permit the requested\n * operation — e.g. a `viewer` calling `grantAccess()`, or an `operator`\n * calling `rotateKeys()`.\n *\n * This is a role-level check (what the user's role allows), distinct from\n * `NoAccessError` (collection not in keyring) and `ReadOnlyError` (in\n * keyring, but write not allowed).\n */\nexport class PermissionDeniedError extends NoydbError {\n constructor(message = 'Permission denied — insufficient role for this operation') {\n super('PERMISSION_DENIED', message)\n this.name = 'PermissionDeniedError'\n }\n}\n\n/**\n * Thrown when an `@noy-db/as-*` export is attempted without the\n * required capability bit on the invoking keyring.\n *\n * Two sub-cases discriminated by the `tier` field:\n *\n * - `tier: 'plaintext'` — a plaintext-tier export (`as-xlsx`,\n * `as-csv`, `as-blob`, `as-zip`, …) was attempted but the\n * keyring's `exportCapability.plaintext` does not include the\n * requested `format` (nor the `'*'` wildcard). Default for every\n * role is `plaintext: []` — the owner must positively grant.\n * - `tier: 'bundle'` — an encrypted `as-noydb` bundle export was\n * attempted but the keyring's `exportCapability.bundle` is\n * `false`. Default for `owner`/`admin` is `true`; for\n * `operator`/`viewer`/`client` it is `false`.\n *\n * Distinct from `PermissionDeniedError` (role-level check) and\n * `NoAccessError` (collection not readable). Surfaces separately so\n * UI layers can show a \"request the export capability from your\n * admin\" flow rather than a generic permission error.\n */\nexport class ExportCapabilityError extends NoydbError {\n readonly tier: 'plaintext' | 'bundle'\n readonly format?: string\n readonly userId: string\n\n constructor(opts: {\n tier: 'plaintext' | 'bundle'\n userId: string\n format?: string\n message?: string\n }) {\n const msg =\n opts.message ??\n (opts.tier === 'plaintext'\n ? `Export capability denied — keyring \"${opts.userId}\" is not granted plaintext-export capability for format \"${opts.format ?? '<unknown>'}\". Ask a vault owner or admin to grant it via vault.grant({ exportCapability: { plaintext: ['${opts.format ?? '<format>'}'] } }).`\n : `Export capability denied — keyring \"${opts.userId}\" is not granted encrypted-bundle export capability. Ask a vault owner or admin to grant it via vault.grant({ exportCapability: { bundle: true } }).`)\n super('EXPORT_CAPABILITY', msg)\n this.name = 'ExportCapabilityError'\n this.tier = opts.tier\n this.userId = opts.userId\n if (opts.format !== undefined) this.format = opts.format\n }\n}\n\n/**\n * Thrown when a keyring file's `expires_at` cutoff has passed.\n * Surfaced by `loadKeyring` before any DEK unwrap is attempted —\n * past the cutoff the slot refuses to open even with the right\n * passphrase. Distinct from PBKDF2 / unwrap errors so consumer code\n * can show a precise \"this bundle slot has expired\" message instead\n * of the generic decryption-failure UX.\n *\n * Used predominantly on `BundleRecipient` slots produced by\n * `writeNoydbBundle({ recipients: [...] })` to time-box audit access.\n */\nexport class KeyringExpiredError extends NoydbError {\n readonly userId: string\n readonly expiresAt: string\n constructor(opts: { userId: string; expiresAt: string }) {\n super(\n 'KEYRING_EXPIRED',\n `Keyring \"${opts.userId}\" expired at ${opts.expiresAt}. ` +\n 'The slot refuses to unlock past its expiry timestamp.',\n )\n this.name = 'KeyringExpiredError'\n this.userId = opts.userId\n this.expiresAt = opts.expiresAt\n }\n}\n\n/**\n * Thrown when an `@noy-db/as-*` import is attempted but the invoking\n * keyring lacks the required import-capability bit (issue ).\n *\n * - `tier: 'plaintext'` — a plaintext-tier import (`as-csv`, `as-json`,\n * `as-ndjson`, `as-zip`, …) was attempted but the keyring's\n * `importCapability.plaintext` does not include the requested\n * `format` (nor the `'*'` wildcard).\n * - `tier: 'bundle'` — a `.noydb` bundle import was attempted but the\n * keyring's `importCapability.bundle` is not `true`.\n *\n * Default for every role on every dimension is closed — owners and\n * admins must positively grant the capability. Distinct from\n * `PermissionDeniedError` and `NoAccessError` so UI layers can show a\n * specific \"request the import capability\" flow.\n */\nexport class ImportCapabilityError extends NoydbError {\n readonly tier: 'plaintext' | 'bundle'\n readonly format?: string\n readonly userId: string\n\n constructor(opts: {\n tier: 'plaintext' | 'bundle'\n userId: string\n format?: string\n message?: string\n }) {\n const msg =\n opts.message ??\n (opts.tier === 'plaintext'\n ? `Import capability denied — keyring \"${opts.userId}\" is not granted plaintext-import capability for format \"${opts.format ?? '<unknown>'}\". Ask a vault owner or admin to grant it via vault.grant({ importCapability: { plaintext: ['${opts.format ?? '<format>'}'] } }).`\n : `Import capability denied — keyring \"${opts.userId}\" is not granted encrypted-bundle import capability. Ask a vault owner or admin to grant it via vault.grant({ importCapability: { bundle: true } }).`)\n super('IMPORT_CAPABILITY', msg)\n this.name = 'ImportCapabilityError'\n this.tier = opts.tier\n this.userId = opts.userId\n if (opts.format !== undefined) this.format = opts.format\n }\n}\n\n/**\n * Thrown when a grant would give the grantee a permission the grantor\n * does not themselves hold — the \"admin cannot grant what admin cannot\n * do\" rule from the admin-delegation work.\n *\n * Distinct from `PermissionDeniedError` so callers can tell the two\n * cases apart in logs and tests:\n *\n * - `PermissionDeniedError` — \"you are not allowed to perform this\n * operation at all\" (wrong role).\n * - `PrivilegeEscalationError` — \"you are allowed to grant, but not\n * with these specific permissions\" (widening attempt).\n *\n * Under the admin model the grantee of an admin-grants-admin call\n * inherits the caller's entire DEK set by construction, so this error\n * is structurally unreachable in typical flows. The check and error\n * class exist so that future per-collection admin scoping cannot\n * accidentally bypass the subset rule — the guard is already wired in.\n *\n * `offendingCollection` carries the first collection name that failed\n * the subset check, to make the violation actionable in error output.\n */\n/**\n * Thrown when a caller invokes an API that requires an optional\n * store capability the active store does not implement.\n *\n * Today the only call site is `Noydb.listAccessibleVaults()`,\n * which depends on the optional `NoydbStore.listVaults()`\n * method. The error message names the missing method and the calling\n * API so consumers know exactly which combination is unsupported,\n * and the `capability` field is machine-readable so library code can\n * pattern-match in catch blocks (e.g. fall back to a candidate-list\n * shape).\n *\n * The class lives in `errors.ts` rather than as a generic\n * `ValidationError` because the diagnostic shape is different: a\n * `ValidationError` says \"the inputs you passed are wrong\"; this\n * error says \"the inputs are fine, but the store you wired up\n * doesn't support what you're asking for.\" Different fix, different\n * documentation.\n */\nexport class StoreCapabilityError extends NoydbError {\n /** The store method/capability that was missing. */\n readonly capability: string\n\n constructor(capability: string, callerApi: string, storeName?: string) {\n super(\n 'STORE_CAPABILITY',\n `${callerApi} requires the optional store capability \"${capability}\" ` +\n `but the active store${storeName ? ` (${storeName})` : ''} does not implement it. ` +\n `Use a store that supports \"${capability}\" (store-memory, store-file) or pass an explicit ` +\n `vault list to bypass enumeration.`,\n )\n this.name = 'StoreCapabilityError'\n this.capability = capability\n }\n}\n\nexport class PrivilegeEscalationError extends NoydbError {\n readonly offendingCollection: string\n\n constructor(offendingCollection: string, message?: string) {\n super(\n 'PRIVILEGE_ESCALATION',\n message ??\n `Privilege escalation: grantor has no DEK for collection \"${offendingCollection}\" and cannot grant access to it.`,\n )\n this.name = 'PrivilegeEscalationError'\n this.offendingCollection = offendingCollection\n }\n}\n\n/**\n * Thrown by `Collection.put` / `.delete` when the target record's\n * envelope `_ts` falls within a closed accounting period.\n *\n * Distinct from `ReadOnlyError` (keyring-level), `ReadOnlyAtInstantError`\n * (historical view), and `ReadOnlyFrameError` (shadow vault): this\n * error is about the STORED RECORD being sealed by an operator call\n * to `vault.closePeriod()`, independent of caller permissions or\n * view type. The `periodName` and `endDate` fields name the sealing\n * period so audit UIs can surface a \"this record is locked in\n * FY2026-Q1 (closed 2026-03-31)\" message without parsing the error\n * string.\n *\n * To apply a correction after close, book a compensating entry in a\n * new period rather than unlocking the old one. Re-opening a closed\n * period is deliberately unsupported.\n */\nexport class PeriodClosedError extends NoydbError {\n readonly periodName: string\n readonly endDate: string\n readonly recordTs: string\n\n constructor(periodName: string, endDate: string, recordTs: string) {\n super(\n 'PERIOD_CLOSED',\n `Cannot modify record (last written ${recordTs}) — sealed by closed period ` +\n `\"${periodName}\" (endDate: ${endDate}). Post a compensating entry in a ` +\n `new period instead.`,\n )\n this.name = 'PeriodClosedError'\n this.periodName = periodName\n this.endDate = endDate\n this.recordTs = recordTs\n }\n}\n\n// ─── Hierarchical Access Errors ─────────────────────\n\n/**\n * Thrown when a user tries to act at a tier they are not cleared for.\n *\n * This is the umbrella error for tier write refusals:\n * - `put({ tier: N })` when the user's keyring lacks tier-N DEK.\n * - `elevate(id, N)` when the caller cannot reach tier N.\n *\n * Distinct from `TierAccessDeniedError` which covers *read* refusals on\n * the invisibility/ghost path.\n */\nexport class TierNotGrantedError extends NoydbError {\n readonly tier: number\n readonly collection: string\n\n constructor(collection: string, tier: number) {\n super(\n 'TIER_NOT_GRANTED',\n `User has no DEK for tier ${tier} in collection \"${collection}\"`,\n )\n this.name = 'TierNotGrantedError'\n this.collection = collection\n this.tier = tier\n }\n}\n\n/**\n * Thrown when an elevated-handle operation runs after the elevation's\n * TTL expired. Reads continue at the original tier; only writes\n * through the scoped handle flip to throwing once expired.\n */\nexport class ElevationExpiredError extends NoydbError {\n readonly tier: number\n readonly expiresAt: number\n\n constructor(opts: { tier: number; expiresAt: number }) {\n super(\n 'ELEVATION_EXPIRED',\n `Elevation to tier ${opts.tier} expired at ${new Date(opts.expiresAt).toISOString()}`,\n )\n this.name = 'ElevationExpiredError'\n this.tier = opts.tier\n this.expiresAt = opts.expiresAt\n }\n}\n\n/**\n * Thrown by `vault.elevate(...)` when an elevation is already active\n * on the vault. Adopters must `release()` the existing handle before\n * starting a new elevation.\n */\nexport class AlreadyElevatedError extends NoydbError {\n readonly activeTier: number\n\n constructor(activeTier: number) {\n super(\n 'ALREADY_ELEVATED',\n `Vault is already elevated to tier ${activeTier}; release the existing handle first`,\n )\n this.name = 'AlreadyElevatedError'\n this.activeTier = activeTier\n }\n}\n\n/**\n * Thrown when `demote()` is called by someone who is not the original\n * elevator and not an owner.\n */\nexport class TierDemoteDeniedError extends NoydbError {\n constructor(id: string, tier: number) {\n super(\n 'TIER_DEMOTE_DENIED',\n `Only the original elevator or an owner can demote record \"${id}\" from tier ${tier}`,\n )\n this.name = 'TierDemoteDeniedError'\n }\n}\n\n/**\n * Thrown when `db.delegate()` is called against a user that has no\n * keyring in the target vault — the delegation token cannot be\n * constructed without the target user's KEK wrap.\n */\nexport class DelegationTargetMissingError extends NoydbError {\n readonly toUser: string\n\n constructor(toUser: string) {\n super(\n 'DELEGATION_TARGET_MISSING',\n `Delegation target user \"${toUser}\" has no keyring in this vault`,\n )\n this.name = 'DelegationTargetMissingError'\n this.toUser = toUser\n }\n}\n\n// ─── Sync Errors ───────────────────────────────────────────────────────\n\n/**\n * Thrown when a `put()` detects an optimistic concurrency conflict.\n *\n * NOYDB uses version numbers (`_v`) for optimistic locking. If a `put()`\n * is called with `expectedVersion: N` but the stored record is at version\n * `M ≠ N`, the write is rejected and the caller must re-read, re-apply their\n * change, and retry. The `version` field carries the actual stored version\n * so callers can decide whether to retry or surface the conflict to the user.\n */\nexport class ConflictError extends NoydbError {\n /** The actual stored version at the time of conflict. */\n readonly version: number\n\n constructor(version: number, message = 'Version conflict') {\n super('CONFLICT', message)\n this.name = 'ConflictError'\n this.version = version\n }\n}\n\n/**\n * Thrown by `LedgerStore.append()` after exhausting its CAS retry\n * budget under multi-writer contention. Two browser tabs, a\n * web app + an offline mobile peer, or a server worker pool all\n * producing ledger entries against the same vault can race on the\n * \"read head, write head+1\" cycle; the optimistic-CAS retry loop\n * resolves the race for `casAtomic: true` stores, but pathological\n * contention (or a buggy peer) can still exhaust the budget. When\n * that happens, the chain is intact — the failed writer simply\n * couldn't claim a slot. Caller's choice whether to retry, queue,\n * or surface the failure to the user.\n */\nexport class LedgerContentionError extends NoydbError {\n readonly attempts: number\n\n constructor(attempts: number) {\n super(\n 'LEDGER_CONTENTION',\n `LedgerStore.append: failed to claim a chain slot after ${attempts} optimistic-CAS retries`,\n )\n this.name = 'LedgerContentionError'\n this.attempts = attempts\n }\n}\n\n/**\n * Thrown when a bundle push is rejected because the remote has been updated\n * since the local bundle was last pulled.\n *\n * Unlike `ConflictError` (per-record), this is a whole-bundle conflict —\n * the remote's bundle handle has changed. The caller must pull the new\n * bundle, merge, and re-push. `remoteVersion` is the handle of the newer\n * remote bundle for use in diagnostics.\n */\nexport class BundleVersionConflictError extends NoydbError {\n /** The bundle handle of the newer remote version that rejected the push. */\n readonly remoteVersion: string\n\n constructor(remoteVersion: string, message = 'Bundle version conflict — remote has been updated') {\n super('BUNDLE_VERSION_CONFLICT', message)\n this.name = 'BundleVersionConflictError'\n this.remoteVersion = remoteVersion\n }\n}\n\n/**\n * Thrown when a sync operation (push or pull) fails due to a network error.\n *\n * NOYDB's offline-first design means network errors are expected during sync.\n * Callers should catch `NetworkError`, surface connectivity status in the UI,\n * and rely on the `SyncScheduler` to retry when connectivity is restored.\n */\nexport class NetworkError extends NoydbError {\n constructor(message = 'Network error') {\n super('NETWORK_ERROR', message)\n this.name = 'NetworkError'\n }\n}\n\n// ─── Data Errors ───────────────────────────────────────────────────────\n\n/**\n * Thrown when `collection.get(id)` is called with an ID that does not exist.\n *\n * NOYDB collections are memory-first, so this error is synchronous and cheap —\n * it does not make a network round-trip. Callers that expect the record to be\n * absent should use `collection.getOrNull(id)` instead.\n */\nexport class NotFoundError extends NoydbError {\n constructor(message = 'Record not found') {\n super('NOT_FOUND', message)\n this.name = 'NotFoundError'\n }\n}\n\n/**\n * Thrown when application-level validation fails before encryption.\n *\n * Distinct from `SchemaValidationError` (Standard Schema v1 validator)\n * and `MissingTranslationError` (i18nText). `ValidationError` is the\n * general-purpose validation base — use it for custom guards in `put()`\n * hooks or store middleware.\n */\nexport class ValidationError extends NoydbError {\n constructor(message = 'Validation error') {\n super('VALIDATION_ERROR', message)\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Thrown when a Standard Schema v1 validator rejects a record on\n * `put()` (input validation) or on read (output validation). Carries\n * the raw issue list so callers can render field-level errors.\n *\n * `direction` distinguishes the two cases:\n * - `'input'`: the user passed bad data into `put()`. This is a\n * normal error case that application code should handle — typically\n * by showing validation messages in the UI.\n * - `'output'`: stored data does not match the current schema. This\n * indicates a schema drift (the schema was changed without\n * migrating the existing records) and should be treated as a bug\n * — the application should not swallow it silently.\n *\n * The `issues` type is deliberately `readonly unknown[]` on this class\n * so that `errors.ts` doesn't need to import from `schema.ts` (and\n * create a dependency cycle). Callers who know they're holding a\n * `SchemaValidationError` can cast to the more precise\n * `readonly StandardSchemaV1Issue[]` from `schema.ts`.\n */\nexport class SchemaValidationError extends NoydbError {\n readonly issues: readonly unknown[]\n readonly direction: 'input' | 'output'\n\n constructor(\n message: string,\n issues: readonly unknown[],\n direction: 'input' | 'output',\n ) {\n super('SCHEMA_VALIDATION_FAILED', message)\n this.name = 'SchemaValidationError'\n this.issues = issues\n this.direction = direction\n }\n}\n\n// ─── Query DSL Errors ─────────────────────────────────────────────────\n\n/**\n * Thrown when `.groupBy().aggregate()` produces more than the hard\n * cardinality cap (default 100_000 groups)..\n *\n * The cap exists because `.groupBy()` materializes one bucket per\n * distinct key value in memory, and runaway cardinality — a groupBy\n * on a high-uniqueness field like `id` or `createdAt` — is almost\n * always a query mistake rather than legitimate use. A hard error is\n * better than silent OOM: the consumer sees an actionable message\n * naming the field and the observed cardinality, with guidance to\n * either narrow the query with `.where()` or accept the ceiling\n * override.\n *\n * A separate one-shot warning fires at 10% of the cap (10_000\n * groups) so consumers get a heads-up before the hard error — same\n * pattern as `JoinTooLargeError` and the `.join()` row ceiling.\n *\n * **Not overridable in.** The 100k cap is a fixed constant so\n * the failure mode is consistent across the codebase; a\n * `{ maxGroups }` override can be added later without a break if a\n * real consumer asks.\n */\nexport class GroupCardinalityError extends NoydbError {\n /** The field being grouped on. */\n readonly field: string\n /** Observed number of distinct groups at the moment the cap tripped. */\n readonly cardinality: number\n /** The cap that was exceeded. */\n readonly maxGroups: number\n\n constructor(field: string, cardinality: number, maxGroups: number) {\n super(\n 'GROUP_CARDINALITY',\n `.groupBy(\"${field}\") produced ${cardinality} distinct groups, ` +\n `exceeding the ${maxGroups}-group ceiling. This is almost always a ` +\n `query mistake — grouping on a high-uniqueness field like \"id\" or ` +\n `\"createdAt\" produces one bucket per record. Narrow the query with ` +\n `.where() before grouping, or group on a lower-cardinality field ` +\n `(status, category, clientId). If you genuinely need high-cardinality ` +\n `grouping, file an issue with your use case.`,\n )\n this.name = 'GroupCardinalityError'\n this.field = field\n this.cardinality = cardinality\n this.maxGroups = maxGroups\n }\n}\n\n/**\n * Thrown in lazy mode when a `.query()` / `.where()` / `.orderBy()` clause\n * references a field that does not have a declared index.\n *\n * Lazy-mode queries only work when every touched field is indexed.\n * This is deliberate — silent scan-fallback would hide the performance\n * cliff that lazy-mode indexes exist to prevent.\n *\n * Payload:\n * - `collection` — name of the collection queried\n * - `touchedFields` — every field referenced by the query (filter + order)\n * - `missingFields` — subset of `touchedFields` that have no declared index\n */\nexport class IndexRequiredError extends NoydbError {\n readonly collection: string\n readonly touchedFields: readonly string[]\n readonly missingFields: readonly string[]\n\n constructor(args: { collection: string; touchedFields: readonly string[]; missingFields: readonly string[] }) {\n super(\n 'INDEX_REQUIRED',\n `Collection \"${args.collection}\": query references unindexed fields in lazy mode ` +\n `(missing: ${args.missingFields.join(', ')}). ` +\n `Declare an index on each field, or use collection.scan() for non-indexed iteration.`,\n )\n this.name = 'IndexRequiredError'\n this.collection = args.collection\n this.touchedFields = [...args.touchedFields]\n this.missingFields = [...args.missingFields]\n }\n}\n\n/**\n * Thrown (or surfaced via the `index:write-partial` event) when one or more\n * per-indexed-field side-car writes fail after the main record write has\n * already succeeded.\n *\n * Not thrown out of `.put()` / `.delete()` directly — those succeed when the\n * main record succeeds. Instead, `IndexWriteFailureError` instances are collected\n * into the session-scoped reconcile queue and emitted on the Collection\n * emitter as `index:write-partial`.\n *\n * Payload:\n * - `recordId` — the id of the main record whose side-car writes failed\n * - `field` — the indexed field whose side-car write failed\n * - `op` — `'put'` or `'delete'`, indicating which mutation was in flight\n * - `cause` — the underlying error from the store\n */\nexport class IndexWriteFailureError extends NoydbError {\n readonly recordId: string\n readonly field: string\n readonly op: 'put' | 'delete'\n override readonly cause: unknown\n\n constructor(args: { recordId: string; field: string; op: 'put' | 'delete'; cause: unknown }) {\n super(\n 'INDEX_WRITE_FAILURE',\n `Index side-car ${args.op} failed for field \"${args.field}\" on record \"${args.recordId}\"`,\n )\n this.name = 'IndexWriteFailureError'\n this.recordId = args.recordId\n this.field = args.field\n this.op = args.op\n this.cause = args.cause\n }\n}\n\n// ─── Bundle Format Errors ─────────────────────────────────\n\n/**\n * Thrown by `readNoydbBundle()` when the body bytes don't match\n * the integrity hash declared in the bundle header — i.e. someone\n * modified the bytes between write and read.\n *\n * Distinct from a generic `Error` (which would be thrown for\n * format violations like a missing magic prefix or malformed\n * header JSON) so consumers can pattern-match the corruption case\n * and handle it differently from a producer bug. A\n * `BundleIntegrityError` indicates \"the bytes you got are not\n * what was written\"; a plain `Error` from `parsePrefixAndHeader`\n * indicates \"what was written wasn't a valid bundle in the first\n * place.\"\n *\n * Also thrown when decompression fails after the integrity hash\n * passed — that's a producer bug (the wrong algorithm byte was\n * written) but it surfaces with the same error class because the\n * end result is \"the body cannot be turned back into a dump.\"\n */\nexport class BundleIntegrityError extends NoydbError {\n constructor(message: string) {\n super('BUNDLE_INTEGRITY', `.noydb bundle integrity check failed: ${message}`)\n this.name = 'BundleIntegrityError'\n }\n}\n\n// ─── i18n / Dictionary Errors ──────────────────────────\n\n/**\n * Thrown when `vault.collection()` is called with a name that is\n * reserved for NOYDB internal use (any name starting with `_dict_`).\n *\n * Dictionary collections are accessed exclusively via\n * `vault.dictionary(name)` — attempting to open one as a regular\n * collection would bypass the dictionary invariants (ACL, rename\n * tracking, reserved-name policy).\n */\nexport class ReservedCollectionNameError extends NoydbError {\n /** The rejected collection name. */\n readonly collectionName: string\n\n constructor(collectionName: string) {\n super(\n 'RESERVED_COLLECTION_NAME',\n `\"${collectionName}\" is a reserved collection name. ` +\n `Use vault.dictionary(\"${collectionName.replace(/^_dict_/, '')}\") ` +\n `to access dictionary collections.`,\n )\n this.name = 'ReservedCollectionNameError'\n this.collectionName = collectionName\n }\n}\n\n/**\n * Thrown by `DictionaryHandle.get()` and `DictionaryHandle.delete()` when\n * the requested key does not exist in the dictionary.\n *\n * Distinct from `NotFoundError` (which is for data records) so callers\n * can distinguish \"data record missing\" from \"dictionary key missing\"\n * without inspecting error messages.\n */\nexport class DictKeyMissingError extends NoydbError {\n /** The dictionary name. */\n readonly dictionaryName: string\n /** The key that was not found. */\n readonly key: string\n\n constructor(dictionaryName: string, key: string) {\n super(\n 'DICT_KEY_MISSING',\n `Dictionary \"${dictionaryName}\" has no entry for key \"${key}\".`,\n )\n this.name = 'DictKeyMissingError'\n this.dictionaryName = dictionaryName\n this.key = key\n }\n}\n\n/**\n * Thrown by `DictionaryHandle.delete()` in strict mode when the key to\n * be deleted is still referenced by one or more records.\n *\n * The caller must either rename the key first (the only sanctioned\n * mass-mutation path) or pass `{ mode: 'warn' }` to skip the check\n * (development only).\n */\nexport class DictKeyInUseError extends NoydbError {\n /** The dictionary name. */\n readonly dictionaryName: string\n /** The key that is still referenced. */\n readonly key: string\n /** Name of the first collection found to reference this key. */\n readonly usedBy: string\n /** Number of records in `usedBy` that reference this key. */\n readonly count: number\n\n constructor(\n dictionaryName: string,\n key: string,\n usedBy: string,\n count: number,\n ) {\n super(\n 'DICT_KEY_IN_USE',\n `Cannot delete key \"${key}\" from dictionary \"${dictionaryName}\": ` +\n `${count} record(s) in \"${usedBy}\" still reference it. ` +\n `Use dictionary.rename(\"${key}\", newKey) to rewrite references first.`,\n )\n this.name = 'DictKeyInUseError'\n this.dictionaryName = dictionaryName\n this.key = key\n this.usedBy = usedBy\n this.count = count\n }\n}\n\n/**\n * Thrown by `Collection.put()` when an `i18nText` field is missing one\n * or more required translations.\n *\n * The `missing` array names each locale code that was absent from the\n * field value. The `field` property names the field so callers can\n * render a field-level error message without parsing the string.\n */\nexport class MissingTranslationError extends NoydbError {\n /** The field name whose translation(s) are missing. */\n readonly field: string\n /** Locale codes that were required but absent. */\n readonly missing: readonly string[]\n\n constructor(field: string, missing: readonly string[], message?: string) {\n super(\n 'MISSING_TRANSLATION',\n message ??\n `Field \"${field}\": missing required translation(s): ${missing.join(', ')}.`,\n )\n this.name = 'MissingTranslationError'\n this.field = field\n this.missing = missing\n }\n}\n\n/**\n * Thrown when reading an `i18nText` field without specifying a locale —\n * either at the call site (`get(id, { locale })`) or on the vault\n * (`openVault(name, { locale })`).\n *\n * Also thrown when `resolveI18nText()` exhausts the fallback chain and\n * no translation is available for the requested locale.\n *\n * The `field` property names the field that triggered the error so the\n * caller can surface it in the UI.\n */\nexport class LocaleNotSpecifiedError extends NoydbError {\n /** The field name that required a locale. */\n readonly field: string\n\n constructor(field: string, message?: string) {\n super(\n 'LOCALE_NOT_SPECIFIED',\n message ??\n `Cannot read i18nText field \"${field}\" without a locale. ` +\n `Pass { locale } to get()/list()/query() or set a default via ` +\n `openVault(name, { locale }).`,\n )\n this.name = 'LocaleNotSpecifiedError'\n this.field = field\n }\n}\n\n// ─── Translator Errors ─────────────────────────────────────\n\n/**\n * Thrown when a collection has an `i18nText` field with\n * `autoTranslate: true` but no `plaintextTranslator` was configured\n * on `createNoydb()`.\n *\n * The error is raised at `put()` time (not at schema construction) so\n * the mis-configuration is surfaced by the first write rather than\n * silently at startup.\n */\nexport class TranslatorNotConfiguredError extends NoydbError {\n /** The field that requested auto-translation. */\n readonly field: string\n /** The collection the put was targeting. */\n readonly collection: string\n\n constructor(field: string, collection: string) {\n super(\n 'TRANSLATOR_NOT_CONFIGURED',\n `Field \"${field}\" in collection \"${collection}\" has autoTranslate: true, ` +\n `but no plaintextTranslator was configured on createNoydb(). ` +\n `Either configure a plaintextTranslator or remove autoTranslate from the schema.`,\n )\n this.name = 'TranslatorNotConfiguredError'\n this.field = field\n this.collection = collection\n }\n}\n\n// ─── Backup Errors ─────────────────────────────────────────\n\n/**\n * Thrown when `Vault.load()` finds that a backup's hash chain\n * doesn't verify, or that its embedded `ledgerHead.hash` doesn't\n * match the chain head reconstructed from the loaded entries.\n *\n * Distinct from `BackupCorruptedError` so callers can choose to\n * recover from one but not the other (e.g., a corrupted JSON file is\n * unrecoverable; a chain mismatch might mean the backup is from an\n * incompatible noy-db version).\n */\nexport class BackupLedgerError extends NoydbError {\n /** First-broken-entry index, if known. */\n readonly divergedAt?: number\n\n constructor(message: string, divergedAt?: number) {\n super('BACKUP_LEDGER', message)\n this.name = 'BackupLedgerError'\n if (divergedAt !== undefined) this.divergedAt = divergedAt\n }\n}\n\n/**\n * Thrown when `Vault.load()` finds that the backup's data\n * collection content doesn't match the ledger's recorded\n * `payloadHash`es. This is the \"envelope was tampered with after\n * dump\" detection — the chain itself can be intact, but if any\n * encrypted record bytes were swapped, this check catches it.\n */\nexport class BackupCorruptedError extends NoydbError {\n /** The (collection, id) pair whose envelope failed the hash check. */\n readonly collection: string\n readonly id: string\n\n constructor(collection: string, id: string, message: string) {\n super('BACKUP_CORRUPTED', message)\n this.name = 'BackupCorruptedError'\n this.collection = collection\n this.id = id\n }\n}\n\n// ─── Session Errors ───────────────────────────────────────\n\n/**\n * Thrown by `resolveSession()` when the session token's `expiresAt`\n * timestamp is in the past. The session key is also removed from the\n * in-memory store when this is thrown, so retrying with the same sessionId\n * will produce `SessionNotFoundError`.\n *\n * Separate from `SessionNotFoundError` so callers can distinguish between\n * \"session is gone\" (key store cleared, tab reloaded) and \"session is\n * still in the store but has exceeded its lifetime\" (idle timeout, absolute\n * timeout, policy-driven expiry). The remediation differs: expired sessions\n * should prompt a fresh unlock; not-found sessions may indicate a bug or a\n * cross-tab scenario where the session was never established.\n */\nexport class SessionExpiredError extends NoydbError {\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super('SESSION_EXPIRED', `Session \"${sessionId}\" has expired. Re-unlock to continue.`)\n this.name = 'SessionExpiredError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown by `resolveSession()` when the session key cannot be found in\n * the module-level store. This happens when:\n * - The session was explicitly revoked via `revokeSession()`.\n * - The JS context was reloaded (tab navigation, page refresh, worker restart).\n * - `Noydb.close()` was called (which calls `revokeAllSessions()`).\n * - The sessionId is wrong or was generated by a different JS context.\n *\n * The session token (if the caller holds it) is permanently useless after\n * this error — the key is gone and cannot be recovered.\n */\nexport class SessionNotFoundError extends NoydbError {\n readonly sessionId: string\n\n constructor(sessionId: string) {\n super('SESSION_NOT_FOUND', `Session key for \"${sessionId}\" not found. The session may have been revoked or the page reloaded.`)\n this.name = 'SessionNotFoundError'\n this.sessionId = sessionId\n }\n}\n\n/**\n * Thrown when a session policy blocks an operation — for example,\n * `requireReAuthFor: ['export']` is set and the caller attempts to\n * call `exportStream()` without re-authenticating for this session.\n *\n * The `operation` field names the specific operation that was blocked\n * (e.g. `'export'`, `'grant'`, `'rotate'`) so the caller can surface\n * a targeted prompt (\"Please re-enter your passphrase to export data\").\n */\nexport class SessionPolicyError extends NoydbError {\n readonly operation: string\n\n constructor(operation: string, message?: string) {\n super(\n 'SESSION_POLICY',\n message ?? `Operation \"${operation}\" requires re-authentication per the active session policy.`,\n )\n this.name = 'SessionPolicyError'\n this.operation = operation\n }\n}\n\n// ─── Query / Join Errors ────────────────────────────────────\n\n/**\n * Thrown when a `.join()` would exceed its configured row ceiling on\n * either side. The ceiling defaults to 50,000 per side and can be\n * overridden via the `{ maxRows }` option on `.join()`.\n *\n * Carries both row counts so the error message can show which side\n * tripped the limit (e.g. \"left had 60,000 rows, right had 1,200,\n * max was 50,000\"). The `side` field is machine-readable so test\n * code and devtools can match on it without regex-parsing the\n * message.\n *\n * The row ceiling exists because joins are bounded in-memory\n * operations over materialized record sets. Consumers whose\n * collections genuinely exceed the ceiling should track \n * (streaming joins over `scan()`) or filter the left side further\n * with `where()` / `limit()` before joining.\n */\nexport class JoinTooLargeError extends NoydbError {\n readonly leftRows: number\n readonly rightRows: number\n readonly maxRows: number\n readonly side: 'left' | 'right'\n\n constructor(opts: {\n leftRows: number\n rightRows: number\n maxRows: number\n side: 'left' | 'right'\n message: string\n }) {\n super('JOIN_TOO_LARGE', opts.message)\n this.name = 'JoinTooLargeError'\n this.leftRows = opts.leftRows\n this.rightRows = opts.rightRows\n this.maxRows = opts.maxRows\n this.side = opts.side\n }\n}\n\n/**\n * Thrown by `.join()` in strict `ref()` mode when a left-side record\n * points at a right-side id that does not exist in the target\n * collection.\n *\n * Distinct from `RefIntegrityError` so test code can pattern-match\n * on the *read-time* dangling case without catching *write-time*\n * integrity violations. Both indicate \"ref points at nothing\" but\n * happen at different lifecycle phases and deserve different\n * remediation in documentation: a RefIntegrityError on `put()`\n * means the input is invalid; a DanglingReferenceError on `.join()`\n * means stored data has drifted and `vault.checkIntegrity()`\n * is the right tool to find the full set of orphans.\n */\nexport class DanglingReferenceError extends NoydbError {\n readonly field: string\n readonly target: string\n readonly refId: string\n\n constructor(opts: {\n field: string\n target: string\n refId: string\n message: string\n }) {\n super('DANGLING_REFERENCE', opts.message)\n this.name = 'DanglingReferenceError'\n this.field = opts.field\n this.target = opts.target\n this.refId = opts.refId\n }\n}\n\n/**\n * Thrown by {@link sanitizeFilename} when an input filename cannot be\n * made safe — NUL byte, empty after normalization, missing\n * `opaqueId` for the opaque profile, `..` segment, or a `maxBytes`\n * cap too small to hold a single code point.\n */\nexport class FilenameSanitizationError extends NoydbError {\n constructor(message: string) {\n super('FILENAME_SANITIZATION', message)\n this.name = 'FilenameSanitizationError'\n }\n}\n\n/**\n * Thrown when a write target resolves OUTSIDE the requested\n * directory after sanitization — the canonical Zip-Slip class. The\n * sanitizer's job is to strip path-traversal segments; this error\n * is the defense-in-depth fallback at the FS write site.\n */\nexport class PathEscapeError extends NoydbError {\n readonly attempted: string\n readonly targetDir: string\n\n constructor(opts: { attempted: string; targetDir: string }) {\n super(\n 'PATH_ESCAPE',\n `Sanitized filename \"${opts.attempted}\" resolves outside target dir \"${opts.targetDir}\"`,\n )\n this.name = 'PathEscapeError'\n this.attempted = opts.attempted\n this.targetDir = opts.targetDir\n }\n}\n","/**\n * Multi-record atomic transactions.\n *\n * Lets an application stage writes across two or more collections (or\n * vaults) and commit them all-or-nothing.\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * const inv = tx.vault('acme').collection<Invoice>('invoices')\n * const pay = tx.vault('acme').collection<Payment>('payments')\n * await inv.put(invoiceId, { ...invoice, status: 'paid' })\n * await pay.put(paymentId, { invoiceId, amount, paidAt })\n * })\n * // If the body throws before returning: nothing persisted.\n * // If the body returns: all puts committed; any CAS mismatch rolls\n * // the batch back and surfaces as ConflictError.\n * ```\n *\n * ## Atomicity semantics\n *\n * Ops are buffered during the body. On body-return the hub:\n *\n * 1. **Pre-flight** — re-reads every touched envelope and enforces\n * any caller-supplied `expectedVersion`. A mismatch throws\n * `ConflictError` with *no* writes performed.\n * 2. **Execute** — calls `Collection.put()` / `.delete()` for each\n * staged op in declaration order. History snapshots, ledger\n * appends, and change events fire as normal per op.\n * 3. **Unwind on failure** — if step 2 throws mid-batch, each\n * already-committed op is reverted via the raw store (restoring\n * the captured prior envelope, or deleting if none existed). The\n * ledger is NOT rewritten — audit history preserves the partial\n * commit and the revert.\n *\n * **Crash window.** Steps 2–3 are not a storage-layer transaction —\n * if the process dies between two executed ops, the on-disk state is\n * partial. True all-or-nothing atomicity requires a store that\n * implements `NoydbStore.tx()` (DynamoDB `TransactWriteItems`,\n * IndexedDB `readwrite` transaction, …). This executor declares\n * that future integration point via the `tx?()` method + the\n * `StoreCapabilities.txAtomic` bit, but does not yet delegate\n * to it — the cascade into `Fork · Stores` tracks the per-adapter\n * wire-up.\n *\n * ## Not covered\n *\n * - Cross-sync-peer atomicity. Transactions commit against the\n * primary store only; the sync engine pushes on its normal\n * schedule. For cross-peer two-phase commit use `SyncTransaction`\n * via `db.transaction(vaultName)`.\n * - Read-your-writes within the body. `tx.collection().get(id)`\n * returns the most-recently-staged value for that id when one\n * exists; if no staged op has touched the id, it reads the current\n * committed state. Version numbers returned by `get` reflect the\n * pre-transaction state (staged puts have no version yet).\n *\n * @module\n */\n\nimport type { Noydb } from '../noydb.js'\nimport type { Vault } from '../vault.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport { ConflictError } from '../errors.js'\n\n/** One op buffered inside a running `TxContext`. @internal */\ninterface StagedOp {\n type: 'put' | 'delete'\n vaultName: string\n collectionName: string\n id: string\n record?: unknown\n expectedVersion?: number\n}\n\n/**\n * Transaction handle passed to the user's body. Use\n * `tx.vault(name).collection<T>(name)` to get a per-collection\n * facade; its `put`/`delete`/`get` calls stage ops against the tx.\n */\nexport class TxContext {\n /** @internal */\n readonly _ops: StagedOp[] = []\n /** @internal */\n readonly _db: Noydb\n\n /** @internal */\n constructor(db: Noydb) {\n this._db = db\n }\n\n /** Scope subsequent `collection()` calls to the named vault. */\n vault(name: string): TxVault {\n const v = this._db.vault(name)\n return new TxVault(this, v)\n }\n}\n\n/** Per-vault facade inside a running transaction. */\nexport class TxVault {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault) {\n this._ctx = ctx\n this._vault = vault\n }\n\n /** Scope subsequent op calls to the named collection. */\n collection<T>(name: string): TxCollection<T> {\n const c = this._vault.collection<T>(name)\n return new TxCollection<T>(this._ctx, this._vault, c, name)\n }\n}\n\n/** Per-collection facade inside a running transaction. */\nexport class TxCollection<T> {\n /** @internal */\n readonly _ctx: TxContext\n /** @internal */\n readonly _vault: Vault\n /** @internal */\n readonly _coll: Collection<T>\n /** @internal */\n readonly _name: string\n\n /** @internal */\n constructor(ctx: TxContext, vault: Vault, coll: Collection<T>, name: string) {\n this._ctx = ctx\n this._vault = vault\n this._coll = coll\n this._name = name\n }\n\n /**\n * Read the current committed value, or the most-recently-staged\n * value from the same transaction if one exists.\n */\n async get(id: string): Promise<T | null> {\n for (let i = this._ctx._ops.length - 1; i >= 0; i--) {\n const op = this._ctx._ops[i]!\n if (\n op.vaultName === this._vault.name &&\n op.collectionName === this._name &&\n op.id === id\n ) {\n if (op.type === 'delete') return null\n return op.record as T\n }\n }\n return this._coll.get(id)\n }\n\n /**\n * Stage a put. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n put(id: string, record: T, options?: { expectedVersion?: number }): void {\n const op: StagedOp = {\n type: 'put',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n record,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n this._ctx._ops.push(op)\n }\n\n /**\n * Stage a delete. Does not write until the transaction body returns.\n * Supply `{ expectedVersion }` to enforce optimistic concurrency\n * during the commit pre-flight.\n */\n delete(id: string, options?: { expectedVersion?: number }): void {\n const op: StagedOp = {\n type: 'delete',\n vaultName: this._vault.name,\n collectionName: this._name,\n id,\n }\n if (options?.expectedVersion !== undefined) op.expectedVersion = options.expectedVersion\n this._ctx._ops.push(op)\n }\n}\n\n/**\n * Commit plan: pre-flight check + execution + revert plan. Returned\n * from `runTransaction`.\n *\n * @internal — exposed only for the `Collection.putMany({atomic:true})`\n * wire-up so the bulk path can share the executor without creating\n * an outer TxContext.\n */\nexport async function runTransaction<T>(\n db: Noydb,\n fn: (tx: TxContext) => Promise<T> | T,\n): Promise<T> {\n const ctx = new TxContext(db)\n const bodyResult = await fn(ctx)\n\n if (ctx._ops.length === 0) return bodyResult\n\n // Phase 1 — pre-flight: snapshot every touched envelope and enforce\n // any caller-supplied expectedVersion. Same (vault, coll, id) touched\n // more than once in one tx snapshots only the *initial* committed\n // state; the in-order replay in Phase 2 takes care of successor ops.\n const priorEnvelopes = new Map<string, EncryptedEnvelope | null>()\n const store = db._store\n for (const op of ctx._ops) {\n const key = keyOf(op)\n if (!priorEnvelopes.has(key)) {\n const env = await store.get(op.vaultName, op.collectionName, op.id)\n priorEnvelopes.set(key, env)\n }\n if (op.expectedVersion !== undefined) {\n const env = priorEnvelopes.get(key) ?? null\n const actual = env?._v ?? 0\n if (actual !== op.expectedVersion) {\n throw new ConflictError(\n actual,\n `Transaction pre-flight: ${op.vaultName}/${op.collectionName}/${op.id} ` +\n `expected v${op.expectedVersion}, found v${actual}`,\n )\n }\n }\n }\n\n // Phase 2 — execute via the Collection layer so history snapshots,\n // ledger entries, and change events fire normally. We capture each\n // successful op so a mid-batch throw can revert in Phase 3.\n const executed: Array<{ op: StagedOp; priorEnvelope: EncryptedEnvelope | null }> = []\n try {\n for (const op of ctx._ops) {\n const coll = db.vault(op.vaultName).collection(op.collectionName)\n const key = keyOf(op)\n const prior = priorEnvelopes.get(key) ?? null\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await coll.put(op.id, op.record as any)\n } else {\n await coll.delete(op.id)\n }\n executed.push({ op, priorEnvelope: prior })\n }\n return bodyResult\n } catch (err) {\n // Phase 3 — best-effort revert. Restore captured prior envelopes\n // via the raw store to avoid re-firing Collection-level side\n // effects (we don't want a cascade of change events undoing\n // themselves). The ledger is left as-is: each committed op\n // appended an entry; the revert is deliberately not recorded as a\n // compensating entry because 's contract is \"atomic or not at\n // all\" from the caller's view, not \"every write visible in the\n // audit trail.\" Auditors who need the intermediate state can still\n // reconstruct it by walking the ledger through the failed-tx\n // timestamp.\n for (const { op, priorEnvelope } of executed.slice().reverse()) {\n try {\n if (priorEnvelope) {\n await store.put(op.vaultName, op.collectionName, op.id, priorEnvelope)\n } else {\n await store.delete(op.vaultName, op.collectionName, op.id)\n }\n } catch {\n // swallow — best-effort. Surfacing the revert error would\n // mask the original one that triggered the rollback.\n }\n }\n throw err\n }\n}\n\nfunction keyOf(op: StagedOp): string {\n return `${op.vaultName}\\x00${op.collectionName}\\x00${op.id}`\n}\n","/**\n * Active transactions strategy. Only reachable via `@noy-db/hub/tx`.\n */\n\nimport { runTransaction } from './transaction.js'\nimport type { TxStrategy } from './strategy.js'\n\n/**\n * Build the default transactions strategy. Pass into\n * `createNoydb({ txStrategy: withTransactions() })` to enable\n * `db.transaction(fn)`.\n */\nexport function withTransactions(): TxStrategy {\n return { runTransaction }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4EO,IAAM,aAAN,cAAyB,MAAM;AAAA;AAAA,EAE3B;AAAA,EAET,YAAY,MAAc,SAAiB;AACzC,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAkdO,IAAM,gBAAN,cAA4B,WAAW;AAAA;AAAA,EAEnC;AAAA,EAET,YAAY,SAAiB,UAAU,oBAAoB;AACzD,UAAM,YAAY,OAAO;AACzB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;;;ACheO,IAAM,YAAN,MAAgB;AAAA;AAAA,EAEZ,OAAmB,CAAC;AAAA;AAAA,EAEpB;AAAA;AAAA,EAGT,YAAY,IAAW;AACrB,SAAK,MAAM;AAAA,EACb;AAAA;AAAA,EAGA,MAAM,MAAuB;AAC3B,UAAM,IAAI,KAAK,IAAI,MAAM,IAAI;AAC7B,WAAO,IAAI,QAAQ,MAAM,CAAC;AAAA,EAC5B;AACF;AAGO,IAAM,UAAN,MAAc;AAAA;AAAA,EAEV;AAAA;AAAA,EAEA;AAAA;AAAA,EAGT,YAAY,KAAgB,OAAc;AACxC,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA,EAGA,WAAc,MAA+B;AAC3C,UAAM,IAAI,KAAK,OAAO,WAAc,IAAI;AACxC,WAAO,IAAI,aAAgB,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAI;AAAA,EAC5D;AACF;AAGO,IAAM,eAAN,MAAsB;AAAA;AAAA,EAElB;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAGT,YAAY,KAAgB,OAAc,MAAqB,MAAc;AAC3E,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,QAAQ;AACb,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,IAAI,IAA+B;AACvC,aAAS,IAAI,KAAK,KAAK,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AACnD,YAAM,KAAK,KAAK,KAAK,KAAK,CAAC;AAC3B,UACE,GAAG,cAAc,KAAK,OAAO,QAC7B,GAAG,mBAAmB,KAAK,SAC3B,GAAG,OAAO,IACV;AACA,YAAI,GAAG,SAAS,SAAU,QAAO;AACjC,eAAO,GAAG;AAAA,MACZ;AAAA,IACF;AACA,WAAO,KAAK,MAAM,IAAI,EAAE;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,IAAY,QAAW,SAA8C;AACvE,UAAM,KAAe;AAAA,MACnB,MAAM;AAAA,MACN,WAAW,KAAK,OAAO;AAAA,MACvB,gBAAgB,KAAK;AAAA,MACrB;AAAA,MACA;AAAA,IACF;AACA,QAAI,SAAS,oBAAoB,OAAW,IAAG,kBAAkB,QAAQ;AACzE,SAAK,KAAK,KAAK,KAAK,EAAE;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,IAAY,SAA8C;AAC/D,UAAM,KAAe;AAAA,MACnB,MAAM;AAAA,MACN,WAAW,KAAK,OAAO;AAAA,MACvB,gBAAgB,KAAK;AAAA,MACrB;AAAA,IACF;AACA,QAAI,SAAS,oBAAoB,OAAW,IAAG,kBAAkB,QAAQ;AACzE,SAAK,KAAK,KAAK,KAAK,EAAE;AAAA,EACxB;AACF;AAUA,eAAsB,eACpB,IACA,IACY;AACZ,QAAM,MAAM,IAAI,UAAU,EAAE;AAC5B,QAAM,aAAa,MAAM,GAAG,GAAG;AAE/B,MAAI,IAAI,KAAK,WAAW,EAAG,QAAO;AAMlC,QAAM,iBAAiB,oBAAI,IAAsC;AACjE,QAAM,QAAQ,GAAG;AACjB,aAAW,MAAM,IAAI,MAAM;AACzB,UAAM,MAAM,MAAM,EAAE;AACpB,QAAI,CAAC,eAAe,IAAI,GAAG,GAAG;AAC5B,YAAM,MAAM,MAAM,MAAM,IAAI,GAAG,WAAW,GAAG,gBAAgB,GAAG,EAAE;AAClE,qBAAe,IAAI,KAAK,GAAG;AAAA,IAC7B;AACA,QAAI,GAAG,oBAAoB,QAAW;AACpC,YAAM,MAAM,eAAe,IAAI,GAAG,KAAK;AACvC,YAAM,SAAS,KAAK,MAAM;AAC1B,UAAI,WAAW,GAAG,iBAAiB;AACjC,cAAM,IAAI;AAAA,UACR;AAAA,UACA,2BAA2B,GAAG,SAAS,IAAI,GAAG,cAAc,IAAI,GAAG,EAAE,cACtD,GAAG,eAAe,YAAY,MAAM;AAAA,QACrD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAKA,QAAM,WAA6E,CAAC;AACpF,MAAI;AACF,eAAW,MAAM,IAAI,MAAM;AACzB,YAAM,OAAO,GAAG,MAAM,GAAG,SAAS,EAAE,WAAW,GAAG,cAAc;AAChE,YAAM,MAAM,MAAM,EAAE;AACpB,YAAM,QAAQ,eAAe,IAAI,GAAG,KAAK;AACzC,UAAI,GAAG,SAAS,OAAO;AAErB,cAAM,KAAK,IAAI,GAAG,IAAI,GAAG,MAAa;AAAA,MACxC,OAAO;AACL,cAAM,KAAK,OAAO,GAAG,EAAE;AAAA,MACzB;AACA,eAAS,KAAK,EAAE,IAAI,eAAe,MAAM,CAAC;AAAA,IAC5C;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AAWZ,eAAW,EAAE,IAAI,cAAc,KAAK,SAAS,MAAM,EAAE,QAAQ,GAAG;AAC9D,UAAI;AACF,YAAI,eAAe;AACjB,gBAAM,MAAM,IAAI,GAAG,WAAW,GAAG,gBAAgB,GAAG,IAAI,aAAa;AAAA,QACvE,OAAO;AACL,gBAAM,MAAM,OAAO,GAAG,WAAW,GAAG,gBAAgB,GAAG,EAAE;AAAA,QAC3D;AAAA,MACF,QAAQ;AAAA,MAGR;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACF;AAEA,SAAS,MAAM,IAAsB;AACnC,SAAO,GAAG,GAAG,SAAS,KAAO,GAAG,cAAc,KAAO,GAAG,EAAE;AAC5D;;;AC3QO,SAAS,mBAA+B;AAC7C,SAAO,EAAE,eAAe;AAC1B;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ak as TxStrategy } from '../types-Bfs0qr5F.cjs';
|
|
2
|
+
export { al as TxCollection, am as TxContext, an as TxVault, ao as runTransaction } from '../types-Bfs0qr5F.cjs';
|
|
3
|
+
import '../lazy-builder-CZVLKh0Z.cjs';
|
|
4
|
+
import '../predicate-SBHmi6D0.cjs';
|
|
5
|
+
import '../strategy-D-SrOLCl.cjs';
|
|
6
|
+
import '../strategy-BSxFXGzb.cjs';
|
|
7
|
+
import '../index-DN-J-5wT.cjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Active transactions strategy. Only reachable via `@noy-db/hub/tx`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Build the default transactions strategy. Pass into
|
|
15
|
+
* `createNoydb({ txStrategy: withTransactions() })` to enable
|
|
16
|
+
* `db.transaction(fn)`.
|
|
17
|
+
*/
|
|
18
|
+
declare function withTransactions(): TxStrategy;
|
|
19
|
+
|
|
20
|
+
export { TxStrategy, withTransactions };
|