/** * Collection – the main API surface for interacting with a document collection. * * Provides a MongoDB-compatible interface including: * insertOne, insertMany, findOne, find, updateOne, updateMany, * deleteOne, deleteMany, replaceOne, countDocuments, distinct, * aggregate, createIndex, dropIndex, watch */ import type { ICollection } from '@digitaldefiance/suite-core-lib'; import { ReadConcern } from '../enumerations/readConcern'; import type { IEnrichedQueryResult } from '../interfaces/blockFetch/enrichedQueryResult'; import type { IBlockStore } from '../interfaces/storage/blockStore'; import type { IHeadRegistry } from '../interfaces/storage/headRegistry'; import { Cursor } from './cursor'; import type { AggregationStage, BsonDocument, BulkWriteOperation, BulkWriteOptions, BulkWriteResult, ChangeListener, CollectionOptions, CollectionSchema, DeleteResult, DocumentId, FilterQuery, FindOptions, IndexOptions, IndexSpec, InsertManyResult, InsertOneResult, ReadPreference, ReplaceResult, TextIndexOptions, UpdateOptions, UpdateQuery, UpdateResult, ValidationFieldError, WriteConcern, WriteOptions } from './types'; import type { UuidGenerator } from './uuidGenerator'; /** * Calculate a content-addressable block ID from data. * Uses SHA3-512, the same algorithm as BrightChain's ChecksumService, * but without requiring the global service provider to be initialised. */ export declare function calculateBlockId(data: Buffer | Uint8Array): string; /** * Lookup resolver type – given a collection name, returns a collection instance. */ export type CollectionResolver = (name: string) => Collection; /** * A single document collection backed by a BrightChain block store. */ export declare class Collection implements ICollection { readonly name: string; private readonly store; private readonly dbName; private readonly headRegistry; /** In-memory document index: logical _id → block checksum */ private readonly docIndex; /** In-memory document cache for fast reads */ private readonly docCache; /** Index manager */ private readonly indexManager; /** Change listeners */ private readonly changeListeners; /** Lookup resolver for $lookup in aggregation */ private collectionResolver?; /** Whether initial index has been loaded */ private loaded; /** Loading promise */ private loading; /** Schema validation (if configured) */ private schema?; /** Write concern for this collection */ private writeConcern; /** Read preference for this collection */ private readPreference; /** TTL index timers */ private ttlTimers; /** Text index config: field name → weight */ private textIndexFields; /** UUID generator for creating document IDs */ private readonly uuidGenerator; constructor(name: string, store: IBlockStore, dbName: string, headRegistry: IHeadRegistry, options?: CollectionOptions, uuidGenerator?: UuidGenerator); /** Set the collection resolver for cross-collection operations */ setCollectionResolver(resolver: CollectionResolver): void; private ensureLoaded; private loadFromStore; private loadAllDocs; private persistMeta; private readDocFromStore; /** * Read a document from the store with read concern support. * * Unlike `readDocFromStore`, this method uses `getData()` (async) instead of * `get()` (sync handle), and propagates the read concern to the store when * the store supports it (i.e., is an IReadConcernBlockStore). * * Throws PendingBlockError if the block is pending remote fetch (Available concern). * Other errors are re-thrown to the caller. * * @param blockId - The block checksum hex string * @param readConcern - The read concern level to use * @returns The parsed document, or null if the block data is invalid * @throws PendingBlockError if the block is pending remote fetch * @see Requirements 3.4 */ private readDocFromStoreWithConcern; private readDoc; private writeDoc; /** * Remove a document from the collection index. * * Copy-on-write: blocks in the store are never deleted. This method only * removes the logical mapping so the document is no longer reachable. * The underlying block remains in the store as an orphan and could be * reclaimed by a separate garbage-collection process if desired. */ private removeDoc; /** * Insert a single document. */ insertOne(doc: T, options?: WriteOptions): Promise; /** * Insert multiple documents. */ insertMany(docs: T[], options?: WriteOptions): Promise; /** * Find a single document matching the filter. */ findOne(filter?: FilterQuery, options?: FindOptions): Promise; /** * Find documents matching the filter. Returns a cursor for chaining. */ find(filter?: FilterQuery, options?: FindOptions): Cursor; /** * Find a document by its _id. */ findById(id: DocumentId): Promise; /** * Find documents matching the filter with availability metadata. * * Unlike `find`/`findOne`, this method returns an enriched result that * includes information about blocks that could not be retrieved (pending * remote fetch). The `readConcern` option is propagated to the underlying * store's `getData` call when the store supports it. * * Existing `find`/`findOne` methods remain unchanged for backward compatibility. * * @param filter - Query filter to match documents * @param options - Find options including optional readConcern * @returns Enriched query result with documents, pending blocks, and completeness flag * @see Requirements 3.1, 3.2, 3.3, 3.4 */ findWithAvailability(filter?: FilterQuery, options?: FindOptions & { readConcern?: ReadConcern; }): Promise>; /** * Update a single document matching the filter. */ updateOne(filter: FilterQuery, update: UpdateQuery, options?: UpdateOptions): Promise; /** * Update all documents matching the filter. */ updateMany(filter: FilterQuery, update: UpdateQuery, options?: WriteOptions): Promise; /** * Delete a single document matching the filter. */ deleteOne(filter: FilterQuery, options?: WriteOptions): Promise; /** * Delete all documents matching the filter. */ deleteMany(filter: FilterQuery, options?: WriteOptions): Promise; /** * Replace a single document matching the filter. */ replaceOne(filter: FilterQuery, replacement: T, options?: UpdateOptions): Promise; /** * Count documents matching the filter. */ countDocuments(filter?: FilterQuery): Promise; /** * Estimated document count (fast, from index size). */ estimatedDocumentCount(): Promise; /** * Get distinct values for a field. */ distinct(field: K, filter?: FilterQuery): Promise>; /** * Run an aggregation pipeline. */ aggregate(pipeline: AggregationStage[]): Promise; /** * Set a schema for this collection. Documents will be validated on * insert and (if level is 'strict') on update. */ setSchema(schema: CollectionSchema): void; /** * Get the current schema (if any). */ getSchema(): CollectionSchema | undefined; /** * Remove validation schema. */ removeSchema(): void; /** * Validate a document without inserting it. * @returns array of validation errors (empty if valid) */ validateDoc(doc: T): ValidationFieldError[]; /** * Internal: validate and apply defaults before write. */ private validateBeforeWrite; /** * Create a text index for full-text search. * * @param options - The fields to index and their weights * @returns The index name * * @example * ```typescript * await coll.createTextIndex({ fields: { title: 10, body: 1 } }); * const results = await coll.find({ $text: { $search: 'hello world' } }).toArray(); * ``` */ createTextIndex(options: TextIndexOptions): string; /** * Drop the text index. */ dropTextIndex(): void; /** * Check if a text index exists. */ hasTextIndex(): boolean; /** * Create a TTL index that automatically removes documents whose * date field is older than `expireAfterSeconds`. * * TTL expiry is checked periodically (every 60 seconds by default). */ createTTLIndex(field: string, expireAfterSeconds: number, intervalMs?: number): Promise; /** * Stop a TTL index timer (does not drop the index itself). */ stopTTL(indexName: string): void; /** * Run a single TTL sweep: delete documents where `field` is older * than `expireAfterSeconds` from now. */ sweepTTL(field: string, expireAfterSeconds: number): Promise; /** * Execute multiple write operations in a single call. * * @param operations - Array of write operations * @param options - Bulk write options (ordered = stop on first error) * @returns Aggregated result of all operations * @throws BulkWriteError if any operations fail and ordered is true * * @example * ```typescript * await coll.bulkWrite([ * { insertOne: { document: { name: 'Alice' } } }, * { updateOne: { filter: { name: 'Bob' }, update: { $set: { age: 30 } } } }, * { deleteOne: { filter: { name: 'Charlie' } } }, * ]); * ``` */ bulkWrite(operations: BulkWriteOperation[], options?: BulkWriteOptions): Promise; /** * Get the current write concern for this collection. */ getWriteConcern(): WriteConcern; /** * Set the write concern for this collection. */ setWriteConcern(wc: WriteConcern): void; /** * Get the current read preference for this collection. */ getReadPreference(): ReadPreference; /** * Set the read preference for this collection. */ setReadPreference(rp: ReadPreference): void; /** * Create an index on this collection. */ createIndex(spec: IndexSpec, options?: IndexOptions): Promise; /** * Drop an index by name. */ dropIndex(name: string): Promise; /** * List all indexes on this collection. */ listIndexes(): Promise; /** * Watch for changes on this collection. */ watch(listener: ChangeListener): () => void; private emitChange; /** Apply a transaction insert */ _txInsert(doc: T): Promise; /** Apply a transaction update – writes a new block (copy-on-write). */ _txUpdate(docId: DocumentId, after: T): Promise; /** Apply a transaction delete – removes mapping only (copy-on-write). */ _txDelete(docId: DocumentId, doc: T): Promise; /** * Rollback a transaction insert. * Copy-on-write: just remove the mapping; the block remains in the store. */ _txRollbackInsert(docId: DocumentId): Promise; /** * Rollback a transaction update. * Copy-on-write: restore the old mapping. The old block still exists in * the store (blocks are never deleted), so writeDoc will detect it via * store.has() and simply re-point the index. */ _txRollbackUpdate(docId: DocumentId, before: T): Promise; /** * Rollback a transaction delete. * Copy-on-write: re-insert the mapping. The block still exists in the * store since blocks are never deleted. */ _txRollbackDelete(doc: T): Promise; /** * Drop the entire collection – remove all document mappings and indexes. * * Copy-on-write: blocks in the store are never deleted. Only the * collection's internal index and cache are cleared. */ drop(): Promise; /** Configure the query engine's text search fields from our text index */ private configureTextSearch; } //# sourceMappingURL=collection.d.ts.map