@brightchain/db 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +81 -0
  2. package/package.json +18 -0
  3. package/src/__tests__/helpers/mockBlockStore.d.ts +113 -0
  4. package/src/__tests__/helpers/mockBlockStore.js +380 -0
  5. package/src/__tests__/helpers/mockBlockStore.js.map +1 -0
  6. package/src/index.d.ts +31 -0
  7. package/src/index.js +78 -0
  8. package/src/index.js.map +1 -0
  9. package/src/lib/aggregation.d.ts +18 -0
  10. package/src/lib/aggregation.js +407 -0
  11. package/src/lib/aggregation.js.map +1 -0
  12. package/src/lib/cblIndex.d.ts +268 -0
  13. package/src/lib/cblIndex.js +856 -0
  14. package/src/lib/cblIndex.js.map +1 -0
  15. package/src/lib/collection.d.ts +305 -0
  16. package/src/lib/collection.js +991 -0
  17. package/src/lib/collection.js.map +1 -0
  18. package/src/lib/cursor.d.ts +8 -0
  19. package/src/lib/cursor.js +13 -0
  20. package/src/lib/cursor.js.map +1 -0
  21. package/src/lib/database.d.ts +158 -0
  22. package/src/lib/database.js +332 -0
  23. package/src/lib/database.js.map +1 -0
  24. package/src/lib/errors.d.ts +85 -0
  25. package/src/lib/errors.js +103 -0
  26. package/src/lib/errors.js.map +1 -0
  27. package/src/lib/expressMiddleware.d.ts +57 -0
  28. package/src/lib/expressMiddleware.js +488 -0
  29. package/src/lib/expressMiddleware.js.map +1 -0
  30. package/src/lib/headRegistry.d.ts +60 -0
  31. package/src/lib/headRegistry.js +216 -0
  32. package/src/lib/headRegistry.js.map +1 -0
  33. package/src/lib/indexing.d.ts +7 -0
  34. package/src/lib/indexing.js +14 -0
  35. package/src/lib/indexing.js.map +1 -0
  36. package/src/lib/model.d.ts +162 -0
  37. package/src/lib/model.js +260 -0
  38. package/src/lib/model.js.map +1 -0
  39. package/src/lib/pooledStoreAdapter.d.ts +44 -0
  40. package/src/lib/pooledStoreAdapter.js +109 -0
  41. package/src/lib/pooledStoreAdapter.js.map +1 -0
  42. package/src/lib/queryEngine.d.ts +48 -0
  43. package/src/lib/queryEngine.js +461 -0
  44. package/src/lib/queryEngine.js.map +1 -0
  45. package/src/lib/schemaValidation.d.ts +80 -0
  46. package/src/lib/schemaValidation.js +353 -0
  47. package/src/lib/schemaValidation.js.map +1 -0
  48. package/src/lib/transaction.d.ts +7 -0
  49. package/src/lib/transaction.js +12 -0
  50. package/src/lib/transaction.js.map +1 -0
  51. package/src/lib/types.d.ts +360 -0
  52. package/src/lib/types.js +6 -0
  53. package/src/lib/types.js.map +1 -0
  54. package/src/lib/updateEngine.d.ts +7 -0
  55. package/src/lib/updateEngine.js +13 -0
  56. package/src/lib/updateEngine.js.map +1 -0
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # @brightchain/db
2
+
3
+ A MongoDB-like document database driver backed by BrightChain's block store.
4
+
5
+ ## Overview
6
+
7
+ `brightchain-db` provides a familiar MongoDB-style API for storing and querying
8
+ structured documents on top of BrightChain's Owner-Free block storage system.
9
+ It supports:
10
+
11
+ - **Collections & Documents** – `db.collection('users')` returns a collection handle
12
+ - **CRUD operations** – `insertOne`, `insertMany`, `findOne`, `find`, `updateOne`, `updateMany`, `deleteOne`, `deleteMany`, `replaceOne`
13
+ - **Rich query operators** – `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$regex`, `$exists`, `$and`, `$or`, `$not`, `$nor`, `$elemMatch`
14
+ - **Projection & sorting** – field selection, multi-field sort
15
+ - **Indexes** – unique, compound, and single-field indexes for fast lookups
16
+ - **Transactions** – multi-document ACID-like transactions with commit/abort
17
+ - **Aggregation pipeline** – `$match`, `$group`, `$sort`, `$limit`, `$skip`, `$project`, `$unwind`, `$count`, `$addFields`, `$lookup`
18
+ - **Cursor API** – lazy iteration with `skip`, `limit`, `sort`, `toArray`
19
+ - **Express middleware** – drop-in router for REST access to collections
20
+ - **Change streams** – subscribe to insert/update/delete events
21
+
22
+ ## Quick Start
23
+
24
+ ```typescript
25
+ import { BrightChainDb } from '@brightchain/brightchain-db';
26
+ import { MemoryBlockStoreAdapter } from '@brightchain/brightchain-lib';
27
+ import { BlockSize } from '@brightchain/brightchain-lib';
28
+
29
+ // Create or connect to a block store
30
+ const blockStore = new MemoryBlockStoreAdapter({ blockSize: BlockSize.Medium });
31
+
32
+ // Open a database
33
+ const db = new BrightChainDb(blockStore);
34
+
35
+ // Get a collection
36
+ const users = db.collection('users');
37
+
38
+ // Insert
39
+ await users.insertOne({ name: 'Alice', email: 'alice@example.com', age: 30 });
40
+
41
+ // Query
42
+ const alice = await users.findOne({ name: 'Alice' });
43
+
44
+ // Rich queries
45
+ const adults = await users.find({ age: { $gte: 18 } }).sort({ name: 1 }).toArray();
46
+
47
+ // Indexes
48
+ await users.createIndex({ email: 1 }, { unique: true });
49
+
50
+ // Transactions
51
+ const session = db.startSession();
52
+ session.startTransaction();
53
+ try {
54
+ await users.insertOne({ name: 'Bob', email: 'bob@example.com' }, { session });
55
+ await users.updateOne({ name: 'Alice' }, { $set: { friend: 'Bob' } }, { session });
56
+ await session.commitTransaction();
57
+ } catch (err) {
58
+ await session.abortTransaction();
59
+ }
60
+
61
+ // Express middleware
62
+ import { createDbRouter } from '@brightchain/brightchain-db';
63
+ app.use('/api/db', createDbRouter(db));
64
+ ```
65
+
66
+ ## Architecture
67
+
68
+ Documents are serialised to JSON and stored as blocks in the BrightChain block store.
69
+ Each collection maintains an in-memory index that maps logical document IDs to
70
+ content-addressable block checksums. The index itself is persisted as a block and
71
+ tracked via a head registry.
72
+
73
+ Indexes are maintained as B-tree-like structures in memory, rebuilt from stored
74
+ index metadata blocks on startup, and persisted after mutations.
75
+
76
+ Transactions use optimistic concurrency: writes are buffered in a journal and
77
+ applied atomically on commit, with automatic rollback on abort.
78
+
79
+ ## License
80
+
81
+ MIT
package/package.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "@brightchain/db",
3
+ "version": "0.20.0",
4
+ "description": "MongoDB-like document database driver backed by BrightChain block store",
5
+ "license": "MIT",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.ts",
8
+ "dependencies": {
9
+ "@noble/hashes": "^1.4.0"
10
+ },
11
+ "peerDependencies": {
12
+ "@brightchain/brightchain-lib": ">=0.20.0",
13
+ "@digitaldefiance/branded-interface": ">=0.0.5",
14
+ "@digitaldefiance/node-express-suite": ">=4.2.2",
15
+ "express": ">=5.0.0"
16
+ },
17
+ "type": "commonjs"
18
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * In-memory mock of IBlockStore for testing.
3
+ *
4
+ * Implements only the methods that brightchain-db actually uses:
5
+ * has(key), get(key), put(key, data), delete(key)
6
+ *
7
+ * All other IBlockStore methods throw "not implemented" so tests catch
8
+ * accidental usage immediately.
9
+ */
10
+ import { BlockSize, BlockStoreOptions, CBLMagnetComponents, CBLStorageResult, CBLWhiteningOptions, Checksum, IBlockStore, IPooledBlockStore, ListOptions, PoolDeletionValidationResult, PoolId, PoolStats } from '@brightchain/brightchain-lib';
11
+ export declare class MockBlockStore implements IBlockStore {
12
+ readonly blocks: Map<string, Uint8Array<ArrayBufferLike>>;
13
+ /** Track method calls for assertions */
14
+ readonly calls: {
15
+ has: string[];
16
+ get: string[];
17
+ put: string[];
18
+ delete: string[];
19
+ };
20
+ /** Optional: simulate errors on specific keys */
21
+ readonly errorKeys: Set<string>;
22
+ has(key: any): Promise<boolean>;
23
+ get(key: any): any;
24
+ put(key: any, data: Uint8Array): Promise<void>;
25
+ delete(key: any): Promise<void>;
26
+ /** Total number of blocks currently stored */
27
+ get size(): number;
28
+ /** Reset all stored data and call tracking */
29
+ reset(): void;
30
+ get blockSize(): any;
31
+ getData(): Promise<any>;
32
+ setData(): Promise<void>;
33
+ deleteData(): Promise<void>;
34
+ getRandomBlocks(): Promise<any[]>;
35
+ getMetadata(): Promise<any>;
36
+ updateMetadata(): Promise<void>;
37
+ generateParityBlocks(): Promise<any[]>;
38
+ getParityBlocks(): Promise<any[]>;
39
+ recoverBlock(): Promise<any>;
40
+ verifyBlockIntegrity(): Promise<boolean>;
41
+ getBlocksPendingReplication(): Promise<any[]>;
42
+ getUnderReplicatedBlocks(): Promise<any[]>;
43
+ recordReplication(): Promise<void>;
44
+ recordReplicaLoss(): Promise<void>;
45
+ brightenBlock(): Promise<any>;
46
+ storeCBLWithWhitening(cblData: Uint8Array): Promise<CBLStorageResult>;
47
+ retrieveCBL(blockId1: string | {
48
+ toString(): string;
49
+ }, _blockId2?: string | {
50
+ toString(): string;
51
+ }, _block1ParityIds?: string[], _block2ParityIds?: string[]): Promise<Uint8Array>;
52
+ parseCBLMagnetUrl(magnetUrl: string): CBLMagnetComponents;
53
+ generateCBLMagnetUrl(blockId1: string | {
54
+ toString(): string;
55
+ }, blockId2: string | {
56
+ toString(): string;
57
+ }, blockSize: number): string;
58
+ }
59
+ /**
60
+ * Mock pooled block store for testing pool-scoped operations.
61
+ *
62
+ * Extends MockBlockStore with IPooledBlockStore methods using simple
63
+ * in-memory maps. Computes SHA3-512 hashes for putInPool.
64
+ */
65
+ export declare class MockPooledBlockStore extends MockBlockStore implements IPooledBlockStore {
66
+ /** Pool-scoped block storage: storageKey -> block data */
67
+ readonly poolBlocks: Map<string, Uint8Array<ArrayBufferLike>>;
68
+ /** Per-pool statistics */
69
+ readonly poolStatsMap: Map<string, PoolStats>;
70
+ /** Track pool method calls for assertions */
71
+ readonly poolCalls: {
72
+ hasInPool: Array<{
73
+ pool: PoolId;
74
+ hash: string;
75
+ }>;
76
+ getFromPool: Array<{
77
+ pool: PoolId;
78
+ hash: string;
79
+ }>;
80
+ putInPool: Array<{
81
+ pool: PoolId;
82
+ dataLength: number;
83
+ }>;
84
+ deleteFromPool: Array<{
85
+ pool: PoolId;
86
+ hash: string;
87
+ }>;
88
+ listPools: number;
89
+ listBlocksInPool: PoolId[];
90
+ getPoolStats: PoolId[];
91
+ deletePool: PoolId[];
92
+ };
93
+ private computeHash;
94
+ private recordPut;
95
+ private recordDelete;
96
+ private touchPool;
97
+ hasInPool(pool: PoolId, hash: string): Promise<boolean>;
98
+ getFromPool(pool: PoolId, hash: string): Promise<Uint8Array>;
99
+ putInPool(pool: PoolId, data: Uint8Array, _options?: BlockStoreOptions): Promise<string>;
100
+ deleteFromPool(pool: PoolId, hash: string): Promise<void>;
101
+ listPools(): Promise<PoolId[]>;
102
+ listBlocksInPool(pool: PoolId, options?: ListOptions): AsyncIterable<string>;
103
+ getPoolStats(pool: PoolId): Promise<PoolStats>;
104
+ deletePool(pool: PoolId): Promise<void>;
105
+ getRandomBlocksFromPool(pool: PoolId, count: number): Promise<Checksum[]>;
106
+ bootstrapPool(pool: PoolId, blockSize: BlockSize, count: number): Promise<void>;
107
+ validatePoolDeletion(pool: PoolId): Promise<PoolDeletionValidationResult>;
108
+ forceDeletePool(pool: PoolId): Promise<void>;
109
+ storeCBLWithWhiteningInPool(_pool: PoolId, _cblData: Uint8Array, _options?: CBLWhiteningOptions): Promise<CBLStorageResult>;
110
+ retrieveCBLFromPool(_pool: PoolId, _blockId1: Checksum | string, _blockId2: Checksum | string, _block1ParityIds?: string[], _block2ParityIds?: string[]): Promise<Uint8Array>;
111
+ /** Reset all stored data including pool data and call tracking */
112
+ reset(): void;
113
+ }
@@ -0,0 +1,380 @@
1
+ "use strict";
2
+ /**
3
+ * In-memory mock of IBlockStore for testing.
4
+ *
5
+ * Implements only the methods that brightchain-db actually uses:
6
+ * has(key), get(key), put(key, data), delete(key)
7
+ *
8
+ * All other IBlockStore methods throw "not implemented" so tests catch
9
+ * accidental usage immediately.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MockPooledBlockStore = exports.MockBlockStore = void 0;
13
+ /* eslint-disable @typescript-eslint/no-explicit-any */
14
+ const brightchain_lib_1 = require("@brightchain/brightchain-lib");
15
+ const sha3_1 = require("@noble/hashes/sha3");
16
+ class MockBlockStore {
17
+ constructor() {
18
+ this.blocks = new Map();
19
+ /** Track method calls for assertions */
20
+ this.calls = {
21
+ has: [],
22
+ get: [],
23
+ put: [],
24
+ delete: [],
25
+ };
26
+ /** Optional: simulate errors on specific keys */
27
+ this.errorKeys = new Set();
28
+ }
29
+ // ── Methods used by brightchain-db ──
30
+ async has(key) {
31
+ const k = String(key);
32
+ this.calls.has.push(k);
33
+ if (this.errorKeys.has(k))
34
+ throw new Error(`MockBlockStore: simulated error on has(${k})`);
35
+ return this.blocks.has(k);
36
+ }
37
+ get(key) {
38
+ const k = String(key);
39
+ this.calls.get.push(k);
40
+ if (this.errorKeys.has(k))
41
+ throw new Error(`MockBlockStore: simulated error on get(${k})`);
42
+ const data = this.blocks.get(k);
43
+ if (!data)
44
+ throw new Error(`Block not found: ${k}`);
45
+ return { fullData: data };
46
+ }
47
+ async put(key, data) {
48
+ const k = String(key);
49
+ this.calls.put.push(k);
50
+ if (this.errorKeys.has(k))
51
+ throw new Error(`MockBlockStore: simulated error on put(${k})`);
52
+ this.blocks.set(k, data);
53
+ }
54
+ async delete(key) {
55
+ const k = String(key);
56
+ this.calls.delete.push(k);
57
+ this.blocks.delete(k);
58
+ }
59
+ // ── Convenience ──
60
+ /** Total number of blocks currently stored */
61
+ get size() {
62
+ return this.blocks.size;
63
+ }
64
+ /** Reset all stored data and call tracking */
65
+ reset() {
66
+ this.blocks.clear();
67
+ this.calls.has.length = 0;
68
+ this.calls.get.length = 0;
69
+ this.calls.put.length = 0;
70
+ this.calls.delete.length = 0;
71
+ this.errorKeys.clear();
72
+ }
73
+ // ── Stubs for remaining IBlockStore methods ──
74
+ get blockSize() {
75
+ return 0;
76
+ }
77
+ async getData() {
78
+ throw new Error('not implemented');
79
+ }
80
+ async setData() {
81
+ throw new Error('not implemented');
82
+ }
83
+ async deleteData() {
84
+ throw new Error('not implemented');
85
+ }
86
+ async getRandomBlocks() {
87
+ throw new Error('not implemented');
88
+ }
89
+ async getMetadata() {
90
+ throw new Error('not implemented');
91
+ }
92
+ async updateMetadata() {
93
+ throw new Error('not implemented');
94
+ }
95
+ async generateParityBlocks() {
96
+ throw new Error('not implemented');
97
+ }
98
+ async getParityBlocks() {
99
+ throw new Error('not implemented');
100
+ }
101
+ async recoverBlock() {
102
+ throw new Error('not implemented');
103
+ }
104
+ async verifyBlockIntegrity() {
105
+ throw new Error('not implemented');
106
+ }
107
+ async getBlocksPendingReplication() {
108
+ throw new Error('not implemented');
109
+ }
110
+ async getUnderReplicatedBlocks() {
111
+ throw new Error('not implemented');
112
+ }
113
+ async recordReplication() {
114
+ throw new Error('not implemented');
115
+ }
116
+ async recordReplicaLoss() {
117
+ throw new Error('not implemented');
118
+ }
119
+ async brightenBlock() {
120
+ throw new Error('not implemented');
121
+ }
122
+ async storeCBLWithWhitening(cblData) {
123
+ // Generate two deterministic block IDs from the data
124
+ const blockId1 = `cbl-block1-${this.blocks.size}-${Date.now()}`;
125
+ const blockId2 = `cbl-block2-${this.blocks.size}-${Date.now()}`;
126
+ // Store the original data under blockId1, and a random XOR component under blockId2
127
+ // For mock purposes, we store the raw data under blockId1 and a marker under blockId2
128
+ this.blocks.set(blockId1, new Uint8Array(cblData));
129
+ this.blocks.set(blockId2, new Uint8Array([0xfe, 0xed])); // marker
130
+ const magnetUrl = `magnet:?xt=urn:brightchain:cbl&bs=256&b1=${blockId1}&b2=${blockId2}`;
131
+ return {
132
+ blockId1,
133
+ blockId2,
134
+ blockSize: 256,
135
+ magnetUrl,
136
+ };
137
+ }
138
+ async retrieveCBL(blockId1, _blockId2, _block1ParityIds, _block2ParityIds) {
139
+ const k1 = String(blockId1);
140
+ const data = this.blocks.get(k1);
141
+ if (!data) {
142
+ throw new Error(`CBL block not found: ${k1}`);
143
+ }
144
+ return new Uint8Array(data);
145
+ }
146
+ parseCBLMagnetUrl(magnetUrl) {
147
+ const url = new URL(magnetUrl);
148
+ const params = url.searchParams;
149
+ return {
150
+ blockId1: params.get('b1') ?? '',
151
+ blockId2: params.get('b2') ?? '',
152
+ blockSize: parseInt(params.get('bs') ?? '0', 10),
153
+ isEncrypted: params.get('enc') === '1',
154
+ };
155
+ }
156
+ generateCBLMagnetUrl(blockId1, blockId2, blockSize) {
157
+ return `magnet:?xt=urn:brightchain:cbl&bs=${blockSize}&b1=${String(blockId1)}&b2=${String(blockId2)}`;
158
+ }
159
+ }
160
+ exports.MockBlockStore = MockBlockStore;
161
+ /**
162
+ * Mock pooled block store for testing pool-scoped operations.
163
+ *
164
+ * Extends MockBlockStore with IPooledBlockStore methods using simple
165
+ * in-memory maps. Computes SHA3-512 hashes for putInPool.
166
+ */
167
+ class MockPooledBlockStore extends MockBlockStore {
168
+ constructor() {
169
+ super(...arguments);
170
+ /** Pool-scoped block storage: storageKey -> block data */
171
+ this.poolBlocks = new Map();
172
+ /** Per-pool statistics */
173
+ this.poolStatsMap = new Map();
174
+ /** Track pool method calls for assertions */
175
+ this.poolCalls = {
176
+ hasInPool: [],
177
+ getFromPool: [],
178
+ putInPool: [],
179
+ deleteFromPool: [],
180
+ listPools: 0,
181
+ listBlocksInPool: [],
182
+ getPoolStats: [],
183
+ deletePool: [],
184
+ };
185
+ }
186
+ // ── Helpers ──
187
+ computeHash(data) {
188
+ const hashBytes = (0, sha3_1.sha3_512)(data);
189
+ return Buffer.from(hashBytes).toString('hex');
190
+ }
191
+ recordPut(poolId, dataLength) {
192
+ const now = new Date();
193
+ const existing = this.poolStatsMap.get(poolId);
194
+ if (existing) {
195
+ existing.blockCount += 1;
196
+ existing.totalBytes += dataLength;
197
+ existing.lastAccessedAt = now;
198
+ }
199
+ else {
200
+ this.poolStatsMap.set(poolId, {
201
+ poolId,
202
+ blockCount: 1,
203
+ totalBytes: dataLength,
204
+ createdAt: now,
205
+ lastAccessedAt: now,
206
+ });
207
+ }
208
+ }
209
+ recordDelete(poolId, dataLength) {
210
+ const existing = this.poolStatsMap.get(poolId);
211
+ if (existing) {
212
+ existing.blockCount -= 1;
213
+ existing.totalBytes -= dataLength;
214
+ existing.lastAccessedAt = new Date();
215
+ }
216
+ }
217
+ touchPool(poolId) {
218
+ const existing = this.poolStatsMap.get(poolId);
219
+ if (existing) {
220
+ existing.lastAccessedAt = new Date();
221
+ }
222
+ }
223
+ // ── Pool-Scoped Block Operations ──
224
+ async hasInPool(pool, hash) {
225
+ (0, brightchain_lib_1.validatePoolId)(pool);
226
+ this.poolCalls.hasInPool.push({ pool, hash });
227
+ const key = (0, brightchain_lib_1.makeStorageKey)(pool, hash);
228
+ this.touchPool(pool);
229
+ return this.poolBlocks.has(key);
230
+ }
231
+ async getFromPool(pool, hash) {
232
+ (0, brightchain_lib_1.validatePoolId)(pool);
233
+ this.poolCalls.getFromPool.push({ pool, hash });
234
+ const key = (0, brightchain_lib_1.makeStorageKey)(pool, hash);
235
+ const data = this.poolBlocks.get(key);
236
+ if (!data) {
237
+ throw new Error(`Block not found in pool "${pool}": ${hash}`);
238
+ }
239
+ this.touchPool(pool);
240
+ return data;
241
+ }
242
+ async putInPool(pool, data, _options) {
243
+ (0, brightchain_lib_1.validatePoolId)(pool);
244
+ const hash = this.computeHash(data);
245
+ this.poolCalls.putInPool.push({ pool, dataLength: data.length });
246
+ const key = (0, brightchain_lib_1.makeStorageKey)(pool, hash);
247
+ if (this.poolBlocks.has(key)) {
248
+ this.touchPool(pool);
249
+ return hash;
250
+ }
251
+ this.poolBlocks.set(key, new Uint8Array(data));
252
+ this.recordPut(pool, data.length);
253
+ return hash;
254
+ }
255
+ async deleteFromPool(pool, hash) {
256
+ (0, brightchain_lib_1.validatePoolId)(pool);
257
+ this.poolCalls.deleteFromPool.push({ pool, hash });
258
+ const key = (0, brightchain_lib_1.makeStorageKey)(pool, hash);
259
+ const data = this.poolBlocks.get(key);
260
+ if (data) {
261
+ this.poolBlocks.delete(key);
262
+ this.recordDelete(pool, data.length);
263
+ }
264
+ }
265
+ // ── Pool Management ──
266
+ async listPools() {
267
+ this.poolCalls.listPools++;
268
+ const pools = [];
269
+ for (const [poolId, stats] of this.poolStatsMap) {
270
+ if (stats.blockCount > 0) {
271
+ pools.push(poolId);
272
+ }
273
+ }
274
+ return pools;
275
+ }
276
+ async *listBlocksInPool(pool, options) {
277
+ (0, brightchain_lib_1.validatePoolId)(pool);
278
+ this.poolCalls.listBlocksInPool.push(pool);
279
+ const prefix = pool + ':';
280
+ const limit = options?.limit;
281
+ const cursor = options?.cursor;
282
+ let pastCursor = cursor === undefined;
283
+ let yielded = 0;
284
+ for (const key of this.poolBlocks.keys()) {
285
+ if (!key.startsWith(prefix)) {
286
+ continue;
287
+ }
288
+ const { hash } = (0, brightchain_lib_1.parseStorageKey)(key);
289
+ if (!pastCursor) {
290
+ if (hash === cursor) {
291
+ pastCursor = true;
292
+ }
293
+ continue;
294
+ }
295
+ yield hash;
296
+ yielded++;
297
+ if (limit !== undefined && yielded >= limit) {
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ async getPoolStats(pool) {
303
+ (0, brightchain_lib_1.validatePoolId)(pool);
304
+ this.poolCalls.getPoolStats.push(pool);
305
+ const stats = this.poolStatsMap.get(pool);
306
+ if (!stats) {
307
+ throw new Error(`Pool "${pool}" not found: no blocks have been stored in this pool`);
308
+ }
309
+ return { ...stats };
310
+ }
311
+ async deletePool(pool) {
312
+ (0, brightchain_lib_1.validatePoolId)(pool);
313
+ this.poolCalls.deletePool.push(pool);
314
+ const prefix = pool + ':';
315
+ const keysToDelete = [];
316
+ for (const key of this.poolBlocks.keys()) {
317
+ if (key.startsWith(prefix)) {
318
+ keysToDelete.push(key);
319
+ }
320
+ }
321
+ for (const key of keysToDelete) {
322
+ this.poolBlocks.delete(key);
323
+ }
324
+ this.poolStatsMap.delete(pool);
325
+ }
326
+ // ── Pool-Scoped Whitening Operations ──
327
+ async getRandomBlocksFromPool(pool, count) {
328
+ (0, brightchain_lib_1.validatePoolId)(pool);
329
+ const prefix = pool + ':';
330
+ const hashes = [];
331
+ for (const key of this.poolBlocks.keys()) {
332
+ if (key.startsWith(prefix)) {
333
+ const { hash } = (0, brightchain_lib_1.parseStorageKey)(key);
334
+ hashes.push(brightchain_lib_1.Checksum.fromHex(hash));
335
+ if (hashes.length >= count)
336
+ break;
337
+ }
338
+ }
339
+ return hashes;
340
+ }
341
+ async bootstrapPool(pool, blockSize, count) {
342
+ (0, brightchain_lib_1.validatePoolId)(pool);
343
+ for (let i = 0; i < count; i++) {
344
+ const data = new Uint8Array(blockSize);
345
+ crypto.getRandomValues(data);
346
+ await this.putInPool(pool, data);
347
+ }
348
+ }
349
+ async validatePoolDeletion(pool) {
350
+ (0, brightchain_lib_1.validatePoolId)(pool);
351
+ return { safe: true, dependentPools: [], referencedBlocks: [] };
352
+ }
353
+ async forceDeletePool(pool) {
354
+ await this.deletePool(pool);
355
+ }
356
+ // ── Pool-Scoped CBL Whitening Operations ──
357
+ async storeCBLWithWhiteningInPool(_pool, _cblData, _options) {
358
+ throw new Error('Not implemented in mock');
359
+ }
360
+ async retrieveCBLFromPool(_pool, _blockId1, _blockId2, _block1ParityIds, _block2ParityIds) {
361
+ throw new Error('Not implemented in mock');
362
+ }
363
+ // ── Convenience ──
364
+ /** Reset all stored data including pool data and call tracking */
365
+ reset() {
366
+ super.reset();
367
+ this.poolBlocks.clear();
368
+ this.poolStatsMap.clear();
369
+ this.poolCalls.hasInPool.length = 0;
370
+ this.poolCalls.getFromPool.length = 0;
371
+ this.poolCalls.putInPool.length = 0;
372
+ this.poolCalls.deleteFromPool.length = 0;
373
+ this.poolCalls.listPools = 0;
374
+ this.poolCalls.listBlocksInPool.length = 0;
375
+ this.poolCalls.getPoolStats.length = 0;
376
+ this.poolCalls.deletePool.length = 0;
377
+ }
378
+ }
379
+ exports.MockPooledBlockStore = MockPooledBlockStore;
380
+ //# sourceMappingURL=mockBlockStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mockBlockStore.js","sourceRoot":"","sources":["../../../../../brightchain-db/src/__tests__/helpers/mockBlockStore.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAEH,uDAAuD;AACvD,kEAgBsC;AACtC,6CAA8C;AAE9C,MAAa,cAAc;IAA3B;QACW,WA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AC,MAAM,GAAG,CAAC,CAAC;QACpC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,MAAM,GAAG,CAAC,CAAC;QACzC,IAAI,CAAC,SAAS,CAAC,SAAS,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,SAAS,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC;QAC3C,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;QACvC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;IACvC,CAAC;CACF;AAlRD,oDAkRC"}
package/src/index.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @brightchain/db
3
+ *
4
+ * A MongoDB-like document database backed by BrightChain's block store.
5
+ */
6
+ export type { AggregationStage, BsonDocument, BulkWriteOperation, BulkWriteOptions, BulkWriteResult, ChangeEvent, ChangeEventType, ChangeListener, ClientSession, CollectionOptions, CursorSession, DeleteResult, DocumentId, FilterOperator, FilterQuery, FindOptions, IndexOptions, IndexSpec, InsertManyResult, InsertOneResult, LogicalOperators, ProjectionSpec, ReadPreference, ReplaceResult, SortSpec, TextIndexOptions, UpdateOperators, UpdateOptions, UpdateQuery, UpdateResult, WriteConcern, WriteOptions, } from './lib/types';
7
+ export { Collection, HeadRegistry, calculateBlockId } from './lib/collection';
8
+ export type { CollectionResolver, ICollectionHeadRegistry, } from './lib/collection';
9
+ export { BrightChainDb } from './lib/database';
10
+ export type { BrightChainDbOptions } from './lib/database';
11
+ export { InMemoryHeadRegistry, PersistentHeadRegistry, } from './lib/headRegistry';
12
+ export type { HeadRegistryOptions } from './lib/headRegistry';
13
+ export { PooledStoreAdapter } from './lib/pooledStoreAdapter';
14
+ export { InMemoryDatabase, createDefaultUuidGenerator, } from '@brightchain/brightchain-lib';
15
+ export { CBLIndex } from './lib/cblIndex';
16
+ export type { CBLIndexOptions } from './lib/cblIndex';
17
+ export { Model, TypedCursor } from './lib/model';
18
+ export type { ModelOptions } from './lib/model';
19
+ export { Cursor } from './lib/cursor';
20
+ export { applyProjection, compareValues, deepEquals, getTextSearchFields, matchesFilter, setTextSearchFields, sortDocuments, tokenize, } from './lib/queryEngine';
21
+ export { applyUpdate, isOperatorUpdate } from './lib/updateEngine';
22
+ export { runAggregation } from './lib/aggregation';
23
+ export { CollectionIndex, DuplicateKeyError, IndexManager, } from './lib/indexing';
24
+ export { DbSession } from './lib/transaction';
25
+ export type { CommitCallback, JournalOp, RollbackCallback, } from './lib/transaction';
26
+ export { createDbRouter } from './lib/expressMiddleware';
27
+ export type { DbRouterOptions } from './lib/expressMiddleware';
28
+ export { BrightChainDbError, BulkWriteError, DocumentNotFoundError, IndexError, TransactionError, ValidationError, WriteConcernError, } from './lib/errors';
29
+ export type { BulkWriteOperationError, ValidationFieldError, WriteConcernSpec, } from './lib/errors';
30
+ export { applyDefaults, validateDocument } from './lib/schemaValidation';
31
+ export type { CollectionSchema, FieldSchema, SchemaType, } from './lib/schemaValidation';