import { type AbstractType } from "@dao-xyz/borsh"; import type { QueryCacheOptions } from "@peerbit/indexer-cache"; import * as indexerTypes from "@peerbit/indexer-interface"; import { type Change, Entry, type ShallowOrFullEntry, type TrimOptions } from "@peerbit/log"; import { Program, type ProgramEvents } from "@peerbit/program"; import { type EntryReplicated, type ReplicationDomain, type SharedAppendOptions, SharedLog, type SharedLogOptions } from "@peerbit/shared-log"; import type { CustomDocumentDomain } from "./domain.js"; import type { DocumentEvents } from "./events.js"; import { DeleteOperation, type Operation, PutOperation, PutWithKeyOperation } from "./operation.js"; import { type CanRead, type CanSearch, DocumentIndex, type GetOptions, type IndexedContextOnly, type PrefetchOptions, type ReachScope, type TransformOptions } from "./search.js"; export declare class OperationError extends Error { constructor(message?: string); } export type DocumentMode = "auto" | "compat" | "native"; export declare class NativeDocumentModeError extends Error { constructor(message: string); } /** * The document `compatibility` open option (6 | 7) was removed: the legacy * document compatibility modes are retired together with the shared-log * replication-info compatibility modes they mapped onto (6 -> log v8, * 7 -> log v9). Any explicitly provided value rejects at open() with this * document-level error before it can reach shared-log semantics. Persisted * data written by compatibility-6 stores (PutWithKeyOperation tag 0, * DeleteByStringKeyOperation tag 2) remains decodable: old stores stay * openable without the option. */ export declare class DocumentCompatibilityRetiredError extends Error { constructor(value: unknown); } type MaybePromise = Promise | T; export type CountEstimate = { estimate: number; /** * Relative error margin (0..1), where e.g. `0.1` means ~±10%. * * Only non-`undefined` when the replication domain is expected to be uniformly * distributed (currently: `domain.type === "hash"`), and when there is * sufficient local sample information to compute it. * * When `undefined`, the caller should treat `estimate` as unreliable. */ errorMargin: number | undefined; }; type CanPerformPut = { type: "put"; value: T; operation: PutOperation; entry: Entry; previousEntries?: Entry[]; }; type CanPerformDelete = { type: "delete"; value?: T; operation: DeleteOperation; entry: Entry; }; export type CanPerformOperations = CanPerformPut | CanPerformDelete; export type CanPerform = (properties: CanPerformOperations) => MaybePromise; type PutChangeReference> = { document: T; operation: PutOperation | PutWithKeyOperation; key: indexerTypes.IdKey; unique?: boolean; existing?: indexerTypes.IndexedResult> | null | undefined; }; type DocumentPutOptions = SharedAppendOptions & { unique?: boolean; replicate?: boolean; checkRemote?: boolean; }; export type DocumentPutManyOptions = DocumentPutOptions & { /** Require a supported independent batch; never fall back to sequential puts. */ batching?: "required"; }; type DocumentPutResult = { readonly entry: Entry; removed: ShallowOrFullEntry[]; }; type DocumentPutManyResult = { entries: Entry[]; removed: ShallowOrFullEntry[]; }; type InferR = D extends ReplicationDomain ? I : "u32"; export type SetupOptions = T extends Record ? T : any, D extends ReplicationDomain = any> = { type: AbstractType; mode?: DocumentMode; canOpen?: (program: T) => MaybePromise; canPerform?: CanPerform; strictHistory?: boolean; id?: (obj: any) => indexerTypes.Ideable; index?: { canSearch?: CanSearch; canRead?: CanRead; idProperty?: string | string[]; cache?: { resolver?: number; query?: QueryCacheOptions; }; prefetch?: boolean | Partial; includeIndexed?: boolean; } & TransformOptions; log?: { trim?: TrimOptions; }; domain?: (db: Documents) => CustomDocumentDomain>; keep?: ((entry: ShallowOrFullEntry | EntryReplicated>) => Promise | boolean) | "self"; } & Omit>, "domain" | "keep">; export type ExtractArgs = T extends ReplicationDomain ? Args : never; export declare class Documents = T extends Record ? T : any, D extends ReplicationDomain = any> extends Program, DocumentEvents & ProgramEvents> { log: SharedLog>; immutable: boolean; private _index; private _clazz; private _optionCanPerform?; private _optionCanPerformNativePolicy?; private _optionCanPerformNativeFastPath?; private _nativeBackboneDocumentIndexEnabled; private _mode; private _nativeModeReplicatedOpen; private _valueClassIsProgram; private _documentChangeListeners; private _documentChangeListenerCount; private _documentInternalChangeListenerCount; private _documentChangeListenerTrackingInitialized; private _documentBackend; private _canAppendDecodedDocuments; private acceptPutOperation; private _nativeDocumentIdExtractionPlan?; private _nativeDocumentFieldExtractionPlans?; private _hasLogTrim; private _hasCustomIdResolver; private idResolver; private domain?; private strictHistory; canOpen?: (program: T) => Promise | boolean; constructor(properties?: { id?: Uint8Array; immutable?: boolean; index?: DocumentIndex>; }); get index(): DocumentIndex; get events(): import("@libp2p/interface").TypedEventTarget & ProgramEvents>; private isNativeMode; private createDocumentBackend; private detachDomainEntryCallback; private detachTrimEntryCallback; private createNativeDocumentBackendContext; private nativeModeError; private assertNativeModeOpenOptions; private assertNativeModeReady; private canPerformAllowsPlainPutFastPath; private nativePlainPutPolicyNeedsPreviousEntries; private nativePlainPutPolicyRequiredPreviousSignerPublicKey; private unsupportedNativePutOptions; private assertNativeModePlainPutSupported; private assertNativeModePlainPutPolicySupported; private canPerformAllowsNativePlainPut; private nativePutPolicyAllows; private nativeFieldValueMatchesLocalPublicKey; private nativeFieldValueMatchesPublicKey; private nativeFieldValueMatchesPublicKeys; private nativeDeletePolicyNeedsEntryPublicKeys; private nativePutOperationPolicyAllows; private nativeDeleteOperationPolicyAllows; private assertNativeModePlainPutManySupported; private assertNativeModeDeleteSupported; private canPerformAllowsNativeDelete; private normalizeNativeModePutOptions; private trackDocumentChangeListeners; private getLocalIndexedContext; /** * The change-delivery variant of `getLocalIndexedContext`, and the ONLY caller * allowed to treat a closed index as "no prior version". * * `getLocalIndexedContext` reaches the backing indexer directly, bypassing * `DocumentIndex`'s guarded wrappers. `terminalChildOrder` now tears the index * down after the log, but a change can still be delivered against a closed * index on paths that do not go through that ordering: a `DocumentIndex` closed * on its own rather than through its parent, and a log teardown that fails, * which opens the rank gate without having drained. For a change that the log * has ALREADY committed, "there is no prior version to compare against" is the * right reading, and the write leg - which already returns without persisting * once the index is closed, see `DocumentIndex.putWithContext` - drops it. * * WHY THIS IS NOT ON THE SHARED HELPER. It was, and that was wrong. The helper * has five callers and only this one is a post-commit change: * * :2689 resolveCanPerformDeleteValue - feeds the user's canPerform policy * :2794 _canAppend PUT - immutable-overwrite protection * :2863 _canAppend DELETE - delete-history validation * :3124 putCompatDocumentBackend - the user-initiated put() path * * Swallowing there is actively harmful rather than merely broad. On :3124 a * put() against a closed index returned SUCCESS with the entry committed to the * log and silently absent from the index - the exact log/index divergence this * recovery exists to avoid, manufactured on the public write path with no error * signal. On :2863 a swallowed read reads as "already deleted" and returns * `assume ok`, turning a REJECT into an ALLOW for inbound remote deletes. * * Those callers must keep throwing: outside change delivery, a closed index is * a caller error, not a state to paper over. */ private getLocalIndexedContextForChange; /** * Deliberately narrow: only `NotStartedError`, and only once the document index * is actually closed. An indexer that breaks while the index is open still * throws. Reachable only from `getLocalIndexedContextForChange`. */ private recoverClosedIndexContextRead; private getNativeEntrySignerPublicKeys; private getSharedLogNativeBackbone; private getNativePreviousEntrySignerPublicKey; private getNativePreviousEntrySignerPublicKeyForPutOperation; private getNativeIndexedContext; private getNativeModeIndexedContext; private hasNativeDocumentContextLookup; private getNativeIndexedContextsAndPreviousSignerPublicKeys; private getExistingContext; private documentFromIdentityIndexedValue; private getLocalIdentityDocumentByHead; private getLocalIndexedDocumentForNativeDeletePolicy; private getNativeDeletePolicyFieldValue; get changes(): import("@libp2p/interface").TypedEventTarget & ProgramEvents>; private maybeSubprogramOpen; private keepCache; open(options: SetupOptions): Promise; recover(): Promise; /** * `Documents` owns two sub-programs: `log` (the source of changes) and * `_index` (a view derived from it, backed by an indexer). `Program` tears * children down concurrently by default, so nothing stopped * `DocumentIndex.close()` -> `indexer.stop()` from completing while a * `Log.joinRecursively()` was still in flight. That join calls `handleChanges` * with an entry it has *already* committed to the log, and `handleChanges` * reads the index (`getLocalIndexedContext`) before it writes - so the read hit * an indexer in state "closed" and threw `NotStartedError` out of a join that * had no business failing. * * Ranking the index behind the log fixes the ordering rather than the symptom: * `SharedLog.close()` drains its in-flight receives and then closes the lower * `Log`, so by the time the index is torn down no further change can be * dispatched, and every change already committed to the log has been applied to * the index. Nothing is dropped. */ protected terminalChildOrder(child: Program): number; private _resolveEntry; protected canAppend(entry: Entry, reference?: { document: T; operation: PutOperation; }): Promise; private nativeCanPerformAllowsAppend; private resolveCanPerformPreviousEntries; private detachDocumentValueForCallback; private resolveCanPerformDeleteValue; protected _canAppend(entry: Entry, reference?: { document: T; operation: PutOperation; }): Promise; private getAppendOperation; private getPlainEntryOperationFromStorage; private getEntryStorageBytesFromBlocks; private getNativeDocumentFieldExtractionPlan; private getNativeDocumentFieldFromPutOperation; private getNativeDocumentIdFromPutOperation; private preparePut; private preparePlainPut; put(doc: T, options?: DocumentPutOptions): Promise; private deliverPersistedDocumentEntries; private deliverPersistedDocumentAppendCommits; private putCompatDocumentBackend; putMany(docs: T[], options?: DocumentPutManyOptions): Promise; private putManyCompatDocumentBackend; private putManySequential; private hasDuplicatePreparedPutKeys; private canUsePlainPutFastPath; private canUsePlainPutManyFastPath; private createPlainPutCommitPlan; private commitPlainPutPlan; private commitNativeDocumentAppend; private commitNativeDocumentAppendWithEvidence; private createNativeCheckedDocumentAppendCommitFacts; private assertNativeModeDocumentAppendCommit; private toNativeBackboneDocumentIndexCommitInput; private prepareNativeBackboneDocumentIndexCommit; private createNativeBackboneDocumentIndexAppendFactsPreparer; private commitNativeDocumentAppendPayloadFallback; private commitNativeDocumentAppendMany; private commitNativeDocumentAppendManyWithEvidence; private prepareNativeBackboneDocumentIndexCommitBatch; private createDocumentAppendCommitFacts; private createDocumentAppendCommitFactsWithLazyContext; private createNativeDocumentAppendTransaction; private createDocumentAppendCommitFactsBatch; private createDocumentAppendCommitFactsWithContext; private hasDocumentChangeConsumers; private dispatchDocumentChangeIfObserved; private nextFromIndexedContext; private finishPreparedPlainPutCommit; private finishPreparedPlainPutManyCommit; private handlePreparedPlainPutCommit; private tryHandlePreparedPlainPutCommitRemovedFromHeads; private tryHandlePreparedPlainPutCommitRemovedHashesFromHeads; private handlePreparedPlainPutCommitRemoved; private handlePreparedPlainPutCommitRemovedHashes; private handlePreparedPlainPutManyCommit; private collectRemovedDocumentChangeFromIndexedHead; private collectRemovedDocumentChangeFromIndexedKey; private collectRemovedDocumentChangesFromIndexedHeads; private collectRemovedDocumentChangesFromIndexedHeadHashes; private collectRemovedDocumentChange; private collectRemovedPutChangeFromNativeId; private putStrictNativeReceivedDocumentIndexWithContext; private putStrictNativeReceivedDocumentIndexStoredWithContext; get(id: indexerTypes.Ideable | indexerTypes.IdKey, options?: Omit, "resolve">): Promise; del(id: indexerTypes.Ideable | indexerTypes.IdKey, options?: SharedAppendOptions): Promise; private delCompatDocumentBackend; private delNativeDocumentBackend; private delNativeDocumentBackendWithEvidence; handleChanges(change: Change, reference?: PutChangeReference): Promise; private handleChangesInOrder; /** * Count documents locally (default), or estimate the global count. * * - `count()` / `count({ query })`: exact local count from the index. * - `count({ approximate: true })`: estimated global count from replication metadata (no remote queries) + error margin when available. */ count(options?: { query?: indexerTypes.Query | indexerTypes.QueryLike; approximate?: false | undefined; }): Promise; count(options: { query?: indexerTypes.Query | indexerTypes.QueryLike; approximate: true | { scope?: ReachScope; }; }): Promise; } export {}; //# sourceMappingURL=program.d.ts.map