@powerhousedao/reactor-hypercore 6.2.0-dev.10 → 6.2.0-dev.11

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.
@@ -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","CreateDocumentActionInput","DocumentModelModule","ISigner","Operation","OperationContext","OperationWithContext","OperationWithContext$1","PHDocument","PHDocumentState","SignatureVerificationHandler","UpgradeDocumentActionInput","UpgradeManifest","UpgradeReducer","UpgradeTransition","actions","documentActions","DocumentDriveDocument","DriveInput","FolderNode","Node","ILogger","kysely","Generated","Insertable","Kysely","Transaction","IProcessor","IProcessorHostModule","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","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","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","SearchFilter","type","parentId","ids","slugs","PagingOptions","cursor","limit","PagedResults","T","results","options","next","nextCursor","totalCount","ConsistencyKey","ConsistencyCoordinate","operationIndex","version","coordinates","IReadModel","name","indexOperations","IReadModelCoordinator","readModels","stop","drain","getChainDepth","ChannelScheme","CONNECT","SWITCHBOARD","JwtHandler","url","PollBehavior","Auto","Manual","RemoteOptions","sinceTimestampUtcMs","pollBehavior","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","ConnectionStateChangedEvent","remoteId","previous","current","snapshot","RemoteStatus","push","pull","ChannelConfig","parameters","RemoteRecord","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","SyncResultStatus","SyncResultError","SyncResult","DuplicateOperationError","constructor","description","OptimisticLockError","RevisionMismatchError","expected","actual","AtomicTxn","addOperations","DocumentRevisions","latestTimestamp","IOperationStore","AbortSignal","OperationFilter","apply","documentType","txn","fn","signal","getSince","paging","getSinceId","getConflicting","minTimestamp","getRevisions","IKeyframeStore","putKeyframe","document","findNearestKeyframe","targetRevision","listKeyframes","deleteKeyframes","ViewFilter$1","excludeSourceRemote","actionTypes","timestampFrom","timestampTo","sinceRevision","IDocumentView","TDocument","init","items","waitForConsistency","token","timeoutMs","exists","documentIds","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","write","IOperationIndex","commit","find","getSinceOrdinal","getLatestTimestampForCollection","getCollectionsForDocuments","driveCollectionId","driveId","IWriteCache","getState","putState","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","ReadModelStage","ReadModelIndexingStage","JobPendingEvent","jobMeta","JobRunningEvent","JobWriteReadyEvent","collectionMemberships","JobReadReadyEvent","JobFailedEvent$1","ReadModelBatchCompletedEvent","batchSize","chainWaitDurationMs","preReadyDurationMs","emitDurationMs","postReadyDurationMs","ReadModelIndexedEvent","readModelName","stage","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","DocumentChangeType","Created","Deleted","Updated","ParentAdded","ParentRemoved","ChildAdded","ChildRemoved","DocumentChangeEvent","documents","CreateDocumentOptions","parentIdentifier","documentModelVersion","IDriveClient","create","addFile","driveIdentifier","parentFolder","addFolder","removeNode","nodeId","renameNode","setPreferredEditorOnNode","preferredEditor","moveNode","srcNodeId","targetParentFolderId","copyNode","getNode","listNodes","IReactorClient","BatchExecutionRequest","BatchExecutionResult","BatchLoadRequest","BatchLoadResult","drives","getDocumentModelModules","namespace","getDocumentModelModule","getOperations","documentIdentifier","getOutgoingRelationships","sourceIdentifier","getIncomingRelationships","targetIdentifier","createEmpty","documentModelType","createDocumentInDrive","execute","executeAsync","executeBatch","request","rename","setPreferredEditor","addRelationship","removeRelationship","moveRelationship","sourceParentIdentifier","targetParentIdentifier","source","target","deleteDocument","propagate","deleteDocuments","identifiers","loadBatch","ReactorClient","IReactor","logger","reactor","signer","subscriptionManager","jobAwaiter","documentIndexer","documentView","getOperationsWithCompositeCursor","removeAllIncomingRelationships","JobResult","operationsWithContext","completedAt","duration","JobExecutorConfig","maxSkipThreshold","maxConcurrency","jobTimeoutMs","retryBaseDelayMs","retryMaxDelayMs","yieldDeadlineMs","JobExecutorEventTypes","JOB_STARTED","JOB_COMPLETED","EXECUTOR_STARTED","EXECUTOR_STOPPED","JobStartedEvent","startedAt","workerId","JobCompletedEvent","JobFailedEvent","willRetry","ExecutorStartedEvent","config","ExecutorStoppedEvent","stoppedAt","graceful","ExecutorManagerStatus","isRunning","numExecutors","activeJobs","totalJobsProcessed","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","correlationId","poolConfig","db","signatureVerifier","models","ExecuteMessage","AbortMessage","targetCorrelationId","reason","ShutdownMessage","graceMs","LoadModelMessage","model","ParentMessage","ReadyMessage","ResultMessage","writeReady","ModelLoadedMessage","ModelLoadFailedMessage","LogMessage","level","args","timestamp","HeartbeatMessage","inFlightCorrelationIds","MetricsMessage","counters","gauges","PoolAcquireSamplesMessage","poolName","durations","size","idle","waiting","WorkerMessage","WorkerInFlightSnapshot","WorkerExecutionOutcome","IExecutorWorker","index","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","isDrained","block","onDrained","unblock","ViewStateTable","readModelId","lastOrdinal","lastOperationTimestamp","DocumentSnapshotTable","content","lastOperationIndex","lastOperationHash","lastUpdatedAt","snapshotVersion","isDeleted","deletedAt","SlugMappingTable","ProcessorCursorTable","processorId","factoryId","processorIndex","lastErrorTimestamp","DocumentViewDatabase","ViewState","DocumentSnapshot","SlugMapping","ProcessorCursor","InsertableDocumentSnapshot","RegistrationResult","item","IDocumentModelLoader","load","resolveSpec","IDocumentModelRegistry","registerModules","modules","unregisterModules","documentTypes","getModule","getAllModules","getSupportedVersions","getLatestVersion","registerUpgradeManifests","manifests","unregisterUpgradeManifests","getUpgradeManifest","computeUpgradePath","fromVersion","toVersion","getUpgradeReducer","IConsistencyTracker","update","getLatest","waitFor","serialize","hydrate","entries","makeConsistencyKey","ConsistencyTracker","waiters","deduplicateCoordinates","areCoordinatesSatisfied","checkWaiters","removeWaiter","OperationTable","opId","prevOpId","writeTimestampUtcMs","timestampUtcMs","action","skip","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","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","Database$1","Keyframe","document_collections","operation_index_operations","sync_remotes","sync_cursors","sync_dead_letters","DocumentTable","DocumentRelationshipTable","IndexerStateTable","lastOperationId","DocumentIndexerDatabase","Document","IndexerState","PoolStats","PoolInstrumentation","getStats","onAcquire","listener","instrumentPgPool","pool","ForwardingPoolInstrumentation","pushSamples","updateStats","stats","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","IChannelFactory","instance","cursorStorage","Remote","ISyncManager","getByName","getById","waitForSync","getSyncStatus","onSyncStatusChange","ExecutionJobPlan","jobs","LoadJobPlan","externalDeps","kill","getDocumentModels","getBySlug","docId","ReactorFeatures","Database","SyncModule","remoteStorage","deadLetterStorage","channelFactory","syncManager","ReactorModule","documentModelRegistry","queue","jobTracker","executorManager","operationStore","keyframeStore","writeCache","documentViewConsistencyTracker","documentIndexerConsistencyTracker","readModelCoordinator","processorManager","processorManagerConsistencyTracker","syncModule","pools","ReactorClientModule","client","reactorModule","DriveClient","documentExists","removeFileNode","ICollectionMembershipCache","IDocumentModelResolver","ensureModelLoaded","ModelLoadedBroadcastHook","DocumentModelResolver","registry","loader","loadingModels","failedModelTypes","broadcastHook","setBroadcastHook","hook","broadcastIfPossible","NullDocumentModelResolver","WorkerFactory","WriteCacheConfig","maxDocuments","ringBufferSize","keyframeInterval","DocumentStreamKey","CachedSnapshot","KeyframeSnapshot","BuiltInReadModelKind","ProjectionInitMessage","shardId","shardIndex","shardCount","preReadyKinds","postReadyKinds","chainDepthReportIntervalMs","ProjectionWriteReadyMessage","ProjectionDrainMessage","ProjectionShutdownMessage","ProjectionParentMessage","ProjectionReadyMessage","ProjectionReadReadyMessage","ProjectionReadModelIndexedMessage","ProjectionBatchCompletedMessage","ProjectionChainDepthMessage","depth","ProjectionPoolAcquireSamplesMessage","ProjectionDrainedMessage","ProjectionLogMessage","ProjectionWorkerMessage","ProjectionTransportEventMap","exit","ProjectionTransportEvent","ProjectionTransportListener","E","payload","IProjectionTransport","postMessage","off","terminate","ProjectionWorkerFactory","ProjectionShardManagerConfig","factory","hostBus","initTimeoutMs","shutdownGraceMs","drainTimeoutMs","poolInstrumentations","SignerConfig","verifier","MigrationStrategy","MigrationResult","migrationsExecuted","SyncBuilder","ReadonlySet","withChannelFactory","withRemoteStorage","storage","withCursorStorage","withDeadLetterStorage","withMaxDeadLettersPerRemote","withMaxInboxBatchSize","build","driveContainerTypes","buildModule","ReadModelFactoryDeps","ReadModelFactory","deps","DocumentModelSpecInput","ProjectionShardBuilderConfig","ReactorBuilder","Partial","documentModels","upgradeManifests","features","readModelFactories","executorConfig","writeCacheConfig","migrationStrategy","syncBuilder","kyselyInstance","signalHandlersEnabled","queueInstance","channelScheme","jwtHandler","documentModelLoader","shutdownHooks","documentModelSpecs","workerPoolConfig","resolvedModelManifest","workerDbConfig","workerSignatureVerifierSpec","workerFactory","projectionShardConfig","projectionWorkerFactory","instrumentedPools","withLogger","withDocumentModels","withUpgradeManifests","withFeatures","withReadModel","readModel","withReadModelFactory","withReadModelCoordinator","withExecutor","executor","withExecutorConfig","withWriteCacheConfig","withDriveContainerTypes","withMigrationStrategy","strategy","withSync","withEventBus","withSignatureVerifier","withKysely","withInstrumentedPool","instrumentation","withQueue","withChannelScheme","scheme","withJwtHandler","handler","withDocumentModelLoader","withSignalHandlers","withShutdownHook","withDocumentModelSpecs","specs","withWorkerPool","withWorkerDbConfig","withWorkerSignatureVerifierSpec","withWorkerFactory","withProjectionShards","withProjectionWorkerFactory","getResolvedModelManifest","createProjectionShardManager","createDefaultProjectionWorkerFactory","createDefaultWorkerFactory","createPostgresDatabase","attachSignalHandlers","ReactorClientBuilder","reactorBuilder","withReactorBuilder","withReactor","withSigner","withSubscriptionManager","withJobAwaiter","DEFAULT_DRIVE_CONTAINER_TYPES","Reactor","shutdownStatus","setShutdown","setCompleted","findByIds","findBySlugs","findByParentId","emitJobPending","ParsedDriveUrl","graphqlEndpoint","parseDriveUrl","driveIdFromUrl","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","unsubscribe","deferredJobs","resultHandler","processNextJob","checkForMoreJobs","processExistingJobs","flushDeferredJobs","CachedDocumentMeta","documentScopeRevision","IDocumentMetaCache","getDocumentMeta","rebuildAtRevision","putDocumentMeta","RingBuffer","buffer","head","capacity","getAll","length","DocumentStream","ringBuffer","KyselyWriteCache","streams","lruTracker","withScopedStores","getStream","coldMissRebuild","warmMissRebuild","findNearestOlderSnapshot","makeStreamKey","getOrCreateStream","isKeyframeRevision","KyselyOperationStore","trx","queryExecutor","withTransaction","resolveUniqueConstraint","executeApply","findIdempotentReplay","rowToOperation","rowToOperationWithContext","KyselyKeyframeStore","ExecutionStores","documentMetaCache","collectionMembershipCache","IExecutionScope","run","stores","SimpleJobExecutor","signatureVerifierModule","documentActionHandler","executionScope","getCollectionMembershipsForOperations","processActions","executeRegularAction","executeLoadJob","accumulateResultOrReturnError","createForwardingLogger","msg","post","tags","errorToInfo","err","sanitizeArg","WeakSet","workerEntryPath","ModuleNotFoundError","requestedVersion","isError","DuplicateModuleError","InvalidModuleError","DuplicateManifestError","DocumentModelRegistry","manifestsToRegister","BaseReadModelConfig","rebuildStateOnInit","BaseReadModel","consistencyTracker","commitOperations","rebuildStateForOperations","loadState","initializeState","saveState","updateConsistencyTracker","IndexerDatabase","KyselyDocumentIndexer","_db","handleAddRelationship","handleRemoveRelationship","handleUpdateRelationship","ReadModelCoordinator","preReady","postReady","chains","emitEmptyReadReady","runChain","indexWithTiming","emitReadModelIndexed","emitBatchCompleted","queueKeyFor","Database$2","KyselyDocumentView","REACTOR_SCHEMA","runMigrations","schema","getMigrationStatus","MigrationInfo","KyselySyncCursorStorage","KyselySyncRemoteStorage","GqlRequestChannelFactory","GqlResponseChannelFactory","IPollTimer","setDelegate","delegate","triggerNow","GqlChannelConfig","fetch","fetchFn","GqlRequestChannel","bufferedOutbox","channelId","pollTimer","abortController","lastPersistedInboxOrdinal","lastPersistedOutboxOrdinal","pushRetryTimer","isPushing","pendingDrain","connectionState","connectionStateCallbacks","transitionConnectionState","poll","handleRemoteDeadLetters","handlePollError","recoverFromChannelNotFound","pollSyncEnvelopes","touchRemoteChannel","attemptPush","schedulePushRetry","drainOutbox","classifyError","pushSyncOperations","getAuthorizationHeader","executeGraphQL","poller","GqlResponseChannel","PollTimerConfig","intervalMs","maxQueueDepth","backpressureCheckIntervalMs","startPaused","IntervalPollTimer","timer","running","consecutiveFailures","tick","scheduleNext","scheduleRetry","scheduleBackpressureRecheck","getIntervalMs","setIntervalMs","ms","envelopesToSyncOperations","envelope","OperationBatch","trimMailboxFromAckOrdinal","mailbox","batchOperationsByDocument","consolidateSyncOperations","syncOps","KeyframeValidationIssue","keyframeHash","replayedHash","SnapshotValidationIssue","snapshotHash","ValidationResult","isConsistent","keyframeIssues","snapshotIssues","RebuildResult","keyframesDeleted","scopesInvalidated","IDocumentIntegrityService","validateDocument","rebuildKeyframes","rebuildSnapshots","DocumentIntegrityService","discoverScopes","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;;;;;;;;;;;;;;;;;;;;;;;AC6f6B;;;;;;;;;AAQN;;;;;;;KAvSnCyM,aAAAA;EACHC,MAAAA;EACAC,KAAAA;AAAAA;;;;KAKGC,YAAAA;EACHE,OAAAA,EAASD,CAAAA;EACTE,OAAAA,EAASN,aAAAA;EACTO,IAAAA,SAAatC,OAAAA,CAAQkC,YAAAA,CAAaC,CAAAA;EAClCI,UAAAA;EACAC,UAAAA;AAAAA;;;;;;;;UAyRQiG,SAAAA;;EAERC,aAAAA,IAAiB1J,UAAAA,EAAY9E,SAAAA;AAAAA;;;;;KAM1ByO,iBAAAA;uDACkDlH,QAAAA,EAAUvE,MAAAA;EAC/D0L,eAAAA;AAAAA;;;;;UAMQC,eAAAA;;;;;;;;;;;;;;;;;;;;;;;EAuBRG,KAAAA,CAAMhM,UAAAA,UAAoBiM,YAAAA,UAAsBnK,KAAAA,UAAeC,MAAAA,UAAgB0C,QAAAA,UAAkB0H,EAAAA,GAAKD,GAAAA,EAAKT,SAAAA,YAAqBzI,OAAAA,QAAeoJ,MAAAA,GAASN,WAAAA,GAAc9I,OAAAA,CAAQ9F,SAAAA;;;;;;;;;;;;;EAa9KmP,QAAAA,CAASrM,UAAAA,UAAoB8B,KAAAA,UAAeC,MAAAA,UAAgB0C,QAAAA,UAAkBqF,MAAAA,GAASiC,eAAAA,EAAiBO,MAAAA,GAASvH,aAAAA,EAAeqH,MAAAA,GAASN,WAAAA,GAAc9I,OAAAA,CAAQkC,YAAAA,CAAahI,SAAAA;;;;;;;;;;EAU5KqP,UAAAA,CAAW3K,EAAAA,UAAY0K,MAAAA,GAASvH,aAAAA,EAAeqH,MAAAA,GAASN,WAAAA,GAAc9I,OAAAA,CAAQkC,YAAAA,CAAa7H,oBAAAA;;;;;;;;;;;;EAY3FmP,cAAAA,CAAexM,UAAAA,UAAoB8B,KAAAA,UAAeC,MAAAA,UAAgB0K,YAAAA,UAAsBH,MAAAA,GAASvH,aAAAA,EAAeqH,MAAAA,GAASN,WAAAA,GAAc9I,OAAAA,CAAQkC,YAAAA,CAAahI,SAAAA;;;;;;;;;;;EAW5JwP,YAAAA,CAAa1M,UAAAA,UAAoB+B,MAAAA,UAAgBqK,MAAAA,GAASN,WAAAA,GAAc9I,OAAAA,CAAQ2I,iBAAAA;AAAAA;;;;;;;;;UAyExEI,eAAAA;;EAERqB,WAAAA;;EAEAC,aAAAA;;EAEAC,WAAAA;;EAEAC,aAAAA;AAAAA;;;;;;;;cChqBW,uBAAA,YAAmC,eAAA;EAAA,QAG1B,GAAA;EAAA,QAFZ,SAAA;cAEY,GAAA,EAAK,QAAA;EAEnB,KAAA,CACJ,UAAA,UACA,YAAA,UACA,KAAA,UACA,MAAA,UACA,QAAA,UACA,EAAA,GAAK,GAAA,EAAK,SAAA,YAAqB,OAAA,QAC/B,MAAA,GAAS,WAAA,GACR,OAAA,CAAQ,SAAA;EAAA,QAwBG,YAAA;EAoFR,QAAA,CACJ,UAAA,UACA,KAAA,UACA,MAAA,UACA,QAAA,UACA,MAAA,GAAS,eAAA,EACT,MAAA,GAAS,aAAA,EACT,MAAA,GAAS,WAAA,GACR,OAAA,CAAQ,YAAA,CAAa,SAAA;EAsFlB,UAAA,CACJ,EAAA,UACA,MAAA,GAAS,aAAA,EACT,MAAA,GAAS,WAAA,GACR,OAAA,CAAQ,YAAA,CAAa,oBAAA;EAiElB,cAAA,CACJ,UAAA,UACA,KAAA,UACA,MAAA,UACA,YAAA,UACA,MAAA,GAAS,aAAA,EACT,MAAA,GAAS,WAAA,GACR,OAAA,CAAQ,YAAA,CAAa,SAAA;EA+DlB,YAAA,CACJ,UAAA,UACA,MAAA,UACA,MAAA,GAAS,WAAA,GACR,OAAA,CAAQ,iBAAA;EAAA,QAkCH,kBAAA;EAAA,QAgBA,WAAA;AAAA;;;KCvbE,eAAA,GAAkB,SAAA;EAC5B,UAAA;EACA,YAAA;EACA,KAAA;EACA,MAAA;AAAA;AAAA,KAGU,qBAAA;EACV,WAAA;AAAA;;;cCNW,0BAAA,YAAsC,SAAA;EAAA,QAIvC,UAAA;EAAA,QACA,YAAA;EAAA,QACA,KAAA;EAAA,QACA,MAAA;EAAA,QANF,UAAA;cAGE,UAAA,UACA,YAAA,UACA,KAAA,UACA,MAAA;EAGV,aAAA,CAAA,GAAiB,UAAA,EAAY,SAAA;EAY7B,aAAA,CAAA,GAAiB,eAAA;AAAA;;;cCvBN,cAAA;EAAA,QACH,KAAA;EAAA,QACA,GAAA;cAEI,WAAA;EAIN,IAAA,CAAA,GAAQ,OAAA;EAUR,KAAA,CAAA,GAAS,OAAA;EAOf,MAAA,CAAA,GAAU,QAAA;AAAA;;;cCxBC,iBAAA;AAAA,iBAEG,GAAA,CAAI,CAAA;AAAA,iBAIJ,YAAA,CACd,UAAA,UACA,KAAA,UACA,MAAA,UACA,KAAA;AAAA,iBAKc,eAAA,CACd,UAAA,UACA,KAAA,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":["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","CreateDocumentActionInput","DocumentModelModule","ISigner","Operation","OperationContext","OperationWithContext","OperationWithContext$1","PHDocument","PHDocumentState","SignatureVerificationHandler","UpgradeDocumentActionInput","UpgradeManifest","UpgradeReducer","UpgradeTransition","actions","documentActions","DocumentDriveDocument","DriveInput","FolderNode","Node","ILogger","kysely","Generated","Insertable","Kysely","Transaction","IProcessor","IProcessorHostModule","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","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","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","SearchFilter","type","parentId","ids","slugs","PagingOptions","cursor","limit","PagedResults","T","results","options","next","nextCursor","totalCount","ConsistencyKey","ConsistencyCoordinate","operationIndex","version","coordinates","IReadModel","name","indexOperations","IReadModelCoordinator","readModels","stop","drain","getChainDepth","ChannelScheme","CONNECT","SWITCHBOARD","JwtHandler","url","PollBehavior","Auto","Manual","RemoteOptions","sinceTimestampUtcMs","pollBehavior","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","ConnectionStateChangedEvent","remoteId","previous","current","snapshot","RemoteStatus","push","pull","ChannelConfig","parameters","RemoteRecord","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","SyncResultStatus","SyncResultError","SyncResult","DuplicateOperationError","constructor","description","OptimisticLockError","RevisionMismatchError","expected","actual","AtomicTxn","addOperations","DocumentRevisions","latestTimestamp","IOperationStore","AbortSignal","OperationFilter","apply","documentType","txn","fn","signal","getSince","paging","getSinceId","getConflicting","minTimestamp","getRevisions","IKeyframeStore","putKeyframe","document","findNearestKeyframe","targetRevision","listKeyframes","deleteKeyframes","ViewFilter$1","excludeSourceRemote","actionTypes","timestampFrom","timestampTo","sinceRevision","IDocumentView","TDocument","init","items","waitForConsistency","token","timeoutMs","exists","documentIds","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","write","IOperationIndex","commit","find","getSinceOrdinal","getLatestTimestampForCollection","getCollectionsForDocuments","driveCollectionId","driveId","IWriteCache","getState","putState","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","ReadModelStage","ReadModelIndexingStage","JobPendingEvent","jobMeta","JobRunningEvent","JobWriteReadyEvent","collectionMemberships","JobReadReadyEvent","JobFailedEvent$1","ReadModelBatchCompletedEvent","batchSize","chainWaitDurationMs","preReadyDurationMs","emitDurationMs","postReadyDurationMs","ReadModelIndexedEvent","readModelName","stage","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","DocumentChangeType","Created","Deleted","Updated","ParentAdded","ParentRemoved","ChildAdded","ChildRemoved","DocumentChangeEvent","documents","CreateDocumentOptions","parentIdentifier","documentModelVersion","IDriveClient","create","addFile","driveIdentifier","parentFolder","addFolder","removeNode","nodeId","renameNode","setPreferredEditorOnNode","preferredEditor","moveNode","srcNodeId","targetParentFolderId","copyNode","getNode","listNodes","IReactorClient","BatchExecutionRequest","BatchExecutionResult","BatchLoadRequest","BatchLoadResult","drives","getDocumentModelModules","namespace","getDocumentModelModule","getOperations","documentIdentifier","getOutgoingRelationships","sourceIdentifier","getIncomingRelationships","targetIdentifier","createEmpty","documentModelType","createDocumentInDrive","execute","executeAsync","executeBatch","request","rename","setPreferredEditor","addRelationship","removeRelationship","moveRelationship","sourceParentIdentifier","targetParentIdentifier","source","target","deleteDocument","propagate","deleteDocuments","identifiers","loadBatch","ReactorClient","IReactor","logger","reactor","signer","subscriptionManager","jobAwaiter","documentIndexer","documentView","getOperationsWithCompositeCursor","removeAllIncomingRelationships","JobResult","operationsWithContext","completedAt","duration","JobExecutorConfig","maxSkipThreshold","maxConcurrency","jobTimeoutMs","retryBaseDelayMs","retryMaxDelayMs","yieldDeadlineMs","JobExecutorEventTypes","JOB_STARTED","JOB_COMPLETED","EXECUTOR_STARTED","EXECUTOR_STOPPED","JobStartedEvent","startedAt","workerId","JobCompletedEvent","JobFailedEvent","willRetry","ExecutorStartedEvent","config","ExecutorStoppedEvent","stoppedAt","graceful","ExecutorManagerStatus","isRunning","numExecutors","activeJobs","totalJobsProcessed","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","correlationId","poolConfig","db","signatureVerifier","models","ExecuteMessage","AbortMessage","targetCorrelationId","reason","ShutdownMessage","graceMs","LoadModelMessage","model","ParentMessage","ReadyMessage","ResultMessage","writeReady","ModelLoadedMessage","ModelLoadFailedMessage","LogMessage","level","args","timestamp","HeartbeatMessage","inFlightCorrelationIds","MetricsMessage","counters","gauges","PoolAcquireSamplesMessage","poolName","durations","size","idle","waiting","WorkerMessage","WorkerInFlightSnapshot","WorkerExecutionOutcome","IExecutorWorker","index","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","isDrained","block","onDrained","unblock","ViewStateTable","readModelId","lastOrdinal","lastOperationTimestamp","DocumentSnapshotTable","content","lastOperationIndex","lastOperationHash","lastUpdatedAt","snapshotVersion","isDeleted","deletedAt","SlugMappingTable","ProcessorCursorTable","processorId","factoryId","processorIndex","lastErrorTimestamp","DocumentViewDatabase","ViewState","DocumentSnapshot","SlugMapping","ProcessorCursor","InsertableDocumentSnapshot","RegistrationResult","item","IDocumentModelLoader","load","resolveSpec","IDocumentModelRegistry","registerModules","modules","unregisterModules","documentTypes","getModule","getAllModules","getSupportedVersions","getLatestVersion","registerUpgradeManifests","manifests","unregisterUpgradeManifests","getUpgradeManifest","computeUpgradePath","fromVersion","toVersion","getUpgradeReducer","IConsistencyTracker","update","getLatest","waitFor","serialize","hydrate","entries","makeConsistencyKey","ConsistencyTracker","waiters","deduplicateCoordinates","areCoordinatesSatisfied","checkWaiters","removeWaiter","OperationTable","opId","prevOpId","writeTimestampUtcMs","timestampUtcMs","action","skip","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","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","Database$1","Keyframe","document_collections","operation_index_operations","sync_remotes","sync_cursors","sync_dead_letters","DocumentTable","DocumentRelationshipTable","IndexerStateTable","lastOperationId","DocumentIndexerDatabase","Document","IndexerState","PoolStats","PoolInstrumentation","getStats","onAcquire","listener","instrumentPgPool","pool","ForwardingPoolInstrumentation","pushSamples","updateStats","stats","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","IChannelFactory","instance","cursorStorage","Remote","ISyncManager","getByName","getById","waitForSync","getSyncStatus","onSyncStatusChange","ExecutionJobPlan","jobs","LoadJobPlan","externalDeps","kill","getDocumentModels","getBySlug","docId","ReactorFeatures","Database","SyncModule","remoteStorage","deadLetterStorage","channelFactory","syncManager","ReactorModule","documentModelRegistry","queue","jobTracker","executorManager","operationStore","keyframeStore","writeCache","documentViewConsistencyTracker","documentIndexerConsistencyTracker","readModelCoordinator","processorManager","processorManagerConsistencyTracker","syncModule","pools","ReactorClientModule","client","reactorModule","DriveClient","documentExists","removeFileNode","ICollectionMembershipCache","IDocumentModelResolver","ensureModelLoaded","ModelLoadedBroadcastHook","DocumentModelResolver","registry","loader","loadingModels","failedModelTypes","broadcastHook","setBroadcastHook","hook","broadcastIfPossible","NullDocumentModelResolver","WorkerFactory","WriteCacheConfig","maxDocuments","ringBufferSize","keyframeInterval","DocumentStreamKey","CachedSnapshot","KeyframeSnapshot","BuiltInReadModelKind","ProjectionInitMessage","shardId","shardIndex","shardCount","preReadyKinds","postReadyKinds","chainDepthReportIntervalMs","ProjectionWriteReadyMessage","ProjectionDrainMessage","ProjectionShutdownMessage","ProjectionParentMessage","ProjectionReadyMessage","ProjectionReadReadyMessage","ProjectionReadModelIndexedMessage","ProjectionBatchCompletedMessage","ProjectionChainDepthMessage","depth","ProjectionPoolAcquireSamplesMessage","ProjectionDrainedMessage","ProjectionLogMessage","ProjectionWorkerMessage","ProjectionTransportEventMap","exit","ProjectionTransportEvent","ProjectionTransportListener","E","payload","IProjectionTransport","postMessage","off","terminate","ProjectionWorkerFactory","ProjectionShardManagerConfig","factory","hostBus","initTimeoutMs","shutdownGraceMs","drainTimeoutMs","poolInstrumentations","SignerConfig","verifier","MigrationStrategy","MigrationResult","migrationsExecuted","SyncBuilder","ReadonlySet","withChannelFactory","withRemoteStorage","storage","withCursorStorage","withDeadLetterStorage","withMaxDeadLettersPerRemote","withMaxInboxBatchSize","build","driveContainerTypes","buildModule","ReadModelFactoryDeps","ReadModelFactory","deps","DocumentModelSpecInput","ProjectionShardBuilderConfig","ReactorBuilder","Partial","documentModels","upgradeManifests","features","readModelFactories","executorConfig","writeCacheConfig","migrationStrategy","syncBuilder","kyselyInstance","signalHandlersEnabled","queueInstance","channelScheme","jwtHandler","documentModelLoader","shutdownHooks","documentModelSpecs","workerPoolConfig","resolvedModelManifest","workerDbConfig","workerSignatureVerifierSpec","workerFactory","projectionShardConfig","projectionWorkerFactory","instrumentedPools","withLogger","withDocumentModels","withUpgradeManifests","withFeatures","withReadModel","readModel","withReadModelFactory","withReadModelCoordinator","withExecutor","executor","withExecutorConfig","withWriteCacheConfig","withDriveContainerTypes","withMigrationStrategy","strategy","withSync","withEventBus","withSignatureVerifier","withKysely","withInstrumentedPool","instrumentation","withQueue","withChannelScheme","scheme","withJwtHandler","handler","withDocumentModelLoader","withSignalHandlers","withShutdownHook","withDocumentModelSpecs","specs","withWorkerPool","withWorkerDbConfig","withWorkerSignatureVerifierSpec","withWorkerFactory","withProjectionShards","withProjectionWorkerFactory","getResolvedModelManifest","createProjectionShardManager","createDefaultProjectionWorkerFactory","createDefaultWorkerFactory","createPostgresDatabase","attachSignalHandlers","ReactorClientBuilder","reactorBuilder","withReactorBuilder","withReactor","withSigner","withSubscriptionManager","withJobAwaiter","DEFAULT_DRIVE_CONTAINER_TYPES","Reactor","shutdownStatus","setShutdown","setCompleted","findByIds","findBySlugs","findByParentId","emitJobPending","ParsedDriveUrl","graphqlEndpoint","parseDriveUrl","driveIdFromUrl","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","unsubscribe","deferredJobs","resultHandler","processNextJob","checkForMoreJobs","processExistingJobs","flushDeferredJobs","CachedDocumentMeta","documentScopeRevision","IDocumentMetaCache","getDocumentMeta","rebuildAtRevision","putDocumentMeta","RingBuffer","buffer","head","capacity","getAll","length","DocumentStream","ringBuffer","KyselyWriteCache","streams","lruTracker","withScopedStores","getStream","coldMissRebuild","resolveModuleVersionForOp","warmMissRebuild","findNearestOlderSnapshot","makeStreamKey","getOrCreateStream","isKeyframeRevision","KyselyOperationStore","trx","queryExecutor","withTransaction","resolveUniqueConstraint","executeApply","findIdempotentReplay","rowToOperation","rowToOperationWithContext","KyselyKeyframeStore","ExecutionStores","documentMetaCache","collectionMembershipCache","IExecutionScope","run","stores","SimpleJobExecutor","signatureVerifierModule","documentActionHandler","executionScope","getCollectionMembershipsForOperations","processActions","executeRegularAction","executeLoadJob","accumulateResultOrReturnError","createForwardingLogger","msg","post","tags","errorToInfo","err","sanitizeArg","WeakSet","workerEntryPath","ModuleNotFoundError","requestedVersion","isError","DuplicateModuleError","InvalidModuleError","DuplicateManifestError","DocumentModelRegistry","manifestsToRegister","BaseReadModelConfig","rebuildStateOnInit","BaseReadModel","consistencyTracker","commitOperations","rebuildStateForOperations","loadState","initializeState","saveState","updateConsistencyTracker","IndexerDatabase","KyselyDocumentIndexer","_db","handleAddRelationship","handleRemoveRelationship","handleUpdateRelationship","ReadModelCoordinator","preReady","postReady","chains","emitEmptyReadReady","runChain","indexWithTiming","emitReadModelIndexed","emitBatchCompleted","queueKeyFor","Database$2","KyselyDocumentView","REACTOR_SCHEMA","runMigrations","schema","getMigrationStatus","MigrationInfo","KyselySyncCursorStorage","KyselySyncRemoteStorage","GqlRequestChannelFactory","GqlResponseChannelFactory","IPollTimer","setDelegate","delegate","triggerNow","GqlChannelConfig","fetch","fetchFn","GqlRequestChannel","bufferedOutbox","channelId","pollTimer","abortController","lastPersistedInboxOrdinal","lastPersistedOutboxOrdinal","pushRetryTimer","isPushing","pendingDrain","connectionState","connectionStateCallbacks","transitionConnectionState","poll","handleRemoteDeadLetters","handlePollError","recoverFromChannelNotFound","pollSyncEnvelopes","touchRemoteChannel","attemptPush","schedulePushRetry","drainOutbox","classifyError","pushSyncOperations","getAuthorizationHeader","executeGraphQL","poller","GqlResponseChannel","PollTimerConfig","intervalMs","maxQueueDepth","backpressureCheckIntervalMs","startPaused","IntervalPollTimer","timer","running","consecutiveFailures","tick","scheduleNext","scheduleRetry","scheduleBackpressureRecheck","getIntervalMs","setIntervalMs","ms","envelopesToSyncOperations","envelope","OperationBatch","trimMailboxFromAckOrdinal","mailbox","batchOperationsByDocument","consolidateSyncOperations","syncOps","KeyframeValidationIssue","keyframeHash","replayedHash","SnapshotValidationIssue","snapshotHash","ValidationResult","isConsistent","keyframeIssues","snapshotIssues","RebuildResult","keyframesDeleted","scopesInvalidated","IDocumentIntegrityService","validateDocument","rebuildKeyframes","rebuildSnapshots","DocumentIntegrityService","discoverScopes","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":"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"}
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "@powerhousedao/shared/document-model";
2
2
  import Corestore from "corestore";
