@powerhousedao/reactor-hypercore 6.2.3-dev.9 → 6.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +74 -62
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +69 -26
- package/dist/index.js.map +1 -1
- package/package.json +8 -8
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Operation, OperationWithContext } from "@powerhousedao/shared/document-model";
|
|
2
|
+
import "document-model";
|
|
3
|
+
import "@powerhousedao/shared/document-drive";
|
|
4
|
+
import "@powerhousedao/shared/processors";
|
|
2
5
|
import Hyperbee from "hyperbee";
|
|
3
|
-
|
|
6
|
+
import "node:worker_threads";
|
|
4
7
|
//#region ../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts
|
|
5
8
|
declare global {
|
|
6
9
|
interface AsyncDisposable {}
|
|
@@ -8,39 +11,6 @@ declare global {
|
|
|
8
11
|
readonly asyncDispose: unique symbol;
|
|
9
12
|
}
|
|
10
13
|
}
|
|
11
|
-
/**
|
|
12
|
-
* The main Kysely class.
|
|
13
|
-
*
|
|
14
|
-
* You should create one instance of `Kysely` per database using the {@link Kysely}
|
|
15
|
-
* constructor. Each `Kysely` instance maintains its own connection pool.
|
|
16
|
-
*
|
|
17
|
-
* ### Examples
|
|
18
|
-
*
|
|
19
|
-
* This example assumes your database has a "person" table:
|
|
20
|
-
*
|
|
21
|
-
* ```ts
|
|
22
|
-
* import * as Sqlite from 'better-sqlite3'
|
|
23
|
-
* import { type Generated, Kysely, SqliteDialect } from 'kysely'
|
|
24
|
-
*
|
|
25
|
-
* interface Database {
|
|
26
|
-
* person: {
|
|
27
|
-
* id: Generated<number>
|
|
28
|
-
* first_name: string
|
|
29
|
-
* last_name: string | null
|
|
30
|
-
* }
|
|
31
|
-
* }
|
|
32
|
-
*
|
|
33
|
-
* const db = new Kysely<Database>({
|
|
34
|
-
* dialect: new SqliteDialect({
|
|
35
|
-
* database: new Sqlite(':memory:'),
|
|
36
|
-
* })
|
|
37
|
-
* })
|
|
38
|
-
* ```
|
|
39
|
-
*
|
|
40
|
-
* @typeParam DB - The database interface type. Keys of this type must be table names
|
|
41
|
-
* in the database and values must be interfaces that describe the rows in those
|
|
42
|
-
* tables. See the examples above.
|
|
43
|
-
*/
|
|
44
14
|
//#endregion
|
|
45
15
|
//#region ../reactor/dist/index.d.ts
|
|
46
16
|
/**
|
|
@@ -58,11 +28,7 @@ type PagedResults<T> = {
|
|
|
58
28
|
options: PagingOptions;
|
|
59
29
|
next?: () => Promise<PagedResults<T>>;
|
|
60
30
|
nextCursor?: string;
|
|
61
|
-
totalCount?: number;
|
|
62
31
|
};
|
|
63
|
-
/**
|
|
64
|
-
* A string key in the format `documentId:scope:branch` used to identify a consistency checkpoint.
|
|
65
|
-
*/
|
|
66
32
|
/**
|
|
67
33
|
* One read-set stream and the highest operation index observed on it, or -1
|
|
68
34
|
* if it was observed empty.
|
|
@@ -80,7 +46,6 @@ type AppendConditionStream = {
|
|
|
80
46
|
type AppendCondition = {
|
|
81
47
|
streams: AppendConditionStream[];
|
|
82
48
|
};
|
|
83
|
-
/** Error history keeps messages, not classes, so failures match by prefix. */
|
|
84
49
|
/**
|
|
85
50
|
* A write transaction passed to {@link IOperationStore.apply}. Accumulates
|
|
86
51
|
* operations that are committed atomically when the callback returns.
|
|
@@ -94,7 +59,9 @@ interface AtomicTxn {
|
|
|
94
59
|
* revision field and lastModified timestamp.
|
|
95
60
|
*/
|
|
96
61
|
type DocumentRevisions = {
|
|
97
|
-
/** Map of scope to operation index for that scope */
|
|
62
|
+
/** Map of scope to operation index for that scope */
|
|
63
|
+
revision: Record<string, number>;
|
|
64
|
+
/** The largest operation timestamp in the document, across every scope. */
|
|
98
65
|
latestTimestamp: string;
|
|
99
66
|
};
|
|
100
67
|
/**
|
|
@@ -136,6 +103,16 @@ interface IOperationStore {
|
|
|
136
103
|
* Returns operations for a document/scope/branch whose index is greater
|
|
137
104
|
* than the given revision.
|
|
138
105
|
*
|
|
106
|
+
* `paging.cursor` is opaque to callers: treat it only as the value
|
|
107
|
+
* returned in `nextCursor` from a previous page, never construct or
|
|
108
|
+
* interpret it directly. An implementation must never emit a `nextCursor`
|
|
109
|
+
* equal to the start-of-stream sentinel ("0"), since a caller that walks
|
|
110
|
+
* `nextCursor` to exhaustion would read that as "start over" and loop
|
|
111
|
+
* forever. The reference encoding (used by the Kysely and Hypercore
|
|
112
|
+
* stores) is the index to resume from, i.e. the last returned row's index
|
|
113
|
+
* plus one, so a page that happens to end at index 0 still produces a
|
|
114
|
+
* cursor distinguishable from the start sentinel.
|
|
115
|
+
*
|
|
139
116
|
* @param documentId - The document id
|
|
140
117
|
* @param scope - The operation scope
|
|
141
118
|
* @param branch - The branch name
|
|
@@ -158,6 +135,16 @@ interface IOperationStore {
|
|
|
158
135
|
/**
|
|
159
136
|
* Gets operations that may conflict with incoming operations during a load.
|
|
160
137
|
*
|
|
138
|
+
* `paging.cursor` is opaque to callers: treat it only as the value
|
|
139
|
+
* returned in `nextCursor` from a previous page, never construct or
|
|
140
|
+
* interpret it directly. An implementation must never emit a `nextCursor`
|
|
141
|
+
* equal to the start-of-stream sentinel ("0"), since a caller that walks
|
|
142
|
+
* `nextCursor` to exhaustion would read that as "start over" and loop
|
|
143
|
+
* forever. The reference encoding (used by the Kysely and Hypercore
|
|
144
|
+
* stores) is the index to resume from, i.e. the last returned row's index
|
|
145
|
+
* plus one, so a page that happens to end at index 0 still produces a
|
|
146
|
+
* cursor distinguishable from the start sentinel.
|
|
147
|
+
*
|
|
161
148
|
* @param documentId - The document id
|
|
162
149
|
* @param scope - The scope to query
|
|
163
150
|
* @param branch - The branch name
|
|
@@ -188,11 +175,14 @@ interface IOperationStore {
|
|
|
188
175
|
* timestamp, so a later timestamp can sit behind the last row.
|
|
189
176
|
*/
|
|
190
177
|
getStreamLatestTimestamp(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
178
|
+
/**
|
|
179
|
+
* The subset of `opIds` stored anywhere in one stream, retracted rows
|
|
180
|
+
* included.
|
|
181
|
+
*/
|
|
182
|
+
findOperationIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Set<string>>;
|
|
183
|
+
/** The latest row of each of `opIds` stored in one stream. */
|
|
184
|
+
getOperationsByIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Operation[]>;
|
|
191
185
|
}
|
|
192
|
-
/**
|
|
193
|
-
* Stores periodic document snapshots (keyframes) so that document state
|
|
194
|
-
* can be reconstructed without replaying the full operation history.
|
|
195
|
-
*/
|
|
196
186
|
/**
|
|
197
187
|
* Filter options for querying operations. When multiple filters are provided,
|
|
198
188
|
* they are combined with AND logic.
|
|
@@ -207,12 +197,9 @@ interface OperationFilter {
|
|
|
207
197
|
/** Filter operations with index >= this value */
|
|
208
198
|
sinceRevision?: number;
|
|
209
199
|
}
|
|
210
|
-
/**
|
|
211
|
-
* Which sense of "exists" a caller of {@link IDocumentView.exists} means.
|
|
212
|
-
*/
|
|
213
200
|
//#endregion
|
|
214
201
|
//#region src/hypercore-operation-store.d.ts
|
|
215
|
-
declare class HypercoreOperationStore implements IOperationStore {
|
|
202
|
+
export declare class HypercoreOperationStore implements IOperationStore {
|
|
216
203
|
private bee;
|
|
217
204
|
private applyLock;
|
|
218
205
|
constructor(bee: Hyperbee);
|
|
@@ -221,8 +208,30 @@ declare class HypercoreOperationStore implements IOperationStore {
|
|
|
221
208
|
private assertConditionHolds;
|
|
222
209
|
private executeApply;
|
|
223
210
|
private isCreate;
|
|
211
|
+
/**
|
|
212
|
+
* The paging cursor encodes the index to resume from (one past the last
|
|
213
|
+
* row returned), not the last row's own index; "" or "0" (or anything
|
|
214
|
+
* unparsable) means the start of the stream. This keeps "0" an unambiguous
|
|
215
|
+
* start-of-stream sentinel even when a page ends at index 0, which would
|
|
216
|
+
* otherwise make `nextCursor` equal the start cursor and loop a caller that
|
|
217
|
+
* walks pages forever. Mirrors the encoding in the Kysely store.
|
|
218
|
+
*/
|
|
224
219
|
getSince(documentId: string, scope: string, branch: string, revision: number, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
|
|
220
|
+
/**
|
|
221
|
+
* The paging cursor encodes the ordinal to resume from (one past the last
|
|
222
|
+
* ordinal returned), not the last ordinal itself; "" or "0" (or anything
|
|
223
|
+
* unparsable) means the start of the stream. Unlike the Kysely store's
|
|
224
|
+
* `getSinceId` (whose auto-increment id starts at 1), this store's ordinal
|
|
225
|
+
* counter starts at 0, so 0 is a real, valid ordinal and the same
|
|
226
|
+
* ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.
|
|
227
|
+
*/
|
|
225
228
|
getSinceId(id: number, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<OperationWithContext>>;
|
|
229
|
+
/**
|
|
230
|
+
* The paging cursor here encodes the index to resume from (one past the
|
|
231
|
+
* last row returned), not the last row's own index, for the same reason as
|
|
232
|
+
* `getSince`: a page ending at index 0 must not produce a cursor that is
|
|
233
|
+
* indistinguishable from the start-of-stream sentinel.
|
|
234
|
+
*/
|
|
226
235
|
getConflicting(documentId: string, scope: string, branch: string, minTimestamp: string, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
|
|
227
236
|
getRevisions(documentId: string, branch: string, signal?: AbortSignal): Promise<DocumentRevisions>;
|
|
228
237
|
/**
|
|
@@ -231,6 +240,8 @@ declare class HypercoreOperationStore implements IOperationStore {
|
|
|
231
240
|
* later one, so it would under-report and admit a backdated auth write.
|
|
232
241
|
*/
|
|
233
242
|
getStreamLatestTimestamp(documentId: string, scope: string, branch: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
243
|
+
findOperationIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Set<string>>;
|
|
244
|
+
getOperationsByIds(documentId: string, scope: string, branch: string, opIds: string[], signal?: AbortSignal): Promise<Operation[]>;
|
|
234
245
|
private serializeOperation;
|
|
235
246
|
private toOperation;
|
|
236
247
|
}
|
|
@@ -247,7 +258,7 @@ type HypercoreStoreOptions = {
|
|
|
247
258
|
};
|
|
248
259
|
//#endregion
|
|
249
260
|
//#region src/hypercore-atomic-transaction.d.ts
|
|
250
|
-
declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
261
|
+
export declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
251
262
|
private documentId;
|
|
252
263
|
private documentType;
|
|
253
264
|
private scope;
|
|
@@ -259,7 +270,7 @@ declare class HypercoreAtomicTransaction implements AtomicTxn {
|
|
|
259
270
|
}
|
|
260
271
|
//#endregion
|
|
261
272
|
//#region src/storage-manager.d.ts
|
|
262
|
-
declare class StorageManager {
|
|
273
|
+
export declare class StorageManager {
|
|
263
274
|
private store;
|
|
264
275
|
private bee;
|
|
265
276
|
constructor(storagePath: string);
|
|
@@ -269,23 +280,23 @@ declare class StorageManager {
|
|
|
269
280
|
}
|
|
270
281
|
//#endregion
|
|
271
282
|
//#region src/key-encoding.d.ts
|
|
272
|
-
declare const RANGE_UPPER_BOUND: string;
|
|
273
|
-
declare function pad(n: number): string;
|
|
274
|
-
declare function operationKey(documentId: string, scope: string, branch: string, index: number): string;
|
|
275
|
-
declare function operationPrefix(documentId: string, scope: string, branch: string): string;
|
|
276
|
-
declare function ordinalKey(ordinal: number): string;
|
|
277
|
-
declare function ordinalPrefix(): string;
|
|
278
|
-
declare function duplicateKey(opId: string, index: number, skip: number): string;
|
|
279
|
-
declare function headKey(documentId: string, scope: string, branch: string): string;
|
|
280
|
-
declare function headPrefix(documentId: string): string;
|
|
281
|
-
declare const ORDINAL_COUNTER_KEY = "_meta/ordinal";
|
|
283
|
+
export declare const RANGE_UPPER_BOUND: string;
|
|
284
|
+
export declare function pad(n: number): string;
|
|
285
|
+
export declare function operationKey(documentId: string, scope: string, branch: string, index: number): string;
|
|
286
|
+
export declare function operationPrefix(documentId: string, scope: string, branch: string): string;
|
|
287
|
+
export declare function ordinalKey(ordinal: number): string;
|
|
288
|
+
export declare function ordinalPrefix(): string;
|
|
289
|
+
export declare function duplicateKey(opId: string, index: number, skip: number): string;
|
|
290
|
+
export declare function headKey(documentId: string, scope: string, branch: string): string;
|
|
291
|
+
export declare function headPrefix(documentId: string): string;
|
|
292
|
+
export declare const ORDINAL_COUNTER_KEY = "_meta/ordinal";
|
|
282
293
|
type ParsedOperationKey = {
|
|
283
294
|
documentId: string;
|
|
284
295
|
scope: string;
|
|
285
296
|
branch: string;
|
|
286
297
|
index: number;
|
|
287
298
|
};
|
|
288
|
-
declare function parseOperationKey(key: string): ParsedOperationKey;
|
|
299
|
+
export declare function parseOperationKey(key: string): ParsedOperationKey;
|
|
289
300
|
type OrdinalEntry = {
|
|
290
301
|
documentId: string;
|
|
291
302
|
documentType: string;
|
|
@@ -299,5 +310,6 @@ type HeadEntryValue = {
|
|
|
299
310
|
latestTimestampUtcMs: string;
|
|
300
311
|
};
|
|
301
312
|
//#endregion
|
|
302
|
-
export {
|
|
313
|
+
export type { HeadEntryValue, HypercoreStoreOptions, OrdinalEntry, ParsedOperationKey, StoredOperation };
|
|
314
|
+
export {};
|
|
303
315
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":["Dialect","SchemaModule","DynamicModule","QueryExecutor","QueryCreator","KyselyPlugin","DatabaseIntrospector","Driver","IsolationLevel","AccessMode","FunctionModule","LogConfig","QueryExecutorProvider","QueryResult","CompiledQuery","QueryId","Compilable","CaseBuilder","Expression","DrainOuterGeneric","ReleaseSavepoint","RollbackToSavepoint","ControlledConnection","_0","global","AsyncDisposable","SymbolConstructor","asyncDispose","sideEffect","Kysely","V","T","R","DB","KyselyConfig","KyselyProps","TransactionBuilder","ControlledTransactionBuilder","ConnectionBuilder","Record","Promise","Symbol","private","constructor","args","schema","dynamic","introspection","case","value","fn","transaction","startTransaction","connection","withPlugin","plugin","withoutPlugins","withSchema","withTables","destroy","isTransaction","getExecutor","executeQuery","query","queryId","Transaction","props","config","driver","executor","dialect","isKyselyProps","obj","plugins","log","ConnectionBuilderProps","execute","db","callback","TransactionBuilderProps","setAccessMode","accessMode","setIsolationLevel","isolationLevel","trx","ControlledTransaction","SN","S","ControlledTransactionProps","Command","isCommitted","isRolledBack","commit","rollback","savepoint","savepointName","rollbackToSavepoint","releaseSavepoint","cb","Action","AuthRequest","AuthSubject","CreateDocumentActionInput","DocumentModelModule","ISigner","Operation","OperationContext","OperationWithContext","OperationWithContext$1","PHAuthState","PHDocument","PHDocumentState","SignatureVerificationHandler","UpgradeDocumentActionInput","UpgradeManifest","UpgradeReducer","UpgradeTransition","actions","documentActions","DocumentDriveDocument","DriveInput","FolderNode","Node","ILogger","kysely","Generated","Insertable","Kysely","Transaction","IProcessor","IProcessorHostModuleBase","IProcessorHostModuleBase$1","IProcessorManager","IProcessorManager$1","IRelationalDb","ProcessorApp","ProcessorFactory","ProcessorFactory$1","ProcessorFactoryBuilder","ProcessorFilter","ProcessorRecord","ProcessorStatus","RelationalDbProcessor","TrackedProcessor","TrackedProcessor$1","createRelationalDb","Pool","AttachmentHash","AttachmentRef","createDocumentAction","input","upgradeDocumentAction","deleteDocumentAction","documentId","addRelationshipAction","Record","sourceId","targetId","relationshipType","metadata","updateRelationshipAction","removeRelationshipAction","JobKind","JobQueueState","UNKNOWN","PREPROCESSING","PENDING","READY","RUNNING","RESOLVED","RetryAccounting","CountAgainstLimit","ExemptFromLimit","IJobExecutionHandle","Job","ErrorInfo$1","job","state","start","complete","fail","error","defer","JobMeta","id","kind","scope","branch","operations","createdAt","queueHint","retryCount","maxRetries","lastError","errorHistory","meta","QueueEventTypes","JOB_AVAILABLE","JobRoutingMeta","JobAvailableEvent","jobId","name","message","stack","ShutdownStatus","Promise","isShutdown","completed","PropagationMode","None","Cascade","RelationshipChangeType","Added","Removed","BatchMeta","batchId","batchJobIds","JobInfo","JobStatus","ConsistencyToken","status","createdAtUtcIso","completedAtUtcIso","result","consistencyToken","WRITE_READY","READ_READY","FAILED","ViewFilter","scopes","revision","subject","SearchFilter","type","parentId","ids","slugs","PagingOptions","cursor","limit","PagedResults","T","results","options","next","nextCursor","totalCount","ConsistencyKey","ConsistencyCoordinate","operationIndex","version","coordinates","IReadModel","indexOperations","IReadModelCoordinator","readModels","stop","drain","getChainDepth","ReadModelRegistrationStage","ILiveReadModelCoordinator","addReadModel","readModel","stage","supportsLiveReadModelRegistration","coordinator","ChannelScheme","CONNECT","SWITCHBOARD","JwtHandler","url","PollBehavior","Auto","Manual","RemoteOptions","sinceTimestampUtcMs","pollBehavior","boundAddress","RemoteFilter","RemoteCursor","remoteName","cursorType","cursorOrdinal","lastSyncedAtUtcMs","ChannelMeta","SyncEnvelopeType","SyncEnvelope","channelMeta","key","dependsOn","SyncOperationStatus","Unknown","TransportPending","ExecutionPending","Applied","Error","ChannelErrorSource","Channel","Inbox","Outbox","SyncOperationErrorType","ChannelHealth","lastSuccessUtcMs","lastFailureUtcMs","failureCount","ConnectionState","ConnectionStateSnapshot","pushBlocked","pushFailureCount","receivingPages","requiresAuth","ConnectionStateChangedEvent","remoteId","previous","current","snapshot","RemoteStatus","push","pull","ChannelConfig","parameters","RemoteRecord","DriveCollectionId","collectionId","channelConfig","filter","SyncEventTypes","SYNC_PENDING","SYNC_SUCCEEDED","SYNC_FAILED","DEAD_LETTER_ADDED","CONNECTION_STATE_CHANGED","SyncPendingEvent","syncOperationCount","remoteNames","SyncSucceededEvent","SyncFailedEvent","Array","successCount","errors","DeadLetterAddedEvent","errorSource","errorType","SyncResultStatus","SyncResultError","SyncResult","DuplicateOperationError","constructor","description","OptimisticLockError","RevisionMismatchError","expected","actual","DocumentAlreadyExistsError","headRevision","isError","AppendConditionStream","AppendCondition","streams","APPEND_CONDITION_FAILED_PREFIX","AppendConditionFailedError","condition","isFailureMessage","AtomicTxn","addOperations","DocumentRevisions","latestTimestamp","IOperationStore","AbortSignal","OperationFilter","apply","documentType","txn","fn","signal","getSince","paging","getSinceId","getConflicting","minTimestamp","getRevisions","getStreamLatestTimestamp","IKeyframeStore","putKeyframe","document","findNearestKeyframe","targetRevision","listKeyframes","deleteKeyframes","ViewFilter$1","excludeSourceRemote","actionTypes","timestampFrom","timestampTo","sinceRevision","DocumentExistence","LiveOnly","IncludingDeleted","IDocumentView","TDocument","init","items","waitForConsistency","token","timeoutMs","exists","documentIds","existence","get","view","getMany","getByIdOrSlug","identifier","findByType","resolveSlug","slug","resolveSlugs","resolveIdOrSlug","DocumentRelationship","Date","updatedAt","DocumentGraphEdge","from","to","IDocumentGraph","nodes","edges","IDocumentIndexer","getOutgoing","types","getIncoming","hasRelationship","getUndirectedRelationships","a","b","getDirectedRelationships","findPath","findAncestors","getOrphanedChildren","parentIds","getRelationshipTypes","ISyncRemoteStorage","list","upsert","remote","remove","ISyncCursorStorage","DeadLetterRecord","jobDependencies","errorMessage","ISyncDeadLetterStorage","add","deadLetter","removeByRemote","listQuarantinedDocumentIds","OperationIndexEntry","ordinal","sourceRemote","IOperationIndexTxn","createCollection","addToCollection","removeFromCollection","recordGroupReferences","groupIds","write","getMembershipInvalidations","IOperationIndex","commit","find","getSinceOrdinal","getLatestTimestampForCollection","getCollectionsForDocuments","getGroupReferencers","groupId","driveId","forDrive","fromKey","toString","equals","other","WriteCacheConfig","maxDocuments","ringBufferSize","keyframeInterval","DocumentStreamKey","SnapshotPosition","Head","Historical","CachedSnapshot","position","KeyframeSnapshot","IWriteCache","getState","putState","putRun","run","invalidate","clear","startup","shutdown","Unsubscribe","Subscriber","data","EventBusAggregateError","ReactorEventTypes","JOB_PENDING","JOB_RUNNING","JOB_WRITE_READY","JOB_READ_READY","JOB_FAILED","READMODEL_BATCH_COMPLETED","READMODEL_INDEXED","MODEL_LOADED","ReadModelStage","ReadModelIndexingStage","ModelLoadedEvent","JobPendingEvent","jobMeta","JobRunningEvent","JobWriteReadyEvent","collectionMemberships","JobReadReadyEvent","JobFailedEvent$1","ReadModelBatchCompletedEvent","batchSize","chainWaitDurationMs","preReadyDurationMs","emitDurationMs","postReadyDurationMs","ReadModelIndexedEvent","readModelName","durationMs","operationCount","success","IEventBus","K","subscribe","event","subscriber","emit","IJobAwaiter","waitForJob","JobAwaiter","eventBus","getJobStatus","pendingJobs","unsubscribers","subscribeToEvents","handleWriteReady","handleReadReady","handleJobFailed","checkAndResolveWaiters","ISubscriptionErrorHandler","SubscriptionErrorContext","handleError","context","eventType","subscriptionId","eventData","IReactorSubscriptionManager","onDocumentCreated","callback","search","onDocumentDeleted","onDocumentStateUpdated","onRelationshipChanged","childId","changeType","StreamQuery","IStreamStateReader","DecisionTarget","DecisionContext","scopeState","actionInput","StreamHistory","Projection","M","Partial","query","model","queryOverHistory","reads","decidingActions","operation","Evaluation","decision","reason","DecisionModel","projections","foldEvaluatedScope","evaluatesScope","decide","request","ctx","BuiltDecisionModel","appendCondition","DocumentChangeType","Created","Deleted","Updated","ParentAdded","ParentRemoved","ChildAdded","ChildRemoved","DocumentChangeEvent","documents","CreateDocumentOptions","parentIdentifier","documentModelVersion","UpgradeDocumentOptions","maxConflictRetries","IDriveClient","create","addFile","driveIdentifier","parentFolder","addFolder","removeNode","nodeId","renameNode","setPreferredEditorOnNode","preferredEditor","moveNode","srcNodeId","targetParentFolderId","copyNode","getNode","listNodes","ActionCandidate","ActionEvaluations","evaluations","allAllowed","anyAllowed","allDenied","anyDenied","IReactorClient","BatchExecutionRequest","BatchExecutionResult","BatchLoadRequest","BatchLoadResult","drives","getDocumentModelModules","namespace","getDocumentModelModule","isDocumentIdTaken","getOperations","documentIdentifier","getOutgoingRelationships","sourceIdentifier","getIncomingRelationships","targetIdentifier","evaluateActions","candidates","createEmpty","documentModelType","getDocumentModelModuleForDocument","upgradeDocument","toVersion","createDocumentInDrive","execute","executeAsync","executeBatch","rename","setPreferredEditor","addRelationship","removeRelationship","moveRelationship","sourceParentIdentifier","targetParentIdentifier","source","target","deleteDocument","propagate","deleteDocuments","identifiers","loadBatch","ICollectionMembershipCache","CachedDocumentMeta","documentScopeRevision","IDocumentMetaCache","getDocumentMeta","rebuildAtRevision","putDocumentMeta","OperationTable","opId","prevOpId","writeTimestampUtcMs","timestampUtcMs","index","action","skip","deniedReason","hash","KeyframeTable","DocumentCollectionTable","joinedOrdinal","leftOrdinal","OperationIndexOperationTable","SyncRemoteTable","collection_id","channel_type","channel_id","remote_name","channel_parameters","filter_document_ids","filter_scopes","filter_branch","push_state","push_last_success_utc_ms","push_last_failure_utc_ms","push_failure_count","pull_state","pull_last_success_utc_ms","pull_last_failure_utc_ms","pull_failure_count","bound_address","created_at","updated_at","SyncCursorTable","cursor_type","cursor_ordinal","last_synced_at_utc_ms","SyncDeadLetterTable","job_id","job_dependencies","document_id","error_source","error_message","error_type","GroupReferenceTable","Database$1","Keyframe","document_collections","operation_index_operations","group_references","sync_remotes","sync_cursors","sync_dead_letters","DocumentTable","DocumentRelationshipTable","IndexerStateTable","lastOperationId","lastOperationTimestamp","DocumentIndexerDatabase","Document","IndexerState","SanitizedArg","ErrorInfo","cause","ModuleRef","packageName","exportName","filePath","FactorySpec","module","initArgs","SignatureVerifierSpec","DocumentModelSpec","ModelManifestEntry","spec","DbConfig","host","port","database","user","password","ssl","applicationName","poolSize","connectionTimeoutMillis","idleTimeoutMillis","WorkerPoolConfig","enabled","numWorkers","workerType","heartbeatMs","workerPgPoolSize","JobWriteReadyPayload","InitMessage","JobExecutorConfig","correlationId","workerId","poolConfig","db","signatureVerifier","models","executorConfig","ExecuteMessage","AbortMessage","targetCorrelationId","ShutdownMessage","graceMs","LoadModelMessage","ParentMessage","ReadyMessage","ResultMessage","JobResult","writeReady","ModelLoadedMessage","ModelLoadFailedMessage","LogMessage","level","args","timestamp","HeartbeatMessage","inFlightCorrelationIds","MetricsMessage","counters","gauges","PoolAcquireSamplesMessage","poolName","durations","size","idle","waiting","WorkerMessage","FileModelSource","PackageModelSource","subpath","DocumentModelSource","RegistrationResult","item","IDocumentModelLoader","load","IDocumentModelRegistry","registerModules","modules","unregisterModules","documentTypes","getModule","getAllModules","getSupportedVersions","getLatestVersion","registerUpgradeManifests","manifests","unregisterUpgradeManifests","getUpgradeManifest","computeUpgradePath","fromVersion","getUpgradeReducer","RingBuffer","buffer","head","capacity","getAll","length","DocumentStream","ringBuffer","KyselyWriteCache","lruTracker","keyframeStore","operationStore","registry","config","withScopedStores","store","persistKeyframe","getStream","coldMissRebuild","applyPendingUpgrades","applyTailPendingUpgrades","applyPendingUpgrade","stampRevisions","operationAt","resolveModuleVersionForOp","warmMissRebuild","findNearestOlderSnapshot","makeStreamKey","getOrCreateStream","isKeyframeRevision","KyselyOperationStore","trx","queryExecutor","withTransaction","resolveUniqueConstraint","executeApply","acquireStreamLocks","insertGuarded","findIdempotentReplay","isCreate","rowToOperation","rowToOperationWithContext","KyselyKeyframeStore","ExecutionStores","writeCache","documentMetaCache","collectionMembershipCache","IExecutionScope","stores","operationsWithContext","completedAt","duration","ReactorFeatureFlags","documentDecisions","authEnforcement","authGroups","authConditions","featureFlags","maxSkipThreshold","maxConcurrency","jobTimeoutMs","deferredJobTtlMs","retryBaseDelayMs","retryMaxDelayMs","yieldDeadlineMs","batchApplies","JobExecutorEventTypes","JOB_STARTED","JOB_COMPLETED","EXECUTOR_STARTED","EXECUTOR_STOPPED","JobStartedEvent","startedAt","JobCompletedEvent","JobFailedEvent","willRetry","ExecutorStartedEvent","ExecutorStoppedEvent","stoppedAt","graceful","ExecutorManagerStatus","isRunning","numExecutors","activeJobs","totalJobsProcessed","DocumentDecisionModel","documentDecisionModel","RegisteredDecisionModel","AdmissionDecision","evaluation","documentVersion","deletedAtUtcIso","AdmissionConditions","carriedDocument","decideAtHead","cache","conditions","selectDecisionModel","flags","ALWAYS_READABLE_SCOPES","ReadonlySet","ReadGateOptions","withholdUninitialized","IReadGate","scopePredicate","readDecisionModel","BareReadGate","SeededStateReader","documentView","seed","assertAbsent","ModelReadGate","servesGroups","logger","servesGroupTo","servesThrough","servesGroup","ownPolicyPredicate","ActionEvaluationConfig","ReactorClient","IReactor","reactor","signer","subscriptionManager","jobAwaiter","documentIndexer","readGate","actionEvaluation","readSubject","readableScopes","gateDocument","getOperationsWithCompositeCursor","buildEvaluationTarget","removeAllIncomingRelationships","WorkerInFlightSnapshot","WorkerExecutionOutcome","IExecutorWorker","abort","loadModel","entry","isIdle","getInFlight","IJobExecutor","executeJob","IJobExecutorManager","getExecutors","getStatus","IJobTracker","registerJob","jobInfo","markRunning","markFailed","IQueue","enqueue","dequeue","dequeueNext","dequeueNextMatching","predicate","totalSize","clearAll","hasJobs","completeJob","failJob","retryJob","accounting","isDrained","block","onDrained","unblock","GroupReevaluationTrigger","queue","unsubscribe","onWriteReady","ViewStateTable","readModelId","lastOrdinal","DocumentSnapshotTable","content","lastOperationIndex","lastOperationHash","lastUpdatedAt","snapshotVersion","isDeleted","deletedAt","SlugMappingTable","ProcessorCursorTable","processorId","factoryId","processorIndex","lastErrorTimestamp","DocumentViewDatabase","ViewState","DocumentSnapshot","SlugMapping","ProcessorCursor","InsertableDocumentSnapshot","IConsistencyTracker","update","getLatest","waitFor","serialize","hydrate","entries","makeConsistencyKey","ConsistencyTracker","waiters","deduplicateCoordinates","areCoordinatesSatisfied","checkWaiters","removeWaiter","PoolStats","PoolInstrumentation","getStats","onAcquire","listener","instrumentPgPool","pool","ForwardingPoolInstrumentation","pushSamples","updateStats","stats","GraphQLRequestErrorCategory","GraphQLRequestError","statusCode","category","codes","RECOVERABLE_GRAPHQL_ERROR_CODES","malformedStoredOperation","isRecoverableGraphQLError","DRIVE_AUTH_ERROR_MESSAGES","forbidden","authenticationRequired","DriveRequestError","isDriveAuthError","PollingChannelError","ChannelError","SyncOperationStatusCallback","SyncOperation","syncOp","prev","SyncOperationAggregateError","deliveredCount","emittedCount","callbacks","on","started","transported","executed","failed","transition","MailboxCallback","IMailbox","ReadonlyArray","ackOrdinal","latestOrdinal","advanceOrdinal","onAdded","onRemoved","pause","resume","flush","isPaused","Mailbox","itemsMap","addedCallbacks","removedCallbacks","paused","addedBuffer","removedBuffer","_ack","_latestOrdinal","SyncStatus","Synced","Outgoing","Incoming","OutgoingAndIncoming","SyncStatusChangeCallback","ISyncStatusTracker","IChannel","onChange","trackRemote","channel","untrackRemote","SyncStatusTracker","remotes","seen","handleAdded","handleRemoved","getOrCreateCounts","notifyChange","ConnectionStateChangeCallback","inbox","outbox","getConnectionState","onConnectionStateChange","triggerPull","notePoll","lastHolderPollUtcMs","IChannelFactory","instance","cursorStorage","RemoteMeta","Remote","ISyncManager","getByName","getById","bindRemote","waitForSync","getSyncStatus","onSyncStatusChange","ExecutionJobPlan","jobs","LoadJobPlan","externalDeps","kill","getDocumentModels","getBySlug","docId","ReactorFeatures","Database","SyncModule","syncManager","InProcessSyncModule","remoteStorage","deadLetterStorage","channelFactory","ReactorModule","documentModelRegistry","syncModule","DegradedComponent","component","InProcessReactorModule","jobTracker","executorManager","documentViewConsistencyTracker","documentIndexerConsistencyTracker","readModelCoordinator","processorManager","processorManagerConsistencyTracker","groupReevaluationTrigger","pools","degradedComponents","ReactorClientModule","client","reactorModule","InProcessReactorClientModule","DriveClient","runJobs","toError","documentExists","removeFileNode","IDocumentModelResolver","ensureModelLoaded","ModelLoadedBroadcastHook","DocumentModelResolver","loader","loadingModels","failedModelTypes","broadcastHook","modelLoadedHook","setBroadcastHook","hook","setModelLoadedHook","loadRegisterAndBroadcast","notifyPeersModelLoaded","NullDocumentModelResolver","WorkerFactory","BuiltInReadModelKind","ChainDepthReport","shardId","depth","ProjectionInitMessage","shardIndex","shardCount","preReadyKinds","postReadyKinds","chainDepthReportIntervalMs","ProjectionWriteReadyMessage","ProjectionDrainMessage","ProjectionShutdownMessage","ProjectionParentMessage","ProjectionReadyMessage","ProjectionInitFailedMessage","ProjectionReadReadyMessage","ProjectionReadModelIndexedMessage","ProjectionBatchCompletedMessage","ProjectionChainDepthMessage","ProjectionPoolAcquireSamplesMessage","ProjectionDrainedMessage","ProjectionLogMessage","ProjectionWorkerMessage","HybridProjectionOptions","onFatal","initTimeoutMs","shutdownGraceMs","drainTimeoutMs","createHybridProjectionCoordinatorFactory","ReadModelCoordinatorFactory","ProjectionTransportEventMap","exit","ProjectionTransportEvent","ProjectionTransportListener","E","payload","IProjectionTransport","postMessage","off","terminate","ProjectionWorkerFactory","ProjectionShardHooks","onReadReady","onShardFatal","ProjectionShardManagerConfig","factory","hostBus","poolInstrumentations","consistencyTrackers","ProjectionShardManager","shards","initPromises","pendingDrains","trackersByReadModelName","hostSubscription","isShuttingDown","emitReadReady","getShardDepths","routeWriteReady","dropWriteReady","handleWorkerMessage","advanceConsistencyTrackers","handlePoolAcquireSamples","failPendingInit","handleReady","handleDrained","releaseDrain","handleLog","handleTransportError","handleTransportExit","relayReadReady","relayReadModelIndexed","relayBatchCompleted","HybridProjectionCoordinatorOptions","manager","preReady","postReady","lookupOnly","HybridProjectionCoordinator","chains","acceptReadReady","runHostChain","indexWithTiming","emitBatchCompleted","emitReadModelIndexed","queueKeyFor","SignerConfig","verifier","MigrationStrategy","MigrationResult","migrationsExecuted","SyncBuilder","withChannelFactory","withRemoteStorage","storage","withCursorStorage","withDeadLetterStorage","withMaxDeadLettersPerRemote","withMaxInboxBatchSize","withMaxHeldOperationsPerRemote","withStaleRemotePollWindowMs","windowMs","build","driveContainerTypes","buildModule","ReadModelFactoryDeps","ReadModelFactory","deps","ReadModelCoordinatorFactoryDeps","ProjectionShardBuilderConfig","subscriptionNotificationReadModel","createProjectionShardManager","registerShutdownHook","WorkerPoolBase","WorkerPoolOptions","ReactorBuilder","documentModelSources","upgradeManifests","features","readModelFactories","writeCacheConfig","migrationStrategy","syncBuilder","readModelCoordinatorFactory","kyselyInstance","signalHandlersEnabled","queueInstance","channelScheme","jwtHandler","documentModelLoader","shutdownHooks","workerPool","resolvedModelManifest","moduleOnlyModelKeys","projectionShardConfig","projectionWorkerFactory","instrumentedPools","withLogger","withDocumentModelSources","sources","withUpgradeManifests","withFeatures","withReadModel","withReadModelFactory","withReadModelCoordinator","withReadModelCoordinatorFactory","withExecutor","executor","withExecutorConfig","withWriteCacheConfig","withDriveContainerTypes","withMigrationStrategy","strategy","withSync","withEventBus","withSignatureVerifier","withKysely","withInstrumentedPool","instrumentation","withQueue","withChannelScheme","scheme","withJwtHandler","handler","withDocumentModelLoader","withSignalHandlers","withShutdownHook","withWorkerPool","withProjectionShards","withProjectionWorkerFactory","getResolvedModelManifest","resolveReactorDbConfig","createDefaultProjectionWorkerFactory","createDefaultWorkerFactory","createPostgresDatabase","attachSignalHandlers","ReactorClientBuilder","reactorBuilder","withReactorBuilder","withReactor","withSigner","withSubscriptionManager","withJobAwaiter","withReadGate","resolveReadGate","resolveActionEvaluation","DEFAULT_DRIVE_CONTAINER_TYPES","Reactor","shutdownStatus","setShutdown","setCompleted","findByIds","findBySlugs","findByParentId","emitJobPending","ParsedDriveUrl","graphqlEndpoint","parseDriveUrl","driveIdFromUrl","AuthEnforcementDisabledError","createMutableShutdownStatus","initialState","value","ParsedPaging","offset","parsePagingOptions","defaultLimit","DefaultSubscriptionErrorHandler","DocumentCreatedCallback","DocumentDeletedCallback","DocumentStateUpdatedCallback","RelationshipChangedCallback","ReactorSubscriptionManager","Map","createdSubscriptions","deletedSubscriptions","updatedSubscriptions","relationshipSubscriptions","subscriptionCounter","errorHandler","notifyDocumentsCreated","notifyDocumentsDeleted","notifyDocumentsUpdated","notifyRelationshipChanged","childType","filterDocumentIds","filterDocuments","matchesRelationshipFilter","EventBus","eventTypeToSubscribers","InMemoryQueue","Set","resolver","queues","jobIdToQueueKey","docIdToJobId","jobIdToDocId","completedJobs","jobIndex","isBlocked","onDrainedCallback","isPausedFlag","toErrorInfo","createQueueKey","getQueue","isDocumentExecuting","markJobExecuting","markJobComplete","areDependenciesMet","getNextJobWithMetDependencies","getCreateDocumentType","deferJob","checkDrained","getPendingJobs","getExecutingJobIds","getJob","InMemoryJobTracker","JobExecutorFactory","SimpleJobExecutorManager","executorFactory","executors","deferredJobs","resultHandler","processNextJob","checkForMoreJobs","processExistingJobs","SimpleJobExecutor","decisionModel","signatureVerifierModule","documentActionHandler","executionScope","executeInScope","evictTouchedStreams","getCollectionMembershipsForOperations","processActions","prepareRegularWrite","commitPreparedWrites","canBatch","executeRegularActionsBatched","conditionsAgree","executeRegularActionsSequentially","executeRegularAction","positionByTimestamp","evaluatePositioned","evaluationOrder","firstNonMonotonicTimestamp","appendedOperations","reevaluateIfCriteriaMet","reevaluateDocument","executeReevaluationJob","executeLoadJob","accumulateResultOrReturnError","createForwardingLogger","msg","post","tags","errorToInfo","err","sanitizeArg","WeakSet","workerEntryPath","ModuleNotFoundError","requestedVersion","DuplicateModuleError","InvalidModuleError","DuplicateManifestError","DocumentModelRegistry","manifestsToRegister","buildDecisionModel","reader","definition","AuthDecisionModel","auth","authDecisionModel","SyncScopeGate","gate","scopePredicateById","OutOfOrderPair","firstOutOfOrderPair","requireStrict","BaseReadModelConfig","rebuildStateOnInit","BaseReadModel","consistencyTracker","commitOperations","rebuildStateForOperations","loadState","initializeState","saveState","updateConsistencyTracker","IndexerDatabase","KyselyDocumentIndexer","_db","handleAddRelationship","handleRemoveRelationship","handleUpdateRelationship","ReadModelCoordinator","emitEmptyReadReady","runChain","Database$2","KyselyDocumentView","servesDeletionBoundary","idsWithStreams","liveIds","DOCUMENT_VIEW_READ_MODEL","DOCUMENT_INDEXER_READ_MODEL","ReactorReadModels","REACTOR_SCHEMA","runMigrations","schema","upTo","getMigrationStatus","MigrationInfo","KyselySyncCursorStorage","KyselySyncRemoteStorage","GqlRequestChannelFactory","GqlResponseChannelFactory","IPollTimer","setDelegate","delegate","triggerNow","GqlChannelConfig","fetch","fetchFn","GqlRequestChannel","bufferedOutbox","channelId","pollTimer","abortController","lastPersistedInboxOrdinal","lastPersistedOutboxOrdinal","pushRetryTimer","isPushing","pendingDrain","peerServesDecisionFields","isRecovering","connectionState","connectionStateCallbacks","transitionConnectionState","poll","handleRemoteDeadLetters","handlePollError","recoverFromChannelNotFound","resumePushAfterRecovery","pollSyncEnvelopes","rejectsDecisionFields","pollQuery","touchRemoteChannel","attemptPush","schedulePushRetry","drainOutbox","classifyError","pushSyncOperations","getAuthorizationHeader","executeGraphQL","poller","GqlResponseChannel","evictedOutboxFloor","appliedOutboxOrdinal","lastPollUtcMs","rememberUnserved","persistOutboxCursor","forgetEvictedBelow","unservedFloor","PollTimerConfig","intervalMs","maxQueueDepth","backpressureCheckIntervalMs","startPaused","IntervalPollTimer","timer","running","consecutiveFailures","tick","scheduleNext","scheduleRetry","scheduleBackpressureRecheck","getIntervalMs","setIntervalMs","ms","envelopesToSyncOperations","envelope","OperationBatch","trimMailboxFromAckOrdinal","mailbox","batchOperationsByDocument","consolidateSyncOperations","syncOps","classifyJobFailure","errorName","syncOperationErrorType","quarantinesDocument","IReactorProcessorHostModuleBase","getReadModel","ReactorHostModuleBaseOptions","Pick","createReactorHostModuleBase","KeyframeValidationIssue","keyframeHash","replayedHash","SnapshotValidationIssue","snapshotHash","StreamOrderIssue","ValidationResult","isConsistent","keyframeIssues","snapshotIssues","streamOrderIssues","RebuildResult","keyframesDeleted","scopesInvalidated","IDocumentIntegrityService","validateDocument","rebuildKeyframes","rebuildSnapshots","DocumentIntegrityService","findStreamOrderIssues","discoverScopes","ProcessorManagerOptions","legacyProcessorIds","ProcessorManager","factoryRegistry","processorsByDrive","factoryToProcessors","knownDrives","cursorCache","registerFactory","unregisterFactory","allTrackedProcessors","detectAndRegisterNewDrives","isDriveCreation","detectAndCleanupDeletedDrives","discoverExistingDrives","isDeletedDocumentADrive","createProcessorsForDrive","backfillProcessor","retryProcessor","cleanupDriveProcessors","safeDisconnect","routeOperationsToProcessors","loadAllCursors","safeSaveProcessorCursor","saveProcessorCursor","deleteProcessorCursors","InMemoryJobExecutor","ReactorJobFailedEvent","StorageDatabase","WorkerErrorInfo"],"sources":["../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts","../../reactor/dist/index.d.ts","../src/hypercore-operation-store.ts","../src/types.ts","../src/hypercore-atomic-transaction.ts","../src/storage-manager.ts","../src/key-encoding.ts"],"x_google_ignoreList":[0],"mappings":";;;;QAoBQwB,MAAAA;EAAAA,UACMC,eAAAA;EAAAA,UAEAC,iBAAAA;IAAAA,SACGC,YAAAA;EAAAA;AAAAA;;;;;;;;;;;;;;;;;;;;;;;ACikBoD;;;;;;;;;;AAU3D;;;;;;KAhVLkN,aAAAA;EACHC,MAAAA;EACAC,KAAAA;AAAAA;;;;KAKGC,YAAAA;EACHE,OAAAA,EAASD,CAAAA;EACTE,OAAAA,EAASN,aAAAA;EACTO,IAAAA,SAAavC,OAAAA,CAAQmC,YAAAA,CAAaC,CAAAA;EAClCI,UAAAA;EACAC,UAAAA;AAAAA;;;;;;;;KAgUG8G,qBAAAA;EACH3M,UAAAA;EACAiC,KAAAA;EACAC,MAAAA;EACA2C,QAAAA;AAAAA;;;;;KAMG+H,eAAAA;EACHC,OAAAA,EAASF,qBAAAA;AAAAA;;;;;;UAmBDO,SAAAA;;EAERC,aAAAA,IAAiBhL,UAAAA,EAAYnF,SAAAA;AAAAA;;;;;KAM1BoQ,iBAAAA;uDACkDvI,QAAAA,EAAU3E,MAAAA;EAC/DmN,eAAAA;AAAAA;;;;;UAMQC,eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8BRG,KAAAA,CAAMzN,UAAAA,UAAoB0N,YAAAA,UAAsBzL,KAAAA,UAAeC,MAAAA,UAAgB2C,QAAAA,UAAkB+I,EAAAA,GAAKD,GAAAA,EAAKT,SAAAA,YAAqB9J,OAAAA,QAAeyK,MAAAA,GAASN,WAAAA,EAAaP,SAAAA,GAAYJ,eAAAA,GAAkBxJ,OAAAA,CAAQpG,SAAAA;;;;;;;;;;;;;EAa3M8Q,QAAAA,CAAS9N,UAAAA,UAAoBiC,KAAAA,UAAeC,MAAAA,UAAgB2C,QAAAA,UAAkB+F,MAAAA,GAAS4C,eAAAA,EAAi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A,UACA,MAAA;AAAA,iBAKc,UAAA,CAAW,OAAA;AAAA,iBAIX,aAAA,CAAA;AAAA,iBAIA,YAAA,CACd,IAAA,UACA,KAAA,UACA,IAAA;AAAA,iBAKc,OAAA,CACd,UAAA,UACA,KAAA,UACA,MAAA;AAAA,iBAKc,UAAA,CAAW,UAAA;AAAA,cAId,mBAAA;AAAA,KAED,kBAAA;EACV,UAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;AAAA;AAAA,iBAGc,iBAAA,CAAkB,GAAA,WAAc,kBAAA;AAAA,KAUpC,YAAA;EACV,UAAA;EACA,YAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;EACA,SAAA,EAAW,eAAA;AAAA;AAAA,KAGD,cAAA;EACV,KAAA;EACA,oBAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../node_modules/.pnpm/kysely@0.28.16/node_modules/kysely/dist/esm/kysely.d.ts","../../reactor/dist/index.d.ts","../src/hypercore-operation-store.ts","../src/types.ts","../src/hypercore-atomic-transaction.ts","../src/storage-manager.ts","../src/key-encoding.ts"],"x_google_ignoreList":[0],"mappings":";;;;;;;QAoBQ;YACM;YAEA;aACG;;;;;;;;KCsSZ;EACH;EACA;;;;;KAKG,aAAa;EAChB,SAAS;EACT,SAAS;EACT,aAAa,QAAQ,aAAa;EAClC;;;;;;KA4XG;EACH;EACA;EACA;EACA;;;;;;KAMG;EACH,SAAS;;;;;;UAmBD;;EAER,iBAAiB,YAAY;;;;;;KAM1B;;EAEH,UAAU;;EAEV;;;;;;UAMQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8BR,MAAM,oBAAoB,sBAAsB,eAAe,gBAAgB,kBAAkB,KAAK,KAAK,qBAAqB,eAAe,SAAS,aAAa,YAAY,kBAAkB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;EAuB3M,SAAS,oBAAoB,eAAe,gBAAgB,kBAAkB,SAAS,iBAAiB,SAAS,eAAe,SAAS,c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,oBACA,sBACA,eACA;EAGV,iBAAiB,YAAY;EAY7B,iBAAiB;;;;qBCvBN;UACH;UACA;EAER,YAAY;EAIN,QAAQ;EAUR,SAAS;EAOf,UAAU;;;;qBCxBC;wBAEG,IAAI;wBAIJ,aACd,oBACA,eACA,gBACA;wBAKc,gBACd,oBACA,eACA;wBAKc,WAAW;wBAIX;wBAIA,aACd,cACA,eACA;wBAKc,QACd,oBACA,eACA;wBAKc,WAAW;qBAId;KAED;EACV;EACA;EACA;EACA;;wBAGc,kBAAkB,cAAc;KAUpC;EACV;EACA;EACA;EACA;EACA;EACA,WAAW;;KAGD;EACV;EACA"}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "@powerhousedao/shared/document-model";
|
|
1
|
+
import { DOCUMENT_SCOPE_ACTION_TYPES } from "@powerhousedao/shared/document-model";
|
|
2
2
|
import Corestore from "corestore";
|
|
3
3
|
import Hyperbee from "hyperbee";
|
|
4
|
-
//#region ../reactor/dist/
|
|
4
|
+
//#region ../reactor/dist/forwarding-logger-BkwlvD9W.js
|
|
5
5
|
/**
|
|
6
6
|
* Thrown when an operation with the same identity already exists in the store.
|
|
7
7
|
*/
|
|
@@ -43,6 +43,7 @@ const APPEND_CONDITION_FAILED_PREFIX = "Append condition failed: ";
|
|
|
43
43
|
* conflict, not a fault: the caller retries against the new stream heads.
|
|
44
44
|
*/
|
|
45
45
|
var AppendConditionFailedError = class extends Error {
|
|
46
|
+
condition;
|
|
46
47
|
constructor(condition) {
|
|
47
48
|
const streams = condition.streams.map((s) => `${s.documentId}:${s.scope}:${s.branch}@${s.revision}`).join(", ");
|
|
48
49
|
super(`${APPEND_CONDITION_FAILED_PREFIX}a read-set stream advanced [${streams}]`);
|
|
@@ -57,19 +58,14 @@ var AppendConditionFailedError = class extends Error {
|
|
|
57
58
|
return message.startsWith(APPEND_CONDITION_FAILED_PREFIX);
|
|
58
59
|
}
|
|
59
60
|
};
|
|
60
|
-
|
|
61
|
-
const DOCUMENT_SCOPE_ACTIONS = new Set([
|
|
62
|
-
"CREATE_DOCUMENT",
|
|
63
|
-
"DELETE_DOCUMENT",
|
|
64
|
-
"UPGRADE_DOCUMENT",
|
|
65
|
-
"ADD_RELATIONSHIP",
|
|
66
|
-
"REMOVE_RELATIONSHIP",
|
|
67
|
-
"UPDATE_RELATIONSHIP"
|
|
68
|
-
]);
|
|
69
|
-
new Set([...DOCUMENT_SCOPE_ACTIONS].filter((type) => type !== "CREATE_DOCUMENT"));
|
|
61
|
+
new Set([...DOCUMENT_SCOPE_ACTION_TYPES].filter((type) => type !== "CREATE_DOCUMENT"));
|
|
70
62
|
//#endregion
|
|
71
63
|
//#region src/hypercore-atomic-transaction.ts
|
|
72
64
|
var HypercoreAtomicTransaction = class {
|
|
65
|
+
documentId;
|
|
66
|
+
documentType;
|
|
67
|
+
scope;
|
|
68
|
+
branch;
|
|
73
69
|
operations = [];
|
|
74
70
|
constructor(documentId, documentType, scope, branch) {
|
|
75
71
|
this.documentId = documentId;
|
|
@@ -131,6 +127,7 @@ function parseOperationKey(key) {
|
|
|
131
127
|
//#endregion
|
|
132
128
|
//#region src/hypercore-operation-store.ts
|
|
133
129
|
var HypercoreOperationStore = class {
|
|
130
|
+
bee;
|
|
134
131
|
applyLock = Promise.resolve();
|
|
135
132
|
constructor(bee) {
|
|
136
133
|
this.bee = bee;
|
|
@@ -206,12 +203,20 @@ var HypercoreOperationStore = class {
|
|
|
206
203
|
isCreate(operations) {
|
|
207
204
|
return operations.some((op) => op.action.type === "CREATE_DOCUMENT");
|
|
208
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* The paging cursor encodes the index to resume from (one past the last
|
|
208
|
+
* row returned), not the last row's own index; "" or "0" (or anything
|
|
209
|
+
* unparsable) means the start of the stream. This keeps "0" an unambiguous
|
|
210
|
+
* start-of-stream sentinel even when a page ends at index 0, which would
|
|
211
|
+
* otherwise make `nextCursor` equal the start cursor and loop a caller that
|
|
212
|
+
* walks pages forever. Mirrors the encoding in the Kysely store.
|
|
213
|
+
*/
|
|
209
214
|
async getSince(documentId, scope, branch, revision, filter, paging, signal) {
|
|
210
215
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
211
216
|
const prefix = operationPrefix(documentId, scope, branch);
|
|
212
217
|
const startIndex = revision + 1;
|
|
213
|
-
const
|
|
214
|
-
const gt = prefix + pad(Math.max(startIndex,
|
|
218
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
219
|
+
const gt = prefix + pad(Math.max(startIndex, Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : startIndex) - 1);
|
|
215
220
|
const lt = prefix + RANGE_UPPER_BOUND;
|
|
216
221
|
const limit = paging?.limit ? paging.limit + 1 : void 0;
|
|
217
222
|
const items = [];
|
|
@@ -236,7 +241,7 @@ var HypercoreOperationStore = class {
|
|
|
236
241
|
hasMore = true;
|
|
237
242
|
resultItems = items.slice(0, paging.limit);
|
|
238
243
|
}
|
|
239
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].index.toString() : void 0;
|
|
244
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].index + 1).toString() : void 0;
|
|
240
245
|
const cursor = paging?.cursor || "0";
|
|
241
246
|
const resultLimit = paging?.limit || 100;
|
|
242
247
|
return {
|
|
@@ -252,11 +257,20 @@ var HypercoreOperationStore = class {
|
|
|
252
257
|
}, signal) : void 0
|
|
253
258
|
};
|
|
254
259
|
}
|
|
260
|
+
/**
|
|
261
|
+
* The paging cursor encodes the ordinal to resume from (one past the last
|
|
262
|
+
* ordinal returned), not the last ordinal itself; "" or "0" (or anything
|
|
263
|
+
* unparsable) means the start of the stream. Unlike the Kysely store's
|
|
264
|
+
* `getSinceId` (whose auto-increment id starts at 1), this store's ordinal
|
|
265
|
+
* counter starts at 0, so 0 is a real, valid ordinal and the same
|
|
266
|
+
* ambiguous-cursor hazard as `getSince`/`getConflicting` applies here too.
|
|
267
|
+
*/
|
|
255
268
|
async getSinceId(id, paging, signal) {
|
|
256
269
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
257
|
-
const
|
|
258
|
-
const
|
|
259
|
-
const
|
|
270
|
+
const startId = id + 1;
|
|
271
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
272
|
+
const effectiveStart = Math.max(startId, Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : startId);
|
|
273
|
+
const gt = ordinalPrefix() + pad(effectiveStart - 1);
|
|
260
274
|
const lt = ordinalPrefix() + RANGE_UPPER_BOUND;
|
|
261
275
|
const limit = paging?.limit ? paging.limit + 1 : void 0;
|
|
262
276
|
const items = [];
|
|
@@ -285,7 +299,7 @@ var HypercoreOperationStore = class {
|
|
|
285
299
|
hasMore = true;
|
|
286
300
|
resultItems = items.slice(0, paging.limit);
|
|
287
301
|
}
|
|
288
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].context.ordinal.toString() : void 0;
|
|
302
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].context.ordinal + 1).toString() : void 0;
|
|
289
303
|
const cursor = paging?.cursor || "0";
|
|
290
304
|
const resultLimit = paging?.limit || 100;
|
|
291
305
|
return {
|
|
@@ -301,21 +315,31 @@ var HypercoreOperationStore = class {
|
|
|
301
315
|
}, signal) : void 0
|
|
302
316
|
};
|
|
303
317
|
}
|
|
318
|
+
/**
|
|
319
|
+
* The paging cursor here encodes the index to resume from (one past the
|
|
320
|
+
* last row returned), not the last row's own index, for the same reason as
|
|
321
|
+
* `getSince`: a page ending at index 0 must not produce a cursor that is
|
|
322
|
+
* indistinguishable from the start-of-stream sentinel.
|
|
323
|
+
*/
|
|
304
324
|
async getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {
|
|
305
325
|
if (signal?.aborted) throw new Error("Operation aborted");
|
|
306
326
|
const prefix = operationPrefix(documentId, scope, branch);
|
|
307
|
-
const
|
|
308
|
-
const
|
|
327
|
+
const parsedCursor = paging?.cursor ? Number.parseInt(paging.cursor, 10) : NaN;
|
|
328
|
+
const cursorIndex = Number.isFinite(parsedCursor) && parsedCursor > 0 ? parsedCursor : -1;
|
|
329
|
+
const gte = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;
|
|
309
330
|
const lt = prefix + RANGE_UPPER_BOUND;
|
|
310
331
|
const stream = this.bee.createReadStream({
|
|
311
|
-
|
|
312
|
-
gte: cursorIndex >= 0 ? void 0 : gt,
|
|
332
|
+
gte,
|
|
313
333
|
lt
|
|
314
334
|
});
|
|
335
|
+
const readLimit = paging?.limit ? paging.limit + 1 : void 0;
|
|
315
336
|
const items = [];
|
|
316
337
|
for await (const entry of stream) {
|
|
317
338
|
const stored = entry.value;
|
|
318
|
-
if (stored.timestampUtcMs >= minTimestamp)
|
|
339
|
+
if (stored.timestampUtcMs >= minTimestamp) {
|
|
340
|
+
items.push(this.toOperation(stored));
|
|
341
|
+
if (readLimit !== void 0 && items.length >= readLimit) break;
|
|
342
|
+
}
|
|
319
343
|
}
|
|
320
344
|
let hasMore = false;
|
|
321
345
|
let resultItems = items;
|
|
@@ -323,7 +347,7 @@ var HypercoreOperationStore = class {
|
|
|
323
347
|
hasMore = true;
|
|
324
348
|
resultItems = items.slice(0, paging.limit);
|
|
325
349
|
}
|
|
326
|
-
const nextCursor = hasMore && resultItems.length > 0 ? resultItems[resultItems.length - 1].index.toString() : void 0;
|
|
350
|
+
const nextCursor = hasMore && resultItems.length > 0 ? (resultItems[resultItems.length - 1].index + 1).toString() : void 0;
|
|
327
351
|
const cursor = paging?.cursor || "0";
|
|
328
352
|
const resultLimit = paging?.limit || 100;
|
|
329
353
|
return {
|
|
@@ -373,6 +397,24 @@ var HypercoreOperationStore = class {
|
|
|
373
397
|
for (const operation of stored.results) if (latest === void 0 || operation.timestampUtcMs > latest) latest = operation.timestampUtcMs;
|
|
374
398
|
return latest;
|
|
375
399
|
}
|
|
400
|
+
async findOperationIds(documentId, scope, branch, opIds, signal) {
|
|
401
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
402
|
+
const found = /* @__PURE__ */ new Set();
|
|
403
|
+
if (opIds.length === 0) return found;
|
|
404
|
+
const wanted = new Set(opIds);
|
|
405
|
+
const stored = await this.getSince(documentId, scope, branch, -1, void 0, void 0, signal);
|
|
406
|
+
for (const operation of stored.results) if (wanted.has(operation.id)) found.add(operation.id);
|
|
407
|
+
return found;
|
|
408
|
+
}
|
|
409
|
+
async getOperationsByIds(documentId, scope, branch, opIds, signal) {
|
|
410
|
+
if (signal?.aborted) throw new Error("Operation aborted");
|
|
411
|
+
if (opIds.length === 0) return [];
|
|
412
|
+
const wanted = new Set(opIds);
|
|
413
|
+
const stored = await this.getSince(documentId, scope, branch, -1, void 0, void 0, signal);
|
|
414
|
+
const latest = /* @__PURE__ */ new Map();
|
|
415
|
+
for (const operation of stored.results) if (wanted.has(operation.id)) latest.set(operation.id, operation);
|
|
416
|
+
return [...latest.values()];
|
|
417
|
+
}
|
|
376
418
|
serializeOperation(op) {
|
|
377
419
|
return {
|
|
378
420
|
id: op.id,
|
|
@@ -412,7 +454,8 @@ var StorageManager = class {
|
|
|
412
454
|
}
|
|
413
455
|
async open() {
|
|
414
456
|
await this.store.ready();
|
|
415
|
-
|
|
457
|
+
const core = this.store.get({ name: "operations" });
|
|
458
|
+
this.bee = new Hyperbee(core, {
|
|
416
459
|
keyEncoding: "utf-8",
|
|
417
460
|
valueEncoding: "json"
|
|
418
461
|
});
|