3
3
  import Hyperbee from "hyperbee";
4
- //#region ../reactor/dist/drive-container-types-BNpMlgT_.js
4
+ //#region ../reactor/dist/drive-container-types-CAhznKRr.js
5
5
  /**
6
6
  * Thrown when an operation with the same identity already exists in the store.
7
7
  */
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../reactor/dist/drive-container-types-BNpMlgT_.js","../src/hypercore-atomic-transaction.ts","../src/key-encoding.ts","../src/hypercore-operation-store.ts","../src/storage-manager.ts"],"sourcesContent":["import { n as ReactorEventTypes, t as EventBusAggregateError } from \"./types-CxSpmNGK.js\";\nimport { createPresignedHeader, defaultBaseState, deriveOperationId, isUndoRedo } from \"@powerhousedao/shared/document-model\";\nimport { v4 } from \"uuid\";\nimport { Migrator, sql } from \"kysely\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/shared/utils.ts\nfunction matchesScope(view = {}, scope) {\n\tif (view.scopes) return view.scopes.includes(scope);\n\treturn true;\n}\nfunction yieldToMain() {\n\tconst s = globalThis.scheduler;\n\tif (s?.yield) return s.yield();\n\treturn new Promise((resolve) => setTimeout(resolve, 0));\n}\nconst defaultAbortError = () => /* @__PURE__ */ new Error(\"Operation aborted\");\nfunction throwIfAborted(signal, makeError = defaultAbortError) {\n\tif (signal?.aborted) throw makeError();\n}\n/**\n* Validates PagingOptions and returns a normalized offset and limit.\n* Throws if the cursor is not empty and not a non-negative integer, or if\n* limit is less than 1. When `paging` is undefined, returns offset 0 and\n* the caller-supplied `defaultLimit`.\n*/\nfunction parsePagingOptions(paging, defaultLimit) {\n\tif (paging === void 0) return {\n\t\toffset: 0,\n\t\tlimit: defaultLimit\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\toffset: 0,\n\t\tlimit: paging.limit\n\t};\n\tconst parsed = Number(paging.cursor);\n\tif (!Number.isInteger(parsed) || parsed < 0) throw new Error(`Invalid paging cursor: ${JSON.stringify(paging.cursor)} (must be empty or a non-negative integer)`);\n\treturn {\n\t\toffset: parsed,\n\t\tlimit: paging.limit\n\t};\n}\n//#endregion\n//#region src/shared/errors.ts\n/**\n* Error thrown when attempting to access a deleted document.\n*/\nvar DocumentDeletedError = class DocumentDeletedError extends Error {\n\tdocumentId;\n\tdeletedAtUtcIso;\n\tconstructor(documentId, deletedAtUtcIso = null) {\n\t\tconst message = deletedAtUtcIso ? `Document ${documentId} was deleted at ${deletedAtUtcIso}` : `Document ${documentId} has been deleted`;\n\t\tsuper(message);\n\t\tthis.name = \"DocumentDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.deletedAtUtcIso = deletedAtUtcIso;\n\t\tError.captureStackTrace(this, DocumentDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentDeletedError\";\n\t}\n};\n/**\n* Error thrown when an operation has an invalid signature.\n*/\nvar InvalidSignatureError = class InvalidSignatureError extends Error {\n\tdocumentId;\n\treason;\n\tconstructor(documentId, reason) {\n\t\tsuper(`Invalid signature in document ${documentId}: ${reason}`);\n\t\tthis.name = \"InvalidSignatureError\";\n\t\tthis.documentId = documentId;\n\t\tthis.reason = reason;\n\t\tError.captureStackTrace(this, InvalidSignatureError);\n\t}\n};\n/**\n* Error thrown when attempting to downgrade a document version.\n*/\nvar DowngradeNotSupportedError$1 = class DowngradeNotSupportedError$1 extends Error {\n\tdocumentType;\n\tfromVersion;\n\ttoVersion;\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Downgrade not supported for ${documentType}: cannot upgrade from version ${fromVersion} to ${toVersion}`);\n\t\tthis.name = \"DowngradeNotSupportedError\";\n\t\tthis.documentType = documentType;\n\t\tthis.fromVersion = fromVersion;\n\t\tthis.toVersion = toVersion;\n\t\tError.captureStackTrace(this, DowngradeNotSupportedError$1);\n\t}\n};\n/**\n* Error thrown when a document is not found (no operations exist for the document ID).\n*/\nvar DocumentNotFoundError = class DocumentNotFoundError extends Error {\n\tdocumentId;\n\tconstructor(documentId) {\n\t\tsuper(`Document ${documentId} not found`);\n\t\tthis.name = \"DocumentNotFoundError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotFoundError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/registry/errors.ts\n/**\n* Error thrown when a document model module is not found in the registry.\n*/\nvar ModuleNotFoundError = class extends Error {\n\tdocumentType;\n\trequestedVersion;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model module not found for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"ModuleNotFoundError\";\n\t\tthis.documentType = documentType;\n\t\tthis.requestedVersion = version;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModuleNotFoundError\";\n\t}\n};\n/**\n* Error thrown when attempting to register a module that already exists.\n*/\nvar DuplicateModuleError = class extends Error {\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` (version ${version})` : \"\";\n\t\tsuper(`Document model module already registered for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"DuplicateModuleError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n\t}\n};\n/**\n* Error thrown when a module is invalid or malformed.\n*/\nvar InvalidModuleError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Invalid document model module: ${message}`);\n\t\tthis.name = \"InvalidModuleError\";\n\t}\n};\n/**\n* Error thrown when attempting to register an upgrade manifest that already exists.\n*/\nvar DuplicateManifestError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest already registered for type: ${documentType}`);\n\t\tthis.name = \"DuplicateManifestError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n\t}\n};\n/**\n* Error thrown when an upgrade manifest is not found.\n*/\nvar ManifestNotFoundError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest not found for type: ${documentType}`);\n\t\tthis.name = \"ManifestNotFoundError\";\n\t}\n};\n/**\n* Error thrown when attempting a downgrade operation.\n*/\nvar DowngradeNotSupportedError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Downgrade not supported for ${documentType}: cannot go from version ${fromVersion} to ${toVersion}`);\n\t\tthis.name = \"DowngradeNotSupportedError\";\n\t}\n};\n/**\n* Error thrown when a required upgrade transition is missing from the manifest.\n*/\nvar MissingUpgradeTransitionError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Missing upgrade transition for ${documentType}: v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"MissingUpgradeTransitionError\";\n\t}\n};\n/**\n* Error thrown when getUpgradeReducer is called with a non-single-step version increment.\n*/\nvar InvalidUpgradeStepError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Invalid upgrade step for ${documentType}: must be single version increment, got v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"InvalidUpgradeStepError\";\n\t}\n};\n//#endregion\n//#region src/cache/collection-membership-cache.ts\nvar CollectionMembershipCache = class CollectionMembershipCache {\n\tcache = /* @__PURE__ */ new Map();\n\tconstructor(operationIndex) {\n\t\tthis.operationIndex = operationIndex;\n\t}\n\twithScopedIndex(operationIndex) {\n\t\tconst scoped = new CollectionMembershipCache(operationIndex);\n\t\tscoped.cache = this.cache;\n\t\treturn scoped;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tconst result = {};\n\t\tconst missing = [];\n\t\tfor (const docId of documentIds) {\n\t\t\tconst cached = this.cache.get(docId);\n\t\t\tif (cached !== void 0) result[docId] = cached;\n\t\t\telse missing.push(docId);\n\t\t}\n\t\tif (missing.length > 0) {\n\t\t\tconst fromDb = await this.operationIndex.getCollectionsForDocuments(missing);\n\t\t\tfor (const docId of missing) {\n\t\t\t\tconst collections = fromDb[docId] ?? [];\n\t\t\t\tresult[docId] = collections;\n\t\t\t\tthis.cache.set(docId, collections);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tinvalidate(documentId) {\n\t\tthis.cache.delete(documentId);\n\t}\n};\n//#endregion\n//#region src/executor/util.ts\n/**\n* Creates a PHDocument from a CREATE_DOCUMENT action input.\n* Reconstructs the document header and initializes the base state.\n*\n* @param action - The CREATE_DOCUMENT action containing the document parameters\n* @returns A newly constructed PHDocument with initialized header and base state\n*/\nfunction createDocumentFromAction(action) {\n\tconst input = action.input;\n\tconst header = createPresignedHeader();\n\theader.id = input.documentId;\n\theader.documentType = input.model;\n\tif (input.signing) {\n\t\theader.createdAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.lastModifiedAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.sig = {\n\t\t\tpublicKey: input.signing.publicKey,\n\t\t\tnonce: input.signing.nonce\n\t\t};\n\t}\n\tif (input.slug !== void 0) header.slug = input.slug;\n\tif (!header.slug) header.slug = input.documentId;\n\tif (input.name !== void 0) header.name = input.name;\n\tif (input.branch !== void 0) header.branch = input.branch;\n\tif (input.meta !== void 0) header.meta = input.meta;\n\tif (input.protocolVersions !== void 0) header.protocolVersions = input.protocolVersions;\n\tconst baseState = defaultBaseState();\n\treturn {\n\t\theader,\n\t\toperations: {},\n\t\tstate: baseState,\n\t\tinitialState: baseState,\n\t\tclipboard: []\n\t};\n}\n/**\n* Applies an UPGRADE_DOCUMENT action to a document.\n* Handles all upgrade scenarios including initial upgrades, no-ops, and multi-step upgrades.\n*\n* Behavior based on fromVersion/toVersion:\n* - fromVersion === toVersion (and fromVersion > 0): No-op - return unchanged document\n* - fromVersion > toVersion: Throw DowngradeNotSupportedError\n* - All other cases: Apply upgradePath transitions (if provided), then apply initialState, set version\n*\n* The initialState from the action is always applied (if provided) to maintain backward\n* compatibility with the original implementation.\n*\n* @param document - The document to upgrade\n* @param action - The UPGRADE_DOCUMENT action\n* @param upgradePath - Optional pre-computed upgrade path for multi-step upgrades\n* @returns The upgraded document (unchanged if no-op)\n* @throws DowngradeNotSupportedError if attempting to downgrade\n*/\nfunction applyUpgradeDocumentAction(document, action, upgradePath) {\n\tconst fromVersion = action.input.fromVersion;\n\tconst toVersion = action.input.toVersion;\n\tif (fromVersion === toVersion && fromVersion > 0) return document;\n\tif (fromVersion > toVersion) throw new DowngradeNotSupportedError$1(document.header.documentType, fromVersion, toVersion);\n\tif (upgradePath) for (const transition of upgradePath) document = transition.upgradeReducer(document, action);\n\tapplyInitialState(document, action);\n\tdocument.state.document = {\n\t\t...document.state.document,\n\t\tversion: toVersion\n\t};\n\treturn document;\n}\nfunction applyInitialState(document, action) {\n\tconst input = action.input;\n\tconst newState = input.initialState || input.state;\n\tif (newState) {\n\t\tdocument.state = {\n\t\t\t...document.state,\n\t\t\t...newState\n\t\t};\n\t\tdocument.initialState = document.state;\n\t}\n}\n/**\n* Applies a DELETE_DOCUMENT action to a document.\n* Marks the document as deleted in the document scope state.\n*\n* @param document - The document to mark as deleted\n* @param action - The DELETE_DOCUMENT action\n* @returns The updated document (mutates in place and returns for convenience)\n*/\nfunction applyDeleteDocumentAction(document, action) {\n\tconst deletedAt = action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\tdocument.state = {\n\t\t...document.state,\n\t\tdocument: {\n\t\t\t...document.state.document,\n\t\t\tisDeleted: true,\n\t\t\tdeletedAtUtcIso: deletedAt\n\t\t}\n\t};\n\treturn document;\n}\n/**\n* Calculate the next operation index for a specific scope.\n* Each scope maintains its own independent index sequence.\n*\n* Per-scope indexing means:\n* - Each scope (document, global, local, etc.) has independent indexes\n* - Indexes start at 0 for each scope\n* - Different scopes can have operations with the same index value\n*\n* This function uses header.revision which is populated by the cache/storage layer\n* and contains the next available index for each scope. This design avoids requiring\n* the full operation history to be loaded, which is crucial for snapshot-based caching.\n*\n* @param document - The document whose header.revision to inspect\n* @param scope - The scope to calculate the next index for\n* @returns The next available index in the specified scope\n*/\nconst getNextIndexForScope = (document, scope) => {\n\treturn document.header.revision[scope] || 0;\n};\n/**\n* Creates an empty consistency token with no coordinates.\n* Used when a job is registered or fails without writing operations.\n*\n* @returns A consistency token with an empty coordinates array\n*/\nfunction createEmptyConsistencyToken() {\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates: []\n\t};\n}\n/**\n* Creates a consistency token from operations written during job execution.\n* Maps each operation to a consistency coordinate tracking (documentId, scope, branch, operationIndex).\n* If no operations are provided, returns an empty token.\n*\n* @param operationsWithContext - Array of operations with their execution context\n* @returns A consistency token representing all operations written\n*/\nfunction createConsistencyToken(operationsWithContext) {\n\tif (operationsWithContext.length === 0) return createEmptyConsistencyToken();\n\tconst coordinates = [];\n\tfor (let i = 0; i < operationsWithContext.length; i++) {\n\t\tconst opWithContext = operationsWithContext[i];\n\t\tcoordinates.push({\n\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\tscope: opWithContext.context.scope,\n\t\t\tbranch: opWithContext.context.branch,\n\t\t\toperationIndex: opWithContext.operation.index\n\t\t});\n\t}\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates\n\t};\n}\nfunction createOperation(action, index, skip, context) {\n\treturn {\n\t\tid: deriveOperationId(context.documentId, context.scope, context.branch, action.id),\n\t\tindex,\n\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\thash: \"\",\n\t\tskip,\n\t\taction\n\t};\n}\nfunction updateDocumentRevision(document, scope, operationIndex) {\n\tdocument.header.revision = {\n\t\t...document.header.revision,\n\t\t[scope]: operationIndex + 1\n\t};\n}\nfunction buildSuccessResult(job, operation, documentId, documentType, resultingState, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: true,\n\t\toperations: [operation],\n\t\toperationsWithContext: [{\n\t\t\toperation,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tdocumentType,\n\t\t\t\tresultingState,\n\t\t\t\tordinal: 0\n\t\t\t}\n\t\t}],\n\t\tduration: Date.now() - startTime\n\t};\n}\nfunction buildErrorResult(job, error, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: false,\n\t\terror,\n\t\tduration: Date.now() - startTime\n\t};\n}\n//#endregion\n//#region src/cache/lru/lru-tracker.ts\nvar LRUNode = class {\n\tkey;\n\tprev;\n\tnext;\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.prev = void 0;\n\t\tthis.next = void 0;\n\t}\n};\nvar LRUTracker = class {\n\tmap;\n\thead;\n\ttail;\n\tconstructor() {\n\t\tthis.map = /* @__PURE__ */ new Map();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\ttouch(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (node) this.moveToFront(node);\n\t\telse this.addToFront(key);\n\t}\n\tevict() {\n\t\tif (!this.tail) return;\n\t\tconst key = this.tail.key;\n\t\tthis.remove(key);\n\t\treturn key;\n\t}\n\tremove(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (!node) return;\n\t\tthis.removeNode(node);\n\t\tthis.map.delete(key);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\taddToFront(key) {\n\t\tconst node = new LRUNode(key);\n\t\tthis.map.set(key, node);\n\t\tif (!this.head) {\n\t\t\tthis.head = node;\n\t\t\tthis.tail = node;\n\t\t} else {\n\t\t\tnode.next = this.head;\n\t\t\tthis.head.prev = node;\n\t\t\tthis.head = node;\n\t\t}\n\t}\n\tmoveToFront(node) {\n\t\tif (node === this.head) return;\n\t\tthis.removeNode(node);\n\t\tnode.prev = void 0;\n\t\tnode.next = this.head;\n\t\tif (this.head) this.head.prev = node;\n\t\tthis.head = node;\n\t\tif (!this.tail) this.tail = node;\n\t}\n\tremoveNode(node) {\n\t\tif (node.prev) node.prev.next = node.next;\n\t\telse this.head = node.next;\n\t\tif (node.next) node.next.prev = node.prev;\n\t\telse this.tail = node.prev;\n\t}\n};\n//#endregion\n//#region src/cache/document-meta-cache.ts\n/**\n* In-memory document metadata cache with LRU eviction.\n*\n* Caches PHDocumentState per (documentId, branch) key. On cache miss,\n* rebuilds from document scope operations. Provides an explicit cross-scope\n* contract for accessing document scope metadata.\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n*/\nvar DocumentMetaCache = class DocumentMetaCache {\n\tcache;\n\tlruTracker;\n\toperationStore;\n\tconfig;\n\tconstructor(operationStore, config) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.config = { maxDocuments: config.maxDocuments };\n\t\tthis.cache = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStore(operationStore) {\n\t\tconst scoped = new DocumentMetaCache(operationStore, this.config);\n\t\tscoped.cache = this.cache;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\tasync getDocumentMeta(documentId, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\tthis.lruTracker.touch(key);\n\t\t\treturn cached;\n\t\t}\n\t\tconst meta = await this.rebuildLatest(documentId, branch, signal);\n\t\tthis.putDocumentMeta(documentId, branch, meta);\n\t\treturn meta;\n\t}\n\tasync rebuildAtRevision(documentId, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn this.rebuildFromOperations(documentId, branch, targetRevision, signal);\n\t}\n\tputDocumentMeta(documentId, branch, meta) {\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tif (!this.cache.has(key) && this.cache.size >= this.config.maxDocuments) {\n\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\tif (evictKey) this.cache.delete(evictKey);\n\t\t}\n\t\tthis.cache.set(key, structuredClone(meta));\n\t\tthis.lruTracker.touch(key);\n\t}\n\tinvalidate(documentId, branch) {\n\t\tlet evicted = 0;\n\t\tif (branch === void 0) {\n\t\t\tfor (const key of this.cache.keys()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = this.makeKey(documentId, branch);\n\t\t\tif (this.cache.has(key)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\tmakeKey(documentId, branch) {\n\t\treturn `${documentId}:${branch}`;\n\t}\n\tasync rebuildLatest(documentId, branch, signal) {\n\t\treturn this.rebuildFromOperations(documentId, branch, void 0, signal);\n\t}\n\tasync rebuildFromOperations(documentId, branch, targetRevision, signal) {\n\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, void 0, signal);\n\t\tif (docScopeOps.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\tconst createOp = docScopeOps.results[0];\n\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\tconst createAction = createOp.action;\n\t\tconst documentType = createAction.input.model;\n\t\tlet document = createDocumentFromAction(createAction);\n\t\tlet documentScopeRevision = 0;\n\t\tfor (const op of docScopeOps.results) {\n\t\t\tif (targetRevision !== void 0 && op.index > targetRevision) break;\n\t\t\tdocumentScopeRevision = op.index;\n\t\t\tif (op.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = op.action;\n\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction);\n\t\t\t} else if (op.action.type === \"DELETE_DOCUMENT\") document = applyDeleteDocumentAction(document, op.action);\n\t\t}\n\t\treturn {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType,\n\t\t\tdocumentScopeRevision: documentScopeRevision + 1\n\t\t};\n\t}\n};\n//#endregion\n//#region src/cache/kysely-operation-index.ts\nvar KyselyOperationIndexTxn = class {\n\tcollections = [];\n\tcollectionMemberships = [];\n\tcollectionRemovals = [];\n\toperations = [];\n\tcreateCollection(collectionId) {\n\t\tthis.collections.push(collectionId);\n\t}\n\taddToCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"addToCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionMemberships.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\tremoveFromCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"removeFromCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionRemovals.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\twrite(operations) {\n\t\tthis.operations.push(...operations);\n\t}\n\tgetCollections() {\n\t\treturn this.collections;\n\t}\n\tgetCollectionMembershipRecords() {\n\t\treturn this.collectionMemberships;\n\t}\n\tgetCollectionRemovals() {\n\t\treturn this.collectionRemovals;\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\nvar KyselyOperationIndex = class KyselyOperationIndex {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationIndex(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tstart() {\n\t\treturn new KyselyOperationIndexTxn();\n\t}\n\tasync commit(txn, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst kyselyTxn = txn;\n\t\tif (this.trx) return this.executeCommit(this.trx, kyselyTxn);\n\t\tlet resultOrdinals = [];\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tresultOrdinals = await this.executeCommit(trx, kyselyTxn);\n\t\t});\n\t\treturn resultOrdinals;\n\t}\n\tasync executeCommit(trx, kyselyTxn) {\n\t\tconst collections = kyselyTxn.getCollections();\n\t\tconst memberships = kyselyTxn.getCollectionMembershipRecords();\n\t\tconst removals = kyselyTxn.getCollectionRemovals();\n\t\tconst operations = kyselyTxn.getOperations();\n\t\tif (collections.length > 0) {\n\t\t\tconst collectionRows = collections.map((collectionId) => ({\n\t\t\t\tdocumentId: collectionId,\n\t\t\t\tcollectionId,\n\t\t\t\tjoinedOrdinal: BigInt(0),\n\t\t\t\tleftOrdinal: null\n\t\t\t}));\n\t\t\tawait trx.insertInto(\"document_collections\").values(collectionRows).onConflict((oc) => oc.doNothing()).execute();\n\t\t}\n\t\tlet operationOrdinals = [];\n\t\tif (operations.length > 0) {\n\t\t\tconst operationRows = operations.map((op) => ({\n\t\t\t\topId: op.id || \"\",\n\t\t\t\tdocumentId: op.documentId,\n\t\t\t\tdocumentType: op.documentType,\n\t\t\t\tscope: op.scope,\n\t\t\t\tbranch: op.branch,\n\t\t\t\ttimestampUtcMs: op.timestampUtcMs,\n\t\t\t\tindex: op.index,\n\t\t\t\tskip: op.skip,\n\t\t\t\thash: op.hash,\n\t\t\t\taction: op.action,\n\t\t\t\tsourceRemote: op.sourceRemote\n\t\t\t}));\n\t\t\toperationOrdinals = (await trx.insertInto(\"operation_index_operations\").values(operationRows).returning(\"ordinal\").execute()).map((row) => row.ordinal);\n\t\t}\n\t\tif (memberships.length > 0) for (const m of memberships) {\n\t\t\tconst ordinal = operationOrdinals[m.operationIndex];\n\t\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\t\tdocumentId: m.documentId,\n\t\t\t\tcollectionId: m.collectionId,\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t})).execute();\n\t\t}\n\t\tif (removals.length > 0) for (const r of removals) {\n\t\t\tconst ordinal = operationOrdinals[r.operationIndex];\n\t\t\tawait trx.updateTable(\"document_collections\").set({ leftOrdinal: BigInt(ordinal) }).where(\"collectionId\", \"=\", r.collectionId).where(\"documentId\", \"=\", r.documentId).where(\"leftOrdinal\", \"is\", null).execute();\n\t\t}\n\t\treturn operationOrdinals;\n\t}\n\tasync find(collectionId, cursor, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst outerCursor = cursor ?? -1;\n\t\tconst pagingCursorOrdinal = paging?.cursor !== void 0 ? Number.parseInt(paging.cursor, 10) : -1;\n\t\tconst buildBranch = (kind) => {\n\t\t\tlet qb = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").selectAll(\"oi\").select([\"dc.documentId\", \"dc.collectionId\"]).where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`);\n\t\t\tif (kind === \"joiner\") qb = qb.where(\"dc.joinedOrdinal\", \">\", BigInt(outerCursor)).where(\"oi.ordinal\", \"<=\", outerCursor);\n\t\t\telse qb = qb.where(\"oi.ordinal\", \">\", outerCursor);\n\t\t\tqb = qb.where(\"oi.ordinal\", \">\", pagingCursorOrdinal);\n\t\t\tif (view?.branch) qb = qb.where(\"oi.branch\", \"=\", view.branch);\n\t\t\tif (view?.scopes && view.scopes.length > 0) qb = qb.where(\"oi.scope\", \"in\", view.scopes);\n\t\t\tif (view?.excludeSourceRemote) qb = qb.where(\"oi.sourceRemote\", \"!=\", view.excludeSourceRemote);\n\t\t\treturn qb;\n\t\t};\n\t\tlet unionQuery = buildBranch(\"joiner\").unionAll(buildBranch(\"newOps\")).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.limit) unionQuery = unionQuery.limit(paging.limit + 1);\n\t\tconst rows = await unionQuery.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.find(collectionId, cursor, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync get(documentId, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"ordinal\", \"asc\");\n\t\tif (view?.branch) query = query.where(\"branch\", \"=\", view.branch);\n\t\tif (view?.scopes && view.scopes.length > 0) query = query.where(\"scope\", \"in\", view.scopes);\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.get(documentId, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync getSinceOrdinal(ordinal, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \">\", ordinal).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationWithContext(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getSinceOrdinal(ordinal, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: {\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\taction: row.action,\n\t\t\t\tid: row.opId\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.ordinal\n\t\t\t}\n\t\t};\n\t}\n\trowToOperationIndexEntry(row) {\n\t\treturn {\n\t\t\tordinal: row.ordinal,\n\t\t\tdocumentId: row.documentId,\n\t\t\tdocumentType: row.documentType,\n\t\t\tbranch: row.branch,\n\t\t\tscope: row.scope,\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\taction: row.action,\n\t\t\tid: row.opId,\n\t\t\tsourceRemote: row.sourceRemote\n\t\t};\n\t}\n\tasync getLatestTimestampForCollection(collectionId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"oi.timestampUtcMs\").where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`).orderBy(\"oi.ordinal\", \"desc\").limit(1).executeTakeFirst())?.timestampUtcMs ?? null;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tif (documentIds.length === 0) return {};\n\t\tconst rows = await this.queryExecutor.selectFrom(\"document_collections\").select([\"documentId\", \"collectionId\"]).where(\"documentId\", \"in\", documentIds).where(\"leftOrdinal\", \"is\", null).execute();\n\t\tconst result = {};\n\t\tfor (const row of rows) {\n\t\t\tif (!(row.documentId in result)) result[row.documentId] = [];\n\t\t\tresult[row.documentId].push(row.collectionId);\n\t\t}\n\t\treturn result;\n\t}\n};\n//#endregion\n//#region src/cache/buffer/ring-buffer.ts\n/**\n* RingBuffer is a generic circular buffer implementation that stores a fixed number\n* of items. When the buffer is full, new items overwrite the oldest items.\n*\n* This implementation maintains O(1) time complexity for push operations and provides\n* items in chronological order (oldest to newest) via getAll().\n*\n* @template T - The type of items stored in the buffer\n*/\nvar RingBuffer = class {\n\tbuffer;\n\thead = 0;\n\tsize = 0;\n\tcapacity;\n\tconstructor(capacity) {\n\t\tif (capacity <= 0) throw new Error(\"Ring buffer capacity must be greater than 0\");\n\t\tthis.capacity = capacity;\n\t\tthis.buffer = new Array(capacity);\n\t}\n\t/**\n\t* Adds an item to the buffer. If the buffer is full, overwrites the oldest item.\n\t*\n\t* @param item - The item to add\n\t*/\n\tpush(item) {\n\t\tconst index = (this.head + this.size) % this.capacity;\n\t\tif (this.size < this.capacity) {\n\t\t\tthis.buffer[index] = item;\n\t\t\tthis.size++;\n\t\t} else {\n\t\t\tthis.buffer[this.head] = item;\n\t\t\tthis.head = (this.head + 1) % this.capacity;\n\t\t}\n\t}\n\t/**\n\t* Returns all items in the buffer in chronological order (oldest to newest).\n\t*\n\t* @returns Array of items in insertion order\n\t*/\n\tgetAll() {\n\t\tif (this.size === 0) return [];\n\t\tconst result = [];\n\t\tfor (let i = 0; i < this.size; i++) {\n\t\t\tconst index = (this.head + i) % this.capacity;\n\t\t\tresult.push(this.buffer[index]);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Clears all items from the buffer.\n\t*/\n\tclear() {\n\t\tthis.buffer = new Array(this.capacity);\n\t\tthis.head = 0;\n\t\tthis.size = 0;\n\t}\n\t/**\n\t* Gets the current number of items in the buffer.\n\t*/\n\tget length() {\n\t\treturn this.size;\n\t}\n};\n//#endregion\n//#region src/cache/kysely-write-cache.ts\nfunction extractModuleVersion(doc) {\n\tconst v = doc.state.document.version;\n\treturn v === 0 ? void 0 : v;\n}\n/**\n* In-memory write cache with keyframe persistence for PHDocuments.\n*\n* Caches document snapshots in ring buffers with LRU eviction. On cache miss,\n* rebuilds documents from nearest keyframe or full operation history.\n*\n* **Performance Characteristics:**\n* - Cache hit: O(1) lookup in ring buffer\n* - Cold miss: O(n) where n is total operation count, or O(k) where k is operations since keyframe\n* - Warm miss: O(m) where m is operations since cached revision\n* - Eviction: O(1) for LRU tracking and removal\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n* External synchronization required for concurrent access across multiple executors.\n*\n* **Example:**\n* ```typescript\n* const cache = new KyselyWriteCache(\n* keyframeStore,\n* operationStore,\n* registry,\n* { maxDocuments: 1000, ringBufferSize: 10, keyframeInterval: 10 }\n* );\n*\n* await cache.startup();\n*\n* // Retrieve or rebuild document\n* const doc = await cache.getState(docId, docType, scope, branch, revision);\n*\n* // Cache result after job execution\n* cache.putState(docId, docType, scope, branch, newRevision, updatedDoc);\n*\n* await cache.shutdown();\n* ```\n*/\nvar KyselyWriteCache = class KyselyWriteCache {\n\tstreams;\n\tlruTracker;\n\tkeyframeStore;\n\toperationStore;\n\tregistry;\n\tconfig;\n\tconstructor(keyframeStore, operationStore, registry, config) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.registry = registry;\n\t\tthis.config = {\n\t\t\tmaxDocuments: config.maxDocuments,\n\t\t\tringBufferSize: config.ringBufferSize,\n\t\t\tkeyframeInterval: config.keyframeInterval\n\t\t};\n\t\tthis.streams = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStores(operationStore, keyframeStore) {\n\t\tconst scoped = new KyselyWriteCache(keyframeStore, operationStore, this.registry, this.config);\n\t\tscoped.streams = this.streams;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\t/**\n\t* Initializes the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Shuts down the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Retrieves document state at a specific revision from cache or rebuilds it.\n\t*\n\t* Cache hit path: Returns cached snapshot if available (O(1))\n\t* Warm miss path: Rebuilds from cached base revision + incremental ops\n\t* Cold miss path: Rebuilds from keyframe or from scratch using all operations\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param targetRevision - The target revision, or undefined for newest\n\t* @param signal - Optional abort signal to cancel the operation\n\t* @returns The document at the target revision\n\t* @throws {Error} \"Operation aborted\" if signal is aborted\n\t* @throws {ModuleNotFoundError} If document type not registered in registry\n\t* @throws {Error} \"Failed to rebuild document\" if operation store fails\n\t* @throws {Error} If reducer throws during operation application\n\t* @throws {Error} If document serialization fails\n\t*/\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.streams.get(streamKey);\n\t\tif (stream) {\n\t\t\tconst snapshots = stream.ringBuffer.getAll();\n\t\t\tif (targetRevision === void 0) {\n\t\t\t\tif (snapshots.length > 0) {\n\t\t\t\t\tconst newest = snapshots[snapshots.length - 1];\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn newest.document;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst exactMatch = snapshots.find((s) => s.revision === targetRevision);\n\t\t\t\tif (exactMatch) {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn exactMatch.document;\n\t\t\t\t}\n\t\t\t\tconst newestOlder = this.findNearestOlderSnapshot(snapshots, targetRevision);\n\t\t\t\tif (newestOlder) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newestOlder.document, newestOlder.revision, documentId, scope, branch, targetRevision, signal);\n\t\t\t\t\tthis.putState(documentId, scope, branch, targetRevision, document);\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst document = await this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tlet revision = targetRevision;\n\t\tif (revision === void 0) revision = document.header.revision[scope] || 0;\n\t\tthis.putState(documentId, scope, branch, revision, document);\n\t\treturn document;\n\t}\n\t/**\n\t* Stores a document snapshot in the cache at a specific revision.\n\t*\n\t* The cached document is a shallow copy of the input with its operation history\n\t* truncated to the last operation per scope and its clipboard cleared. This keeps\n\t* memory use and copy costs constant regardless of operation count. Consumers of\n\t* getState() must not rely on the full operation history being present; the only\n\t* guaranteed invariant is that operations[scope].at(-1) reflects the latest\n\t* operation index for each scope.\n\t*\n\t* Updates LRU tracker and may evict least recently used stream if at capacity.\n\t* Asynchronously persists keyframes at configured intervals (fire-and-forget).\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param revision - The revision number\n\t* @param document - The document to cache\n\t* @throws {Error} If document serialization fails\n\t*/\n\tputState(documentId, scope, branch, revision, document) {\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.getOrCreateStream(streamKey);\n\t\tconst snapshot = {\n\t\t\trevision,\n\t\t\tdocument: {\n\t\t\t\t...document,\n\t\t\t\toperations: Object.fromEntries(Object.entries(document.operations).map(([k, ops]) => [k, ops.length ? [ops.at(-1)] : []])),\n\t\t\t\tclipboard: []\n\t\t\t}\n\t\t};\n\t\tstream.ringBuffer.push(snapshot);\n\t\tif (this.isKeyframeRevision(revision)) this.keyframeStore.putKeyframe(documentId, scope, branch, revision, {\n\t\t\t...document,\n\t\t\toperations: {},\n\t\t\tclipboard: []\n\t\t}).catch((err) => {\n\t\t\tconsole.error(`Failed to persist keyframe ${documentId}@${revision}:`, err);\n\t\t});\n\t}\n\t/**\n\t* Invalidates cached document streams.\n\t*\n\t* Supports three invalidation scopes:\n\t* - Document-level: invalidate(documentId) - removes all streams for document\n\t* - Scope-level: invalidate(documentId, scope) - removes all branches for scope\n\t* - Stream-level: invalidate(documentId, scope, branch) - removes specific stream\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - Optional scope to narrow invalidation\n\t* @param branch - Optional branch to narrow invalidation (requires scope)\n\t* @returns The number of streams evicted\n\t*/\n\tinvalidate(documentId, scope, branch) {\n\t\tlet evicted = 0;\n\t\tif (scope === void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:${scope}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch !== void 0) {\n\t\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\t\tif (this.streams.has(key)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\t/**\n\t* Clears the entire cache, removing all cached document streams.\n\t* Resets LRU tracking state. This operation always succeeds.\n\t*/\n\tclear() {\n\t\tthis.streams.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\t/**\n\t* Retrieves a specific stream for a document. Exposed on the implementation\n\t* for testing, but not on the interface.\n\t*\n\t* @internal\n\t*/\n\tgetStream(documentId, scope, branch) {\n\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\treturn this.streams.get(key);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (targetRevision === Number.MAX_SAFE_INTEGER || targetRevision <= 0) return;\n\t\treturn this.keyframeStore.findNearestKeyframe(documentId, scope, branch, targetRevision, signal);\n\t}\n\tasync coldMissRebuild(documentId, scope, branch, targetRevision, signal) {\n\t\tconst effectiveTargetRevision = targetRevision || Number.MAX_SAFE_INTEGER;\n\t\tconst keyframe = await this.findNearestKeyframe(documentId, scope, branch, effectiveTargetRevision, signal);\n\t\tlet document;\n\t\tlet startRevision;\n\t\tlet documentType;\n\t\tif (keyframe) {\n\t\t\tdocument = keyframe.document;\n\t\t\tstartRevision = keyframe.revision;\n\t\t\tdocumentType = keyframe.document.header.documentType;\n\t\t} else {\n\t\t\tstartRevision = -1;\n\t\t\tconst createOpResult = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 1\n\t\t\t}, signal);\n\t\t\tif (createOpResult.results.length === 0) throw new Error(`Failed to rebuild document ${documentId}: no CREATE_DOCUMENT operation found in document scope`);\n\t\t\tconst createOp = createOpResult.results[0];\n\t\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Failed to rebuild document ${documentId}: first operation in document scope must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\t\tconst documentCreateAction = createOp.action;\n\t\t\tdocumentType = documentCreateAction.input.model;\n\t\t\tif (!documentType) throw new Error(`Failed to rebuild document ${documentId}: CREATE_DOCUMENT action missing model in input`);\n\t\t\tdocument = createDocumentFromAction(documentCreateAction);\n\t\t\tlet docModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, 0, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOps.results) {\n\t\t\t\tif (operation.index === 0) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction);\n\t\t\t\t\tdocModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\") applyDeleteDocumentAction(document, operation.action);\n\t\t\t\telse {\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = docModule.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst module = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\tlet cursor = void 0;\n\t\tconst pageSize = 100;\n\t\tlet hasMorePages;\n\t\tdo {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst paging = {\n\t\t\t\tcursor: cursor || \"0\",\n\t\t\t\tlimit: pageSize\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await this.operationStore.getSince(documentId, scope, branch, startRevision, void 0, paging, signal);\n\t\t\t\tfor (const operation of result.results) {\n\t\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = module.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst reachedTarget = targetRevision !== void 0 && result.results.some((op) => op.index >= targetRevision);\n\t\t\t\thasMorePages = Boolean(result.nextCursor) && !reachedTarget;\n\t\t\t\tif (hasMorePages) cursor = result.nextCursor;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t}\n\t\t} while (hasMorePages);\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tasync warmMissRebuild(baseDocument, baseRevision, documentId, scope, branch, targetRevision, signal) {\n\t\tconst documentType = baseDocument.header.documentType;\n\t\tconst module = this.registry.getModule(documentType);\n\t\tlet document = baseDocument;\n\t\ttry {\n\t\t\tconst pagedResults = await this.operationStore.getSince(documentId, scope, branch, baseRevision, void 0, void 0, signal);\n\t\t\tfor (const operation of pagedResults.results) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\tdocument = module.reducer(document, operation.action, void 0, {\n\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\tprotocolVersion\n\t\t\t\t});\n\t\t\t\tif (targetRevision !== void 0 && operation.index === targetRevision) break;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t}\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tfindNearestOlderSnapshot(snapshots, targetRevision) {\n\t\tlet nearest = void 0;\n\t\tfor (const snapshot of snapshots) if (snapshot.revision < targetRevision) {\n\t\t\tif (!nearest || snapshot.revision > nearest.revision) nearest = snapshot;\n\t\t}\n\t\treturn nearest;\n\t}\n\tmakeStreamKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\tgetOrCreateStream(key) {\n\t\tlet stream = this.streams.get(key);\n\t\tif (!stream) {\n\t\t\tif (this.streams.size >= this.config.maxDocuments) {\n\t\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\t\tif (evictKey) this.streams.delete(evictKey);\n\t\t\t}\n\t\t\tstream = {\n\t\t\t\tkey,\n\t\t\t\tringBuffer: new RingBuffer(this.config.ringBufferSize)\n\t\t\t};\n\t\t\tthis.streams.set(key, stream);\n\t\t}\n\t\tthis.lruTracker.touch(key);\n\t\treturn stream;\n\t}\n\tisKeyframeRevision(revision) {\n\t\treturn revision > 0 && revision % this.config.keyframeInterval === 0;\n\t}\n};\n//#endregion\n//#region src/events/event-bus.ts\nvar EventBus = class {\n\teventTypeToSubscribers = /* @__PURE__ */ new Map();\n\tsubscribe(type, subscriber) {\n\t\tlet list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis.eventTypeToSubscribers.set(type, list);\n\t\t}\n\t\tlist.push(subscriber);\n\t\tlet done = false;\n\t\treturn () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tconst arr = this.eventTypeToSubscribers.get(type);\n\t\t\tif (!arr) return;\n\t\t\tconst idx = arr.indexOf(subscriber);\n\t\t\tif (idx !== -1) arr.splice(idx, 1);\n\t\t\tif (arr.length === 0) this.eventTypeToSubscribers.delete(type);\n\t\t};\n\t}\n\tasync emit(type, data) {\n\t\tconst list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list || list.length === 0) return;\n\t\tconst snapshot = list.slice();\n\t\tconst errors = [];\n\t\tfor (const fn of snapshot) try {\n\t\t\tawait Promise.resolve(fn(type, data));\n\t\t} catch (err) {\n\t\t\terrors.push(err);\n\t\t}\n\t\tif (errors.length > 0) throw new EventBusAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/executor/execution-scope.ts\nvar DefaultExecutionScope = class {\n\tconstructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn fn({\n\t\t\toperationStore: this.operationStore,\n\t\t\toperationIndex: this.operationIndex,\n\t\t\twriteCache: this.writeCache,\n\t\t\tdocumentMetaCache: this.documentMetaCache,\n\t\t\tcollectionMembershipCache: this.collectionMembershipCache\n\t\t});\n\t}\n};\nvar KyselyExecutionScope = class {\n\tconstructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.db = db;\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn this.db.transaction().execute(async (trx) => {\n\t\t\tconst scopedOperationStore = this.operationStore.withTransaction(trx);\n\t\t\tconst scopedOperationIndex = this.operationIndex.withTransaction(trx);\n\t\t\tconst scopedKeyframeStore = this.keyframeStore.withTransaction(trx);\n\t\t\treturn fn({\n\t\t\t\toperationStore: scopedOperationStore,\n\t\t\t\toperationIndex: scopedOperationIndex,\n\t\t\t\twriteCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),\n\t\t\t\tdocumentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),\n\t\t\t\tcollectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex)\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/utils/reshuffle.ts\nconst STRICT_ORDER_ACTION_TYPES = new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\n/**\n* Reshuffles operations by timestamp, then applies deterministic tie-breaking.\n* Used for merging concurrent operations from different branches.\n*\n* For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),\n* logical index (index - skip) is prioritized to preserve causal replay order.\n*\n* For other actions, action ID is prioritized to ensure a canonical cross-reactor order\n* for concurrent operations that may have diverged local indices due to prior reshuffles.\n* Logical index and operation ID are then used as deterministic tie-breakers.\n*\n* Example:\n* [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n* GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n* Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n* Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n* merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n*/\nfunction reshuffleByTimestamp(startIndex, opsA, opsB) {\n\treturn [...opsA, ...opsB].sort((a, b) => {\n\t\tconst timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();\n\t\tif (timestampDiff !== 0) return timestampDiff;\n\t\tconst shouldPrioritizeLogicalIndex = STRICT_ORDER_ACTION_TYPES.has(a.action?.type ?? \"\") || STRICT_ORDER_ACTION_TYPES.has(b.action?.type ?? \"\");\n\t\tconst logicalIndexDiff = a.index - a.skip - (b.index - b.skip);\n\t\tif (shouldPrioritizeLogicalIndex) {\n\t\t\tif (logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\t}\n\t\tconst actionIdDiff = (a.action?.id ?? \"\").localeCompare(b.action?.id ?? \"\");\n\t\tif (actionIdDiff !== 0) return actionIdDiff;\n\t\tif (!shouldPrioritizeLogicalIndex && logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\treturn a.id.localeCompare(b.id);\n\t}).map((op, i) => ({\n\t\t...op,\n\t\tindex: startIndex.index + i,\n\t\tskip: i === 0 ? startIndex.skip : 0\n\t}));\n}\n//#endregion\n//#region src/cache/operation-index-types.ts\nfunction driveCollectionId(branch, driveId) {\n\treturn `drive.${branch}.${driveId}`;\n}\n//#endregion\n//#region src/executor/document-action-handler.ts\nvar DocumentActionHandler = class {\n\tconstructor(registry, logger, driveContainerTypes) {\n\t\tthis.registry = registry;\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t}\n\tasync execute(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tswitch (action.type) {\n\t\t\tcase \"CREATE_DOCUMENT\": return this.executeCreate(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"DELETE_DOCUMENT\": return this.executeDelete(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPGRADE_DOCUMENT\": return this.executeUpgrade(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"ADD_RELATIONSHIP\": return this.executeAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"REMOVE_RELATIONSHIP\": return this.executeRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPDATE_RELATIONSHIP\": return this.executeUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tdefault: return buildErrorResult(job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), startTime);\n\t\t}\n\t}\n\tasync executeCreate(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tif (job.scope !== \"document\") return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in \"document\" scope, got \"${job.scope}\"`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst document = createDocumentFromAction(action);\n\t\tlet operation = createOperation(action, 0, skip, {\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(document.header.id, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (this.driveContainerTypes.has(document.header.documentType)) {\n\t\t\tconst collectionId = driveCollectionId(job.branch, document.header.id);\n\t\t\tindexTxn.createCollection(collectionId);\n\t\t\tindexTxn.addToCollection(collectionId, document.header.id);\n\t\t}\n\t\tstores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeDelete(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"DELETE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tlet operation = createOperation(action, getNextIndexForScope(document, job.scope), 0, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tapplyDeleteDocumentAction(document, action);\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\tdocument: document.state.document\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeUpgrade(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"UPGRADE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tconst fromVersion = input.fromVersion;\n\t\tconst toVersion = input.toVersion;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\tlet upgradePath;\n\t\tif (fromVersion > 0 && fromVersion < toVersion) try {\n\t\t\tupgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (fromVersion === toVersion && fromVersion > 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\ttry {\n\t\t\tdocument = applyUpgradeDocumentAction(document, action, upgradePath);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\texecuteAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"ADD_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error(\"ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)\") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = driveCollectionId(j.branch, input.sourceId);\n\t\t\t\ttxn.addToCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"REMOVE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = driveCollectionId(j.branch, input.sourceId);\n\t\t\t\ttxn.removeFromCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"UPDATE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, null);\n\t}\n\tasync withRelationshipAction(actionTypeName, job, action, startTime, indexTxn, stores, sourceRemote, signal, preValidate, postWrite) {\n\t\tif (job.scope !== \"document\") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in \"document\" scope, got \"${job.scope}\"`), startTime);\n\t\tconst input = action.input;\n\t\tif (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);\n\t\tif (preValidate !== null) {\n\t\t\tconst validationError = preValidate(input);\n\t\t\tif (validationError !== null) return buildErrorResult(job, validationError, startTime);\n\t\t}\n\t\tlet sourceDoc;\n\t\ttry {\n\t\t\tsourceDoc = await stores.writeCache.getState(input.sourceId, \"document\", job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, getNextIndexForScope(sourceDoc, job.scope), 0, {\n\t\t\tdocumentId: input.sourceId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst writeResult = await this.writeOperationToStore(input.sourceId, sourceDoc.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tsourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\t\tupdateDocumentRevision(sourceDoc, job.scope, operation.index);\n\t\tsourceDoc.operations = {\n\t\t\t...sourceDoc.operations,\n\t\t\t[job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tconst scopeState = sourceDoc.state[job.scope];\n\t\tconst resultingStateObj = {\n\t\t\theader: structuredClone(sourceDoc.header),\n\t\t\t[job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tstores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (postWrite !== null) postWrite({\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsourceDoc,\n\t\t\tinput,\n\t\t\tjob\n\t\t});\n\t\tstores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {\n\t\t\tstate: sourceDoc.state.document,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);\n\t}\n\tasync writeOperationToStore(documentId, documentType, scope, branch, operation, job, startTime, stores, signal) {\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(operation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", operation, error);\n\t\t\tstores.writeCache.invalidate(documentId, scope, branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\treturn storedOperations;\n\t}\n};\n//#endregion\n//#region src/executor/signature-verifier.ts\nvar SignatureVerifier = class {\n\tconstructor(verifier) {\n\t\tthis.verifier = verifier;\n\t}\n\tasync verifyActions(documentId, branch, actions) {\n\t\tif (!this.verifier) return;\n\t\tfor (const action of actions) {\n\t\t\tconst signer = action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Action ${action.id} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tconst tempOperation = {\n\t\t\t\t\tid: deriveOperationId(documentId, action.scope, branch, action.id),\n\t\t\t\t\tindex: 0,\n\t\t\t\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\t\thash: \"\",\n\t\t\t\t\tskip: 0,\n\t\t\t\t\taction\n\t\t\t\t};\n\t\t\t\tisValid = await this.verifier(tempOperation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Action ${action.id} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Action ${action.id} signature verification returned false`);\n\t\t}\n\t}\n\tasync verifyOperations(documentId, operations) {\n\t\tif (!this.verifier) return;\n\t\tfor (let i = 0; i < operations.length; i++) {\n\t\t\tconst operation = operations[i];\n\t\t\tconst signer = operation.action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tisValid = await this.verifier(operation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} signature verification returned false`);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/executor/simple-job-executor.ts\nconst MAX_SKIP_THRESHOLD = 1e3;\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\nfunction isValidISOTimestamp(value) {\n\tif (!ISO_TIMESTAMP_REGEX.test(value)) return false;\n\treturn !isNaN(new Date(value).getTime());\n}\nconst documentScopeActions = [\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\"\n];\n/**\n* Simple job executor that processes a job by applying actions through document model reducers.\n*/\nvar SimpleJobExecutor = class {\n\tconfig;\n\tsignatureVerifierModule;\n\tdocumentActionHandler;\n\texecutionScope;\n\tconstructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, signatureVerifier, executionScope) {\n\t\tthis.logger = logger;\n\t\tthis.registry = registry;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.writeCache = writeCache;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.config = {\n\t\t\tmaxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,\n\t\t\tmaxConcurrency: config.maxConcurrency ?? 1,\n\t\t\tjobTimeoutMs: config.jobTimeoutMs ?? 3e4,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs ?? 100,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,\n\t\t\tyieldDeadlineMs: config.yieldDeadlineMs ?? 50\n\t\t};\n\t\tthis.signatureVerifierModule = new SignatureVerifier(signatureVerifier);\n\t\tthis.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes);\n\t\tthis.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);\n\t}\n\t/**\n\t* Execute a single job by applying all its actions through the appropriate reducers.\n\t* Actions are processed sequentially in order.\n\t*/\n\tasync executeJob(job, signal) {\n\t\tconst startTime = Date.now();\n\t\tconst touchedCacheEntries = [];\n\t\tlet pendingEvent;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.executionScope.run(async (stores) => {\n\t\t\t\tconst indexTxn = stores.operationIndex.start();\n\t\t\t\tif (job.kind === \"load\") {\n\t\t\t\t\tconst loadResult = await this.executeLoadJob(job, startTime, indexTxn, stores, signal);\n\t\t\t\t\tif (loadResult.success && loadResult.operationsWithContext) {\n\t\t\t\t\t\tfor (const owc of loadResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\t\t\tfor (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\t\tconst collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};\n\t\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\t\toperations: loadResult.operationsWithContext,\n\t\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn loadResult;\n\t\t\t\t}\n\t\t\t\tconst actionResult = await this.processActions(job, job.actions, startTime, indexTxn, stores, void 0, void 0, \"\", signal);\n\t\t\t\tif (!actionResult.success) return {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionResult.error,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) for (const owc of actionResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t});\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) {\n\t\t\t\t\tfor (let i = 0; i < actionResult.operationsWithContext.length; i++) actionResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(actionResult.operationsWithContext, stores);\n\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\toperations: actionResult.operationsWithContext,\n\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toperations: actionResult.generatedOperations,\n\t\t\t\t\toperationsWithContext: actionResult.operationsWithContext,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tfor (const entry of touchedCacheEntries) {\n\t\t\t\tthis.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\t\t\tthis.documentMetaCache.invalidate(entry.documentId, entry.branch);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (pendingEvent) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Event : @Error\", pendingEvent, error);\n\t\t});\n\t\treturn result;\n\t}\n\tasync getCollectionMembershipsForOperations(operations, stores) {\n\t\tconst documentIds = [...new Set(operations.map((op) => op.context.documentId))];\n\t\treturn stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t}\n\tasync processActions(job, actions, startTime, indexTxn, stores, skipValues, sourceOperations, sourceRemote = \"\", signal) {\n\t\tconst generatedOperations = [];\n\t\tconst operationsWithContext = [];\n\t\ttry {\n\t\t\tawait this.signatureVerifierModule.verifyActions(job.documentId, job.branch, actions);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t};\n\t\t}\n\t\tfor (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {\n\t\t\tsuccess: false,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${action.timestampUtcMs}\" on action ${action.type} (id: ${action.id})`)\n\t\t};\n\t\tlet lastYield = performance.now();\n\t\tfor (let actionIndex = 0; actionIndex < actions.length; actionIndex++) {\n\t\t\tconst action = actions[actionIndex];\n\t\t\tconst skip = skipValues?.[actionIndex] ?? 0;\n\t\t\tconst sourceOperation = sourceOperations?.[actionIndex];\n\t\t\tconst result = documentScopeActions.includes(action.type) ? await this.documentActionHandler.execute(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal) : await this.executeRegularAction(job, action, startTime, indexTxn, stores, skip, sourceOperation, sourceRemote, signal);\n\t\t\tconst error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (signal?.aborted) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tgeneratedOperations,\n\t\t\t\t\toperationsWithContext,\n\t\t\t\t\terror: /* @__PURE__ */ new Error(\"Aborted\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext\n\t\t};\n\t}\n\tasync executeRegularAction(job, action, startTime, indexTxn, stores, skip = 0, sourceOperation, sourceRemote = \"\", signal) {\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tif (isUndoRedo(action) || action.type === \"PRUNE\" || action.type === \"NOOP\" && skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet module;\n\t\ttry {\n\t\t\tconst moduleVersion = docMeta.state.version === 0 ? void 0 : docMeta.state.version;\n\t\t\tmodule = this.registry.getModule(document.header.documentType, moduleVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet updatedDocument;\n\t\ttry {\n\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\tconst reducerOptions = sourceOperation ? {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\treplayOptions: { operation: sourceOperation },\n\t\t\t\tprotocolVersion\n\t\t\t} : {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tprotocolVersion\n\t\t\t};\n\t\t\tupdatedDocument = module.reducer(document, action, void 0, reducerOptions);\n\t\t} catch (error) {\n\t\t\tconst contextMessage = `Failed to apply action to document:\\n Action type: ${action.type}\\n Document ID: ${job.documentId}\\n Document type: ${document.header.documentType}\\n Scope: ${job.scope}\\n Original error: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\tconst enhancedError = new Error(contextMessage);\n\t\t\tif (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\\n\\nOriginal stack trace:\\n${error.stack}`;\n\t\t\treturn buildErrorResult(job, enhancedError, startTime);\n\t\t}\n\t\tconst scope = job.scope;\n\t\tconst operations = updatedDocument.operations[scope];\n\t\tif (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"No operation generated from action\"), startTime);\n\t\tconst newOperation = operations[operations.length - 1];\n\t\tif (!isUndoRedo(action)) newOperation.skip = skip;\n\t\tconst resultingState = JSON.stringify({\n\t\t\t...updatedDocument.state,\n\t\t\theader: updatedDocument.header\n\t\t});\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(job.documentId, document.header.documentType, scope, job.branch, newOperation.index, (txn) => {\n\t\t\t\ttxn.addOperations(newOperation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", newOperation, error);\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst storedOperation = storedOperations[0];\n\t\tupdatedDocument.header.revision = {\n\t\t\t...updatedDocument.header.revision,\n\t\t\t[scope]: storedOperation.index + 1\n\t\t};\n\t\tstores.writeCache.putState(job.documentId, scope, job.branch, storedOperation.index, updatedDocument);\n\t\tindexTxn.write([{\n\t\t\t...storedOperation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [storedOperation],\n\t\t\toperationsWithContext: [{\n\t\t\t\toperation: storedOperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId: job.documentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch: job.branch,\n\t\t\t\t\tdocumentType: document.header.documentType,\n\t\t\t\t\tresultingState,\n\t\t\t\t\tordinal: 0\n\t\t\t\t}\n\t\t\t}],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\tasync executeLoadJob(job, startTime, indexTxn, stores, signal) {\n\t\tif (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"Load job must include at least one operation\"), startTime);\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch {}\n\t\tif (docMeta?.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tconst scope = job.scope;\n\t\tlet latestRevision;\n\t\ttry {\n\t\t\tlatestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;\n\t\t} catch {\n\t\t\tlatestRevision = 0;\n\t\t}\n\t\tfor (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${operation.timestampUtcMs}\" on operation (index: ${operation.index})`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet minIncomingIndex = Number.POSITIVE_INFINITY;\n\t\tlet minIncomingTimestamp = job.operations[0]?.timestampUtcMs || \"\";\n\t\tfor (const operation of job.operations) {\n\t\t\tminIncomingIndex = Math.min(minIncomingIndex, operation.index);\n\t\t\tconst ts = operation.timestampUtcMs || \"\";\n\t\t\tif (ts < minIncomingTimestamp) minIncomingTimestamp = ts;\n\t\t}\n\t\tlet conflictingOps;\n\t\ttry {\n\t\t\tconflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;\n\t\t} catch {\n\t\t\tconflictingOps = [];\n\t\t}\n\t\tlet allOpsFromMinConflictingIndex = conflictingOps;\n\t\tif (conflictingOps.length > 0) {\n\t\t\tconst minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));\n\t\t\ttry {\n\t\t\t\tallOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;\n\t\t\t} catch {\n\t\t\t\tallOpsFromMinConflictingIndex = conflictingOps;\n\t\t\t}\n\t\t}\n\t\tconst incomingActionIds = new Set(job.operations.map((op) => op.action.id));\n\t\tconst nonSupersededOps = conflictingOps.filter((op) => {\n\t\t\tif (op.index < minIncomingIndex && !incomingActionIds.has(op.action.id)) return false;\n\t\t\tfor (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0) {\n\t\t\t\tif (laterOp.index - laterOp.skip <= op.index) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\tconst existingOpsToReshuffle = nonSupersededOps;\n\t\tif (existingOpsToReshuffle.length > this.config.maxSkipThreshold) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Excessive reshuffle detected: existing op count of ${existingOpsToReshuffle.length} exceeds threshold of ${this.config.maxSkipThreshold}. This indicates a significant divergence between local and incoming operations.`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet skipCount = existingOpsToReshuffle.length;\n\t\tif (existingOpsToReshuffle.length > 0) {\n\t\t\tlet minLogicalIndex = Number.POSITIVE_INFINITY;\n\t\t\tfor (const op of existingOpsToReshuffle) {\n\t\t\t\tconst logical = op.index - op.skip;\n\t\t\t\tif (logical < minLogicalIndex) minLogicalIndex = logical;\n\t\t\t}\n\t\t\tconst logicalSkip = latestRevision - minLogicalIndex;\n\t\t\tif (logicalSkip > skipCount) skipCount = logicalSkip;\n\t\t}\n\t\tconst existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));\n\t\tconst seenIncomingActionIds = /* @__PURE__ */ new Set();\n\t\tconst incomingOpsToApply = job.operations.filter((op) => {\n\t\t\tif (existingActionIds.has(op.action.id)) return false;\n\t\t\tif (seenIncomingActionIds.has(op.action.id)) return false;\n\t\t\tseenIncomingActionIds.add(op.action.id);\n\t\t\treturn true;\n\t\t});\n\t\tif (incomingOpsToApply.length === 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({\n\t\t\t...operation,\n\t\t\tindex: latestRevision + i\n\t\t})) : reshuffleByTimestamp({\n\t\t\tindex: latestRevision,\n\t\t\tskip: skipCount\n\t\t}, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({\n\t\t\t...operation,\n\t\t\tid: operation.id\n\t\t})));\n\t\tfor (const operation of reshuffledOperations) if (operation.action.type === \"NOOP\") operation.skip = 1;\n\t\tconst actions = reshuffledOperations.map((operation) => operation.action);\n\t\tconst skipValues = reshuffledOperations.map((operation) => operation.skip);\n\t\tconst effectiveSourceRemote = skipCount > 0 ? \"\" : job.meta.sourceRemote || \"\";\n\t\tconst result = await this.processActions(job, actions, startTime, indexTxn, stores, skipValues, reshuffledOperations, effectiveSourceRemote, signal);\n\t\tif (!result.success) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: result.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\tif (scope === \"document\") stores.documentMetaCache.invalidate(job.documentId, job.branch);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: result.generatedOperations,\n\t\t\toperationsWithContext: result.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\taccumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {\n\t\tif (!result.success) return result;\n\t\tif (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);\n\t\tif (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);\n\t\treturn null;\n\t}\n};\n//#endregion\n//#region src/registry/implementation.ts\n/**\n* In-memory implementation of the IDocumentModelRegistry interface.\n* Manages document model modules with version-aware storage and upgrade manifest support.\n*/\nvar DocumentModelRegistry = class {\n\tmodules = [];\n\tmanifests = [];\n\tregisterModules(...modules) {\n\t\treturn modules.map((module) => {\n\t\t\ttry {\n\t\t\t\tconst documentType = module.documentModel.global.id;\n\t\t\t\tconst version = module.version ?? 1;\n\t\t\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\t\t\tconst existing = this.modules[i];\n\t\t\t\t\tconst existingType = existing.documentModel.global.id;\n\t\t\t\t\tconst existingVersion = existing.version ?? 1;\n\t\t\t\t\tif (existingType === documentType && existingVersion === version) throw new DuplicateModuleError(documentType, version);\n\t\t\t\t}\n\t\t\t\tthis.modules.push(module);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: module\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: module,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterModules(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.modules.some((m) => m.documentModel.global.id === documentType)) allFound = false;\n\t\t\tthis.modules = this.modules.filter((m) => m.documentModel.global.id !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetModule(documentType, version) {\n\t\tlet latestModule;\n\t\tlet latestVersion = -1;\n\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\tconst module = this.modules[i];\n\t\t\tconst moduleType = module.documentModel.global.id;\n\t\t\tconst moduleVersion = module.version ?? 1;\n\t\t\tif (moduleType === documentType) {\n\t\t\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\t\t\tif (moduleVersion > latestVersion) {\n\t\t\t\t\tlatestModule = module;\n\t\t\t\t\tlatestVersion = moduleVersion;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (version === void 0 && latestModule !== void 0) return latestModule;\n\t\tthrow new ModuleNotFoundError(documentType, version);\n\t}\n\tgetAllModules() {\n\t\treturn [...this.modules];\n\t}\n\tclear() {\n\t\tthis.modules = [];\n\t\tthis.manifests = [];\n\t}\n\tgetSupportedVersions(documentType) {\n\t\tconst versions = [];\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) versions.push(module.version ?? 1);\n\t\tif (versions.length === 0) throw new ModuleNotFoundError(documentType);\n\t\treturn versions.sort((a, b) => a - b);\n\t}\n\tgetLatestVersion(documentType) {\n\t\tlet latest = -1;\n\t\tlet found = false;\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) {\n\t\t\tfound = true;\n\t\t\tconst version = module.version ?? 1;\n\t\t\tif (version > latest) latest = version;\n\t\t}\n\t\tif (!found) throw new ModuleNotFoundError(documentType);\n\t\treturn latest;\n\t}\n\tregisterUpgradeManifests(...manifestsToRegister) {\n\t\treturn manifestsToRegister.map((manifestToRegister) => {\n\t\t\ttry {\n\t\t\t\tif (!manifestToRegister.documentType) throw new Error(\"Upgrade manifest is missing a documentType\");\n\t\t\t\tfor (const registeredManifest of this.manifests) if (registeredManifest.documentType === manifestToRegister.documentType) throw new DuplicateManifestError(manifestToRegister.documentType);\n\t\t\t\tthis.manifests.push(manifestToRegister);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: manifestToRegister\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: manifestToRegister,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterUpgradeManifests(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.manifests.some((m) => m.documentType === documentType)) allFound = false;\n\t\t\tthis.manifests = this.manifests.filter((m) => m.documentType !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetUpgradeManifest(documentType) {\n\t\tfor (let i = 0; i < this.manifests.length; i++) if (this.manifests[i].documentType === documentType) return this.manifests[i];\n\t\tthrow new ManifestNotFoundError(documentType);\n\t}\n\tcomputeUpgradePath(documentType, fromVersion, toVersion) {\n\t\tif (fromVersion === toVersion) return [];\n\t\tif (toVersion < fromVersion) throw new DowngradeNotSupportedError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst path = [];\n\t\tfor (let v = fromVersion + 1; v <= toVersion; v++) {\n\t\t\tconst key = `v${v}`;\n\t\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, v - 1, v);\n\t\t\tconst transition = manifest.upgrades[key];\n\t\t\tpath.push(transition);\n\t\t}\n\t\treturn path;\n\t}\n\tgetUpgradeReducer(documentType, fromVersion, toVersion) {\n\t\tif (toVersion !== fromVersion + 1) throw new InvalidUpgradeStepError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst key = `v${toVersion}`;\n\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, fromVersion, toVersion);\n\t\treturn manifest.upgrades[key].upgradeReducer;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/keyframe-store.ts\nvar KyselyKeyframeStore = class KyselyKeyframeStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyKeyframeStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync putKeyframe(documentId, scope, branch, revision, document, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.queryExecutor.insertInto(\"Keyframe\").values({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope,\n\t\t\tbranch,\n\t\t\trevision,\n\t\t\tdocument\n\t\t}).onConflict((oc) => oc.columns([\n\t\t\t\"documentId\",\n\t\t\t\"scope\",\n\t\t\t\"branch\",\n\t\t\t\"revision\"\n\t\t]).doUpdateSet({ document })).execute();\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"revision\", \"<=\", targetRevision).orderBy(\"revision\", \"desc\").limit(1).executeTakeFirst();\n\t\tif (!row) return;\n\t\treturn {\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t};\n\t}\n\tasync listKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"revision\", \"asc\");\n\t\tif (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tif (branch !== void 0) query = query.where(\"branch\", \"=\", branch);\n\t\treturn (await query.execute()).map((row) => ({\n\t\t\tscope: row.scope,\n\t\t\tbranch: row.branch,\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t}));\n\t}\n\tasync deleteKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.deleteFrom(\"Keyframe\").where(\"documentId\", \"=\", documentId);\n\t\tif (scope !== void 0 && branch !== void 0) query = query.where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch);\n\t\telse if (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows || 0n);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/pagination.ts\nconst DEFAULT_LIMIT = 100;\nfunction paginateRows(rows, paging, cursorOf, toItem, refetch) {\n\tlet hasMore = false;\n\tlet items = rows;\n\tif (paging?.limit && rows.length > paging.limit) {\n\t\thasMore = true;\n\t\titems = rows.slice(0, paging.limit);\n\t}\n\tconst nextCursor = hasMore && items.length > 0 ? cursorOf(items[items.length - 1]).toString() : void 0;\n\tconst cursor = paging?.cursor || \"0\";\n\tconst limit = paging?.limit || DEFAULT_LIMIT;\n\treturn {\n\t\tresults: items.map(toItem),\n\t\toptions: {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t},\n\t\tnextCursor,\n\t\tnext: hasMore ? () => refetch(nextCursor, limit) : void 0\n\t};\n}\n//#endregion\n//#region src/storage/interfaces.ts\n/**\n* Thrown when an operation with the same identity already exists in the store.\n*/\nvar DuplicateOperationError = class extends Error {\n\tconstructor(description) {\n\t\tsuper(`Duplicate operation: ${description}`);\n\t\tthis.name = \"DuplicateOperationError\";\n\t}\n};\n/**\n* Thrown when a concurrent write conflict is detected during an atomic apply.\n*/\nvar OptimisticLockError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"OptimisticLockError\";\n\t}\n};\n/**\n* Thrown when the caller-provided revision does not match the current\n* stored revision, indicating a stale read.\n*/\nvar RevisionMismatchError = class extends Error {\n\tconstructor(expected, actual) {\n\t\tsuper(`Revision mismatch: expected ${expected}, got ${actual}`);\n\t\tthis.name = \"RevisionMismatchError\";\n\t}\n};\n//#endregion\n//#region src/storage/txn.ts\nvar AtomicTransaction = class {\n\toperations = [];\n\tconstructor(documentId, documentType, scope, branch, baseRevision) {\n\t\tthis.documentId = documentId;\n\t\tthis.documentType = documentType;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.baseRevision = baseRevision;\n\t}\n\taddOperations(...operations) {\n\t\tfor (const op of operations) this.operations.push({\n\t\t\tjobId: v4(),\n\t\t\topId: op.id,\n\t\t\tprevOpId: \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tdocumentType: this.documentType,\n\t\t\tscope: this.scope,\n\t\t\tbranch: this.branch,\n\t\t\ttimestampUtcMs: new Date(op.timestampUtcMs),\n\t\t\tindex: op.index,\n\t\t\taction: JSON.stringify(op.action),\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || null,\n\t\t\thash: op.hash\n\t\t});\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/store.ts\nvar _UniqueConstraintContext = class extends Error {\n\tconstructor(documentId, scope, branch, revision, stagedOps) {\n\t\tsuper(\"unique constraint\");\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.revision = revision;\n\t\tthis.stagedOps = stagedOps;\n\t\tthis.name = \"UniqueConstraintContext\";\n\t}\n};\nvar KyselyOperationStore = class KyselyOperationStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync apply(documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tif (this.trx) {\n\t\t\tlet executeResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\texecuteResult = await this.executeApply(this.trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn executeResult;\n\t\t} else {\n\t\t\tlet transactionResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\ttransactionResult = await this.db.transaction().execute(async (trx) => {\n\t\t\t\t\treturn this.executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn transactionResult;\n\t\t}\n\t}\n\tasync resolveUniqueConstraint(ctx) {\n\t\tlet replayOps = null;\n\t\ttry {\n\t\t\treplayOps = await this.findIdempotentReplay(this.db, ctx.documentId, ctx.scope, ctx.branch, ctx.revision, ctx.stagedOps);\n\t\t} catch {}\n\t\tif (replayOps !== null) return replayOps;\n\t\tconst op = ctx.stagedOps[0];\n\t\tthrow new DuplicateOperationError(`${op.opId} at index ${op.index} with skip ${op.skip}`);\n\t}\n\tasync executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst atomicTxn = new AtomicTransaction(documentId, documentType, scope, branch, revision);\n\t\tawait fn(atomicTxn);\n\t\tconst operations = atomicTxn.getOperations();\n\t\tif (operations.length === 0) return [];\n\t\tconst latestOp = await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"desc\").limit(1).executeTakeFirst();\n\t\tconst currentRevision = latestOp ? latestOp.index : -1;\n\t\tif (currentRevision !== revision - 1) {\n\t\t\tlet replayOps = null;\n\t\t\ttry {\n\t\t\t\treplayOps = await this.findIdempotentReplay(trx, documentId, scope, branch, revision, operations);\n\t\t\t} catch {}\n\t\t\tif (replayOps !== null) return replayOps;\n\t\t\tthrow new RevisionMismatchError(currentRevision + 1, revision);\n\t\t}\n\t\tlet prevOpId = latestOp?.opId || \"\";\n\t\tfor (const op of operations) {\n\t\t\top.prevOpId = prevOpId;\n\t\t\tprevOpId = op.opId;\n\t\t}\n\t\ttry {\n\t\t\tawait trx.insertInto(\"Operation\").values(operations).execute();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message.includes(\"unique constraint\")) throw new _UniqueConstraintContext(documentId, scope, branch, revision, operations);\n\t\t\tthrow error;\n\t\t}\n\t\treturn operations.map((op) => ({\n\t\t\tindex: op.index,\n\t\t\ttimestampUtcMs: op.timestampUtcMs.toISOString(),\n\t\t\thash: op.hash,\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || void 0,\n\t\t\tid: op.opId,\n\t\t\taction: JSON.parse(op.action)\n\t\t}));\n\t}\n\tasync findIdempotentReplay(executor, documentId, scope, branch, revision, stagedOps) {\n\t\tconst minIndex = revision;\n\t\tconst maxIndex = revision + stagedOps.length - 1;\n\t\tconst storedRows = await executor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">=\", minIndex).where(\"index\", \"<=\", maxIndex).orderBy(\"index\", \"asc\").execute();\n\t\tif (storedRows.length !== stagedOps.length) return null;\n\t\tfor (let i = 0; i < stagedOps.length; i++) {\n\t\t\tconst staged = stagedOps[i];\n\t\t\tconst stored = storedRows[i];\n\t\t\tif (stored.opId !== staged.opId || stored.index !== staged.index || stored.skip !== staged.skip) return null;\n\t\t}\n\t\treturn storedRows.map((row) => this.rowToOperation(row));\n\t}\n\tasync getSince(documentId, scope, branch, revision, filter, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">\", revision).orderBy(\"index\", \"asc\");\n\t\tif (filter) {\n\t\t\tif (filter.actionTypes && filter.actionTypes.length > 0) {\n\t\t\t\tconst actionTypesArray = filter.actionTypes.map((t) => `'${t.replace(/'/g, \"''\")}'`).join(\",\");\n\t\t\t\tquery = query.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(actionTypesArray)}]::text[])`);\n\t\t\t}\n\t\t\tif (filter.timestampFrom) query = query.where(\"timestampUtcMs\", \">=\", new Date(filter.timestampFrom));\n\t\t\tif (filter.timestampTo) query = query.where(\"timestampUtcMs\", \"<=\", new Date(filter.timestampTo));\n\t\t\tif (filter.sinceRevision !== void 0) query = query.where(\"index\", \">=\", filter.sinceRevision);\n\t\t}\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getSince(documentId, scope, branch, revision, filter, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getSinceId(id, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"id\", \">\", id).orderBy(\"id\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"id\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.id, (row) => this.rowToOperationWithContext(row), (cursor, limit) => this.getSinceId(id, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"timestampUtcMs\", \">=\", new Date(minTimestamp)).orderBy(\"index\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getConflicting(documentId, scope, branch, minTimestamp, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getRevisions(documentId, branch, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst scopeRevisions = await this.queryExecutor.selectFrom(\"Operation as o1\").select([\n\t\t\t\"o1.scope\",\n\t\t\t\"o1.index\",\n\t\t\t\"o1.timestampUtcMs\"\n\t\t]).where(\"o1.documentId\", \"=\", documentId).where(\"o1.branch\", \"=\", branch).where((eb) => eb(\"o1.index\", \"=\", eb.selectFrom(\"Operation as o2\").select((eb2) => eb2.fn.max(\"o2.index\").as(\"maxIndex\")).where(\"o2.documentId\", \"=\", eb.ref(\"o1.documentId\")).where(\"o2.branch\", \"=\", eb.ref(\"o1.branch\")).where(\"o2.scope\", \"=\", eb.ref(\"o1.scope\")))).execute();\n\t\tconst revision = {};\n\t\tlet latestTimestamp = (/* @__PURE__ */ new Date(0)).toISOString();\n\t\tfor (const row of scopeRevisions) {\n\t\t\trevision[row.scope] = row.index + 1;\n\t\t\tconst timestamp = row.timestampUtcMs.toISOString();\n\t\t\tif (timestamp > latestTimestamp) latestTimestamp = timestamp;\n\t\t}\n\t\treturn {\n\t\t\trevision,\n\t\t\tlatestTimestamp\n\t\t};\n\t}\n\trowToOperation(row) {\n\t\treturn {\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\terror: row.error || void 0,\n\t\t\tid: row.opId,\n\t\t\taction: row.action\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: this.rowToOperation(row),\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.id\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\n//#region src/storage/pool-instrumentation.ts\n/**\n* Wraps an existing pg.Pool with acquire-wait timing and an event\n* subscription surface. The pool is mutated in place: pool.connect()\n* is replaced with a timing wrapper so all callers (Kysely included)\n* pick up the instrumentation transparently.\n*/\nfunction instrumentPgPool(pool, name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tconst originalConnect = pool.connect.bind(pool);\n\tconst wrappedConnect = async () => {\n\t\tconst start = performance.now();\n\t\tconst client = await originalConnect();\n\t\tconst durationMs = performance.now() - start;\n\t\tfor (const listener of listeners) try {\n\t\t\tlistener(durationMs);\n\t\t} catch {}\n\t\treturn client;\n\t};\n\tpool.connect = wrappedConnect;\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn {\n\t\t\t\tsize: pool.totalCount,\n\t\t\t\tidle: pool.idleCount,\n\t\t\t\twaiting: pool.waitingCount\n\t\t\t};\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t}\n\t};\n}\nfunction createForwardingPoolInstrumentation(name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet stats = {\n\t\tsize: 0,\n\t\tidle: 0,\n\t\twaiting: 0\n\t};\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn stats;\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tpushSamples(durations) {\n\t\t\tfor (const durationMs of durations) for (const listener of listeners) try {\n\t\t\t\tlistener(durationMs);\n\t\t\t} catch {}\n\t\t},\n\t\tupdateStats(next) {\n\t\t\tstats = next;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/storage/migrations/001_create_operation_table.ts\nvar _001_create_operation_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$13 });\nasync function up$13(db) {\n\tawait db.schema.createTable(\"Operation\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"jobId\", \"text\", (col) => col.notNull()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"prevOpId\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"timestamptz\", (col) => col.notNull()).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"error\", \"text\").addColumn(\"hash\", \"text\", (col) => col.notNull()).addUniqueConstraint(\"unique_revision\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"index\"\n\t]).addUniqueConstraint(\"unique_operation_instance\", [\n\t\t\"opId\",\n\t\t\"index\",\n\t\t\"skip\"\n\t]).execute();\n\tawait db.schema.createIndex(\"streamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"id\"\n\t]).execute();\n\tawait db.schema.createIndex(\"branchlessStreamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"id\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/002_create_keyframe_table.ts\nvar _002_create_keyframe_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$12 });\nasync function up$12(db) {\n\tawait db.schema.createTable(\"Keyframe\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"revision\", \"integer\", (col) => col.notNull()).addColumn(\"document\", \"jsonb\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_keyframe\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n\tawait db.schema.createIndex(\"keyframe_lookup\").on(\"Keyframe\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/003_create_document_table.ts\nvar _003_create_document_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$11 });\nasync function up$11(db) {\n\tawait db.schema.createTable(\"Document\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/004_create_document_relationship_table.ts\nvar _004_create_document_relationship_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$10 });\nasync function up$10(db) {\n\tawait db.schema.createTable(\"DocumentRelationship\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"sourceId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"targetId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"relationshipType\", \"text\", (col) => col.notNull()).addColumn(\"metadata\", \"jsonb\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_source_target_type\", [\n\t\t\"sourceId\",\n\t\t\"targetId\",\n\t\t\"relationshipType\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_relationship_source\").on(\"DocumentRelationship\").column(\"sourceId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_target\").on(\"DocumentRelationship\").column(\"targetId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_type\").on(\"DocumentRelationship\").column(\"relationshipType\").execute();\n}\n//#endregion\n//#region src/storage/migrations/005_create_indexer_state_table.ts\nvar _005_create_indexer_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$9 });\nasync function up$9(db) {\n\tawait db.schema.createTable(\"IndexerState\").addColumn(\"id\", \"integer\", (col) => col.primaryKey().generatedAlwaysAsIdentity()).addColumn(\"lastOperationId\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/006_create_document_snapshot_table.ts\nvar _006_create_document_snapshot_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$8 });\nasync function up$8(db) {\n\tawait db.schema.createTable(\"DocumentSnapshot\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"slug\", \"text\").addColumn(\"name\", \"text\").addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"content\", \"jsonb\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"lastOperationIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationHash\", \"text\", (col) => col.notNull()).addColumn(\"lastUpdatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"snapshotVersion\", \"integer\", (col) => col.notNull().defaultTo(1)).addColumn(\"identifiers\", \"jsonb\").addColumn(\"metadata\", \"jsonb\").addColumn(\"isDeleted\", \"boolean\", (col) => col.notNull().defaultTo(false)).addColumn(\"deletedAt\", \"timestamptz\").addUniqueConstraint(\"unique_doc_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"slug\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_doctype_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"documentType\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_last_updated\").on(\"DocumentSnapshot\").column(\"lastUpdatedAt\").execute();\n\tawait db.schema.createIndex(\"idx_is_deleted\").on(\"DocumentSnapshot\").column(\"isDeleted\").execute();\n}\n//#endregion\n//#region src/storage/migrations/007_create_slug_mapping_table.ts\nvar _007_create_slug_mapping_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$7 });\nasync function up$7(db) {\n\tawait db.schema.createTable(\"SlugMapping\").addColumn(\"slug\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_docid_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_documentid\").on(\"SlugMapping\").column(\"documentId\").execute();\n}\n//#endregion\n//#region src/storage/migrations/008_create_view_state_table.ts\nvar _008_create_view_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$6 });\nasync function up$6(db) {\n\tawait db.schema.createTable(\"ViewState\").addColumn(\"readModelId\", \"text\", (col) => col.primaryKey()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/009_create_operation_index_tables.ts\nvar _009_create_operation_index_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$5 });\nasync function up$5(db) {\n\tawait db.schema.createTable(\"document_collections\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"collectionId\", \"text\", (col) => col.notNull()).addColumn(\"joinedOrdinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"leftOrdinal\", \"bigint\").addPrimaryKeyConstraint(\"document_collections_pkey\", [\"documentId\", \"collectionId\"]).execute();\n\tawait db.schema.createIndex(\"idx_document_collections_collectionId\").on(\"document_collections\").column(\"collectionId\").execute();\n\tawait db.schema.createIndex(\"idx_doc_collections_collection_range\").on(\"document_collections\").columns([\"collectionId\", \"joinedOrdinal\"]).execute();\n\tawait db.schema.createTable(\"operation_index_operations\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"hash\", \"text\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_document\").on(\"operation_index_operations\").columns([\n\t\t\"documentId\",\n\t\t\"branch\",\n\t\t\"scope\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_ordinal\").on(\"operation_index_operations\").column(\"ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/010_create_sync_tables.ts\nvar _010_create_sync_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$4 });\nasync function up$4(db) {\n\tawait db.schema.createTable(\"sync_remotes\").addColumn(\"name\", \"text\", (col) => col.primaryKey()).addColumn(\"collection_id\", \"text\", (col) => col.notNull()).addColumn(\"channel_type\", \"text\", (col) => col.notNull()).addColumn(\"channel_id\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"remote_name\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"channel_parameters\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn(\"filter_document_ids\", \"jsonb\").addColumn(\"filter_scopes\", \"jsonb\").addColumn(\"filter_branch\", \"text\", (col) => col.notNull().defaultTo(\"main\")).addColumn(\"push_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"push_last_success_utc_ms\", \"text\").addColumn(\"push_last_failure_utc_ms\", \"text\").addColumn(\"push_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"pull_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"pull_last_success_utc_ms\", \"text\").addColumn(\"pull_last_failure_utc_ms\", \"text\").addColumn(\"pull_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_remotes_collection\").on(\"sync_remotes\").column(\"collection_id\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.primaryKey().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/011_add_cursor_type_column.ts\nvar _011_add_cursor_type_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$3 });\nasync function up$3(db) {\n\tawait db.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"like\", \"outbox::%\").execute();\n\tawait db.deleteFrom(\"sync_remotes\").where(\"name\", \"like\", \"outbox::%\").execute();\n\tawait db.schema.dropTable(\"sync_cursors\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"cursor_type\", \"text\", (col) => col.notNull().defaultTo(\"inbox\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"sync_cursors_pk\", [\"remote_name\", \"cursor_type\"]).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/012_add_source_remote_column.ts\nvar _012_add_source_remote_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$2 });\nasync function up$2(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"sourceRemote\", \"text\", (col) => col.notNull().defaultTo(\"\")).execute();\n}\n//#endregion\n//#region src/storage/migrations/013_create_sync_dead_letters_table.ts\nvar _013_create_sync_dead_letters_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$1 });\nasync function up$1(db) {\n\tawait db.schema.createTable(\"sync_dead_letters\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"id\", \"text\", (col) => col.unique().notNull()).addColumn(\"job_id\", \"text\", (col) => col.notNull()).addColumn(\"job_dependencies\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"scopes\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operations\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"error_source\", \"text\", (col) => col.notNull()).addColumn(\"error_message\", \"text\", (col) => col.notNull()).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_dead_letters_remote\").on(\"sync_dead_letters\").column(\"remote_name\").execute();\n}\n//#endregion\n//#region src/storage/migrations/014_create_processor_cursor_table.ts\nvar _014_create_processor_cursor_table_exports = /* @__PURE__ */ __exportAll({ up: () => up });\nasync function up(db) {\n\tawait db.schema.createTable(\"ProcessorCursor\").addColumn(\"processorId\", \"text\", (col) => col.primaryKey()).addColumn(\"factoryId\", \"text\", (col) => col.notNull()).addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"processorIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(sql`0`)).addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(sql`'active'`)).addColumn(\"lastError\", \"text\").addColumn(\"lastErrorTimestamp\", \"timestamptz\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/migrator.ts\nconst REACTOR_SCHEMA = \"reactor\";\nconst migrations = {\n\t\"001_create_operation_table\": _001_create_operation_table_exports,\n\t\"002_create_keyframe_table\": _002_create_keyframe_table_exports,\n\t\"003_create_document_table\": _003_create_document_table_exports,\n\t\"004_create_document_relationship_table\": _004_create_document_relationship_table_exports,\n\t\"005_create_indexer_state_table\": _005_create_indexer_state_table_exports,\n\t\"006_create_document_snapshot_table\": _006_create_document_snapshot_table_exports,\n\t\"007_create_slug_mapping_table\": _007_create_slug_mapping_table_exports,\n\t\"008_create_view_state_table\": _008_create_view_state_table_exports,\n\t\"009_create_operation_index_tables\": _009_create_operation_index_tables_exports,\n\t\"010_create_sync_tables\": _010_create_sync_tables_exports,\n\t\"011_add_cursor_type_column\": _011_add_cursor_type_column_exports,\n\t\"012_add_source_remote_column\": _012_add_source_remote_column_exports,\n\t\"013_create_sync_dead_letters_table\": _013_create_sync_dead_letters_table_exports,\n\t\"014_create_processor_cursor_table\": _014_create_processor_cursor_table_exports\n};\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\nasync function runMigrations(db, schema = REACTOR_SCHEMA) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getMigrationStatus(db, schema = REACTOR_SCHEMA) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t}).getMigrations();\n}\n//#endregion\n//#region src/core/drive-container-types.ts\nconst DEFAULT_DRIVE_CONTAINER_TYPES = new Set([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"]);\n//#endregion\nexport { parsePagingOptions as A, DuplicateManifestError as C, DocumentDeletedError as D, ModuleNotFoundError as E, __exportAll as M, DocumentNotFoundError as O, CollectionMembershipCache as S, InvalidModuleError as T, KyselyWriteCache as _, createForwardingPoolInstrumentation as a, createConsistencyToken as b, DuplicateOperationError as c, KyselyKeyframeStore as d, DocumentModelRegistry as f, EventBus as g, KyselyExecutionScope as h, runMigrations as i, throwIfAborted as j, matchesScope as k, OptimisticLockError as l, driveCollectionId as m, REACTOR_SCHEMA as n, instrumentPgPool as o, SimpleJobExecutor as p, getMigrationStatus as r, KyselyOperationStore as s, DEFAULT_DRIVE_CONTAINER_TYPES as t, RevisionMismatchError as u, KyselyOperationIndex as v, DuplicateModuleError as w, createEmptyConsistencyToken as x, DocumentMetaCache as y };\n\n//# sourceMappingURL=drive-container-types-BNpMlgT_.js.map","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport type { AtomicTxn } from \"@powerhousedao/reactor\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreAtomicTransaction implements AtomicTxn {\n private operations: StoredOperation[] = [];\n\n constructor(\n private documentId: string,\n private documentType: string,\n private scope: string,\n private branch: string,\n ) {}\n\n addOperations(...operations: Operation[]): void {\n for (const op of operations) {\n this.operations.push({\n ...op,\n documentId: this.documentId,\n documentType: this.documentType,\n scope: this.scope,\n branch: this.branch,\n });\n }\n }\n\n getOperations(): StoredOperation[] {\n return this.operations;\n }\n}\n","import type { StoredOperation } from \"./types.js\";\n\nconst PAD_WIDTH = 10;\n\nexport const RANGE_UPPER_BOUND = \"9\".repeat(PAD_WIDTH) + \"~\";\n\nexport function pad(n: number): string {\n return n.toString().padStart(PAD_WIDTH, \"0\");\n}\n\nexport function operationKey(\n documentId: string,\n scope: string,\n branch: string,\n index: number,\n): string {\n return `op/${documentId}/${scope}/${branch}/${pad(index)}`;\n}\n\nexport function operationPrefix(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `op/${documentId}/${scope}/${branch}/`;\n}\n\nexport function ordinalKey(ordinal: number): string {\n return `ord/${pad(ordinal)}`;\n}\n\nexport function ordinalPrefix(): string {\n return \"ord/\";\n}\n\nexport function duplicateKey(\n opId: string,\n index: number,\n skip: number,\n): string {\n return `dup/${opId}/${pad(index)}/${pad(skip)}`;\n}\n\nexport function headKey(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `_meta/head/${documentId}/${scope}/${branch}`;\n}\n\nexport function headPrefix(documentId: string): string {\n return `_meta/head/${documentId}/`;\n}\n\nexport const ORDINAL_COUNTER_KEY = \"_meta/ordinal\";\n\nexport type ParsedOperationKey = {\n documentId: string;\n scope: string;\n branch: string;\n index: number;\n};\n\nexport function parseOperationKey(key: string): ParsedOperationKey {\n const parts = key.split(\"/\");\n return {\n documentId: parts[1],\n scope: parts[2],\n branch: parts[3],\n index: parseInt(parts[4], 10),\n };\n}\n\nexport type OrdinalEntry = {\n documentId: string;\n documentType: string;\n scope: string;\n branch: string;\n index: number;\n operation: StoredOperation;\n};\n\nexport type HeadEntryValue = {\n index: number;\n latestTimestampUtcMs: string;\n};\n","import type {\n Operation,\n OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n AtomicTxn,\n DocumentRevisions,\n IOperationStore,\n OperationFilter,\n PagedResults,\n PagingOptions,\n} from \"@powerhousedao/reactor\";\nimport {\n DuplicateOperationError,\n RevisionMismatchError,\n} from \"@powerhousedao/reactor\";\nimport type Hyperbee from \"hyperbee\";\nimport { HypercoreAtomicTransaction } from \"./hypercore-atomic-transaction.js\";\nimport {\n ORDINAL_COUNTER_KEY,\n RANGE_UPPER_BOUND,\n duplicateKey,\n headKey,\n headPrefix,\n operationKey,\n operationPrefix,\n ordinalKey,\n ordinalPrefix,\n pad,\n} from \"./key-encoding.js\";\nimport type { HeadEntryValue, OrdinalEntry } from \"./key-encoding.js\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreOperationStore implements IOperationStore {\n private applyLock: Promise<void> = Promise.resolve();\n\n constructor(private bee: Hyperbee) {}\n\n async apply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n const prevLock = this.applyLock;\n let releaseLock: () => void;\n this.applyLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n await prevLock;\n\n try {\n return await this.executeApply(\n documentId,\n documentType,\n scope,\n branch,\n revision,\n fn,\n signal,\n );\n } finally {\n releaseLock!();\n }\n }\n\n private async executeApply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const hKey = headKey(documentId, scope, branch);\n const headEntry = await this.bee.get(hKey);\n const currentRevision = headEntry\n ? (headEntry.value as HeadEntryValue).index\n : -1;\n\n if (currentRevision !== revision - 1) {\n throw new RevisionMismatchError(currentRevision + 1, revision);\n }\n\n const atomicTxn = new HypercoreAtomicTransaction(\n documentId,\n documentType,\n scope,\n branch,\n );\n await fn(atomicTxn);\n\n const operations = atomicTxn.getOperations();\n if (operations.length === 0) {\n return [];\n }\n\n for (const op of operations) {\n const dupKey = duplicateKey(op.id, op.index, op.skip);\n const existing = await this.bee.get(dupKey);\n if (existing) {\n throw new DuplicateOperationError(\n `${op.id} at index ${op.index} with skip ${op.skip}`,\n );\n }\n }\n\n const ordinalEntry = await this.bee.get(ORDINAL_COUNTER_KEY);\n let nextOrdinal: number = ordinalEntry ? (ordinalEntry.value as number) : 0;\n\n const batch = this.bee.batch();\n\n for (const op of operations) {\n const opKey = operationKey(documentId, scope, branch, op.index);\n const serialized = this.serializeOperation(op);\n await batch.put(opKey, serialized);\n\n const ordEntry: OrdinalEntry = {\n documentId,\n documentType,\n scope,\n branch,\n index: op.index,\n operation: serialized,\n };\n await batch.put(ordinalKey(nextOrdinal), ordEntry);\n\n await batch.put(duplicateKey(op.id, op.index, op.skip), \"\");\n\n nextOrdinal++;\n }\n\n const lastOp = operations[operations.length - 1];\n const headValue: HeadEntryValue = {\n index: lastOp.index,\n latestTimestampUtcMs: lastOp.timestampUtcMs,\n };\n await batch.put(hKey, headValue);\n await batch.put(ORDINAL_COUNTER_KEY, nextOrdinal);\n\n await batch.flush();\n\n return operations.map((op) => this.toOperation(op));\n }\n\n async getSince(\n documentId: string,\n scope: string,\n branch: string,\n revision: number,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const startIndex = revision + 1;\n const cursorIndex =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10) + 1\n : startIndex;\n const effectiveStart = Math.max(startIndex, cursorIndex);\n\n const gt = prefix + pad(effectiveStart - 1);\n const lt = prefix + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n\n if (filter) {\n if (\n filter.actionTypes &&\n filter.actionTypes.length > 0 &&\n !filter.actionTypes.includes((stored.action as { type: string }).type)\n ) {\n continue;\n }\n if (\n filter.timestampFrom &&\n stored.timestampUtcMs < filter.timestampFrom\n ) {\n continue;\n }\n if (filter.timestampTo && stored.timestampUtcMs > filter.timestampTo) {\n continue;\n }\n if (\n filter.sinceRevision !== undefined &&\n stored.index < filter.sinceRevision\n ) {\n continue;\n }\n }\n\n items.push(this.toOperation(stored));\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].index.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSince(\n documentId,\n scope,\n branch,\n revision,\n filter,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getSinceId(\n id: number,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<OperationWithContext>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const cursorValue =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10)\n : id;\n const effectiveId = Math.max(id, cursorValue);\n\n const gt = ordinalPrefix() + pad(effectiveId);\n const lt = ordinalPrefix() + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: OperationWithContext[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const ordEntry = entry.value as OrdinalEntry;\n const ordinal = parseInt(entry.key.split(\"/\")[1], 10);\n\n items.push({\n operation: this.toOperation(ordEntry.operation),\n context: {\n documentId: ordEntry.documentId,\n documentType: ordEntry.documentType,\n scope: ordEntry.scope,\n branch: ordEntry.branch,\n ordinal,\n },\n });\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].context.ordinal.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSinceId(\n id,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getConflicting(\n documentId: string,\n scope: string,\n branch: string,\n minTimestamp: string,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const cursorIndex =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10)\n : -1;\n\n const gt = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;\n const lt = prefix + RANGE_UPPER_BOUND;\n\n const stream = this.bee.createReadStream({\n gt: cursorIndex >= 0 ? gt : undefined,\n gte: cursorIndex >= 0 ? undefined : gt,\n lt,\n });\n\n const items: Operation[] = [];\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n if (stored.timestampUtcMs >= minTimestamp) {\n items.push(this.toOperation(stored));\n }\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].index.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getConflicting(\n documentId,\n scope,\n branch,\n minTimestamp,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getRevisions(\n documentId: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<DocumentRevisions> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = headPrefix(documentId);\n const stream = this.bee.createReadStream({\n gte: prefix,\n lt: prefix + \"~\",\n });\n\n const revision: Record<string, number> = {};\n let latestTimestamp = new Date(0).toISOString();\n\n for await (const entry of stream) {\n const parts = entry.key.split(\"/\");\n const entryScope = parts[3];\n const entryBranch = parts[4];\n\n if (entryBranch !== branch) {\n continue;\n }\n\n const headValue = entry.value as HeadEntryValue;\n revision[entryScope] = headValue.index + 1;\n\n if (headValue.latestTimestampUtcMs > latestTimestamp) {\n latestTimestamp = headValue.latestTimestampUtcMs;\n }\n }\n\n return { revision, latestTimestamp };\n }\n\n private serializeOperation(op: StoredOperation): StoredOperation {\n return {\n id: op.id,\n index: op.index,\n skip: op.skip,\n timestampUtcMs: op.timestampUtcMs,\n hash: op.hash,\n error: op.error,\n action: op.action,\n documentId: op.documentId,\n documentType: op.documentType,\n scope: op.scope,\n branch: op.branch,\n };\n }\n\n private toOperation(stored: StoredOperation): Operation {\n return {\n id: stored.id,\n index: stored.index,\n skip: stored.skip,\n timestampUtcMs: stored.timestampUtcMs,\n hash: stored.hash,\n error: stored.error || undefined,\n action: stored.action,\n };\n }\n}\n","import Corestore from \"corestore\";\nimport Hyperbee from \"hyperbee\";\n\nexport class StorageManager {\n private store: Corestore;\n private bee: Hyperbee | undefined;\n\n constructor(storagePath: string) {\n this.store = new Corestore(storagePath);\n }\n\n async open(): Promise<void> {\n await this.store.ready();\n const core = this.store.get({ name: \"operations\" });\n this.bee = new Hyperbee(core, {\n keyEncoding: \"utf-8\",\n valueEncoding: \"json\",\n });\n await this.bee.ready();\n }\n\n async close(): Promise<void> {\n if (this.bee) {\n await this.bee.close();\n }\n await this.store.close();\n }\n\n getBee(): Hyperbee {\n if (!this.bee) {\n throw new Error(\"StorageManager not opened. Call open() first.\");\n }\n return this.bee;\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../reactor/dist/drive-container-types-CAhznKRr.js","../src/hypercore-atomic-transaction.ts","../src/key-encoding.ts","../src/hypercore-operation-store.ts","../src/storage-manager.ts"],"sourcesContent":["import { n as ReactorEventTypes, t as EventBusAggregateError } from \"./types-CxSpmNGK.js\";\nimport { DowngradeNotSupportedError, applyDeleteDocumentAction, applyDeleteDocumentAction as applyDeleteDocumentAction$1, applyUpgradeDocumentAction, applyUpgradeDocumentAction as applyUpgradeDocumentAction$1, createPresignedHeader, defaultBaseState, deriveOperationId, isUndoRedo } from \"@powerhousedao/shared/document-model\";\nimport { v4 } from \"uuid\";\nimport { Migrator, sql } from \"kysely\";\n//#region \\0rolldown/runtime.js\nvar __defProp = Object.defineProperty;\nvar __exportAll = (all, no_symbols) => {\n\tlet target = {};\n\tfor (var name in all) __defProp(target, name, {\n\t\tget: all[name],\n\t\tenumerable: true\n\t});\n\tif (!no_symbols) __defProp(target, Symbol.toStringTag, { value: \"Module\" });\n\treturn target;\n};\n//#endregion\n//#region src/shared/utils.ts\nfunction matchesScope(view = {}, scope) {\n\tif (view.scopes) return view.scopes.includes(scope);\n\treturn true;\n}\nfunction yieldToMain() {\n\tconst s = globalThis.scheduler;\n\tif (s?.yield) return s.yield();\n\treturn new Promise((resolve) => setTimeout(resolve, 0));\n}\nconst defaultAbortError = () => /* @__PURE__ */ new Error(\"Operation aborted\");\nfunction throwIfAborted(signal, makeError = defaultAbortError) {\n\tif (signal?.aborted) throw makeError();\n}\n/**\n* Validates PagingOptions and returns a normalized offset and limit.\n* Throws if the cursor is not empty and not a non-negative integer, or if\n* limit is less than 1. When `paging` is undefined, returns offset 0 and\n* the caller-supplied `defaultLimit`.\n*/\nfunction parsePagingOptions(paging, defaultLimit) {\n\tif (paging === void 0) return {\n\t\toffset: 0,\n\t\tlimit: defaultLimit\n\t};\n\tif (!Number.isInteger(paging.limit) || paging.limit < 1) throw new Error(`Invalid paging limit: ${String(paging.limit)} (must be an integer >= 1)`);\n\tif (paging.cursor === \"\") return {\n\t\toffset: 0,\n\t\tlimit: paging.limit\n\t};\n\tconst parsed = Number(paging.cursor);\n\tif (!Number.isInteger(parsed) || parsed < 0) throw new Error(`Invalid paging cursor: ${JSON.stringify(paging.cursor)} (must be empty or a non-negative integer)`);\n\treturn {\n\t\toffset: parsed,\n\t\tlimit: paging.limit\n\t};\n}\n//#endregion\n//#region src/shared/errors.ts\n/**\n* Error thrown when attempting to access a deleted document.\n*/\nvar DocumentDeletedError = class DocumentDeletedError extends Error {\n\tdocumentId;\n\tdeletedAtUtcIso;\n\tconstructor(documentId, deletedAtUtcIso = null) {\n\t\tconst message = deletedAtUtcIso ? `Document ${documentId} was deleted at ${deletedAtUtcIso}` : `Document ${documentId} has been deleted`;\n\t\tsuper(message);\n\t\tthis.name = \"DocumentDeletedError\";\n\t\tthis.documentId = documentId;\n\t\tthis.deletedAtUtcIso = deletedAtUtcIso;\n\t\tError.captureStackTrace(this, DocumentDeletedError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentDeletedError\";\n\t}\n};\n/**\n* Error thrown when an operation has an invalid signature.\n*/\nvar InvalidSignatureError = class InvalidSignatureError extends Error {\n\tdocumentId;\n\treason;\n\tconstructor(documentId, reason) {\n\t\tsuper(`Invalid signature in document ${documentId}: ${reason}`);\n\t\tthis.name = \"InvalidSignatureError\";\n\t\tthis.documentId = documentId;\n\t\tthis.reason = reason;\n\t\tError.captureStackTrace(this, InvalidSignatureError);\n\t}\n};\n/**\n* Error thrown when a document is not found (no operations exist for the document ID).\n*/\nvar DocumentNotFoundError = class DocumentNotFoundError extends Error {\n\tdocumentId;\n\tconstructor(documentId) {\n\t\tsuper(`Document ${documentId} not found`);\n\t\tthis.name = \"DocumentNotFoundError\";\n\t\tthis.documentId = documentId;\n\t\tError.captureStackTrace(this, DocumentNotFoundError);\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DocumentNotFoundError\";\n\t}\n};\n//#endregion\n//#region src/registry/errors.ts\n/**\n* Error thrown when a document model module is not found in the registry.\n*/\nvar ModuleNotFoundError = class extends Error {\n\tdocumentType;\n\trequestedVersion;\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` version ${version}` : \"\";\n\t\tsuper(`Document model module not found for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"ModuleNotFoundError\";\n\t\tthis.documentType = documentType;\n\t\tthis.requestedVersion = version;\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"ModuleNotFoundError\";\n\t}\n};\n/**\n* Error thrown when attempting to register a module that already exists.\n*/\nvar DuplicateModuleError = class extends Error {\n\tconstructor(documentType, version) {\n\t\tconst versionSuffix = version !== void 0 ? ` (version ${version})` : \"\";\n\t\tsuper(`Document model module already registered for type: ${documentType}${versionSuffix}`);\n\t\tthis.name = \"DuplicateModuleError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateModuleError\";\n\t}\n};\n/**\n* Error thrown when a module is invalid or malformed.\n*/\nvar InvalidModuleError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(`Invalid document model module: ${message}`);\n\t\tthis.name = \"InvalidModuleError\";\n\t}\n};\n/**\n* Error thrown when attempting to register an upgrade manifest that already exists.\n*/\nvar DuplicateManifestError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest already registered for type: ${documentType}`);\n\t\tthis.name = \"DuplicateManifestError\";\n\t}\n\tstatic isError(error) {\n\t\treturn Error.isError(error) && error.name === \"DuplicateManifestError\";\n\t}\n};\n/**\n* Error thrown when an upgrade manifest is not found.\n*/\nvar ManifestNotFoundError = class extends Error {\n\tconstructor(documentType) {\n\t\tsuper(`Upgrade manifest not found for type: ${documentType}`);\n\t\tthis.name = \"ManifestNotFoundError\";\n\t}\n};\n/**\n* Error thrown when a required upgrade transition is missing from the manifest.\n*/\nvar MissingUpgradeTransitionError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Missing upgrade transition for ${documentType}: v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"MissingUpgradeTransitionError\";\n\t}\n};\n/**\n* Error thrown when getUpgradeReducer is called with a non-single-step version increment.\n*/\nvar InvalidUpgradeStepError = class extends Error {\n\tconstructor(documentType, fromVersion, toVersion) {\n\t\tsuper(`Invalid upgrade step for ${documentType}: must be single version increment, got v${fromVersion} to v${toVersion}`);\n\t\tthis.name = \"InvalidUpgradeStepError\";\n\t}\n};\n//#endregion\n//#region src/cache/collection-membership-cache.ts\nvar CollectionMembershipCache = class CollectionMembershipCache {\n\tcache = /* @__PURE__ */ new Map();\n\tconstructor(operationIndex) {\n\t\tthis.operationIndex = operationIndex;\n\t}\n\twithScopedIndex(operationIndex) {\n\t\tconst scoped = new CollectionMembershipCache(operationIndex);\n\t\tscoped.cache = this.cache;\n\t\treturn scoped;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tconst result = {};\n\t\tconst missing = [];\n\t\tfor (const docId of documentIds) {\n\t\t\tconst cached = this.cache.get(docId);\n\t\t\tif (cached !== void 0) result[docId] = cached;\n\t\t\telse missing.push(docId);\n\t\t}\n\t\tif (missing.length > 0) {\n\t\t\tconst fromDb = await this.operationIndex.getCollectionsForDocuments(missing);\n\t\t\tfor (const docId of missing) {\n\t\t\t\tconst collections = fromDb[docId] ?? [];\n\t\t\t\tresult[docId] = collections;\n\t\t\t\tthis.cache.set(docId, collections);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\tinvalidate(documentId) {\n\t\tthis.cache.delete(documentId);\n\t}\n};\n//#endregion\n//#region src/executor/util.ts\n/**\n* Creates a PHDocument from a CREATE_DOCUMENT action input.\n* Reconstructs the document header and initializes the base state.\n*\n* @param action - The CREATE_DOCUMENT action containing the document parameters\n* @returns A newly constructed PHDocument with initialized header and base state\n*/\nfunction createDocumentFromAction(action) {\n\tconst input = action.input;\n\tconst header = createPresignedHeader();\n\theader.id = input.documentId;\n\theader.documentType = input.model;\n\tif (input.signing) {\n\t\theader.createdAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.lastModifiedAtUtcIso = input.signing.createdAtUtcIso;\n\t\theader.sig = {\n\t\t\tpublicKey: input.signing.publicKey,\n\t\t\tnonce: input.signing.nonce\n\t\t};\n\t}\n\tif (input.slug !== void 0) header.slug = input.slug;\n\tif (!header.slug) header.slug = input.documentId;\n\tif (input.name !== void 0) header.name = input.name;\n\tif (input.branch !== void 0) header.branch = input.branch;\n\tif (input.meta !== void 0) header.meta = input.meta;\n\tif (input.protocolVersions !== void 0) header.protocolVersions = input.protocolVersions;\n\tconst baseState = defaultBaseState();\n\treturn {\n\t\theader,\n\t\toperations: {},\n\t\tstate: baseState,\n\t\tinitialState: baseState,\n\t\tclipboard: []\n\t};\n}\n/**\n* Calculate the next operation index for a specific scope.\n* Each scope maintains its own independent index sequence.\n*\n* Per-scope indexing means:\n* - Each scope (document, global, local, etc.) has independent indexes\n* - Indexes start at 0 for each scope\n* - Different scopes can have operations with the same index value\n*\n* This function uses header.revision which is populated by the cache/storage layer\n* and contains the next available index for each scope. This design avoids requiring\n* the full operation history to be loaded, which is crucial for snapshot-based caching.\n*\n* @param document - The document whose header.revision to inspect\n* @param scope - The scope to calculate the next index for\n* @returns The next available index in the specified scope\n*/\nconst getNextIndexForScope = (document, scope) => {\n\treturn document.header.revision[scope] || 0;\n};\n/**\n* Creates an empty consistency token with no coordinates.\n* Used when a job is registered or fails without writing operations.\n*\n* @returns A consistency token with an empty coordinates array\n*/\nfunction createEmptyConsistencyToken() {\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates: []\n\t};\n}\n/**\n* Creates a consistency token from operations written during job execution.\n* Maps each operation to a consistency coordinate tracking (documentId, scope, branch, operationIndex).\n* If no operations are provided, returns an empty token.\n*\n* @param operationsWithContext - Array of operations with their execution context\n* @returns A consistency token representing all operations written\n*/\nfunction createConsistencyToken(operationsWithContext) {\n\tif (operationsWithContext.length === 0) return createEmptyConsistencyToken();\n\tconst coordinates = [];\n\tfor (let i = 0; i < operationsWithContext.length; i++) {\n\t\tconst opWithContext = operationsWithContext[i];\n\t\tcoordinates.push({\n\t\t\tdocumentId: opWithContext.context.documentId,\n\t\t\tscope: opWithContext.context.scope,\n\t\t\tbranch: opWithContext.context.branch,\n\t\t\toperationIndex: opWithContext.operation.index\n\t\t});\n\t}\n\treturn {\n\t\tversion: 1,\n\t\tcreatedAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),\n\t\tcoordinates\n\t};\n}\nfunction createOperation(action, index, skip, context) {\n\treturn {\n\t\tid: deriveOperationId(context.documentId, context.scope, context.branch, action.id),\n\t\tindex,\n\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\thash: \"\",\n\t\tskip,\n\t\taction\n\t};\n}\nfunction updateDocumentRevision(document, scope, operationIndex) {\n\tdocument.header.revision = {\n\t\t...document.header.revision,\n\t\t[scope]: operationIndex + 1\n\t};\n}\nfunction buildSuccessResult(job, operation, documentId, documentType, resultingState, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: true,\n\t\toperations: [operation],\n\t\toperationsWithContext: [{\n\t\t\toperation,\n\t\t\tcontext: {\n\t\t\t\tdocumentId,\n\t\t\t\tscope: job.scope,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tdocumentType,\n\t\t\t\tresultingState,\n\t\t\t\tordinal: 0\n\t\t\t}\n\t\t}],\n\t\tduration: Date.now() - startTime\n\t};\n}\nfunction buildErrorResult(job, error, startTime) {\n\treturn {\n\t\tjob,\n\t\tsuccess: false,\n\t\terror,\n\t\tduration: Date.now() - startTime\n\t};\n}\n//#endregion\n//#region src/cache/lru/lru-tracker.ts\nvar LRUNode = class {\n\tkey;\n\tprev;\n\tnext;\n\tconstructor(key) {\n\t\tthis.key = key;\n\t\tthis.prev = void 0;\n\t\tthis.next = void 0;\n\t}\n};\nvar LRUTracker = class {\n\tmap;\n\thead;\n\ttail;\n\tconstructor() {\n\t\tthis.map = /* @__PURE__ */ new Map();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\tget size() {\n\t\treturn this.map.size;\n\t}\n\ttouch(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (node) this.moveToFront(node);\n\t\telse this.addToFront(key);\n\t}\n\tevict() {\n\t\tif (!this.tail) return;\n\t\tconst key = this.tail.key;\n\t\tthis.remove(key);\n\t\treturn key;\n\t}\n\tremove(key) {\n\t\tconst node = this.map.get(key);\n\t\tif (!node) return;\n\t\tthis.removeNode(node);\n\t\tthis.map.delete(key);\n\t}\n\tclear() {\n\t\tthis.map.clear();\n\t\tthis.head = void 0;\n\t\tthis.tail = void 0;\n\t}\n\taddToFront(key) {\n\t\tconst node = new LRUNode(key);\n\t\tthis.map.set(key, node);\n\t\tif (!this.head) {\n\t\t\tthis.head = node;\n\t\t\tthis.tail = node;\n\t\t} else {\n\t\t\tnode.next = this.head;\n\t\t\tthis.head.prev = node;\n\t\t\tthis.head = node;\n\t\t}\n\t}\n\tmoveToFront(node) {\n\t\tif (node === this.head) return;\n\t\tthis.removeNode(node);\n\t\tnode.prev = void 0;\n\t\tnode.next = this.head;\n\t\tif (this.head) this.head.prev = node;\n\t\tthis.head = node;\n\t\tif (!this.tail) this.tail = node;\n\t}\n\tremoveNode(node) {\n\t\tif (node.prev) node.prev.next = node.next;\n\t\telse this.head = node.next;\n\t\tif (node.next) node.next.prev = node.prev;\n\t\telse this.tail = node.prev;\n\t}\n};\n//#endregion\n//#region src/cache/document-meta-cache.ts\n/**\n* In-memory document metadata cache with LRU eviction.\n*\n* Caches PHDocumentState per (documentId, branch) key. On cache miss,\n* rebuilds from document scope operations. Provides an explicit cross-scope\n* contract for accessing document scope metadata.\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n*/\nvar DocumentMetaCache = class DocumentMetaCache {\n\tcache;\n\tlruTracker;\n\toperationStore;\n\tconfig;\n\tconstructor(operationStore, config) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.config = { maxDocuments: config.maxDocuments };\n\t\tthis.cache = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStore(operationStore) {\n\t\tconst scoped = new DocumentMetaCache(operationStore, this.config);\n\t\tscoped.cache = this.cache;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\tasync getDocumentMeta(documentId, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tconst cached = this.cache.get(key);\n\t\tif (cached) {\n\t\t\tthis.lruTracker.touch(key);\n\t\t\treturn cached;\n\t\t}\n\t\tconst meta = await this.rebuildLatest(documentId, branch, signal);\n\t\tthis.putDocumentMeta(documentId, branch, meta);\n\t\treturn meta;\n\t}\n\tasync rebuildAtRevision(documentId, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn this.rebuildFromOperations(documentId, branch, targetRevision, signal);\n\t}\n\tputDocumentMeta(documentId, branch, meta) {\n\t\tconst key = this.makeKey(documentId, branch);\n\t\tif (!this.cache.has(key) && this.cache.size >= this.config.maxDocuments) {\n\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\tif (evictKey) this.cache.delete(evictKey);\n\t\t}\n\t\tthis.cache.set(key, structuredClone(meta));\n\t\tthis.lruTracker.touch(key);\n\t}\n\tinvalidate(documentId, branch) {\n\t\tlet evicted = 0;\n\t\tif (branch === void 0) {\n\t\t\tfor (const key of this.cache.keys()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else {\n\t\t\tconst key = this.makeKey(documentId, branch);\n\t\t\tif (this.cache.has(key)) {\n\t\t\t\tthis.cache.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\tclear() {\n\t\tthis.cache.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\tmakeKey(documentId, branch) {\n\t\treturn `${documentId}:${branch}`;\n\t}\n\tasync rebuildLatest(documentId, branch, signal) {\n\t\treturn this.rebuildFromOperations(documentId, branch, void 0, signal);\n\t}\n\tasync rebuildFromOperations(documentId, branch, targetRevision, signal) {\n\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, void 0, signal);\n\t\tif (docScopeOps.results.length === 0) throw new DocumentNotFoundError(documentId);\n\t\tconst createOp = docScopeOps.results[0];\n\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Invalid document: first operation must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\tconst createAction = createOp.action;\n\t\tconst documentType = createAction.input.model;\n\t\tlet document = createDocumentFromAction(createAction);\n\t\tlet documentScopeRevision = 0;\n\t\tfor (const op of docScopeOps.results) {\n\t\t\tif (targetRevision !== void 0 && op.index > targetRevision) break;\n\t\t\tdocumentScopeRevision = op.index;\n\t\t\tif (op.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = op.action;\n\t\t\t\tdocument = applyUpgradeDocumentAction$1(document, upgradeAction);\n\t\t\t} else if (op.action.type === \"DELETE_DOCUMENT\") document = applyDeleteDocumentAction$1(document, op.action);\n\t\t}\n\t\treturn {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType,\n\t\t\tdocumentScopeRevision: documentScopeRevision + 1\n\t\t};\n\t}\n};\n//#endregion\n//#region src/cache/kysely-operation-index.ts\nvar KyselyOperationIndexTxn = class {\n\tcollections = [];\n\tcollectionMemberships = [];\n\tcollectionRemovals = [];\n\toperations = [];\n\tcreateCollection(collectionId) {\n\t\tthis.collections.push(collectionId);\n\t}\n\taddToCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"addToCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionMemberships.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\tremoveFromCollection(collectionId, documentId) {\n\t\tconst lastOpIndex = this.operations.length - 1;\n\t\tif (lastOpIndex < 0) throw new Error(\"removeFromCollection must be called after write() - no operations in transaction\");\n\t\tthis.collectionRemovals.push({\n\t\t\tcollectionId,\n\t\t\tdocumentId,\n\t\t\toperationIndex: lastOpIndex\n\t\t});\n\t}\n\twrite(operations) {\n\t\tthis.operations.push(...operations);\n\t}\n\tgetCollections() {\n\t\treturn this.collections;\n\t}\n\tgetCollectionMembershipRecords() {\n\t\treturn this.collectionMemberships;\n\t}\n\tgetCollectionRemovals() {\n\t\treturn this.collectionRemovals;\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\nvar KyselyOperationIndex = class KyselyOperationIndex {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationIndex(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tstart() {\n\t\treturn new KyselyOperationIndexTxn();\n\t}\n\tasync commit(txn, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst kyselyTxn = txn;\n\t\tif (this.trx) return this.executeCommit(this.trx, kyselyTxn);\n\t\tlet resultOrdinals = [];\n\t\tawait this.db.transaction().execute(async (trx) => {\n\t\t\tresultOrdinals = await this.executeCommit(trx, kyselyTxn);\n\t\t});\n\t\treturn resultOrdinals;\n\t}\n\tasync executeCommit(trx, kyselyTxn) {\n\t\tconst collections = kyselyTxn.getCollections();\n\t\tconst memberships = kyselyTxn.getCollectionMembershipRecords();\n\t\tconst removals = kyselyTxn.getCollectionRemovals();\n\t\tconst operations = kyselyTxn.getOperations();\n\t\tif (collections.length > 0) {\n\t\t\tconst collectionRows = collections.map((collectionId) => ({\n\t\t\t\tdocumentId: collectionId,\n\t\t\t\tcollectionId,\n\t\t\t\tjoinedOrdinal: BigInt(0),\n\t\t\t\tleftOrdinal: null\n\t\t\t}));\n\t\t\tawait trx.insertInto(\"document_collections\").values(collectionRows).onConflict((oc) => oc.doNothing()).execute();\n\t\t}\n\t\tlet operationOrdinals = [];\n\t\tif (operations.length > 0) {\n\t\t\tconst operationRows = operations.map((op) => ({\n\t\t\t\topId: op.id || \"\",\n\t\t\t\tdocumentId: op.documentId,\n\t\t\t\tdocumentType: op.documentType,\n\t\t\t\tscope: op.scope,\n\t\t\t\tbranch: op.branch,\n\t\t\t\ttimestampUtcMs: op.timestampUtcMs,\n\t\t\t\tindex: op.index,\n\t\t\t\tskip: op.skip,\n\t\t\t\thash: op.hash,\n\t\t\t\taction: op.action,\n\t\t\t\tsourceRemote: op.sourceRemote\n\t\t\t}));\n\t\t\toperationOrdinals = (await trx.insertInto(\"operation_index_operations\").values(operationRows).returning(\"ordinal\").execute()).map((row) => row.ordinal);\n\t\t}\n\t\tif (memberships.length > 0) for (const m of memberships) {\n\t\t\tconst ordinal = operationOrdinals[m.operationIndex];\n\t\t\tawait trx.insertInto(\"document_collections\").values({\n\t\t\t\tdocumentId: m.documentId,\n\t\t\t\tcollectionId: m.collectionId,\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t}).onConflict((oc) => oc.columns([\"documentId\", \"collectionId\"]).doUpdateSet({\n\t\t\t\tjoinedOrdinal: BigInt(ordinal),\n\t\t\t\tleftOrdinal: null\n\t\t\t})).execute();\n\t\t}\n\t\tif (removals.length > 0) for (const r of removals) {\n\t\t\tconst ordinal = operationOrdinals[r.operationIndex];\n\t\t\tawait trx.updateTable(\"document_collections\").set({ leftOrdinal: BigInt(ordinal) }).where(\"collectionId\", \"=\", r.collectionId).where(\"documentId\", \"=\", r.documentId).where(\"leftOrdinal\", \"is\", null).execute();\n\t\t}\n\t\treturn operationOrdinals;\n\t}\n\tasync find(collectionId, cursor, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst outerCursor = cursor ?? -1;\n\t\tconst pagingCursorOrdinal = paging?.cursor !== void 0 ? Number.parseInt(paging.cursor, 10) : -1;\n\t\tconst buildBranch = (kind) => {\n\t\t\tlet qb = this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").selectAll(\"oi\").select([\"dc.documentId\", \"dc.collectionId\"]).where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`);\n\t\t\tif (kind === \"joiner\") qb = qb.where(\"dc.joinedOrdinal\", \">\", BigInt(outerCursor)).where(\"oi.ordinal\", \"<=\", outerCursor);\n\t\t\telse qb = qb.where(\"oi.ordinal\", \">\", outerCursor);\n\t\t\tqb = qb.where(\"oi.ordinal\", \">\", pagingCursorOrdinal);\n\t\t\tif (view?.branch) qb = qb.where(\"oi.branch\", \"=\", view.branch);\n\t\t\tif (view?.scopes && view.scopes.length > 0) qb = qb.where(\"oi.scope\", \"in\", view.scopes);\n\t\t\tif (view?.excludeSourceRemote) qb = qb.where(\"oi.sourceRemote\", \"!=\", view.excludeSourceRemote);\n\t\t\treturn qb;\n\t\t};\n\t\tlet unionQuery = buildBranch(\"joiner\").unionAll(buildBranch(\"newOps\")).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.limit) unionQuery = unionQuery.limit(paging.limit + 1);\n\t\tconst rows = await unionQuery.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.find(collectionId, cursor, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync get(documentId, view, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"ordinal\", \"asc\");\n\t\tif (view?.branch) query = query.where(\"branch\", \"=\", view.branch);\n\t\tif (view?.scopes && view.scopes.length > 0) query = query.where(\"scope\", \"in\", view.scopes);\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationIndexEntry(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.get(documentId, view, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\tasync getSinceOrdinal(ordinal, paging, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"operation_index_operations\").selectAll().where(\"ordinal\", \">\", ordinal).orderBy(\"ordinal\", \"asc\");\n\t\tif (paging?.cursor) {\n\t\t\tconst cursorOrdinal = Number.parseInt(paging.cursor, 10);\n\t\t\tquery = query.where(\"ordinal\", \">\", cursorOrdinal);\n\t\t}\n\t\tif (paging?.limit) query = query.limit(paging.limit + 1);\n\t\tconst rows = await query.execute();\n\t\tlet hasMore = false;\n\t\tlet items = rows;\n\t\tif (paging?.limit && rows.length > paging.limit) {\n\t\t\thasMore = true;\n\t\t\titems = rows.slice(0, paging.limit);\n\t\t}\n\t\tconst nextCursor = hasMore && items.length > 0 ? items[items.length - 1].ordinal.toString() : void 0;\n\t\tconst cursorValue = paging?.cursor || \"0\";\n\t\tconst limit = paging?.limit || 100;\n\t\treturn {\n\t\t\tresults: items.map((row) => this.rowToOperationWithContext(row)),\n\t\t\toptions: {\n\t\t\t\tcursor: cursorValue,\n\t\t\t\tlimit\n\t\t\t},\n\t\t\tnextCursor,\n\t\t\tnext: hasMore ? () => this.getSinceOrdinal(ordinal, {\n\t\t\t\tcursor: nextCursor,\n\t\t\t\tlimit\n\t\t\t}, signal) : void 0\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: {\n\t\t\t\tindex: row.index,\n\t\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\t\thash: row.hash,\n\t\t\t\tskip: row.skip,\n\t\t\t\taction: row.action,\n\t\t\t\tid: row.opId\n\t\t\t},\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.ordinal\n\t\t\t}\n\t\t};\n\t}\n\trowToOperationIndexEntry(row) {\n\t\treturn {\n\t\t\tordinal: row.ordinal,\n\t\t\tdocumentId: row.documentId,\n\t\t\tdocumentType: row.documentType,\n\t\t\tbranch: row.branch,\n\t\t\tscope: row.scope,\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs,\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\taction: row.action,\n\t\t\tid: row.opId,\n\t\t\tsourceRemote: row.sourceRemote\n\t\t};\n\t}\n\tasync getLatestTimestampForCollection(collectionId, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\treturn (await this.queryExecutor.selectFrom(\"operation_index_operations as oi\").innerJoin(\"document_collections as dc\", \"oi.documentId\", \"dc.documentId\").select(\"oi.timestampUtcMs\").where(\"dc.collectionId\", \"=\", collectionId).where(sql`(dc.\"leftOrdinal\" IS NULL OR oi.ordinal < dc.\"leftOrdinal\")`).orderBy(\"oi.ordinal\", \"desc\").limit(1).executeTakeFirst())?.timestampUtcMs ?? null;\n\t}\n\tasync getCollectionsForDocuments(documentIds) {\n\t\tif (documentIds.length === 0) return {};\n\t\tconst rows = await this.queryExecutor.selectFrom(\"document_collections\").select([\"documentId\", \"collectionId\"]).where(\"documentId\", \"in\", documentIds).where(\"leftOrdinal\", \"is\", null).execute();\n\t\tconst result = {};\n\t\tfor (const row of rows) {\n\t\t\tif (!(row.documentId in result)) result[row.documentId] = [];\n\t\t\tresult[row.documentId].push(row.collectionId);\n\t\t}\n\t\treturn result;\n\t}\n};\n//#endregion\n//#region src/cache/buffer/ring-buffer.ts\n/**\n* RingBuffer is a generic circular buffer implementation that stores a fixed number\n* of items. When the buffer is full, new items overwrite the oldest items.\n*\n* This implementation maintains O(1) time complexity for push operations and provides\n* items in chronological order (oldest to newest) via getAll().\n*\n* @template T - The type of items stored in the buffer\n*/\nvar RingBuffer = class {\n\tbuffer;\n\thead = 0;\n\tsize = 0;\n\tcapacity;\n\tconstructor(capacity) {\n\t\tif (capacity <= 0) throw new Error(\"Ring buffer capacity must be greater than 0\");\n\t\tthis.capacity = capacity;\n\t\tthis.buffer = new Array(capacity);\n\t}\n\t/**\n\t* Adds an item to the buffer. If the buffer is full, overwrites the oldest item.\n\t*\n\t* @param item - The item to add\n\t*/\n\tpush(item) {\n\t\tconst index = (this.head + this.size) % this.capacity;\n\t\tif (this.size < this.capacity) {\n\t\t\tthis.buffer[index] = item;\n\t\t\tthis.size++;\n\t\t} else {\n\t\t\tthis.buffer[this.head] = item;\n\t\t\tthis.head = (this.head + 1) % this.capacity;\n\t\t}\n\t}\n\t/**\n\t* Returns all items in the buffer in chronological order (oldest to newest).\n\t*\n\t* @returns Array of items in insertion order\n\t*/\n\tgetAll() {\n\t\tif (this.size === 0) return [];\n\t\tconst result = [];\n\t\tfor (let i = 0; i < this.size; i++) {\n\t\t\tconst index = (this.head + i) % this.capacity;\n\t\t\tresult.push(this.buffer[index]);\n\t\t}\n\t\treturn result;\n\t}\n\t/**\n\t* Clears all items from the buffer.\n\t*/\n\tclear() {\n\t\tthis.buffer = new Array(this.capacity);\n\t\tthis.head = 0;\n\t\tthis.size = 0;\n\t}\n\t/**\n\t* Gets the current number of items in the buffer.\n\t*/\n\tget length() {\n\t\treturn this.size;\n\t}\n};\n//#endregion\n//#region src/cache/kysely-write-cache.ts\nfunction extractModuleVersion(doc) {\n\tconst v = doc.state.document.version;\n\treturn v === 0 ? void 0 : v;\n}\n/**\n* In-memory write cache with keyframe persistence for PHDocuments.\n*\n* Caches document snapshots in ring buffers with LRU eviction. On cache miss,\n* rebuilds documents from nearest keyframe or full operation history.\n*\n* **Performance Characteristics:**\n* - Cache hit: O(1) lookup in ring buffer\n* - Cold miss: O(n) where n is total operation count, or O(k) where k is operations since keyframe\n* - Warm miss: O(m) where m is operations since cached revision\n* - Eviction: O(1) for LRU tracking and removal\n*\n* **Thread Safety:**\n* Not thread-safe. Designed for single-threaded job executor environment.\n* External synchronization required for concurrent access across multiple executors.\n*\n* **Example:**\n* ```typescript\n* const cache = new KyselyWriteCache(\n* keyframeStore,\n* operationStore,\n* registry,\n* { maxDocuments: 1000, ringBufferSize: 10, keyframeInterval: 10 }\n* );\n*\n* await cache.startup();\n*\n* // Retrieve or rebuild document\n* const doc = await cache.getState(docId, docType, scope, branch, revision);\n*\n* // Cache result after job execution\n* cache.putState(docId, docType, scope, branch, newRevision, updatedDoc);\n*\n* await cache.shutdown();\n* ```\n*/\nvar KyselyWriteCache = class KyselyWriteCache {\n\tstreams;\n\tlruTracker;\n\tkeyframeStore;\n\toperationStore;\n\tregistry;\n\tconfig;\n\tconstructor(keyframeStore, operationStore, registry, config) {\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.operationStore = operationStore;\n\t\tthis.registry = registry;\n\t\tthis.config = {\n\t\t\tmaxDocuments: config.maxDocuments,\n\t\t\tringBufferSize: config.ringBufferSize,\n\t\t\tkeyframeInterval: config.keyframeInterval\n\t\t};\n\t\tthis.streams = /* @__PURE__ */ new Map();\n\t\tthis.lruTracker = new LRUTracker();\n\t}\n\twithScopedStores(operationStore, keyframeStore) {\n\t\tconst scoped = new KyselyWriteCache(keyframeStore, operationStore, this.registry, this.config);\n\t\tscoped.streams = this.streams;\n\t\tscoped.lruTracker = this.lruTracker;\n\t\treturn scoped;\n\t}\n\t/**\n\t* Initializes the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync startup() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Shuts down the write cache.\n\t* Currently a no-op as keyframe store lifecycle is managed externally.\n\t*/\n\tasync shutdown() {\n\t\treturn Promise.resolve();\n\t}\n\t/**\n\t* Retrieves document state at a specific revision from cache or rebuilds it.\n\t*\n\t* Cache hit path: Returns cached snapshot if available (O(1))\n\t* Warm miss path: Rebuilds from cached base revision + incremental ops\n\t* Cold miss path: Rebuilds from keyframe or from scratch using all operations\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param targetRevision - The target revision, or undefined for newest\n\t* @param signal - Optional abort signal to cancel the operation\n\t* @returns The document at the target revision\n\t* @throws {Error} \"Operation aborted\" if signal is aborted\n\t* @throws {ModuleNotFoundError} If document type not registered in registry\n\t* @throws {Error} \"Failed to rebuild document\" if operation store fails\n\t* @throws {Error} If reducer throws during operation application\n\t* @throws {Error} If document serialization fails\n\t*/\n\tasync getState(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.streams.get(streamKey);\n\t\tif (stream) {\n\t\t\tconst snapshots = stream.ringBuffer.getAll();\n\t\t\tif (targetRevision === void 0) {\n\t\t\t\tif (snapshots.length > 0) {\n\t\t\t\t\tconst newest = snapshots[snapshots.length - 1];\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn newest.document;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst exactMatch = snapshots.find((s) => s.revision === targetRevision);\n\t\t\t\tif (exactMatch) {\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn exactMatch.document;\n\t\t\t\t}\n\t\t\t\tconst newestOlder = this.findNearestOlderSnapshot(snapshots, targetRevision);\n\t\t\t\tif (newestOlder) {\n\t\t\t\t\tconst document = await this.warmMissRebuild(newestOlder.document, newestOlder.revision, documentId, scope, branch, targetRevision, signal);\n\t\t\t\t\tthis.putState(documentId, scope, branch, targetRevision, document);\n\t\t\t\t\tthis.lruTracker.touch(streamKey);\n\t\t\t\t\treturn document;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst document = await this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tlet revision = targetRevision;\n\t\tif (revision === void 0) revision = document.header.revision[scope] || 0;\n\t\tthis.putState(documentId, scope, branch, revision, document);\n\t\treturn document;\n\t}\n\t/**\n\t* Stores a document snapshot in the cache at a specific revision.\n\t*\n\t* The cached document is a shallow copy of the input with its operation history\n\t* truncated to the last operation per scope and its clipboard cleared. This keeps\n\t* memory use and copy costs constant regardless of operation count. Consumers of\n\t* getState() must not rely on the full operation history being present; the only\n\t* guaranteed invariant is that operations[scope].at(-1) reflects the latest\n\t* operation index for each scope.\n\t*\n\t* Updates LRU tracker and may evict least recently used stream if at capacity.\n\t* Asynchronously persists keyframes at configured intervals (fire-and-forget).\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - The operation scope\n\t* @param branch - The operation branch\n\t* @param revision - The revision number\n\t* @param document - The document to cache\n\t* @throws {Error} If document serialization fails\n\t*/\n\tputState(documentId, scope, branch, revision, document) {\n\t\tconst streamKey = this.makeStreamKey(documentId, scope, branch);\n\t\tconst stream = this.getOrCreateStream(streamKey);\n\t\tconst snapshot = {\n\t\t\trevision,\n\t\t\tdocument: {\n\t\t\t\t...document,\n\t\t\t\toperations: Object.fromEntries(Object.entries(document.operations).map(([k, ops]) => [k, ops.length ? [ops.at(-1)] : []])),\n\t\t\t\tclipboard: []\n\t\t\t}\n\t\t};\n\t\tstream.ringBuffer.push(snapshot);\n\t\tif (this.isKeyframeRevision(revision)) this.keyframeStore.putKeyframe(documentId, scope, branch, revision, {\n\t\t\t...document,\n\t\t\toperations: {},\n\t\t\tclipboard: []\n\t\t}).catch((err) => {\n\t\t\tconsole.error(`Failed to persist keyframe ${documentId}@${revision}:`, err);\n\t\t});\n\t}\n\t/**\n\t* Invalidates cached document streams.\n\t*\n\t* Supports three invalidation scopes:\n\t* - Document-level: invalidate(documentId) - removes all streams for document\n\t* - Scope-level: invalidate(documentId, scope) - removes all branches for scope\n\t* - Stream-level: invalidate(documentId, scope, branch) - removes specific stream\n\t*\n\t* @param documentId - The document identifier\n\t* @param scope - Optional scope to narrow invalidation\n\t* @param branch - Optional branch to narrow invalidation (requires scope)\n\t* @returns The number of streams evicted\n\t*/\n\tinvalidate(documentId, scope, branch) {\n\t\tlet evicted = 0;\n\t\tif (scope === void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch === void 0) {\n\t\t\tfor (const [key] of this.streams.entries()) if (key.startsWith(`${documentId}:${scope}:`)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted++;\n\t\t\t}\n\t\t} else if (scope !== void 0 && branch !== void 0) {\n\t\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\t\tif (this.streams.has(key)) {\n\t\t\t\tthis.streams.delete(key);\n\t\t\t\tthis.lruTracker.remove(key);\n\t\t\t\tevicted = 1;\n\t\t\t}\n\t\t}\n\t\treturn evicted;\n\t}\n\t/**\n\t* Clears the entire cache, removing all cached document streams.\n\t* Resets LRU tracking state. This operation always succeeds.\n\t*/\n\tclear() {\n\t\tthis.streams.clear();\n\t\tthis.lruTracker.clear();\n\t}\n\t/**\n\t* Retrieves a specific stream for a document. Exposed on the implementation\n\t* for testing, but not on the interface.\n\t*\n\t* @internal\n\t*/\n\tgetStream(documentId, scope, branch) {\n\t\tconst key = this.makeStreamKey(documentId, scope, branch);\n\t\treturn this.streams.get(key);\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (targetRevision === Number.MAX_SAFE_INTEGER || targetRevision <= 0) return;\n\t\treturn this.keyframeStore.findNearestKeyframe(documentId, scope, branch, targetRevision, signal);\n\t}\n\tasync coldMissRebuild(documentId, scope, branch, targetRevision, signal) {\n\t\tconst effectiveTargetRevision = targetRevision || Number.MAX_SAFE_INTEGER;\n\t\tconst keyframe = await this.findNearestKeyframe(documentId, scope, branch, effectiveTargetRevision, signal);\n\t\tlet document;\n\t\tlet startRevision;\n\t\tlet documentType;\n\t\tconst validatedUpgrades = [];\n\t\tif (keyframe) {\n\t\t\tdocument = keyframe.document;\n\t\t\tstartRevision = keyframe.revision;\n\t\t\tdocumentType = keyframe.document.header.documentType;\n\t\t\tconst docScopeOpsAfterKeyframe = await this.operationStore.getSince(documentId, \"document\", branch, keyframe.revision, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOpsAfterKeyframe.results) if (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\tlet upgradePath;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t}\n\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t});\n\t\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction, upgradePath);\n\t\t\t\t}\n\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\") applyDeleteDocumentAction(document, operation.action);\n\t\t} else {\n\t\t\tstartRevision = -1;\n\t\t\tconst createOpResult = await this.operationStore.getSince(documentId, \"document\", branch, -1, void 0, {\n\t\t\t\tcursor: \"0\",\n\t\t\t\tlimit: 1\n\t\t\t}, signal);\n\t\t\tif (createOpResult.results.length === 0) throw new Error(`Failed to rebuild document ${documentId}: no CREATE_DOCUMENT operation found in document scope`);\n\t\t\tconst createOp = createOpResult.results[0];\n\t\t\tif (createOp.action.type !== \"CREATE_DOCUMENT\") throw new Error(`Failed to rebuild document ${documentId}: first operation in document scope must be CREATE_DOCUMENT, found ${createOp.action.type}`);\n\t\t\tconst documentCreateAction = createOp.action;\n\t\t\tdocumentType = documentCreateAction.input.model;\n\t\t\tif (!documentType) throw new Error(`Failed to rebuild document ${documentId}: CREATE_DOCUMENT action missing model in input`);\n\t\t\tdocument = createDocumentFromAction(documentCreateAction);\n\t\t\tlet docModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\tconst docScopeOps = await this.operationStore.getSince(documentId, \"document\", branch, 0, void 0, void 0, signal);\n\t\t\tfor (const operation of docScopeOps.results) {\n\t\t\t\tif (operation.index === 0) continue;\n\t\t\t\tif (operation.action.type === \"UPGRADE_DOCUMENT\") {\n\t\t\t\t\tconst upgradeAction = operation.action;\n\t\t\t\t\tconst fromVersion = upgradeAction.input.fromVersion;\n\t\t\t\t\tconst toVersion = upgradeAction.input.toVersion;\n\t\t\t\t\tlet upgradePath;\n\t\t\t\t\tif (fromVersion > 0 && fromVersion < toVersion) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tupgradePath = this.registry.computeUpgradePath(documentType, fromVersion, toVersion);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tif (upgradeAction.input.initialState !== void 0) upgradePath = void 0;\n\t\t\t\t\t\t\telse throw new Error(`Failed to rebuild document ${documentId}: no upgrade manifest for ${documentType} v${fromVersion}→v${toVersion} and no initialState snapshot. ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalidatedUpgrades.push({\n\t\t\t\t\t\t\tfromVersion,\n\t\t\t\t\t\t\ttoVersion,\n\t\t\t\t\t\t\trevision: upgradeAction.input.revision,\n\t\t\t\t\t\t\ttimestampUtcMs: operation.timestampUtcMs\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tdocument = applyUpgradeDocumentAction(document, upgradeAction, upgradePath);\n\t\t\t\t\tdocModule = this.registry.getModule(documentType, extractModuleVersion(document));\n\t\t\t\t} else if (operation.action.type === \"DELETE_DOCUMENT\") applyDeleteDocumentAction(document, operation.action);\n\t\t\t\telse {\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = docModule.reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst moduleCache = /* @__PURE__ */ new Map();\n\t\tconst getModuleCached = (version) => {\n\t\t\tconst key = version ?? 0;\n\t\t\tlet mod = moduleCache.get(key);\n\t\t\tif (!mod) {\n\t\t\t\tmod = this.registry.getModule(documentType, version);\n\t\t\t\tmoduleCache.set(key, mod);\n\t\t\t}\n\t\t\treturn mod;\n\t\t};\n\t\tlet cursor = void 0;\n\t\tconst pageSize = 100;\n\t\tlet hasMorePages;\n\t\tdo {\n\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\tconst paging = {\n\t\t\t\tcursor: cursor || \"0\",\n\t\t\t\tlimit: pageSize\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tconst result = await this.operationStore.getSince(documentId, scope, branch, startRevision, void 0, paging, signal);\n\t\t\t\tfor (const operation of result.results) {\n\t\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\t\tconst moduleVersion = this.resolveModuleVersionForOp(operation.index, operation.timestampUtcMs, scope, validatedUpgrades, extractModuleVersion(document));\n\t\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\t\tdocument = getModuleCached(moduleVersion).reducer(document, operation.action, void 0, {\n\t\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\t\tprotocolVersion\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst reachedTarget = targetRevision !== void 0 && result.results.some((op) => op.index >= targetRevision);\n\t\t\t\thasMorePages = Boolean(result.nextCursor) && !reachedTarget;\n\t\t\t\tif (hasMorePages) cursor = result.nextCursor;\n\t\t\t} catch (err) {\n\t\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t\t}\n\t\t} while (hasMorePages);\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\t/**\n\t* Resolves which module version to use for a given operation in phase 2.\n\t*\n\t* Uses the validated-upgrade boundary rules from D7:\n\t* - If `input.revision` is present: op.index < revision[scope] → before the upgrade boundary\n\t* - Otherwise: timestamp fallback\n\t* - Falls back to final module version when neither is decidable\n\t*/\n\tresolveModuleVersionForOp(opIndex, opTimestamp, scope, validatedUpgrades, finalVersion) {\n\t\tif (validatedUpgrades.length === 0) return finalVersion;\n\t\tlet currentVersion = validatedUpgrades[0]?.fromVersion;\n\t\tfor (const upgrade of validatedUpgrades) {\n\t\t\tlet beforeUpgrade;\n\t\t\tif (upgrade.revision !== void 0) beforeUpgrade = opIndex < (upgrade.revision[scope] ?? 0);\n\t\t\telse beforeUpgrade = opTimestamp < upgrade.timestampUtcMs;\n\t\t\tif (beforeUpgrade) return currentVersion;\n\t\t\tcurrentVersion = upgrade.toVersion;\n\t\t}\n\t\treturn currentVersion;\n\t}\n\tasync warmMissRebuild(baseDocument, baseRevision, documentId, scope, branch, targetRevision, signal) {\n\t\tconst documentType = baseDocument.header.documentType;\n\t\tconst docScopeNextIndex = baseDocument.header.revision[\"document\"] ?? 0;\n\t\tif ((await this.operationStore.getSince(documentId, \"document\", branch, docScopeNextIndex - 1, void 0, void 0, signal)).results.some((op) => op.action.type === \"UPGRADE_DOCUMENT\")) return this.coldMissRebuild(documentId, scope, branch, targetRevision, signal);\n\t\tconst module = this.registry.getModule(documentType, extractModuleVersion(baseDocument));\n\t\tlet document = baseDocument;\n\t\ttry {\n\t\t\tconst pagedResults = await this.operationStore.getSince(documentId, scope, branch, baseRevision, void 0, void 0, signal);\n\t\t\tfor (const operation of pagedResults.results) {\n\t\t\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\t\t\tif (targetRevision !== void 0 && operation.index > targetRevision) break;\n\t\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\t\tdocument = module.reducer(document, operation.action, void 0, {\n\t\t\t\t\tskip: operation.skip,\n\t\t\t\t\tprotocolVersion\n\t\t\t\t});\n\t\t\t\tif (targetRevision !== void 0 && operation.index === targetRevision) break;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tthrow new Error(`Failed to rebuild document ${documentId}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });\n\t\t}\n\t\tconst revisions = await this.operationStore.getRevisions(documentId, branch, signal);\n\t\tdocument.header.revision = revisions.revision;\n\t\tdocument.header.lastModifiedAtUtcIso = revisions.latestTimestamp;\n\t\treturn document;\n\t}\n\tfindNearestOlderSnapshot(snapshots, targetRevision) {\n\t\tlet nearest = void 0;\n\t\tfor (const snapshot of snapshots) if (snapshot.revision < targetRevision) {\n\t\t\tif (!nearest || snapshot.revision > nearest.revision) nearest = snapshot;\n\t\t}\n\t\treturn nearest;\n\t}\n\tmakeStreamKey(documentId, scope, branch) {\n\t\treturn `${documentId}:${scope}:${branch}`;\n\t}\n\tgetOrCreateStream(key) {\n\t\tlet stream = this.streams.get(key);\n\t\tif (!stream) {\n\t\t\tif (this.streams.size >= this.config.maxDocuments) {\n\t\t\t\tconst evictKey = this.lruTracker.evict();\n\t\t\t\tif (evictKey) this.streams.delete(evictKey);\n\t\t\t}\n\t\t\tstream = {\n\t\t\t\tkey,\n\t\t\t\tringBuffer: new RingBuffer(this.config.ringBufferSize)\n\t\t\t};\n\t\t\tthis.streams.set(key, stream);\n\t\t}\n\t\tthis.lruTracker.touch(key);\n\t\treturn stream;\n\t}\n\tisKeyframeRevision(revision) {\n\t\treturn revision > 0 && revision % this.config.keyframeInterval === 0;\n\t}\n};\n//#endregion\n//#region src/events/event-bus.ts\nvar EventBus = class {\n\teventTypeToSubscribers = /* @__PURE__ */ new Map();\n\tsubscribe(type, subscriber) {\n\t\tlet list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list) {\n\t\t\tlist = [];\n\t\t\tthis.eventTypeToSubscribers.set(type, list);\n\t\t}\n\t\tlist.push(subscriber);\n\t\tlet done = false;\n\t\treturn () => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tconst arr = this.eventTypeToSubscribers.get(type);\n\t\t\tif (!arr) return;\n\t\t\tconst idx = arr.indexOf(subscriber);\n\t\t\tif (idx !== -1) arr.splice(idx, 1);\n\t\t\tif (arr.length === 0) this.eventTypeToSubscribers.delete(type);\n\t\t};\n\t}\n\tasync emit(type, data) {\n\t\tconst list = this.eventTypeToSubscribers.get(type);\n\t\tif (!list || list.length === 0) return;\n\t\tconst snapshot = list.slice();\n\t\tconst errors = [];\n\t\tfor (const fn of snapshot) try {\n\t\t\tawait Promise.resolve(fn(type, data));\n\t\t} catch (err) {\n\t\t\terrors.push(err);\n\t\t}\n\t\tif (errors.length > 0) throw new EventBusAggregateError(errors);\n\t}\n};\n//#endregion\n//#region src/executor/execution-scope.ts\nvar DefaultExecutionScope = class {\n\tconstructor(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn fn({\n\t\t\toperationStore: this.operationStore,\n\t\t\toperationIndex: this.operationIndex,\n\t\t\twriteCache: this.writeCache,\n\t\t\tdocumentMetaCache: this.documentMetaCache,\n\t\t\tcollectionMembershipCache: this.collectionMembershipCache\n\t\t});\n\t}\n};\nvar KyselyExecutionScope = class {\n\tconstructor(db, operationStore, operationIndex, keyframeStore, writeCache, documentMetaCache, collectionMembershipCache) {\n\t\tthis.db = db;\n\t\tthis.operationStore = operationStore;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.keyframeStore = keyframeStore;\n\t\tthis.writeCache = writeCache;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t}\n\tasync run(fn, signal) {\n\t\tsignal?.throwIfAborted();\n\t\treturn this.db.transaction().execute(async (trx) => {\n\t\t\tconst scopedOperationStore = this.operationStore.withTransaction(trx);\n\t\t\tconst scopedOperationIndex = this.operationIndex.withTransaction(trx);\n\t\t\tconst scopedKeyframeStore = this.keyframeStore.withTransaction(trx);\n\t\t\treturn fn({\n\t\t\t\toperationStore: scopedOperationStore,\n\t\t\t\toperationIndex: scopedOperationIndex,\n\t\t\t\twriteCache: this.writeCache.withScopedStores(scopedOperationStore, scopedKeyframeStore),\n\t\t\t\tdocumentMetaCache: this.documentMetaCache.withScopedStore(scopedOperationStore),\n\t\t\t\tcollectionMembershipCache: this.collectionMembershipCache.withScopedIndex(scopedOperationIndex)\n\t\t\t});\n\t\t});\n\t}\n};\n//#endregion\n//#region src/utils/reshuffle.ts\nconst STRICT_ORDER_ACTION_TYPES = new Set([\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\",\n\t\"ADD_FOLDER\",\n\t\"UPDATE_FOLDER\",\n\t\"REMOVE_FOLDER\"\n]);\n/**\n* Reshuffles operations by timestamp, then applies deterministic tie-breaking.\n* Used for merging concurrent operations from different branches.\n*\n* For strict document-structure actions (e.g., CREATE_DOCUMENT/UPGRADE_DOCUMENT),\n* logical index (index - skip) is prioritized to preserve causal replay order.\n*\n* For other actions, action ID is prioritized to ensure a canonical cross-reactor order\n* for concurrent operations that may have diverged local indices due to prior reshuffles.\n* Logical index and operation ID are then used as deterministic tie-breakers.\n*\n* Example:\n* [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, 2:0, B3:0, B4:2, B5:0]\n* GC => [0:0, 1:0, 2:0, A3:0, A4:0, A5:0] + [0:0, 1:0, B4:2, B5:0]\n* Split => [0:0, 1:0] + [2:0, A3:0, A4:0, A5:0] + [B4:2, B5:0]\n* Reshuffle(6:4) => [6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n* merge => [0:0, 1:0, 6:4, 7:0, 8:0, 9:0, 10:0, 11:0]\n*/\nfunction reshuffleByTimestamp(startIndex, opsA, opsB) {\n\treturn [...opsA, ...opsB].sort((a, b) => {\n\t\tconst timestampDiff = new Date(a.timestampUtcMs).getTime() - new Date(b.timestampUtcMs).getTime();\n\t\tif (timestampDiff !== 0) return timestampDiff;\n\t\tconst shouldPrioritizeLogicalIndex = STRICT_ORDER_ACTION_TYPES.has(a.action?.type ?? \"\") || STRICT_ORDER_ACTION_TYPES.has(b.action?.type ?? \"\");\n\t\tconst logicalIndexDiff = a.index - a.skip - (b.index - b.skip);\n\t\tif (shouldPrioritizeLogicalIndex) {\n\t\t\tif (logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\t}\n\t\tconst actionIdDiff = (a.action?.id ?? \"\").localeCompare(b.action?.id ?? \"\");\n\t\tif (actionIdDiff !== 0) return actionIdDiff;\n\t\tif (!shouldPrioritizeLogicalIndex && logicalIndexDiff !== 0) return logicalIndexDiff;\n\t\treturn a.id.localeCompare(b.id);\n\t}).map((op, i) => ({\n\t\t...op,\n\t\tindex: startIndex.index + i,\n\t\tskip: i === 0 ? startIndex.skip : 0\n\t}));\n}\n//#endregion\n//#region src/cache/operation-index-types.ts\nfunction driveCollectionId(branch, driveId) {\n\treturn `drive.${branch}.${driveId}`;\n}\n//#endregion\n//#region src/executor/document-action-handler.ts\nvar DocumentActionHandler = class {\n\tconstructor(registry, logger, driveContainerTypes) {\n\t\tthis.registry = registry;\n\t\tthis.logger = logger;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t}\n\tasync execute(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tswitch (action.type) {\n\t\t\tcase \"CREATE_DOCUMENT\": return this.executeCreate(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"DELETE_DOCUMENT\": return this.executeDelete(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPGRADE_DOCUMENT\": return this.executeUpgrade(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal);\n\t\t\tcase \"ADD_RELATIONSHIP\": return this.executeAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"REMOVE_RELATIONSHIP\": return this.executeRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tcase \"UPDATE_RELATIONSHIP\": return this.executeUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote, signal);\n\t\t\tdefault: return buildErrorResult(job, /* @__PURE__ */ new Error(`Unknown document action type: ${action.type}`), startTime);\n\t\t}\n\t}\n\tasync executeCreate(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tif (job.scope !== \"document\") return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`CREATE_DOCUMENT must be in \"document\" scope, got \"${job.scope}\"`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst document = createDocumentFromAction(action);\n\t\tlet operation = createOperation(action, 0, skip, {\n\t\t\tdocumentId: document.header.id,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(document.header.id, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(document.header.id, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: document.header.id,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (this.driveContainerTypes.has(document.header.documentType)) {\n\t\t\tconst collectionId = driveCollectionId(job.branch, document.header.id);\n\t\t\tindexTxn.createCollection(collectionId);\n\t\t\tindexTxn.addToCollection(collectionId, document.header.id);\n\t\t}\n\t\tstores.documentMetaCache.putDocumentMeta(document.header.id, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, document.header.id, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeDelete(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"DELETE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document before deletion: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tlet operation = createOperation(action, getNextIndexForScope(document, job.scope), 0, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tapplyDeleteDocumentAction$1(document, action);\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\tdocument: document.state.document\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\tasync executeUpgrade(job, action, startTime, indexTxn, stores, skip = 0, sourceRemote = \"\", signal) {\n\t\tconst input = action.input;\n\t\tif (!input.documentId) return buildErrorResult(job, /* @__PURE__ */ new Error(\"UPGRADE_DOCUMENT action requires a documentId in input\"), startTime);\n\t\tconst documentId = input.documentId;\n\t\tconst fromVersion = input.fromVersion;\n\t\tconst toVersion = input.toVersion;\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`Failed to fetch document for upgrade: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tconst documentState = document.state.document;\n\t\tif (documentState.isDeleted) return buildErrorResult(job, new DocumentDeletedError(documentId, documentState.deletedAtUtcIso), startTime);\n\t\tconst nextIndex = getNextIndexForScope(document, job.scope);\n\t\tlet upgradePath;\n\t\tif (fromVersion > 0 && fromVersion < toVersion) try {\n\t\t\tupgradePath = this.registry.computeUpgradePath(document.header.documentType, fromVersion, toVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (fromVersion === toVersion && fromVersion > 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\ttry {\n\t\t\tdocument = applyUpgradeDocumentAction$1(document, action, upgradePath);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, nextIndex, skip, {\n\t\t\tdocumentId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst resultingStateObj = {\n\t\t\theader: document.header,\n\t\t\t...document.state\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tconst writeResult = await this.writeOperationToStore(documentId, document.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tupdateDocumentRevision(document, job.scope, operation.index);\n\t\tdocument.operations = {\n\t\t\t...document.operations,\n\t\t\t[job.scope]: [...document.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tstores.writeCache.putState(documentId, job.scope, job.branch, operation.index, document);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tstores.documentMetaCache.putDocumentMeta(documentId, job.branch, {\n\t\t\tstate: document.state.document,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, documentId, document.header.documentType, resultingState, startTime);\n\t}\n\texecuteAddRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"ADD_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, (input) => input.sourceId === input.targetId ? /* @__PURE__ */ new Error(\"ADD_RELATIONSHIP: sourceId and targetId cannot be the same (self-relationships not allowed)\") : null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = driveCollectionId(j.branch, input.sourceId);\n\t\t\t\ttxn.addToCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteRemoveRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"REMOVE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, ({ indexTxn: txn, stores: s, sourceDoc, input, job: j }) => {\n\t\t\tif (this.driveContainerTypes.has(sourceDoc.header.documentType)) {\n\t\t\t\tconst collectionId = driveCollectionId(j.branch, input.sourceId);\n\t\t\t\ttxn.removeFromCollection(collectionId, input.targetId);\n\t\t\t\ts.collectionMembershipCache.invalidate(input.targetId);\n\t\t\t}\n\t\t});\n\t}\n\texecuteUpdateRelationship(job, action, startTime, indexTxn, stores, sourceRemote = \"\", signal) {\n\t\treturn this.withRelationshipAction(\"UPDATE_RELATIONSHIP\", job, action, startTime, indexTxn, stores, sourceRemote, signal, null, null);\n\t}\n\tasync withRelationshipAction(actionTypeName, job, action, startTime, indexTxn, stores, sourceRemote, signal, preValidate, postWrite) {\n\t\tif (job.scope !== \"document\") return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} must be in \"document\" scope, got \"${job.scope}\"`), startTime);\n\t\tconst input = action.input;\n\t\tif (!input.sourceId || !input.targetId || !input.relationshipType) return buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName} action requires sourceId, targetId, and relationshipType in input`), startTime);\n\t\tif (preValidate !== null) {\n\t\t\tconst validationError = preValidate(input);\n\t\t\tif (validationError !== null) return buildErrorResult(job, validationError, startTime);\n\t\t}\n\t\tlet sourceDoc;\n\t\ttry {\n\t\t\tsourceDoc = await stores.writeCache.getState(input.sourceId, \"document\", job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, /* @__PURE__ */ new Error(`${actionTypeName}: source document ${input.sourceId} not found: ${error instanceof Error ? error.message : String(error)}`), startTime);\n\t\t}\n\t\tlet operation = createOperation(action, getNextIndexForScope(sourceDoc, job.scope), 0, {\n\t\t\tdocumentId: input.sourceId,\n\t\t\tscope: job.scope,\n\t\t\tbranch: job.branch\n\t\t});\n\t\tconst writeResult = await this.writeOperationToStore(input.sourceId, sourceDoc.header.documentType, job.scope, job.branch, operation, job, startTime, stores, signal);\n\t\tif (!Array.isArray(writeResult)) return writeResult;\n\t\toperation = writeResult[0];\n\t\tsourceDoc.header.lastModifiedAtUtcIso = operation.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString();\n\t\tupdateDocumentRevision(sourceDoc, job.scope, operation.index);\n\t\tsourceDoc.operations = {\n\t\t\t...sourceDoc.operations,\n\t\t\t[job.scope]: [...sourceDoc.operations[job.scope] ?? [], operation]\n\t\t};\n\t\tconst scopeState = sourceDoc.state[job.scope];\n\t\tconst resultingStateObj = {\n\t\t\theader: structuredClone(sourceDoc.header),\n\t\t\t[job.scope]: scopeState === void 0 ? {} : structuredClone(scopeState)\n\t\t};\n\t\tconst resultingState = JSON.stringify(resultingStateObj);\n\t\tstores.writeCache.putState(input.sourceId, job.scope, job.branch, operation.index, sourceDoc);\n\t\tindexTxn.write([{\n\t\t\t...operation,\n\t\t\tdocumentId: input.sourceId,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope: job.scope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\tif (postWrite !== null) postWrite({\n\t\t\tindexTxn,\n\t\t\tstores,\n\t\t\tsourceDoc,\n\t\t\tinput,\n\t\t\tjob\n\t\t});\n\t\tstores.documentMetaCache.putDocumentMeta(input.sourceId, job.branch, {\n\t\t\tstate: sourceDoc.state.document,\n\t\t\tdocumentType: sourceDoc.header.documentType,\n\t\t\tdocumentScopeRevision: operation.index + 1\n\t\t});\n\t\treturn buildSuccessResult(job, operation, input.sourceId, sourceDoc.header.documentType, resultingState, startTime);\n\t}\n\tasync writeOperationToStore(documentId, documentType, scope, branch, operation, job, startTime, stores, signal) {\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(documentId, documentType, scope, branch, operation.index, (txn) => {\n\t\t\t\ttxn.addOperations(operation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", operation, error);\n\t\t\tstores.writeCache.invalidate(documentId, scope, branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\treturn storedOperations;\n\t}\n};\n//#endregion\n//#region src/executor/signature-verifier.ts\nvar SignatureVerifier = class {\n\tconstructor(verifier) {\n\t\tthis.verifier = verifier;\n\t}\n\tasync verifyActions(documentId, branch, actions) {\n\t\tif (!this.verifier) return;\n\t\tfor (const action of actions) {\n\t\t\tconst signer = action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Action ${action.id} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tconst tempOperation = {\n\t\t\t\t\tid: deriveOperationId(documentId, action.scope, branch, action.id),\n\t\t\t\t\tindex: 0,\n\t\t\t\t\ttimestampUtcMs: action.timestampUtcMs || (/* @__PURE__ */ new Date()).toISOString(),\n\t\t\t\t\thash: \"\",\n\t\t\t\t\tskip: 0,\n\t\t\t\t\taction\n\t\t\t\t};\n\t\t\t\tisValid = await this.verifier(tempOperation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Action ${action.id} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Action ${action.id} signature verification returned false`);\n\t\t}\n\t}\n\tasync verifyOperations(documentId, operations) {\n\t\tif (!this.verifier) return;\n\t\tfor (let i = 0; i < operations.length; i++) {\n\t\t\tconst operation = operations[i];\n\t\t\tconst signer = operation.action.context?.signer;\n\t\t\tif (!signer) continue;\n\t\t\tif (signer.signatures.length === 0) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} has signer but no signatures`);\n\t\t\tconst publicKey = signer.app.key;\n\t\t\tlet isValid;\n\t\t\ttry {\n\t\t\t\tisValid = await this.verifier(operation, publicKey);\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMessage = error instanceof Error ? error.message : String(error);\n\t\t\t\tthrow new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} verification failed: ${errorMessage}`);\n\t\t\t}\n\t\t\tif (!isValid) throw new InvalidSignatureError(documentId, `Operation ${operation.id} at index ${operation.index} signature verification returned false`);\n\t\t}\n\t}\n};\n//#endregion\n//#region src/executor/simple-job-executor.ts\nconst MAX_SKIP_THRESHOLD = 1e3;\nconst ISO_TIMESTAMP_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$/;\nfunction isValidISOTimestamp(value) {\n\tif (!ISO_TIMESTAMP_REGEX.test(value)) return false;\n\treturn !isNaN(new Date(value).getTime());\n}\nconst documentScopeActions = [\n\t\"CREATE_DOCUMENT\",\n\t\"DELETE_DOCUMENT\",\n\t\"UPGRADE_DOCUMENT\",\n\t\"ADD_RELATIONSHIP\",\n\t\"REMOVE_RELATIONSHIP\",\n\t\"UPDATE_RELATIONSHIP\"\n];\n/**\n* Simple job executor that processes a job by applying actions through document model reducers.\n*/\nvar SimpleJobExecutor = class {\n\tconfig;\n\tsignatureVerifierModule;\n\tdocumentActionHandler;\n\texecutionScope;\n\tconstructor(logger, registry, operationStore, eventBus, writeCache, operationIndex, documentMetaCache, collectionMembershipCache, driveContainerTypes, config, signatureVerifier, executionScope) {\n\t\tthis.logger = logger;\n\t\tthis.registry = registry;\n\t\tthis.operationStore = operationStore;\n\t\tthis.eventBus = eventBus;\n\t\tthis.writeCache = writeCache;\n\t\tthis.operationIndex = operationIndex;\n\t\tthis.documentMetaCache = documentMetaCache;\n\t\tthis.collectionMembershipCache = collectionMembershipCache;\n\t\tthis.driveContainerTypes = driveContainerTypes;\n\t\tthis.config = {\n\t\t\tmaxSkipThreshold: config.maxSkipThreshold ?? MAX_SKIP_THRESHOLD,\n\t\t\tmaxConcurrency: config.maxConcurrency ?? 1,\n\t\t\tjobTimeoutMs: config.jobTimeoutMs ?? 3e4,\n\t\t\tretryBaseDelayMs: config.retryBaseDelayMs ?? 100,\n\t\t\tretryMaxDelayMs: config.retryMaxDelayMs ?? 5e3,\n\t\t\tyieldDeadlineMs: config.yieldDeadlineMs ?? 50\n\t\t};\n\t\tthis.signatureVerifierModule = new SignatureVerifier(signatureVerifier);\n\t\tthis.documentActionHandler = new DocumentActionHandler(registry, logger, driveContainerTypes);\n\t\tthis.executionScope = executionScope ?? new DefaultExecutionScope(operationStore, operationIndex, writeCache, documentMetaCache, collectionMembershipCache);\n\t}\n\t/**\n\t* Execute a single job by applying all its actions through the appropriate reducers.\n\t* Actions are processed sequentially in order.\n\t*/\n\tasync executeJob(job, signal) {\n\t\tconst startTime = Date.now();\n\t\tconst touchedCacheEntries = [];\n\t\tlet pendingEvent;\n\t\tlet result;\n\t\ttry {\n\t\t\tresult = await this.executionScope.run(async (stores) => {\n\t\t\t\tconst indexTxn = stores.operationIndex.start();\n\t\t\t\tif (job.kind === \"load\") {\n\t\t\t\t\tconst loadResult = await this.executeLoadJob(job, startTime, indexTxn, stores, signal);\n\t\t\t\t\tif (loadResult.success && loadResult.operationsWithContext) {\n\t\t\t\t\t\tfor (const owc of loadResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\t\t\tfor (let i = 0; i < loadResult.operationsWithContext.length; i++) loadResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\t\tconst collectionMemberships = loadResult.operationsWithContext.length > 0 ? await this.getCollectionMembershipsForOperations(loadResult.operationsWithContext, stores) : {};\n\t\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\t\toperations: loadResult.operationsWithContext,\n\t\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\treturn loadResult;\n\t\t\t\t}\n\t\t\t\tconst actionResult = await this.processActions(job, job.actions, startTime, indexTxn, stores, void 0, void 0, \"\", signal);\n\t\t\t\tif (!actionResult.success) return {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: actionResult.error,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) for (const owc of actionResult.operationsWithContext) touchedCacheEntries.push({\n\t\t\t\t\tdocumentId: owc.context.documentId,\n\t\t\t\t\tscope: owc.context.scope,\n\t\t\t\t\tbranch: owc.context.branch\n\t\t\t\t});\n\t\t\t\tconst ordinals = await stores.operationIndex.commit(indexTxn, signal);\n\t\t\t\tif (actionResult.operationsWithContext.length > 0) {\n\t\t\t\t\tfor (let i = 0; i < actionResult.operationsWithContext.length; i++) actionResult.operationsWithContext[i].context.ordinal = ordinals[i];\n\t\t\t\t\tconst collectionMemberships = await this.getCollectionMembershipsForOperations(actionResult.operationsWithContext, stores);\n\t\t\t\t\tpendingEvent = {\n\t\t\t\t\t\tjobId: job.id,\n\t\t\t\t\t\toperations: actionResult.operationsWithContext,\n\t\t\t\t\t\tjobMeta: job.meta,\n\t\t\t\t\t\tcollectionMemberships\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tjob,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toperations: actionResult.generatedOperations,\n\t\t\t\t\toperationsWithContext: actionResult.operationsWithContext,\n\t\t\t\t\tduration: Date.now() - startTime\n\t\t\t\t};\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tfor (const entry of touchedCacheEntries) {\n\t\t\t\tthis.writeCache.invalidate(entry.documentId, entry.scope, entry.branch);\n\t\t\t\tthis.documentMetaCache.invalidate(entry.documentId, entry.branch);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (pendingEvent) this.eventBus.emit(ReactorEventTypes.JOB_WRITE_READY, pendingEvent).catch((error) => {\n\t\t\tthis.logger.error(\"Failed to emit JOB_WRITE_READY event: @Event : @Error\", pendingEvent, error);\n\t\t});\n\t\treturn result;\n\t}\n\tasync getCollectionMembershipsForOperations(operations, stores) {\n\t\tconst documentIds = [...new Set(operations.map((op) => op.context.documentId))];\n\t\treturn stores.collectionMembershipCache.getCollectionsForDocuments(documentIds);\n\t}\n\tasync processActions(job, actions, startTime, indexTxn, stores, skipValues, sourceOperations, sourceRemote = \"\", signal) {\n\t\tconst generatedOperations = [];\n\t\tconst operationsWithContext = [];\n\t\ttry {\n\t\t\tawait this.signatureVerifierModule.verifyActions(job.documentId, job.branch, actions);\n\t\t} catch (error) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t};\n\t\t}\n\t\tfor (const action of actions) if (action.timestampUtcMs && !isValidISOTimestamp(action.timestampUtcMs)) return {\n\t\t\tsuccess: false,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${action.timestampUtcMs}\" on action ${action.type} (id: ${action.id})`)\n\t\t};\n\t\tlet lastYield = performance.now();\n\t\tfor (let actionIndex = 0; actionIndex < actions.length; actionIndex++) {\n\t\t\tconst action = actions[actionIndex];\n\t\t\tconst skip = skipValues?.[actionIndex] ?? 0;\n\t\t\tconst sourceOperation = sourceOperations?.[actionIndex];\n\t\t\tconst result = documentScopeActions.includes(action.type) ? await this.documentActionHandler.execute(job, action, startTime, indexTxn, stores, skip, sourceRemote, signal) : await this.executeRegularAction(job, action, startTime, indexTxn, stores, skip, sourceOperation, sourceRemote, signal);\n\t\t\tconst error = this.accumulateResultOrReturnError(result, generatedOperations, operationsWithContext);\n\t\t\tif (error !== null) return {\n\t\t\t\tsuccess: false,\n\t\t\t\tgeneratedOperations,\n\t\t\t\toperationsWithContext,\n\t\t\t\terror: error.error\n\t\t\t};\n\t\t\tif (performance.now() - lastYield > this.config.yieldDeadlineMs) {\n\t\t\t\tawait yieldToMain();\n\t\t\t\tlastYield = performance.now();\n\t\t\t\tif (signal?.aborted) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\tgeneratedOperations,\n\t\t\t\t\toperationsWithContext,\n\t\t\t\t\terror: /* @__PURE__ */ new Error(\"Aborted\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tgeneratedOperations,\n\t\t\toperationsWithContext\n\t\t};\n\t}\n\tasync executeRegularAction(job, action, startTime, indexTxn, stores, skip = 0, sourceOperation, sourceRemote = \"\", signal) {\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tif (docMeta.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tif (isUndoRedo(action) || action.type === \"PRUNE\" || action.type === \"NOOP\" && skip > 0) stores.writeCache.invalidate(job.documentId, job.scope, job.branch);\n\t\tlet document;\n\t\ttry {\n\t\t\tdocument = await stores.writeCache.getState(job.documentId, job.scope, job.branch, void 0, signal);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet module;\n\t\ttry {\n\t\t\tconst moduleVersion = docMeta.state.version === 0 ? void 0 : docMeta.state.version;\n\t\t\tmodule = this.registry.getModule(document.header.documentType, moduleVersion);\n\t\t} catch (error) {\n\t\t\treturn buildErrorResult(job, error instanceof Error ? error : new Error(String(error)), startTime);\n\t\t}\n\t\tlet updatedDocument;\n\t\ttry {\n\t\t\tconst protocolVersion = document.header.protocolVersions?.[\"base-reducer\"] ?? 1;\n\t\t\tconst reducerOptions = sourceOperation ? {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\treplayOptions: { operation: sourceOperation },\n\t\t\t\tprotocolVersion\n\t\t\t} : {\n\t\t\t\tskip,\n\t\t\t\tbranch: job.branch,\n\t\t\t\tprotocolVersion\n\t\t\t};\n\t\t\tupdatedDocument = module.reducer(document, action, void 0, reducerOptions);\n\t\t} catch (error) {\n\t\t\tconst contextMessage = `Failed to apply action to document:\\n Action type: ${action.type}\\n Document ID: ${job.documentId}\\n Document type: ${document.header.documentType}\\n Scope: ${job.scope}\\n Original error: ${error instanceof Error ? error.message : String(error)}`;\n\t\t\tconst enhancedError = new Error(contextMessage);\n\t\t\tif (error instanceof Error && error.stack) enhancedError.stack = `${contextMessage}\\n\\nOriginal stack trace:\\n${error.stack}`;\n\t\t\treturn buildErrorResult(job, enhancedError, startTime);\n\t\t}\n\t\tconst scope = job.scope;\n\t\tconst operations = updatedDocument.operations[scope];\n\t\tif (operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"No operation generated from action\"), startTime);\n\t\tconst newOperation = operations[operations.length - 1];\n\t\tif (!isUndoRedo(action)) newOperation.skip = skip;\n\t\tconst resultingState = JSON.stringify({\n\t\t\t...updatedDocument.state,\n\t\t\theader: updatedDocument.header\n\t\t});\n\t\tlet storedOperations;\n\t\ttry {\n\t\t\tstoredOperations = await stores.operationStore.apply(job.documentId, document.header.documentType, scope, job.branch, newOperation.index, (txn) => {\n\t\t\t\ttxn.addOperations(newOperation);\n\t\t\t}, signal);\n\t\t} catch (error) {\n\t\t\tthis.logger.error(\"Error writing @Operation to IOperationStore: @Error\", newOperation, error);\n\t\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\t\treturn {\n\t\t\t\tjob,\n\t\t\t\tsuccess: false,\n\t\t\t\terror: /* @__PURE__ */ new Error(`Failed to write operation to IOperationStore: ${error instanceof Error ? error.message : String(error)}`),\n\t\t\t\tduration: Date.now() - startTime\n\t\t\t};\n\t\t}\n\t\tconst storedOperation = storedOperations[0];\n\t\tupdatedDocument.header.revision = {\n\t\t\t...updatedDocument.header.revision,\n\t\t\t[scope]: storedOperation.index + 1\n\t\t};\n\t\tstores.writeCache.putState(job.documentId, scope, job.branch, storedOperation.index, updatedDocument);\n\t\tindexTxn.write([{\n\t\t\t...storedOperation,\n\t\t\tdocumentId: job.documentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tbranch: job.branch,\n\t\t\tscope,\n\t\t\tsourceRemote\n\t\t}]);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [storedOperation],\n\t\t\toperationsWithContext: [{\n\t\t\t\toperation: storedOperation,\n\t\t\t\tcontext: {\n\t\t\t\t\tdocumentId: job.documentId,\n\t\t\t\t\tscope,\n\t\t\t\t\tbranch: job.branch,\n\t\t\t\t\tdocumentType: document.header.documentType,\n\t\t\t\t\tresultingState,\n\t\t\t\t\tordinal: 0\n\t\t\t\t}\n\t\t\t}],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\tasync executeLoadJob(job, startTime, indexTxn, stores, signal) {\n\t\tif (job.operations.length === 0) return buildErrorResult(job, /* @__PURE__ */ new Error(\"Load job must include at least one operation\"), startTime);\n\t\tlet docMeta;\n\t\ttry {\n\t\t\tdocMeta = await stores.documentMetaCache.getDocumentMeta(job.documentId, job.branch, signal);\n\t\t} catch {}\n\t\tif (docMeta?.state.isDeleted) return buildErrorResult(job, new DocumentDeletedError(job.documentId, docMeta.state.deletedAtUtcIso), startTime);\n\t\tconst scope = job.scope;\n\t\tlet latestRevision;\n\t\ttry {\n\t\t\tlatestRevision = (await stores.operationStore.getRevisions(job.documentId, job.branch, signal)).revision[scope] ?? 0;\n\t\t} catch {\n\t\t\tlatestRevision = 0;\n\t\t}\n\t\tfor (const operation of job.operations) if (operation.timestampUtcMs && !isValidISOTimestamp(operation.timestampUtcMs)) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Invalid timestamp \"${operation.timestampUtcMs}\" on operation (index: ${operation.index})`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet minIncomingIndex = Number.POSITIVE_INFINITY;\n\t\tlet minIncomingTimestamp = job.operations[0]?.timestampUtcMs || \"\";\n\t\tfor (const operation of job.operations) {\n\t\t\tminIncomingIndex = Math.min(minIncomingIndex, operation.index);\n\t\t\tconst ts = operation.timestampUtcMs || \"\";\n\t\t\tif (ts < minIncomingTimestamp) minIncomingTimestamp = ts;\n\t\t}\n\t\tlet conflictingOps;\n\t\ttry {\n\t\t\tconflictingOps = (await stores.operationStore.getConflicting(job.documentId, scope, job.branch, minIncomingTimestamp, void 0, signal)).results;\n\t\t} catch {\n\t\t\tconflictingOps = [];\n\t\t}\n\t\tlet allOpsFromMinConflictingIndex = conflictingOps;\n\t\tif (conflictingOps.length > 0) {\n\t\t\tconst minConflictingIndex = Math.min(...conflictingOps.map((op) => op.index));\n\t\t\ttry {\n\t\t\t\tallOpsFromMinConflictingIndex = (await stores.operationStore.getSince(job.documentId, scope, job.branch, minConflictingIndex - 1, void 0, void 0, signal)).results;\n\t\t\t} catch {\n\t\t\t\tallOpsFromMinConflictingIndex = conflictingOps;\n\t\t\t}\n\t\t}\n\t\tconst incomingActionIds = new Set(job.operations.map((op) => op.action.id));\n\t\tconst nonSupersededOps = conflictingOps.filter((op) => {\n\t\t\tif (op.index < minIncomingIndex && !incomingActionIds.has(op.action.id)) return false;\n\t\t\tfor (const laterOp of allOpsFromMinConflictingIndex) if (laterOp.index > op.index && laterOp.skip > 0) {\n\t\t\t\tif (laterOp.index - laterOp.skip <= op.index) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t});\n\t\tconst existingOpsToReshuffle = nonSupersededOps;\n\t\tif (existingOpsToReshuffle.length > this.config.maxSkipThreshold) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: /* @__PURE__ */ new Error(`Excessive reshuffle detected: existing op count of ${existingOpsToReshuffle.length} exceeds threshold of ${this.config.maxSkipThreshold}. This indicates a significant divergence between local and incoming operations.`),\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tlet skipCount = existingOpsToReshuffle.length;\n\t\tif (existingOpsToReshuffle.length > 0) {\n\t\t\tlet minLogicalIndex = Number.POSITIVE_INFINITY;\n\t\t\tfor (const op of existingOpsToReshuffle) {\n\t\t\t\tconst logical = op.index - op.skip;\n\t\t\t\tif (logical < minLogicalIndex) minLogicalIndex = logical;\n\t\t\t}\n\t\t\tconst logicalSkip = latestRevision - minLogicalIndex;\n\t\t\tif (logicalSkip > skipCount) skipCount = logicalSkip;\n\t\t}\n\t\tconst existingActionIds = new Set(nonSupersededOps.map((op) => op.action.id));\n\t\tconst seenIncomingActionIds = /* @__PURE__ */ new Set();\n\t\tconst incomingOpsToApply = job.operations.filter((op) => {\n\t\t\tif (existingActionIds.has(op.action.id)) return false;\n\t\t\tif (seenIncomingActionIds.has(op.action.id)) return false;\n\t\t\tseenIncomingActionIds.add(op.action.id);\n\t\t\treturn true;\n\t\t});\n\t\tif (incomingOpsToApply.length === 0) return {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: [],\n\t\t\toperationsWithContext: [],\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tconst reshuffledOperations = existingOpsToReshuffle.length === 0 && skipCount === 0 ? incomingOpsToApply.slice().sort((a, b) => a.index - b.index).map((operation, i) => ({\n\t\t\t...operation,\n\t\t\tindex: latestRevision + i\n\t\t})) : reshuffleByTimestamp({\n\t\t\tindex: latestRevision,\n\t\t\tskip: skipCount\n\t\t}, existingOpsToReshuffle, incomingOpsToApply.map((operation) => ({\n\t\t\t...operation,\n\t\t\tid: operation.id\n\t\t})));\n\t\tfor (const operation of reshuffledOperations) if (operation.action.type === \"NOOP\") operation.skip = 1;\n\t\tconst actions = reshuffledOperations.map((operation) => operation.action);\n\t\tconst skipValues = reshuffledOperations.map((operation) => operation.skip);\n\t\tconst effectiveSourceRemote = skipCount > 0 ? \"\" : job.meta.sourceRemote || \"\";\n\t\tconst result = await this.processActions(job, actions, startTime, indexTxn, stores, skipValues, reshuffledOperations, effectiveSourceRemote, signal);\n\t\tif (!result.success) return {\n\t\t\tjob,\n\t\t\tsuccess: false,\n\t\t\terror: result.error,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t\tstores.writeCache.invalidate(job.documentId, scope, job.branch);\n\t\tif (scope === \"document\") stores.documentMetaCache.invalidate(job.documentId, job.branch);\n\t\treturn {\n\t\t\tjob,\n\t\t\tsuccess: true,\n\t\t\toperations: result.generatedOperations,\n\t\t\toperationsWithContext: result.operationsWithContext,\n\t\t\tduration: Date.now() - startTime\n\t\t};\n\t}\n\taccumulateResultOrReturnError(result, generatedOperations, operationsWithContext) {\n\t\tif (!result.success) return result;\n\t\tif (result.operations && result.operations.length > 0) generatedOperations.push(...result.operations);\n\t\tif (result.operationsWithContext) operationsWithContext.push(...result.operationsWithContext);\n\t\treturn null;\n\t}\n};\n//#endregion\n//#region src/registry/implementation.ts\n/**\n* In-memory implementation of the IDocumentModelRegistry interface.\n* Manages document model modules with version-aware storage and upgrade manifest support.\n*/\nvar DocumentModelRegistry = class {\n\tmodules = [];\n\tmanifests = [];\n\tregisterModules(...modules) {\n\t\treturn modules.map((module) => {\n\t\t\ttry {\n\t\t\t\tconst documentType = module.documentModel.global.id;\n\t\t\t\tconst version = module.version ?? 1;\n\t\t\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\t\t\tconst existing = this.modules[i];\n\t\t\t\t\tconst existingType = existing.documentModel.global.id;\n\t\t\t\t\tconst existingVersion = existing.version ?? 1;\n\t\t\t\t\tif (existingType === documentType && existingVersion === version) throw new DuplicateModuleError(documentType, version);\n\t\t\t\t}\n\t\t\t\tthis.modules.push(module);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: module\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: module,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterModules(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.modules.some((m) => m.documentModel.global.id === documentType)) allFound = false;\n\t\t\tthis.modules = this.modules.filter((m) => m.documentModel.global.id !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetModule(documentType, version) {\n\t\tlet latestModule;\n\t\tlet latestVersion = -1;\n\t\tfor (let i = 0; i < this.modules.length; i++) {\n\t\t\tconst module = this.modules[i];\n\t\t\tconst moduleType = module.documentModel.global.id;\n\t\t\tconst moduleVersion = module.version ?? 1;\n\t\t\tif (moduleType === documentType) {\n\t\t\t\tif (version !== void 0 && moduleVersion === version) return module;\n\t\t\t\tif (moduleVersion > latestVersion) {\n\t\t\t\t\tlatestModule = module;\n\t\t\t\t\tlatestVersion = moduleVersion;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (version === void 0 && latestModule !== void 0) return latestModule;\n\t\tthrow new ModuleNotFoundError(documentType, version);\n\t}\n\tgetAllModules() {\n\t\treturn [...this.modules];\n\t}\n\tclear() {\n\t\tthis.modules = [];\n\t\tthis.manifests = [];\n\t}\n\tgetSupportedVersions(documentType) {\n\t\tconst versions = [];\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) versions.push(module.version ?? 1);\n\t\tif (versions.length === 0) throw new ModuleNotFoundError(documentType);\n\t\treturn versions.sort((a, b) => a - b);\n\t}\n\tgetLatestVersion(documentType) {\n\t\tlet latest = -1;\n\t\tlet found = false;\n\t\tfor (const module of this.modules) if (module.documentModel.global.id === documentType) {\n\t\t\tfound = true;\n\t\t\tconst version = module.version ?? 1;\n\t\t\tif (version > latest) latest = version;\n\t\t}\n\t\tif (!found) throw new ModuleNotFoundError(documentType);\n\t\treturn latest;\n\t}\n\tregisterUpgradeManifests(...manifestsToRegister) {\n\t\treturn manifestsToRegister.map((manifestToRegister) => {\n\t\t\ttry {\n\t\t\t\tif (!manifestToRegister.documentType) throw new Error(\"Upgrade manifest is missing a documentType\");\n\t\t\t\tfor (const registeredManifest of this.manifests) if (registeredManifest.documentType === manifestToRegister.documentType) throw new DuplicateManifestError(manifestToRegister.documentType);\n\t\t\t\tthis.manifests.push(manifestToRegister);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\titem: manifestToRegister\n\t\t\t\t};\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"error\",\n\t\t\t\t\titem: manifestToRegister,\n\t\t\t\t\terror: error instanceof Error ? error : new Error(String(error))\n\t\t\t\t};\n\t\t\t}\n\t\t});\n\t}\n\tunregisterUpgradeManifests(...documentTypes) {\n\t\tlet allFound = true;\n\t\tfor (const documentType of documentTypes) {\n\t\t\tif (!this.manifests.some((m) => m.documentType === documentType)) allFound = false;\n\t\t\tthis.manifests = this.manifests.filter((m) => m.documentType !== documentType);\n\t\t}\n\t\treturn allFound;\n\t}\n\tgetUpgradeManifest(documentType) {\n\t\tfor (let i = 0; i < this.manifests.length; i++) if (this.manifests[i].documentType === documentType) return this.manifests[i];\n\t\tthrow new ManifestNotFoundError(documentType);\n\t}\n\tcomputeUpgradePath(documentType, fromVersion, toVersion) {\n\t\tif (fromVersion === toVersion) return [];\n\t\tif (toVersion < fromVersion) throw new DowngradeNotSupportedError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst path = [];\n\t\tfor (let v = fromVersion + 1; v <= toVersion; v++) {\n\t\t\tconst key = `v${v}`;\n\t\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, v - 1, v);\n\t\t\tconst transition = manifest.upgrades[key];\n\t\t\tpath.push(transition);\n\t\t}\n\t\treturn path;\n\t}\n\tgetUpgradeReducer(documentType, fromVersion, toVersion) {\n\t\tif (toVersion !== fromVersion + 1) throw new InvalidUpgradeStepError(documentType, fromVersion, toVersion);\n\t\tconst manifest = this.getUpgradeManifest(documentType);\n\t\tconst key = `v${toVersion}`;\n\t\tif (!(key in manifest.upgrades)) throw new MissingUpgradeTransitionError(documentType, fromVersion, toVersion);\n\t\treturn manifest.upgrades[key].upgradeReducer;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/keyframe-store.ts\nvar KyselyKeyframeStore = class KyselyKeyframeStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyKeyframeStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync putKeyframe(documentId, scope, branch, revision, document, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tawait this.queryExecutor.insertInto(\"Keyframe\").values({\n\t\t\tdocumentId,\n\t\t\tdocumentType: document.header.documentType,\n\t\t\tscope,\n\t\t\tbranch,\n\t\t\trevision,\n\t\t\tdocument\n\t\t}).onConflict((oc) => oc.columns([\n\t\t\t\"documentId\",\n\t\t\t\"scope\",\n\t\t\t\"branch\",\n\t\t\t\"revision\"\n\t\t]).doUpdateSet({ document })).execute();\n\t}\n\tasync findNearestKeyframe(documentId, scope, branch, targetRevision, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tconst row = await this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"revision\", \"<=\", targetRevision).orderBy(\"revision\", \"desc\").limit(1).executeTakeFirst();\n\t\tif (!row) return;\n\t\treturn {\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t};\n\t}\n\tasync listKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.selectFrom(\"Keyframe\").selectAll().where(\"documentId\", \"=\", documentId).orderBy(\"revision\", \"asc\");\n\t\tif (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tif (branch !== void 0) query = query.where(\"branch\", \"=\", branch);\n\t\treturn (await query.execute()).map((row) => ({\n\t\t\tscope: row.scope,\n\t\t\tbranch: row.branch,\n\t\t\trevision: row.revision,\n\t\t\tdocument: row.document\n\t\t}));\n\t}\n\tasync deleteKeyframes(documentId, scope, branch, signal) {\n\t\tif (signal?.aborted) throw new Error(\"Operation aborted\");\n\t\tlet query = this.queryExecutor.deleteFrom(\"Keyframe\").where(\"documentId\", \"=\", documentId);\n\t\tif (scope !== void 0 && branch !== void 0) query = query.where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch);\n\t\telse if (scope !== void 0) query = query.where(\"scope\", \"=\", scope);\n\t\tconst result = await query.executeTakeFirst();\n\t\treturn Number(result.numDeletedRows || 0n);\n\t}\n};\n//#endregion\n//#region src/storage/kysely/pagination.ts\nconst DEFAULT_LIMIT = 100;\nfunction paginateRows(rows, paging, cursorOf, toItem, refetch) {\n\tlet hasMore = false;\n\tlet items = rows;\n\tif (paging?.limit && rows.length > paging.limit) {\n\t\thasMore = true;\n\t\titems = rows.slice(0, paging.limit);\n\t}\n\tconst nextCursor = hasMore && items.length > 0 ? cursorOf(items[items.length - 1]).toString() : void 0;\n\tconst cursor = paging?.cursor || \"0\";\n\tconst limit = paging?.limit || DEFAULT_LIMIT;\n\treturn {\n\t\tresults: items.map(toItem),\n\t\toptions: {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t},\n\t\tnextCursor,\n\t\tnext: hasMore ? () => refetch(nextCursor, limit) : void 0\n\t};\n}\n//#endregion\n//#region src/storage/interfaces.ts\n/**\n* Thrown when an operation with the same identity already exists in the store.\n*/\nvar DuplicateOperationError = class extends Error {\n\tconstructor(description) {\n\t\tsuper(`Duplicate operation: ${description}`);\n\t\tthis.name = \"DuplicateOperationError\";\n\t}\n};\n/**\n* Thrown when a concurrent write conflict is detected during an atomic apply.\n*/\nvar OptimisticLockError = class extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = \"OptimisticLockError\";\n\t}\n};\n/**\n* Thrown when the caller-provided revision does not match the current\n* stored revision, indicating a stale read.\n*/\nvar RevisionMismatchError = class extends Error {\n\tconstructor(expected, actual) {\n\t\tsuper(`Revision mismatch: expected ${expected}, got ${actual}`);\n\t\tthis.name = \"RevisionMismatchError\";\n\t}\n};\n//#endregion\n//#region src/storage/txn.ts\nvar AtomicTransaction = class {\n\toperations = [];\n\tconstructor(documentId, documentType, scope, branch, baseRevision) {\n\t\tthis.documentId = documentId;\n\t\tthis.documentType = documentType;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.baseRevision = baseRevision;\n\t}\n\taddOperations(...operations) {\n\t\tfor (const op of operations) this.operations.push({\n\t\t\tjobId: v4(),\n\t\t\topId: op.id,\n\t\t\tprevOpId: \"\",\n\t\t\tdocumentId: this.documentId,\n\t\t\tdocumentType: this.documentType,\n\t\t\tscope: this.scope,\n\t\t\tbranch: this.branch,\n\t\t\ttimestampUtcMs: new Date(op.timestampUtcMs),\n\t\t\tindex: op.index,\n\t\t\taction: JSON.stringify(op.action),\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || null,\n\t\t\thash: op.hash\n\t\t});\n\t}\n\tgetOperations() {\n\t\treturn this.operations;\n\t}\n};\n//#endregion\n//#region src/storage/kysely/store.ts\nvar _UniqueConstraintContext = class extends Error {\n\tconstructor(documentId, scope, branch, revision, stagedOps) {\n\t\tsuper(\"unique constraint\");\n\t\tthis.documentId = documentId;\n\t\tthis.scope = scope;\n\t\tthis.branch = branch;\n\t\tthis.revision = revision;\n\t\tthis.stagedOps = stagedOps;\n\t\tthis.name = \"UniqueConstraintContext\";\n\t}\n};\nvar KyselyOperationStore = class KyselyOperationStore {\n\ttrx;\n\tconstructor(db) {\n\t\tthis.db = db;\n\t}\n\tget queryExecutor() {\n\t\treturn this.trx ?? this.db;\n\t}\n\twithTransaction(trx) {\n\t\tconst instance = new KyselyOperationStore(this.db);\n\t\tinstance.trx = trx;\n\t\treturn instance;\n\t}\n\tasync apply(documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tif (this.trx) {\n\t\t\tlet executeResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\texecuteResult = await this.executeApply(this.trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn executeResult;\n\t\t} else {\n\t\t\tlet transactionResult = null;\n\t\t\tlet uniqueCtx = null;\n\t\t\ttry {\n\t\t\t\ttransactionResult = await this.db.transaction().execute(async (trx) => {\n\t\t\t\t\treturn this.executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal);\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof _UniqueConstraintContext) uniqueCtx = error;\n\t\t\t\telse throw error;\n\t\t\t}\n\t\t\tif (uniqueCtx !== null) return this.resolveUniqueConstraint(uniqueCtx);\n\t\t\treturn transactionResult;\n\t\t}\n\t}\n\tasync resolveUniqueConstraint(ctx) {\n\t\tlet replayOps = null;\n\t\ttry {\n\t\t\treplayOps = await this.findIdempotentReplay(this.db, ctx.documentId, ctx.scope, ctx.branch, ctx.revision, ctx.stagedOps);\n\t\t} catch {}\n\t\tif (replayOps !== null) return replayOps;\n\t\tconst op = ctx.stagedOps[0];\n\t\tthrow new DuplicateOperationError(`${op.opId} at index ${op.index} with skip ${op.skip}`);\n\t}\n\tasync executeApply(trx, documentId, documentType, scope, branch, revision, fn, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst atomicTxn = new AtomicTransaction(documentId, documentType, scope, branch, revision);\n\t\tawait fn(atomicTxn);\n\t\tconst operations = atomicTxn.getOperations();\n\t\tif (operations.length === 0) return [];\n\t\tconst latestOp = await trx.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).orderBy(\"index\", \"desc\").limit(1).executeTakeFirst();\n\t\tconst currentRevision = latestOp ? latestOp.index : -1;\n\t\tif (currentRevision !== revision - 1) {\n\t\t\tlet replayOps = null;\n\t\t\ttry {\n\t\t\t\treplayOps = await this.findIdempotentReplay(trx, documentId, scope, branch, revision, operations);\n\t\t\t} catch {}\n\t\t\tif (replayOps !== null) return replayOps;\n\t\t\tthrow new RevisionMismatchError(currentRevision + 1, revision);\n\t\t}\n\t\tlet prevOpId = latestOp?.opId || \"\";\n\t\tfor (const op of operations) {\n\t\t\top.prevOpId = prevOpId;\n\t\t\tprevOpId = op.opId;\n\t\t}\n\t\ttry {\n\t\t\tawait trx.insertInto(\"Operation\").values(operations).execute();\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message.includes(\"unique constraint\")) throw new _UniqueConstraintContext(documentId, scope, branch, revision, operations);\n\t\t\tthrow error;\n\t\t}\n\t\treturn operations.map((op) => ({\n\t\t\tindex: op.index,\n\t\t\ttimestampUtcMs: op.timestampUtcMs.toISOString(),\n\t\t\thash: op.hash,\n\t\t\tskip: op.skip,\n\t\t\terror: op.error || void 0,\n\t\t\tid: op.opId,\n\t\t\taction: JSON.parse(op.action)\n\t\t}));\n\t}\n\tasync findIdempotentReplay(executor, documentId, scope, branch, revision, stagedOps) {\n\t\tconst minIndex = revision;\n\t\tconst maxIndex = revision + stagedOps.length - 1;\n\t\tconst storedRows = await executor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">=\", minIndex).where(\"index\", \"<=\", maxIndex).orderBy(\"index\", \"asc\").execute();\n\t\tif (storedRows.length !== stagedOps.length) return null;\n\t\tfor (let i = 0; i < stagedOps.length; i++) {\n\t\t\tconst staged = stagedOps[i];\n\t\t\tconst stored = storedRows[i];\n\t\t\tif (stored.opId !== staged.opId || stored.index !== staged.index || stored.skip !== staged.skip) return null;\n\t\t}\n\t\treturn storedRows.map((row) => this.rowToOperation(row));\n\t}\n\tasync getSince(documentId, scope, branch, revision, filter, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"index\", \">\", revision).orderBy(\"index\", \"asc\");\n\t\tif (filter) {\n\t\t\tif (filter.actionTypes && filter.actionTypes.length > 0) {\n\t\t\t\tconst actionTypesArray = filter.actionTypes.map((t) => `'${t.replace(/'/g, \"''\")}'`).join(\",\");\n\t\t\t\tquery = query.where(sql`action->>'type' = ANY(ARRAY[${sql.raw(actionTypesArray)}]::text[])`);\n\t\t\t}\n\t\t\tif (filter.timestampFrom) query = query.where(\"timestampUtcMs\", \">=\", new Date(filter.timestampFrom));\n\t\t\tif (filter.timestampTo) query = query.where(\"timestampUtcMs\", \"<=\", new Date(filter.timestampTo));\n\t\t\tif (filter.sinceRevision !== void 0) query = query.where(\"index\", \">=\", filter.sinceRevision);\n\t\t}\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getSince(documentId, scope, branch, revision, filter, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getSinceId(id, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"id\", \">\", id).orderBy(\"id\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"id\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.id, (row) => this.rowToOperationWithContext(row), (cursor, limit) => this.getSinceId(id, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getConflicting(documentId, scope, branch, minTimestamp, paging, signal) {\n\t\tthrowIfAborted(signal);\n\t\tlet query = this.queryExecutor.selectFrom(\"Operation\").selectAll().where(\"documentId\", \"=\", documentId).where(\"scope\", \"=\", scope).where(\"branch\", \"=\", branch).where(\"timestampUtcMs\", \">=\", new Date(minTimestamp)).orderBy(\"index\", \"asc\");\n\t\tif (paging) {\n\t\t\tconst cursorValue = Number.parseInt(paging.cursor, 10);\n\t\t\tif (cursorValue > 0) query = query.where(\"index\", \">\", cursorValue);\n\t\t\tif (paging.limit) query = query.limit(paging.limit + 1);\n\t\t}\n\t\treturn paginateRows(await query.execute(), paging, (row) => row.index, (row) => this.rowToOperation(row), (cursor, limit) => this.getConflicting(documentId, scope, branch, minTimestamp, {\n\t\t\tcursor,\n\t\t\tlimit\n\t\t}, signal));\n\t}\n\tasync getRevisions(documentId, branch, signal) {\n\t\tthrowIfAborted(signal);\n\t\tconst scopeRevisions = await this.queryExecutor.selectFrom(\"Operation as o1\").select([\n\t\t\t\"o1.scope\",\n\t\t\t\"o1.index\",\n\t\t\t\"o1.timestampUtcMs\"\n\t\t]).where(\"o1.documentId\", \"=\", documentId).where(\"o1.branch\", \"=\", branch).where((eb) => eb(\"o1.index\", \"=\", eb.selectFrom(\"Operation as o2\").select((eb2) => eb2.fn.max(\"o2.index\").as(\"maxIndex\")).where(\"o2.documentId\", \"=\", eb.ref(\"o1.documentId\")).where(\"o2.branch\", \"=\", eb.ref(\"o1.branch\")).where(\"o2.scope\", \"=\", eb.ref(\"o1.scope\")))).execute();\n\t\tconst revision = {};\n\t\tlet latestTimestamp = (/* @__PURE__ */ new Date(0)).toISOString();\n\t\tfor (const row of scopeRevisions) {\n\t\t\trevision[row.scope] = row.index + 1;\n\t\t\tconst timestamp = row.timestampUtcMs.toISOString();\n\t\t\tif (timestamp > latestTimestamp) latestTimestamp = timestamp;\n\t\t}\n\t\treturn {\n\t\t\trevision,\n\t\t\tlatestTimestamp\n\t\t};\n\t}\n\trowToOperation(row) {\n\t\treturn {\n\t\t\tindex: row.index,\n\t\t\ttimestampUtcMs: row.timestampUtcMs.toISOString(),\n\t\t\thash: row.hash,\n\t\t\tskip: row.skip,\n\t\t\terror: row.error || void 0,\n\t\t\tid: row.opId,\n\t\t\taction: row.action\n\t\t};\n\t}\n\trowToOperationWithContext(row) {\n\t\treturn {\n\t\t\toperation: this.rowToOperation(row),\n\t\t\tcontext: {\n\t\t\t\tdocumentId: row.documentId,\n\t\t\t\tdocumentType: row.documentType,\n\t\t\t\tscope: row.scope,\n\t\t\t\tbranch: row.branch,\n\t\t\t\tordinal: row.id\n\t\t\t}\n\t\t};\n\t}\n};\n//#endregion\n//#region src/storage/pool-instrumentation.ts\n/**\n* Wraps an existing pg.Pool with acquire-wait timing and an event\n* subscription surface. The pool is mutated in place: pool.connect()\n* is replaced with a timing wrapper so all callers (Kysely included)\n* pick up the instrumentation transparently.\n*/\nfunction instrumentPgPool(pool, name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tconst originalConnect = pool.connect.bind(pool);\n\tconst wrappedConnect = async () => {\n\t\tconst start = performance.now();\n\t\tconst client = await originalConnect();\n\t\tconst durationMs = performance.now() - start;\n\t\tfor (const listener of listeners) try {\n\t\t\tlistener(durationMs);\n\t\t} catch {}\n\t\treturn client;\n\t};\n\tpool.connect = wrappedConnect;\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn {\n\t\t\t\tsize: pool.totalCount,\n\t\t\t\tidle: pool.idleCount,\n\t\t\t\twaiting: pool.waitingCount\n\t\t\t};\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t}\n\t};\n}\nfunction createForwardingPoolInstrumentation(name) {\n\tconst listeners = /* @__PURE__ */ new Set();\n\tlet stats = {\n\t\tsize: 0,\n\t\tidle: 0,\n\t\twaiting: 0\n\t};\n\treturn {\n\t\tname,\n\t\tgetStats() {\n\t\t\treturn stats;\n\t\t},\n\t\tonAcquire(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tpushSamples(durations) {\n\t\t\tfor (const durationMs of durations) for (const listener of listeners) try {\n\t\t\t\tlistener(durationMs);\n\t\t\t} catch {}\n\t\t},\n\t\tupdateStats(next) {\n\t\t\tstats = next;\n\t\t}\n\t};\n}\n//#endregion\n//#region src/storage/migrations/001_create_operation_table.ts\nvar _001_create_operation_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$13 });\nasync function up$13(db) {\n\tawait db.schema.createTable(\"Operation\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"jobId\", \"text\", (col) => col.notNull()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"prevOpId\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"timestamptz\", (col) => col.notNull()).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"error\", \"text\").addColumn(\"hash\", \"text\", (col) => col.notNull()).addUniqueConstraint(\"unique_revision\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"index\"\n\t]).addUniqueConstraint(\"unique_operation_instance\", [\n\t\t\"opId\",\n\t\t\"index\",\n\t\t\"skip\"\n\t]).execute();\n\tawait db.schema.createIndex(\"streamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"id\"\n\t]).execute();\n\tawait db.schema.createIndex(\"branchlessStreamOperations\").on(\"Operation\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"id\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/002_create_keyframe_table.ts\nvar _002_create_keyframe_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$12 });\nasync function up$12(db) {\n\tawait db.schema.createTable(\"Keyframe\").addColumn(\"id\", \"serial\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"revision\", \"integer\", (col) => col.notNull()).addColumn(\"document\", \"jsonb\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_keyframe\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n\tawait db.schema.createIndex(\"keyframe_lookup\").on(\"Keyframe\").columns([\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\",\n\t\t\"revision\"\n\t]).execute();\n}\n//#endregion\n//#region src/storage/migrations/003_create_document_table.ts\nvar _003_create_document_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$11 });\nasync function up$11(db) {\n\tawait db.schema.createTable(\"Document\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/004_create_document_relationship_table.ts\nvar _004_create_document_relationship_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$10 });\nasync function up$10(db) {\n\tawait db.schema.createTable(\"DocumentRelationship\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"sourceId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"targetId\", \"text\", (col) => col.notNull().references(\"Document.id\").onDelete(\"cascade\")).addColumn(\"relationshipType\", \"text\", (col) => col.notNull()).addColumn(\"metadata\", \"jsonb\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_source_target_type\", [\n\t\t\"sourceId\",\n\t\t\"targetId\",\n\t\t\"relationshipType\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_relationship_source\").on(\"DocumentRelationship\").column(\"sourceId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_target\").on(\"DocumentRelationship\").column(\"targetId\").execute();\n\tawait db.schema.createIndex(\"idx_relationship_type\").on(\"DocumentRelationship\").column(\"relationshipType\").execute();\n}\n//#endregion\n//#region src/storage/migrations/005_create_indexer_state_table.ts\nvar _005_create_indexer_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$9 });\nasync function up$9(db) {\n\tawait db.schema.createTable(\"IndexerState\").addColumn(\"id\", \"integer\", (col) => col.primaryKey().generatedAlwaysAsIdentity()).addColumn(\"lastOperationId\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/006_create_document_snapshot_table.ts\nvar _006_create_document_snapshot_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$8 });\nasync function up$8(db) {\n\tawait db.schema.createTable(\"DocumentSnapshot\").addColumn(\"id\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"slug\", \"text\").addColumn(\"name\", \"text\").addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"content\", \"jsonb\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"lastOperationIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOperationHash\", \"text\", (col) => col.notNull()).addColumn(\"lastUpdatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"snapshotVersion\", \"integer\", (col) => col.notNull().defaultTo(1)).addColumn(\"identifiers\", \"jsonb\").addColumn(\"metadata\", \"jsonb\").addColumn(\"isDeleted\", \"boolean\", (col) => col.notNull().defaultTo(false)).addColumn(\"deletedAt\", \"timestamptz\").addUniqueConstraint(\"unique_doc_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"slug\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_doctype_scope_branch\").on(\"DocumentSnapshot\").columns([\n\t\t\"documentType\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_last_updated\").on(\"DocumentSnapshot\").column(\"lastUpdatedAt\").execute();\n\tawait db.schema.createIndex(\"idx_is_deleted\").on(\"DocumentSnapshot\").column(\"isDeleted\").execute();\n}\n//#endregion\n//#region src/storage/migrations/007_create_slug_mapping_table.ts\nvar _007_create_slug_mapping_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$7 });\nasync function up$7(db) {\n\tawait db.schema.createTable(\"SlugMapping\").addColumn(\"slug\", \"text\", (col) => col.primaryKey()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addUniqueConstraint(\"unique_docid_scope_branch\", [\n\t\t\"documentId\",\n\t\t\"scope\",\n\t\t\"branch\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_slug_documentid\").on(\"SlugMapping\").column(\"documentId\").execute();\n}\n//#endregion\n//#region src/storage/migrations/008_create_view_state_table.ts\nvar _008_create_view_state_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$6 });\nasync function up$6(db) {\n\tawait db.schema.createTable(\"ViewState\").addColumn(\"readModelId\", \"text\", (col) => col.primaryKey()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"lastOperationTimestamp\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/009_create_operation_index_tables.ts\nvar _009_create_operation_index_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$5 });\nasync function up$5(db) {\n\tawait db.schema.createTable(\"document_collections\").addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"collectionId\", \"text\", (col) => col.notNull()).addColumn(\"joinedOrdinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"leftOrdinal\", \"bigint\").addPrimaryKeyConstraint(\"document_collections_pkey\", [\"documentId\", \"collectionId\"]).execute();\n\tawait db.schema.createIndex(\"idx_document_collections_collectionId\").on(\"document_collections\").column(\"collectionId\").execute();\n\tawait db.schema.createIndex(\"idx_doc_collections_collection_range\").on(\"document_collections\").columns([\"collectionId\", \"joinedOrdinal\"]).execute();\n\tawait db.schema.createTable(\"operation_index_operations\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"opId\", \"text\", (col) => col.notNull()).addColumn(\"documentId\", \"text\", (col) => col.notNull()).addColumn(\"documentType\", \"text\", (col) => col.notNull()).addColumn(\"scope\", \"text\", (col) => col.notNull()).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"timestampUtcMs\", \"text\", (col) => col.notNull()).addColumn(\"writeTimestampUtcMs\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"index\", \"integer\", (col) => col.notNull()).addColumn(\"skip\", \"integer\", (col) => col.notNull()).addColumn(\"hash\", \"text\", (col) => col.notNull()).addColumn(\"action\", \"jsonb\", (col) => col.notNull()).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_document\").on(\"operation_index_operations\").columns([\n\t\t\"documentId\",\n\t\t\"branch\",\n\t\t\"scope\"\n\t]).execute();\n\tawait db.schema.createIndex(\"idx_operation_index_operations_ordinal\").on(\"operation_index_operations\").column(\"ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/010_create_sync_tables.ts\nvar _010_create_sync_tables_exports = /* @__PURE__ */ __exportAll({ up: () => up$4 });\nasync function up$4(db) {\n\tawait db.schema.createTable(\"sync_remotes\").addColumn(\"name\", \"text\", (col) => col.primaryKey()).addColumn(\"collection_id\", \"text\", (col) => col.notNull()).addColumn(\"channel_type\", \"text\", (col) => col.notNull()).addColumn(\"channel_id\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"remote_name\", \"text\", (col) => col.notNull().defaultTo(\"\")).addColumn(\"channel_parameters\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'{}'::jsonb`)).addColumn(\"filter_document_ids\", \"jsonb\").addColumn(\"filter_scopes\", \"jsonb\").addColumn(\"filter_branch\", \"text\", (col) => col.notNull().defaultTo(\"main\")).addColumn(\"push_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"push_last_success_utc_ms\", \"text\").addColumn(\"push_last_failure_utc_ms\", \"text\").addColumn(\"push_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"pull_state\", \"text\", (col) => col.notNull().defaultTo(\"idle\")).addColumn(\"pull_last_success_utc_ms\", \"text\").addColumn(\"pull_last_failure_utc_ms\", \"text\").addColumn(\"pull_failure_count\", \"integer\", (col) => col.notNull().defaultTo(0)).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_remotes_collection\").on(\"sync_remotes\").column(\"collection_id\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.primaryKey().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/011_add_cursor_type_column.ts\nvar _011_add_cursor_type_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$3 });\nasync function up$3(db) {\n\tawait db.deleteFrom(\"sync_cursors\").where(\"remote_name\", \"like\", \"outbox::%\").execute();\n\tawait db.deleteFrom(\"sync_remotes\").where(\"name\", \"like\", \"outbox::%\").execute();\n\tawait db.schema.dropTable(\"sync_cursors\").execute();\n\tawait db.schema.createTable(\"sync_cursors\").addColumn(\"remote_name\", \"text\", (col) => col.notNull()).addColumn(\"cursor_type\", \"text\", (col) => col.notNull().defaultTo(\"inbox\")).addColumn(\"cursor_ordinal\", \"bigint\", (col) => col.notNull().defaultTo(0)).addColumn(\"last_synced_at_utc_ms\", \"text\").addColumn(\"updated_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addPrimaryKeyConstraint(\"sync_cursors_pk\", [\"remote_name\", \"cursor_type\"]).execute();\n\tawait db.schema.createIndex(\"idx_sync_cursors_ordinal\").on(\"sync_cursors\").column(\"cursor_ordinal\").execute();\n}\n//#endregion\n//#region src/storage/migrations/012_add_source_remote_column.ts\nvar _012_add_source_remote_column_exports = /* @__PURE__ */ __exportAll({ up: () => up$2 });\nasync function up$2(db) {\n\tawait db.schema.alterTable(\"operation_index_operations\").addColumn(\"sourceRemote\", \"text\", (col) => col.notNull().defaultTo(\"\")).execute();\n}\n//#endregion\n//#region src/storage/migrations/013_create_sync_dead_letters_table.ts\nvar _013_create_sync_dead_letters_table_exports = /* @__PURE__ */ __exportAll({ up: () => up$1 });\nasync function up$1(db) {\n\tawait db.schema.createTable(\"sync_dead_letters\").addColumn(\"ordinal\", \"serial\", (col) => col.primaryKey()).addColumn(\"id\", \"text\", (col) => col.unique().notNull()).addColumn(\"job_id\", \"text\", (col) => col.notNull()).addColumn(\"job_dependencies\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"remote_name\", \"text\", (col) => col.notNull().references(\"sync_remotes.name\").onDelete(\"cascade\")).addColumn(\"document_id\", \"text\", (col) => col.notNull()).addColumn(\"scopes\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"branch\", \"text\", (col) => col.notNull()).addColumn(\"operations\", \"jsonb\", (col) => col.notNull().defaultTo(sql`'[]'::jsonb`)).addColumn(\"error_source\", \"text\", (col) => col.notNull()).addColumn(\"error_message\", \"text\", (col) => col.notNull()).addColumn(\"created_at\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n\tawait db.schema.createIndex(\"idx_sync_dead_letters_remote\").on(\"sync_dead_letters\").column(\"remote_name\").execute();\n}\n//#endregion\n//#region src/storage/migrations/014_create_processor_cursor_table.ts\nvar _014_create_processor_cursor_table_exports = /* @__PURE__ */ __exportAll({ up: () => up });\nasync function up(db) {\n\tawait db.schema.createTable(\"ProcessorCursor\").addColumn(\"processorId\", \"text\", (col) => col.primaryKey()).addColumn(\"factoryId\", \"text\", (col) => col.notNull()).addColumn(\"driveId\", \"text\", (col) => col.notNull()).addColumn(\"processorIndex\", \"integer\", (col) => col.notNull()).addColumn(\"lastOrdinal\", \"integer\", (col) => col.notNull().defaultTo(sql`0`)).addColumn(\"status\", \"text\", (col) => col.notNull().defaultTo(sql`'active'`)).addColumn(\"lastError\", \"text\").addColumn(\"lastErrorTimestamp\", \"timestamptz\").addColumn(\"createdAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).addColumn(\"updatedAt\", \"timestamptz\", (col) => col.notNull().defaultTo(sql`NOW()`)).execute();\n}\n//#endregion\n//#region src/storage/migrations/migrator.ts\nconst REACTOR_SCHEMA = \"reactor\";\nconst migrations = {\n\t\"001_create_operation_table\": _001_create_operation_table_exports,\n\t\"002_create_keyframe_table\": _002_create_keyframe_table_exports,\n\t\"003_create_document_table\": _003_create_document_table_exports,\n\t\"004_create_document_relationship_table\": _004_create_document_relationship_table_exports,\n\t\"005_create_indexer_state_table\": _005_create_indexer_state_table_exports,\n\t\"006_create_document_snapshot_table\": _006_create_document_snapshot_table_exports,\n\t\"007_create_slug_mapping_table\": _007_create_slug_mapping_table_exports,\n\t\"008_create_view_state_table\": _008_create_view_state_table_exports,\n\t\"009_create_operation_index_tables\": _009_create_operation_index_tables_exports,\n\t\"010_create_sync_tables\": _010_create_sync_tables_exports,\n\t\"011_add_cursor_type_column\": _011_add_cursor_type_column_exports,\n\t\"012_add_source_remote_column\": _012_add_source_remote_column_exports,\n\t\"013_create_sync_dead_letters_table\": _013_create_sync_dead_letters_table_exports,\n\t\"014_create_processor_cursor_table\": _014_create_processor_cursor_table_exports\n};\nvar ProgrammaticMigrationProvider = class {\n\tgetMigrations() {\n\t\treturn Promise.resolve(migrations);\n\t}\n};\nasync function runMigrations(db, schema = REACTOR_SCHEMA) {\n\ttry {\n\t\tawait sql`CREATE SCHEMA IF NOT EXISTS ${sql.id(schema)}`.execute(db);\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tmigrationsExecuted: [],\n\t\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Failed to create schema\")\n\t\t};\n\t}\n\tconst migrator = new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t});\n\tlet error;\n\tlet results;\n\ttry {\n\t\tconst result = await migrator.migrateToLatest();\n\t\terror = result.error;\n\t\tresults = result.results;\n\t} catch (e) {\n\t\terror = e;\n\t\tresults = [];\n\t}\n\tconst migrationsExecuted = results?.map((result) => result.migrationName) ?? [];\n\tif (error) return {\n\t\tsuccess: false,\n\t\tmigrationsExecuted,\n\t\terror: error instanceof Error ? error : /* @__PURE__ */ new Error(\"Unknown migration error\")\n\t};\n\treturn {\n\t\tsuccess: true,\n\t\tmigrationsExecuted\n\t};\n}\nasync function getMigrationStatus(db, schema = REACTOR_SCHEMA) {\n\treturn await new Migrator({\n\t\tdb: db.withSchema(schema),\n\t\tprovider: new ProgrammaticMigrationProvider(),\n\t\tmigrationTableSchema: schema\n\t}).getMigrations();\n}\n//#endregion\n//#region src/core/drive-container-types.ts\nconst DEFAULT_DRIVE_CONTAINER_TYPES = new Set([\"powerhouse/document-drive\", \"powerhouse/reactor-drive\"]);\n//#endregion\nexport { parsePagingOptions as A, DuplicateManifestError as C, DocumentDeletedError as D, ModuleNotFoundError as E, __exportAll as M, DocumentNotFoundError as O, CollectionMembershipCache as S, InvalidModuleError as T, KyselyWriteCache as _, createForwardingPoolInstrumentation as a, createConsistencyToken as b, DuplicateOperationError as c, KyselyKeyframeStore as d, DocumentModelRegistry as f, EventBus as g, KyselyExecutionScope as h, runMigrations as i, throwIfAborted as j, matchesScope as k, OptimisticLockError as l, driveCollectionId as m, REACTOR_SCHEMA as n, instrumentPgPool as o, SimpleJobExecutor as p, getMigrationStatus as r, KyselyOperationStore as s, DEFAULT_DRIVE_CONTAINER_TYPES as t, RevisionMismatchError as u, KyselyOperationIndex as v, DuplicateModuleError as w, createEmptyConsistencyToken as x, DocumentMetaCache as y };\n\n//# sourceMappingURL=drive-container-types-CAhznKRr.js.map","import type { Operation } from \"@powerhousedao/shared/document-model\";\nimport type { AtomicTxn } from \"@powerhousedao/reactor\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreAtomicTransaction implements AtomicTxn {\n private operations: StoredOperation[] = [];\n\n constructor(\n private documentId: string,\n private documentType: string,\n private scope: string,\n private branch: string,\n ) {}\n\n addOperations(...operations: Operation[]): void {\n for (const op of operations) {\n this.operations.push({\n ...op,\n documentId: this.documentId,\n documentType: this.documentType,\n scope: this.scope,\n branch: this.branch,\n });\n }\n }\n\n getOperations(): StoredOperation[] {\n return this.operations;\n }\n}\n","import type { StoredOperation } from \"./types.js\";\n\nconst PAD_WIDTH = 10;\n\nexport const RANGE_UPPER_BOUND = \"9\".repeat(PAD_WIDTH) + \"~\";\n\nexport function pad(n: number): string {\n return n.toString().padStart(PAD_WIDTH, \"0\");\n}\n\nexport function operationKey(\n documentId: string,\n scope: string,\n branch: string,\n index: number,\n): string {\n return `op/${documentId}/${scope}/${branch}/${pad(index)}`;\n}\n\nexport function operationPrefix(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `op/${documentId}/${scope}/${branch}/`;\n}\n\nexport function ordinalKey(ordinal: number): string {\n return `ord/${pad(ordinal)}`;\n}\n\nexport function ordinalPrefix(): string {\n return \"ord/\";\n}\n\nexport function duplicateKey(\n opId: string,\n index: number,\n skip: number,\n): string {\n return `dup/${opId}/${pad(index)}/${pad(skip)}`;\n}\n\nexport function headKey(\n documentId: string,\n scope: string,\n branch: string,\n): string {\n return `_meta/head/${documentId}/${scope}/${branch}`;\n}\n\nexport function headPrefix(documentId: string): string {\n return `_meta/head/${documentId}/`;\n}\n\nexport const ORDINAL_COUNTER_KEY = \"_meta/ordinal\";\n\nexport type ParsedOperationKey = {\n documentId: string;\n scope: string;\n branch: string;\n index: number;\n};\n\nexport function parseOperationKey(key: string): ParsedOperationKey {\n const parts = key.split(\"/\");\n return {\n documentId: parts[1],\n scope: parts[2],\n branch: parts[3],\n index: parseInt(parts[4], 10),\n };\n}\n\nexport type OrdinalEntry = {\n documentId: string;\n documentType: string;\n scope: string;\n branch: string;\n index: number;\n operation: StoredOperation;\n};\n\nexport type HeadEntryValue = {\n index: number;\n latestTimestampUtcMs: string;\n};\n","import type {\n Operation,\n OperationWithContext,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n AtomicTxn,\n DocumentRevisions,\n IOperationStore,\n OperationFilter,\n PagedResults,\n PagingOptions,\n} from \"@powerhousedao/reactor\";\nimport {\n DuplicateOperationError,\n RevisionMismatchError,\n} from \"@powerhousedao/reactor\";\nimport type Hyperbee from \"hyperbee\";\nimport { HypercoreAtomicTransaction } from \"./hypercore-atomic-transaction.js\";\nimport {\n ORDINAL_COUNTER_KEY,\n RANGE_UPPER_BOUND,\n duplicateKey,\n headKey,\n headPrefix,\n operationKey,\n operationPrefix,\n ordinalKey,\n ordinalPrefix,\n pad,\n} from \"./key-encoding.js\";\nimport type { HeadEntryValue, OrdinalEntry } from \"./key-encoding.js\";\nimport type { StoredOperation } from \"./types.js\";\n\nexport class HypercoreOperationStore implements IOperationStore {\n private applyLock: Promise<void> = Promise.resolve();\n\n constructor(private bee: Hyperbee) {}\n\n async apply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n const prevLock = this.applyLock;\n let releaseLock: () => void;\n this.applyLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n await prevLock;\n\n try {\n return await this.executeApply(\n documentId,\n documentType,\n scope,\n branch,\n revision,\n fn,\n signal,\n );\n } finally {\n releaseLock!();\n }\n }\n\n private async executeApply(\n documentId: string,\n documentType: string,\n scope: string,\n branch: string,\n revision: number,\n fn: (txn: AtomicTxn) => void | Promise<void>,\n signal?: AbortSignal,\n ): Promise<Operation[]> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const hKey = headKey(documentId, scope, branch);\n const headEntry = await this.bee.get(hKey);\n const currentRevision = headEntry\n ? (headEntry.value as HeadEntryValue).index\n : -1;\n\n if (currentRevision !== revision - 1) {\n throw new RevisionMismatchError(currentRevision + 1, revision);\n }\n\n const atomicTxn = new HypercoreAtomicTransaction(\n documentId,\n documentType,\n scope,\n branch,\n );\n await fn(atomicTxn);\n\n const operations = atomicTxn.getOperations();\n if (operations.length === 0) {\n return [];\n }\n\n for (const op of operations) {\n const dupKey = duplicateKey(op.id, op.index, op.skip);\n const existing = await this.bee.get(dupKey);\n if (existing) {\n throw new DuplicateOperationError(\n `${op.id} at index ${op.index} with skip ${op.skip}`,\n );\n }\n }\n\n const ordinalEntry = await this.bee.get(ORDINAL_COUNTER_KEY);\n let nextOrdinal: number = ordinalEntry ? (ordinalEntry.value as number) : 0;\n\n const batch = this.bee.batch();\n\n for (const op of operations) {\n const opKey = operationKey(documentId, scope, branch, op.index);\n const serialized = this.serializeOperation(op);\n await batch.put(opKey, serialized);\n\n const ordEntry: OrdinalEntry = {\n documentId,\n documentType,\n scope,\n branch,\n index: op.index,\n operation: serialized,\n };\n await batch.put(ordinalKey(nextOrdinal), ordEntry);\n\n await batch.put(duplicateKey(op.id, op.index, op.skip), \"\");\n\n nextOrdinal++;\n }\n\n const lastOp = operations[operations.length - 1];\n const headValue: HeadEntryValue = {\n index: lastOp.index,\n latestTimestampUtcMs: lastOp.timestampUtcMs,\n };\n await batch.put(hKey, headValue);\n await batch.put(ORDINAL_COUNTER_KEY, nextOrdinal);\n\n await batch.flush();\n\n return operations.map((op) => this.toOperation(op));\n }\n\n async getSince(\n documentId: string,\n scope: string,\n branch: string,\n revision: number,\n filter?: OperationFilter,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const startIndex = revision + 1;\n const cursorIndex =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10) + 1\n : startIndex;\n const effectiveStart = Math.max(startIndex, cursorIndex);\n\n const gt = prefix + pad(effectiveStart - 1);\n const lt = prefix + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: Operation[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n\n if (filter) {\n if (\n filter.actionTypes &&\n filter.actionTypes.length > 0 &&\n !filter.actionTypes.includes((stored.action as { type: string }).type)\n ) {\n continue;\n }\n if (\n filter.timestampFrom &&\n stored.timestampUtcMs < filter.timestampFrom\n ) {\n continue;\n }\n if (filter.timestampTo && stored.timestampUtcMs > filter.timestampTo) {\n continue;\n }\n if (\n filter.sinceRevision !== undefined &&\n stored.index < filter.sinceRevision\n ) {\n continue;\n }\n }\n\n items.push(this.toOperation(stored));\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].index.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSince(\n documentId,\n scope,\n branch,\n revision,\n filter,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getSinceId(\n id: number,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<OperationWithContext>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const cursorValue =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10)\n : id;\n const effectiveId = Math.max(id, cursorValue);\n\n const gt = ordinalPrefix() + pad(effectiveId);\n const lt = ordinalPrefix() + RANGE_UPPER_BOUND;\n const limit = paging?.limit ? paging.limit + 1 : undefined;\n\n const items: OperationWithContext[] = [];\n const stream = this.bee.createReadStream({ gt, lt, limit });\n\n for await (const entry of stream) {\n const ordEntry = entry.value as OrdinalEntry;\n const ordinal = parseInt(entry.key.split(\"/\")[1], 10);\n\n items.push({\n operation: this.toOperation(ordEntry.operation),\n context: {\n documentId: ordEntry.documentId,\n documentType: ordEntry.documentType,\n scope: ordEntry.scope,\n branch: ordEntry.branch,\n ordinal,\n },\n });\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].context.ordinal.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getSinceId(\n id,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getConflicting(\n documentId: string,\n scope: string,\n branch: string,\n minTimestamp: string,\n paging?: PagingOptions,\n signal?: AbortSignal,\n ): Promise<PagedResults<Operation>> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = operationPrefix(documentId, scope, branch);\n const cursorIndex =\n paging?.cursor && parseInt(paging.cursor, 10) > 0\n ? parseInt(paging.cursor, 10)\n : -1;\n\n const gt = cursorIndex >= 0 ? prefix + pad(cursorIndex) : prefix;\n const lt = prefix + RANGE_UPPER_BOUND;\n\n const stream = this.bee.createReadStream({\n gt: cursorIndex >= 0 ? gt : undefined,\n gte: cursorIndex >= 0 ? undefined : gt,\n lt,\n });\n\n const items: Operation[] = [];\n\n for await (const entry of stream) {\n const stored = entry.value as StoredOperation;\n if (stored.timestampUtcMs >= minTimestamp) {\n items.push(this.toOperation(stored));\n }\n }\n\n let hasMore = false;\n let resultItems = items;\n\n if (paging?.limit && items.length > paging.limit) {\n hasMore = true;\n resultItems = items.slice(0, paging.limit);\n }\n\n const nextCursor =\n hasMore && resultItems.length > 0\n ? resultItems[resultItems.length - 1].index.toString()\n : undefined;\n\n const cursor = paging?.cursor || \"0\";\n const resultLimit = paging?.limit || 100;\n\n return {\n results: resultItems,\n options: { cursor, limit: resultLimit },\n nextCursor,\n next: hasMore\n ? () =>\n this.getConflicting(\n documentId,\n scope,\n branch,\n minTimestamp,\n { cursor: nextCursor!, limit: resultLimit },\n signal,\n )\n : undefined,\n };\n }\n\n async getRevisions(\n documentId: string,\n branch: string,\n signal?: AbortSignal,\n ): Promise<DocumentRevisions> {\n if (signal?.aborted) {\n throw new Error(\"Operation aborted\");\n }\n\n const prefix = headPrefix(documentId);\n const stream = this.bee.createReadStream({\n gte: prefix,\n lt: prefix + \"~\",\n });\n\n const revision: Record<string, number> = {};\n let latestTimestamp = new Date(0).toISOString();\n\n for await (const entry of stream) {\n const parts = entry.key.split(\"/\");\n const entryScope = parts[3];\n const entryBranch = parts[4];\n\n if (entryBranch !== branch) {\n continue;\n }\n\n const headValue = entry.value as HeadEntryValue;\n revision[entryScope] = headValue.index + 1;\n\n if (headValue.latestTimestampUtcMs > latestTimestamp) {\n latestTimestamp = headValue.latestTimestampUtcMs;\n }\n }\n\n return { revision, latestTimestamp };\n }\n\n private serializeOperation(op: StoredOperation): StoredOperation {\n return {\n id: op.id,\n index: op.index,\n skip: op.skip,\n timestampUtcMs: op.timestampUtcMs,\n hash: op.hash,\n error: op.error,\n action: op.action,\n documentId: op.documentId,\n documentType: op.documentType,\n scope: op.scope,\n branch: op.branch,\n };\n }\n\n private toOperation(stored: StoredOperation): Operation {\n return {\n id: stored.id,\n index: stored.index,\n skip: stored.skip,\n timestampUtcMs: stored.timestampUtcMs,\n hash: stored.hash,\n error: stored.error || undefined,\n action: stored.action,\n };\n }\n}\n","import Corestore from \"corestore\";\nimport Hyperbee from \"hyperbee\";\n\nexport class StorageManager {\n private store: Corestore;\n private bee: Hyperbee | undefined;\n\n constructor(storagePath: string) {\n this.store = new Corestore(storagePath);\n }\n\n async open(): Promise<void> {\n await this.store.ready();\n const core = this.store.get({ name: \"operations\" });\n this.bee = new Hyperbee(core, {\n keyEncoding: \"utf-8\",\n valueEncoding: \"json\",\n });\n await this.bee.ready();\n }\n\n async close(): Promise<void> {\n if (this.bee) {\n await this.bee.close();\n }\n await this.store.close();\n }\n\n getBee(): Hyperbee {\n if (!this.bee) {\n throw new Error(\"StorageManager not opened. Call open() first.\");\n }\n return this.bee;\n }\n}\n"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/reactor-hypercore",
3
- "version": "6.2.0-dev.10",
3
+ "version": "6.2.0-dev.11",
4
4
  "description": "Hypercore-backed IOperationStore for the Powerhouse Reactor",
5
5
  "repository": {
6
6
  "url": "https://github.com/powerhouse-inc/powerhouse",
@@ -27,17 +27,17 @@
27
27
  "dependencies": {
28
28
  "corestore": "^6.18.4",
29
29
  "hyperbee": "^2.21.0",
30
- "@powerhousedao/shared": "6.2.0-dev.10"
30
+ "@powerhousedao/shared": "6.2.0-dev.11"
31
31
  },
32
32
  "devDependencies": {
33
33
  "tsdown": "0.21.1",
34
34
  "vitest": "4.1.1",
35
35
  "tsx": "4.21.0",
36
- "document-model": "6.2.0-dev.10",
37
- "@powerhousedao/reactor": "6.2.0-dev.10"
36
+ "@powerhousedao/reactor": "6.2.0-dev.11",
37
+ "document-model": "6.2.0-dev.11"
38
38
  },
39
39
  "peerDependencies": {
40
- "document-model": "6.2.0-dev.10"
40
+ "document-model": "6.2.0-dev.11"
41
41
  },
42
42
  "scripts": {
43
43
  "build": "tsdown",