@tearleads/client-sdk 0.1.222 → 0.1.223

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +1 -1
  2. package/data/persistence/container-contents/containerContentsPersistenceTypes.js +0 -1
  3. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  4. package/data/persistence/container-contents/containerCreateIntentSettlement.js +2 -2
  5. package/data/persistence/container-contents/containerCreateIntentSettlement.js.map +1 -1
  6. package/data/persistence/container-contents/containerIntentPersistence.js +2 -2
  7. package/data/persistence/container-contents/containerIntentPersistence.js.map +1 -1
  8. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +10 -9
  9. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +14 -3
  10. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  11. package/data/persistence/documents/documentsPersistence.d.ts +2 -1
  12. package/data/persistence/documents/documentsPersistence.js +3 -3
  13. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  14. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js +1 -1
  15. package/data/persistence/documents/internal/containerDocumentTombstoneHolds.js.map +1 -1
  16. package/data/persistence/documents/internal/containerDocumentTombstones.d.ts +10 -0
  17. package/data/persistence/documents/internal/containerDocumentTombstones.js +3 -14
  18. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  19. package/data/persistence/documents/internal/discoveredDocumentPlacement.js +1 -1
  20. package/data/persistence/documents/internal/discoveredDocumentPlacement.js.map +1 -1
  21. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +1 -1
  22. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  23. package/data/persistence/{container-contents → documents}/pendingContainerCreate.js +1 -2
  24. package/data/persistence/documents/pendingContainerCreate.js.map +1 -0
  25. package/data/sqlite/schema/index.d.ts +1 -1
  26. package/data/sqlite/schema/index.js +1 -1
  27. package/data/sqlite/schema/index.js.map +1 -1
  28. package/data/sqlite/schema/localIntentSchema.d.ts +6 -0
  29. package/data/sqlite/schema/localIntentSchema.js +6 -0
  30. package/data/sqlite/schema/localIntentSchema.js.map +1 -1
  31. package/package.json +1 -1
  32. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +1 -1
  33. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  34. package/workflows/container-contents/documentQueries/index.js +2 -2
  35. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  36. package/workflows/documents/create/index.js +1 -1
  37. package/workflows/documents/create/index.js.map +1 -1
  38. package/data/persistence/container-contents/pendingContainerCreate.js.map +0 -1
  39. /package/data/persistence/{container-contents → documents}/documentPlacement.d.ts +0 -0
  40. /package/data/persistence/{container-contents → documents}/documentPlacement.js +0 -0
  41. /package/data/persistence/{container-contents → documents}/documentPlacement.js.map +0 -0
@@ -1,11 +1,11 @@
1
1
  import type { AccessManifestCheckpoint } from "../../../internal/crypto/index.js";
2
2
  import type { DocumentSyncPullContinuation } from "../../documents/shared/sync/pullContinuation.js";
3
+ import type { CONTAINER_CREATE_INTENT_TYPE } from "../../sqlite/schema/index.js";
3
4
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
5
  import type { DocumentRecord, PendingUpdateFields, PendingUpdateRecord } from "../documents/records/index.js";
5
6
  import type { HeldContainerBinding } from "./containerBinding.js";
6
7
  import type { ContainerRecord } from "./containerPersistence.js";
7
8
  import type { DormantMetadataSweepPersistence } from "./dormantMetadataSweep.js";
8
- export declare const CONTAINER_CREATE_INTENT_TYPE = "container.create";
9
9
  export declare const CONTAINER_MOVE_INTENT_TYPE = "container.move";
10
10
  export type ContainerCreateIntentSyncStatus = "pending" | "synced";
11
11
  export type ContainerMoveIntentSyncStatus = "pending" | "blocked";
@@ -1,3 +1,2 @@
1
- export const CONTAINER_CREATE_INTENT_TYPE = "container.create";
2
1
  export const CONTAINER_MOVE_INTENT_TYPE = "container.move";
3
2
  //# sourceMappingURL=containerContentsPersistenceTypes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAYA,MAAM,CAAC,MAAM,4BAA4B,GAAG,kBAAkB,CAAC;AAC/D,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_CREATE_INTENT_TYPE = \"container.create\";\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?:\n | {\n createIntent?: ContainerCreateIntentInput;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n }\n | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
1
+ {"version":3,"file":"containerContentsPersistenceTypes.js","sourceRoot":"","sources":["containerContentsPersistenceTypes.ts"],"names":[],"mappings":"AAaA,MAAM,CAAC,MAAM,0BAA0B,GAAG,gBAAgB,CAAC","sourcesContent":["import type { AccessManifestCheckpoint } from \"@tearleads/crypto\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { CONTAINER_CREATE_INTENT_TYPE } from \"../../sqlite/schema\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type {\n DocumentRecord,\n PendingUpdateFields,\n PendingUpdateRecord,\n} from \"../documents/records\";\nimport type { HeldContainerBinding } from \"./containerBinding\";\nimport type { ContainerRecord } from \"./containerPersistence\";\nimport type { DormantMetadataSweepPersistence } from \"./dormantMetadataSweep\";\n\nexport const CONTAINER_MOVE_INTENT_TYPE = \"container.move\";\n\nexport type ContainerCreateIntentSyncStatus = \"pending\" | \"synced\";\nexport type ContainerMoveIntentSyncStatus = \"pending\" | \"blocked\";\n\nexport interface ContainerCreateIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n intentType: typeof CONTAINER_CREATE_INTENT_TYPE;\n syncStatus: ContainerCreateIntentSyncStatus;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerMoveIntentRecord {\n id: string;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n intentType: typeof CONTAINER_MOVE_INTENT_TYPE;\n syncStatus: ContainerMoveIntentSyncStatus;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface ContainerCreateIntentInput {\n id?: string;\n parentContainerId: string;\n}\n\nexport interface ContainerMoveIntentInput {\n id?: string;\n parentContainerId: string;\n previousParentContainerId?: string | null | undefined;\n}\n\nexport interface ContainerCreateIntentErrorInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type ContainerCreateIntentErrorInputRecorder = (\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n) => Promise<void>;\n\nexport interface ContainerMoveIntentRevisionInput {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n stillCurrent: () => boolean;\n}\n\nexport interface ContainerCreateIntentRevisionInput\n extends ContainerMoveIntentRevisionInput {\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /** The remote parent now; a move settlement queues cites it as previous. */\n supersededMovePreviousParentId?: string | undefined;\n /**\n * The parent the create committed under. A desired parent equal to it, or\n * to the current one, owes no move: the user never moved the folder away,\n * and a later remote move by another writer stands.\n */\n createdParentContainerId?: string | undefined;\n /** The parent the settled intent wants. */\n desiredParentContainerId?: string | undefined;\n}\n\nexport interface LocalRootDescendantReparentInput {\n containerId: string;\n parentContainerId: string | null;\n updateCreateIntent?: boolean | undefined;\n}\n\n/**\n * A container's metadata document record plus its durable content: the full\n * Loro updates export of the metadata document, stored in the shared\n * history-checkpoint table under the container-metadata app kind. Metadata\n * documents are tiny registries, so the whole update log is the checkpoint.\n */\nexport interface ContainerMetadataRecord extends DocumentRecord {\n metadataUpdates: string;\n}\n\nexport interface StoredContainerState {\n container: ContainerRecord;\n record: ContainerMetadataRecord | null;\n}\n\nexport interface ContainerRemoval {\n containerId: string;\n reason: \"access_revoked\" | \"deleted\";\n updatedAt: string;\n}\n\nexport interface ContainerHydrationTombstone extends ContainerRemoval {\n generation: number;\n}\n\nexport interface ContainerDeletionGuard {\n containerId: string;\n expectedContainer: ContainerRecord | null;\n}\n\nexport interface SaveContainerOptions {\n createIntent?: ContainerCreateIntentInput;\n stillCurrent?: (() => boolean) | undefined;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n}\n\nexport interface SaveContainerWithPendingUpdateOptions\n extends SaveContainerOptions {\n pendingUpdate: PendingUpdateFields;\n}\n\nexport interface ContainerContentsPersistence\n extends DormantMetadataSweepPersistence {\n containerExists: (execSql: ExecSql, containerId: string) => Promise<boolean>;\n /**\n * Create an absent remotely hydrated container only when no newer durable\n * tombstone or concurrent container/dormant-metadata mutation won first.\n */\n commitHydratedContainer: (\n execSql: ExecSql,\n input: {\n container: ContainerRecord;\n expectedDormantRecord: ContainerMetadataRecord | null;\n /** Tombstone observed before the remote request began, or null. */\n expectedHydrationTombstone?:\n | ContainerHydrationTombstone\n | null\n | undefined;\n /** Current placement verified and pinned before recovery insertion. */\n expectedPlacementCheckpoint?: AccessManifestCheckpoint | undefined;\n record: ContainerMetadataRecord;\n remoteUpdatedAt: string;\n saveOptions: {\n localUpdatedAt?: string;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n { committed: true; container: ContainerRecord } | { committed: false }\n >;\n /** Capture anti-resurrection fences immediately before a remote fetch. */\n loadContainerHydrationTombstones: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<ContainerHydrationTombstone>>;\n deleteContainer: (\n execSql: ExecSql,\n containerId: string,\n options?: {\n reason?: ContainerRemoval[\"reason\"];\n updatedAt?: string;\n },\n ) => Promise<void>;\n deleteContainers: (\n execSql: ExecSql,\n removals: ReadonlyArray<ContainerRemoval>,\n options?: {\n /** Must run inside the deletion transaction before any row is removed. */\n beforeDeleteInTransaction?:\n | ((transactionExecSql: ExecSql) => Promise<boolean>)\n | undefined;\n /** Unsigned discovery removes listings but preserves metadata and local intent. */\n discoveryOnly?: boolean;\n /**\n * Request-time states rechecked inside the deletion transaction. An\n * absent or changed row means another pane won and aborts the cascade.\n */\n expectedContainers?: ReadonlyArray<ContainerDeletionGuard>;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ReadonlyArray<string>>;\n deletePendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n enqueuePendingUpdate: (\n execSql: ExecSql,\n input: PendingUpdateFields & { containerId: string },\n ) => Promise<string>;\n listPendingCreateIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerCreateIntentRecord[]>;\n // Every move intent that has not yet synced, regardless of syncStatus —\n // a blocked move (destination parent not synced yet) is still unsynced, and\n // synced moves are deleted (see markMoveIntentRevisionSynced), so every surviving\n // row qualifies. Blocked intents replay too: \"blocked\" names the reason the\n // last attempt could not proceed, not a terminal verdict.\n listUnsyncedMoveIntents: (\n execSql: ExecSql,\n ) => Promise<ContainerMoveIntentRecord[]>;\n listContainerIdsWithPendingUpdates: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listContainerIdsWithPullContinuations: (\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n ) => Promise<string[]>;\n listPendingUpdates: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<PendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n /** Revision-CAS error recorder used by asynchronous create replay. */\n recordCreateIntentRevisionError: ContainerCreateIntentErrorInputRecorder;\n recordMoveIntentError: (\n execSql: ExecSql,\n input: {\n blocked?: boolean | undefined;\n containerId: string;\n expectedIntentId?: string | undefined;\n expectedUpdatedAt?: string | undefined;\n message: string;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<void>;\n reassignContainerDocuments: (\n execSql: ExecSql,\n input: {\n fromContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n toContainerId: string;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalRootContainer: (\n execSql: ExecSql,\n input: {\n descendantReparents: ReadonlyArray<LocalRootDescendantReparentInput>;\n localRootContainerId: string;\n remoteOrganizationId: string;\n remoteRootContainerId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n reconcileLocalSystemContainer: (\n execSql: ExecSql,\n input: {\n localContainerId: string;\n remoteContainerId: string;\n remoteOrganizationId: string;\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n ) => Promise<void>;\n loadContainers: (\n execSql: ExecSql,\n ) => Promise<ReadonlyArray<StoredContainerState>>;\n loadContainerMetadataState: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<StoredContainerState | null>;\n /**\n * The organization and metadata target this device holds for a container,\n * from its live row or retained dormant metadata; null when never held.\n */\n loadHeldContainerBinding: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<HeldContainerBinding | null>;\n /** Whether a held folder was re-homed away from this organization. */\n isSupersededContainerBinding: (\n execSql: ExecSql,\n input: { containerId: string; organizationId: string },\n ) => Promise<boolean>;\n /**\n * Move a held folder to the binding its own user re-created it under,\n * resetting the metadata record's remote stream; false if the held binding\n * changed since it was read.\n */\n rebindHeldContainer: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expected: HeldContainerBinding;\n next: { metadataDocumentId: string; organizationId: string };\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<boolean>;\n /**\n * Load a container-metadata record by container id alone, without\n * requiring a containers row — the dormant shape row 4's access_revoked\n * branch leaves behind, re-attached on rehydration.\n */\n loadContainerMetadataRecord: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Atomically replace the exact rejected metadata pull continuation with its\n * durable recovery marker and return the authoritative current record.\n */\n invalidateMetadataPullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n containerId: string;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<ContainerMetadataRecord | null>;\n /**\n * Conditionally commit metadata content, its outgoing row, accepted queue\n * settlement, container fields, and the canonical record in one transaction.\n */\n commitMetadataMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n clearSyncFailure?: boolean | undefined;\n container: ContainerRecord;\n expectedContainer: ContainerRecord;\n expectedRecord: ContainerMetadataRecord;\n createIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n /**\n * When present, an overtaking create revision is adopted as the\n * desired local parent and converted to a move from this remotely\n * committed parent instead of rejecting the remote identity.\n */\n supersededMovePreviousParentId?: string | undefined;\n }\n | undefined;\n moveIntentSettlement?:\n | {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n }\n | undefined;\n /** Present only for an explicit local primary change; null clears it. */\n primaryDocumentId?: string | null | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n preserveDurableStructureWhenPending?: boolean | undefined;\n record: ContainerMetadataRecord;\n saveOptions?:\n | {\n createIntent?: ContainerCreateIntentInput;\n localUpdatedAt?: string;\n moveIntent?: ContainerMoveIntentInput | undefined;\n serverTimestamps?:\n | {\n createdAt?: string | null;\n updatedAt?: string | null;\n }\n | undefined;\n updatedAt?: string;\n }\n | undefined;\n settleAcceptedPendingOnConflict: boolean;\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<\n | {\n committed: true;\n container: ContainerRecord;\n createIntentSettled?: true | undefined;\n moveIntentSettled?: true | undefined;\n }\n | {\n committed: false;\n currentState: StoredContainerState | null;\n staleServerState?: true;\n }\n >;\n settleAcceptedMetadataPendingUpdates: (\n execSql: ExecSql,\n input: {\n containerId: string;\n expectedRecord: ContainerMetadataRecord;\n pendingUpdateIds: readonly string[];\n stillCurrent?: (() => boolean) | undefined;\n },\n ) => Promise<StoredContainerState | null>;\n saveContainer: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord | null,\n options?: SaveContainerOptions,\n ) => Promise<ContainerRecord>;\n /**\n * Atomically saves a container and enqueues its first metadata update.\n * Host adapters must implement the compound write in their own transaction.\n */\n saveContainerWithPendingUpdate: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n options: SaveContainerWithPendingUpdateOptions,\n ) => Promise<ContainerRecord>;\n saveContainerAndDeletePendingUpdates: (\n execSql: ExecSql,\n container: ContainerRecord,\n record: ContainerMetadataRecord,\n pendingUpdateIds: readonly string[],\n ) => Promise<ContainerRecord>;\n /**\n * Revision-CAS settlement used by asynchronous create replay. Invalid\n * adapters are rejected before the remote mutation begins.\n */\n markCreateIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Explicit revision-CAS settlement. Move replay instead settles inside\n * commitMetadataMutation and requires its atomic acknowledgment.\n */\n markMoveIntentRevisionSynced: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n ) => Promise<boolean>;\n /**\n * Drop a move revision the server refuses for good and restore the\n * folder's previous parent in the same transaction; false if superseded.\n */\n abandonMoveIntentRevision: (\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput & {\n previousParentContainerId: string;\n },\n ) => Promise<boolean>;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { and, eq } from "drizzle-orm";
2
- import { inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../sqlite/schema/index.js";
3
- import { CONTAINER_CREATE_INTENT_TYPE, CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
2
+ import { CONTAINER_CREATE_INTENT_TYPE, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../sqlite/schema/index.js";
3
+ import { CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
4
4
  import { saveContainerMoveIntent } from "./containerMoveIntentRows.js";
5
5
  async function markContainerCreateIntentRevisionSynced(input) {
6
6
  const updated = await input.tx
@@ -1 +1 @@
1
- {"version":3,"file":"containerCreateIntentSettlement.js","sourceRoot":"","sources":["containerCreateIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,E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C,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,EAC7C,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,EACzD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,SAAS,CAAC,CACvC,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,aAAa,EAAE,EAAE;QAAE,OAAO,YAAY,CAAC;IAE5C,MAAM,OAAO,GAAG,MAAM,uCAAuC,CAAC;QAC5D,GAAG,KAAK;QACR,gBAAgB,EAAE,aAAa,CAAC,EAAE;QAClC,iBAAiB,EAAE,aAAa,CAAC,SAAS;KAC3C,CAAC,CAAC;IACH,IAAI,CAAC,OAAO;QAAE,OAAO,YAAY,CAAC;IAClC,OAAO,mBAAmB,CAAC;QACzB,GAAG,KAAK;QACR,wBAAwB,EAAE,aAAa,CAAC,iBAAiB;QACzD,8BAA8B,EAAE,gBAAgB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerMoveIntentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerMoveIntent } from \"./containerMoveIntentRows\";\n\nasync function markContainerCreateIntentRevisionSynced(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const updated = await input.tx\n .update(localIntents)\n .set({\n syncStatus: \"synced\",\n remoteContainerId: input.remoteContainerId,\n remoteMetadataDocumentId: input.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: input.remoteMetadataAccessStateHash,\n lastError: null,\n updatedAt: new Date().toISOString(),\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return updated.length > 0;\n}\n\n/**\n * The move an adopted create still owes: to the desired parent, citing where\n * the folder is now. A desired parent equal to the created one means the user\n * never moved it away, so a later remote move by another writer stands.\n */\nfunction owedCreateMove(input: {\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n}): ContainerMoveIntentInput | null {\n const desired = input.desiredParentContainerId;\n if (\n desired === input.supersededMovePreviousParentId ||\n desired === input.createdParentContainerId\n ) {\n return null;\n }\n return {\n parentContainerId: desired,\n previousParentContainerId: input.supersededMovePreviousParentId,\n };\n}\n\n/**\n * A local move of a folder the listing already carried queues its own move\n * intent, which is newer than the create's parent: it keeps its destination,\n * and now cites where the folder sits remotely rather than the parent it was\n * queued from, which never committed. One whose destination is already that\n * parent is done and is dropped.\n */\nasync function rebaseQueuedMove(input: {\n readonly containerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"none\" | \"synced\"> {\n const queued = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n );\n const arrived = await input.tx\n .delete(localIntents)\n .where(\n and(\n queued,\n eq(\n localIntents.targetContainerId,\n input.supersededMovePreviousParentId,\n ),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n if (arrived.length > 0) return \"synced\";\n const rebased = await input.tx\n .update(localIntents)\n .set({ sourceContainerId: input.supersededMovePreviousParentId })\n .where(queued)\n .returning({ containerId: localIntents.subjectId });\n return rebased.length > 0 ? \"converted-to-move\" : \"none\";\n}\n\nasync function queueOwedCreateMove(input: {\n readonly containerId: string;\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"synced\"> {\n const queued = await rebaseQueuedMove(input);\n if (queued !== \"none\") return queued;\n const moveIntent = owedCreateMove(input);\n if (!moveIntent) return \"synced\";\n await saveContainerMoveIntent({\n containerId: input.containerId,\n moveIntent,\n tx: input.tx,\n updatedAt: new Date().toISOString(),\n });\n return \"converted-to-move\";\n}\n\nexport async function settleContainerCreateIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n supersededMovePreviousParentId?: string | undefined;\n createdParentContainerId?: string | undefined;\n desiredParentContainerId?: string | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"superseded\" | \"synced\"> {\n const previousParentId = input.supersededMovePreviousParentId;\n if (await markContainerCreateIntentRevisionSynced(input)) {\n // An adopted create may still owe a move: the user can move the folder\n // after its create committed.\n if (\n previousParentId === undefined ||\n input.desiredParentContainerId === undefined\n ) {\n return \"synced\";\n }\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: input.desiredParentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n }\n if (previousParentId === undefined) {\n return \"superseded\";\n }\n\n const [currentIntent] = await input.tx\n .select({\n id: localIntents.id,\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n )\n .limit(1);\n if (!currentIntent?.id) return \"superseded\";\n\n const adopted = await markContainerCreateIntentRevisionSynced({\n ...input,\n expectedIntentId: currentIntent.id,\n expectedUpdatedAt: currentIntent.updatedAt,\n });\n if (!adopted) return \"superseded\";\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: currentIntent.parentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n}\n"]}
1
+ {"version":3,"file":"containerCreateIntentSettlement.js","sourceRoot":"","sources":["containerCreateIntentSettlement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACL,0BAA0B,GAE3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,KAAK,UAAU,uCAAuC,CAAC,KAQtD;IACC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,EAAE;SAC3B,MAAM,CAAC,YAAY,CAAC;SACpB,GAAG,CAAC;QACH,UAAU,EAAE,QAAQ;QACpB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,6BAA6B,EAAE,KAAK,CAAC,6BAA6B;QAClE,SAAS,EAAE,IAAI;QACf,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;SACD,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,EAC7C,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,EACz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wB,EAAE,KAAK,CAAC,wBAAwB;YACxD,8BAA8B,EAAE,gBAAgB;SACjD,CAAC,CAAC;IACL,CAAC;IACD,IAAI,gBAAgB,KAAK,SAAS,EAAE,CAAC;QACnC,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,KAAK,CAAC,EAAE;SACnC,MAAM,CAAC;QACN,EAAE,EAAE,YAAY,CAAC,EAAE;QACnB,iBAAiB,EAAE,YAAY,CAAC,iBAAiB;QACjD,SAAS,EAAE,YAAY,CAAC,SAAS;KAClC,CAAC;SACD,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,eAAe,CAAC,EACrD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC,EAC7C,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,4BAA4B,CAAC,EACzD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,SAAS,CAAC,CACvC,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,IAAI,CAAC,aAAa,EAAE,EAAE;QAAE,OAAO,YAAY,CAAC;IAE5C,MAAM,OAAO,GAAG,MAAM,uCAAuC,CAAC;QAC5D,GAAG,KAAK;QACR,gBAAgB,EAAE,aAAa,CAAC,EAAE;QAClC,iBAAiB,EAAE,aAAa,CAAC,SAAS;KAC3C,CAAC,CAAC;IACH,IAAI,CAAC,OAAO;QAAE,OAAO,YAAY,CAAC;IAClC,OAAO,mBAAmB,CAAC;QACzB,GAAG,KAAK;QACR,wBAAwB,EAAE,aAAa,CAAC,iBAAiB;QACzD,8BAA8B,EAAE,gBAAgB;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq } from \"drizzle-orm\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerMoveIntentInput,\n} from \"./containerContentsPersistenceTypes\";\nimport { saveContainerMoveIntent } from \"./containerMoveIntentRows\";\n\nasync function markContainerCreateIntentRevisionSynced(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const updated = await input.tx\n .update(localIntents)\n .set({\n syncStatus: \"synced\",\n remoteContainerId: input.remoteContainerId,\n remoteMetadataDocumentId: input.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: input.remoteMetadataAccessStateHash,\n lastError: null,\n updatedAt: new Date().toISOString(),\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return updated.length > 0;\n}\n\n/**\n * The move an adopted create still owes: to the desired parent, citing where\n * the folder is now. A desired parent equal to the created one means the user\n * never moved it away, so a later remote move by another writer stands.\n */\nfunction owedCreateMove(input: {\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n}): ContainerMoveIntentInput | null {\n const desired = input.desiredParentContainerId;\n if (\n desired === input.supersededMovePreviousParentId ||\n desired === input.createdParentContainerId\n ) {\n return null;\n }\n return {\n parentContainerId: desired,\n previousParentContainerId: input.supersededMovePreviousParentId,\n };\n}\n\n/**\n * A local move of a folder the listing already carried queues its own move\n * intent, which is newer than the create's parent: it keeps its destination,\n * and now cites where the folder sits remotely rather than the parent it was\n * queued from, which never committed. One whose destination is already that\n * parent is done and is dropped.\n */\nasync function rebaseQueuedMove(input: {\n readonly containerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"none\" | \"synced\"> {\n const queued = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n );\n const arrived = await input.tx\n .delete(localIntents)\n .where(\n and(\n queued,\n eq(\n localIntents.targetContainerId,\n input.supersededMovePreviousParentId,\n ),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n if (arrived.length > 0) return \"synced\";\n const rebased = await input.tx\n .update(localIntents)\n .set({ sourceContainerId: input.supersededMovePreviousParentId })\n .where(queued)\n .returning({ containerId: localIntents.subjectId });\n return rebased.length > 0 ? \"converted-to-move\" : \"none\";\n}\n\nasync function queueOwedCreateMove(input: {\n readonly containerId: string;\n readonly createdParentContainerId?: string | undefined;\n readonly desiredParentContainerId: string;\n readonly supersededMovePreviousParentId: string;\n readonly tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"synced\"> {\n const queued = await rebaseQueuedMove(input);\n if (queued !== \"none\") return queued;\n const moveIntent = owedCreateMove(input);\n if (!moveIntent) return \"synced\";\n await saveContainerMoveIntent({\n containerId: input.containerId,\n moveIntent,\n tx: input.tx,\n updatedAt: new Date().toISOString(),\n });\n return \"converted-to-move\";\n}\n\nexport async function settleContainerCreateIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n remoteContainerId: string;\n remoteMetadataAccessStateHash: string;\n remoteMetadataDocumentId: string;\n supersededMovePreviousParentId?: string | undefined;\n createdParentContainerId?: string | undefined;\n desiredParentContainerId?: string | undefined;\n tx: ClientSQLiteTransactionScope;\n}): Promise<\"converted-to-move\" | \"superseded\" | \"synced\"> {\n const previousParentId = input.supersededMovePreviousParentId;\n if (await markContainerCreateIntentRevisionSynced(input)) {\n // An adopted create may still owe a move: the user can move the folder\n // after its create committed.\n if (\n previousParentId === undefined ||\n input.desiredParentContainerId === undefined\n ) {\n return \"synced\";\n }\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: input.desiredParentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n }\n if (previousParentId === undefined) {\n return \"superseded\";\n }\n\n const [currentIntent] = await input.tx\n .select({\n id: localIntents.id,\n parentContainerId: localIntents.targetContainerId,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.syncStatus, \"pending\"),\n ),\n )\n .limit(1);\n if (!currentIntent?.id) return \"superseded\";\n\n const adopted = await markContainerCreateIntentRevisionSynced({\n ...input,\n expectedIntentId: currentIntent.id,\n expectedUpdatedAt: currentIntent.updatedAt,\n });\n if (!adopted) return \"superseded\";\n return queueOwedCreateMove({\n ...input,\n desiredParentContainerId: currentIntent.parentContainerId,\n supersededMovePreviousParentId: previousParentId,\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { and, asc, eq, inArray } from "drizzle-orm";
2
- import { inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "../../sqlite/schema/index.js";
2
+ import { CONTAINER_CREATE_INTENT_TYPE, inLocalIntentLane, LOCAL_INTENT_LANES, LOCAL_INTENT_SUBJECT, localIntents, } from "../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
4
- import { CONTAINER_CREATE_INTENT_TYPE, CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
4
+ import { CONTAINER_MOVE_INTENT_TYPE, } from "./containerContentsPersistenceTypes.js";
5
5
  import { settleContainerCreateIntentRevision } from "./containerCreateIntentSettlement.js";
6
6
  function parseCreateIntentSyncStatus(value) {
7
7
  return value === "synced" ? "synced" : "pending";
@@ -1 +1 @@
1
- {"version":3,"file":"containerIntentPersistence.js","sourceRoot":"","sources":["containerIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EACL,4BAA4B,EAC5B,0BAA0B,GAU3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,SAAS,2BAA2B,CAClC,KAAc;IAEd,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACnD,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAc;IAEd,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC;AACrD,CAAC;AA4BD,SAAS,8BAA8B,CACrC,GAAwC;IAExC,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,CAAC;QACxB,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,iBAAiB,EAAE,GAAG,CAAC,iBAAiB;QACxC,UAAU,EAAE,4BAA4B;QACxC,UAAU,EAAE,2BAA2B,CAAC,GAAG,CAAC,UAAU,CAAC;QACvD,iBAAiB,EAAE,GAAG,CAAC,iBAAiB;QACxC,wBAAwB,EAAE,GAAG,CAAC,wBAAwB;QACtD,6BAA6B,EAAE,GAAG,CAAC,6BAA6B;QAChE,SAAS,EAAE,GAAG,CAAC,SAAS;QACxB,eA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AE,KAAK,CAAC,iBAAiB,CAAC,CAAC;gBACvD,CAAC,CAAC,EAAE,CAAC,CACR,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC,CAAC;QACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;YACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;gBAC3D,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/D,CAAC;IACD,8BAA8B;IAC9B,4BAA4B;CACQ,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerContentsPersistence,\n type ContainerCreateIntentErrorInput,\n type ContainerCreateIntentInput,\n type ContainerCreateIntentRecord,\n type ContainerCreateIntentRevisionInput,\n type ContainerCreateIntentSyncStatus,\n type ContainerMoveIntentRecord,\n type ContainerMoveIntentRevisionInput,\n type ContainerMoveIntentSyncStatus,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\n\nfunction parseCreateIntentSyncStatus(\n value: unknown,\n): ContainerCreateIntentSyncStatus {\n return value === \"synced\" ? \"synced\" : \"pending\";\n}\n\nfunction parseMoveIntentSyncStatus(\n value: unknown,\n): ContainerMoveIntentSyncStatus {\n return value === \"blocked\" ? \"blocked\" : \"pending\";\n}\n\ninterface SelectedContainerCreateIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n syncStatus: string;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedContainerMoveIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n syncStatus: string;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction mapContainerCreateIntentRecord(\n row: SelectedContainerCreateIntentRecord,\n): ContainerCreateIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: parseCreateIntentSyncStatus(row.syncStatus),\n remoteContainerId: row.remoteContainerId,\n remoteMetadataDocumentId: row.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: row.remoteMetadataAccessStateHash,\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction mapContainerMoveIntentRecord(\n row: SelectedContainerMoveIntentRecord,\n): ContainerMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n previousParentContainerId: row.previousParentContainerId,\n intentType: CONTAINER_MOVE_INTENT_TYPE,\n syncStatus: parseMoveIntentSyncStatus(row.syncStatus),\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport async function saveContainerCreateIntent(input: {\n tx: ClientSQLiteTransactionScope;\n containerId: string;\n createIntent: ContainerCreateIntentInput;\n updatedAt: string;\n}) {\n const { containerId, createIntent, tx, updatedAt } = input;\n const id = createIntent.id ?? crypto.randomUUID();\n await tx\n .insert(localIntents)\n .values({\n id,\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: containerId,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n createdAt: updatedAt,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: {\n // Timestamps can collide when a create is re-queued in one clock tick,\n // so every enqueue owns a fresh revision token too.\n id,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n updatedAt,\n },\n })\n .run();\n}\n\nexport class ContainerCreateIntentSupersededError extends Error {\n constructor() {\n super(\"Container create intent was superseded before local settlement\");\n }\n}\n\nexport async function deleteContainerMoveIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const deleted = await input.tx\n .delete(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return deleted.length > 0;\n}\n\nasync function recordCreateIntentErrorAttempt(\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n): Promise<void> {\n const {\n containerId,\n expectedIntentId,\n expectedUpdatedAt,\n message,\n stillCurrent,\n } = input;\n if (!message) throw new Error(\"Container create intent error is required\");\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: message,\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, containerId),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.id, expectedIntentId),\n eq(localIntents.updatedAt, expectedUpdatedAt),\n ),\n )\n .run();\n };\n if (stillCurrent) {\n await runtime.guardedTransaction(record, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n}\n\nasync function markMoveIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => {\n return deleteContainerMoveIntentRevision({ ...input, tx });\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result === true;\n}\n\nasync function markCreateIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => settleContainerCreateIntentRevision({ ...input, tx }),\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result !== \"superseded\";\n}\n\ntype ContainerIntentPersistence = Pick<\n ContainerContentsPersistence,\n | \"listPendingCreateIntents\"\n | \"listUnsyncedMoveIntents\"\n | \"recordCreateIntentRevisionError\"\n | \"recordMoveIntentError\"\n | \"markCreateIntentRevisionSynced\"\n | \"markMoveIntentRevisionSynced\"\n>;\n\nexport const containerIntentPersistence = {\n async listPendingCreateIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n syncStatus: localIntents.syncStatus,\n remoteContainerId: localIntents.remoteContainerId,\n remoteMetadataDocumentId: localIntents.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash:\n localIntents.remoteMetadataAccessStateHash,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerCreateIntentRecord(row));\n },\n async listUnsyncedMoveIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // No status filter: markMoveIntentRevisionSynced deletes settled rows,\n // so every surviving row is unsynced. Blocked intents replay too: \"blocked\"\n // names the reason the last attempt could not proceed, not a terminal\n // verdict — the missing container can appear via hydration, after which\n // the move completes — and hydration must still not revert them.\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n previousParentContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerMoveIntentRecord(row));\n },\n recordCreateIntentRevisionError: (execSql, input) =>\n recordCreateIntentErrorAttempt(execSql, input),\n async recordMoveIntentError(execSql, input) {\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: input.blocked ? \"blocked\" : \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n // Blocked rows stay updatable so a retried intent records its\n // fresh outcome and a transient failure unblocks it.\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(record, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n },\n markCreateIntentRevisionSynced,\n markMoveIntentRevisionSynced,\n} satisfies ContainerIntentPersistence;\n"]}
1
+ {"version":3,"file":"containerIntentPersistence.js","sourceRoot":"","sources":["containerIntentPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EACL,0BAA0B,GAU3B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,mCAAmC,EAAE,MAAM,mCAAmC,CAAC;AAExF,SAAS,2BAA2B,CAClC,KAAc;IAEd,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;AACnD,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAc;IAEd,OAAO,KAAK,K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BAAkB,CAAC,aAAa,CAAC,EACnD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,WAAW,CAAC;YAC7C,8DAA8D;YAC9D,qDAAqD;YACrD,OAAO,CAAC,YAAY,CAAC,UAAU,EAAE,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,EACxD,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,0BAA0B,CAAC,EACvD,GAAG,CAAC,KAAK,CAAC,gBAAgB;gBACxB,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,EAAE,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAC;gBAC/C,CAAC,CAAC,EAAE,CAAC,EACP,GAAG,CAAC,KAAK,CAAC,iBAAiB;gBACzB,CAAC,CAAC,CAAC,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,iBAAiB,CAAC,CAAC;gBACvD,CAAC,CAAC,EAAE,CAAC,CACR,CACF;iBACA,GAAG,EAAE,CAAC;QACX,CAAC,CAAC;QACF,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;YACvB,MAAM,OAAO,CAAC,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,YAAY,EAAE;gBAC3D,QAAQ,EAAE,WAAW;aACtB,CAAC,CAAC;YACH,OAAO;QACT,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;IAC/D,CAAC;IACD,8BAA8B;IAC9B,4BAA4B;CACQ,CAAC","sourcesContent":["import { and, asc, eq, inArray } from \"drizzle-orm\";\nimport {\n CONTAINER_CREATE_INTENT_TYPE,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n LOCAL_INTENT_SUBJECT,\n localIntents,\n} from \"../../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport {\n CONTAINER_MOVE_INTENT_TYPE,\n type ContainerContentsPersistence,\n type ContainerCreateIntentErrorInput,\n type ContainerCreateIntentInput,\n type ContainerCreateIntentRecord,\n type ContainerCreateIntentRevisionInput,\n type ContainerCreateIntentSyncStatus,\n type ContainerMoveIntentRecord,\n type ContainerMoveIntentRevisionInput,\n type ContainerMoveIntentSyncStatus,\n} from \"./containerContentsPersistenceTypes\";\nimport { settleContainerCreateIntentRevision } from \"./containerCreateIntentSettlement\";\n\nfunction parseCreateIntentSyncStatus(\n value: unknown,\n): ContainerCreateIntentSyncStatus {\n return value === \"synced\" ? \"synced\" : \"pending\";\n}\n\nfunction parseMoveIntentSyncStatus(\n value: unknown,\n): ContainerMoveIntentSyncStatus {\n return value === \"blocked\" ? \"blocked\" : \"pending\";\n}\n\ninterface SelectedContainerCreateIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n syncStatus: string;\n remoteContainerId: string | null;\n remoteMetadataDocumentId: string | null;\n remoteMetadataAccessStateHash: string | null;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface SelectedContainerMoveIntentRecord {\n id: string | null;\n containerId: string;\n parentContainerId: string;\n previousParentContainerId: string | null;\n syncStatus: string;\n lastError: string | null;\n lastAttemptedAt: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction mapContainerCreateIntentRecord(\n row: SelectedContainerCreateIntentRecord,\n): ContainerCreateIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: parseCreateIntentSyncStatus(row.syncStatus),\n remoteContainerId: row.remoteContainerId,\n remoteMetadataDocumentId: row.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash: row.remoteMetadataAccessStateHash,\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nfunction mapContainerMoveIntentRecord(\n row: SelectedContainerMoveIntentRecord,\n): ContainerMoveIntentRecord {\n return {\n id: String(row.id ?? \"\"),\n containerId: row.containerId,\n parentContainerId: row.parentContainerId,\n previousParentContainerId: row.previousParentContainerId,\n intentType: CONTAINER_MOVE_INTENT_TYPE,\n syncStatus: parseMoveIntentSyncStatus(row.syncStatus),\n lastError: row.lastError,\n lastAttemptedAt: row.lastAttemptedAt,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport async function saveContainerCreateIntent(input: {\n tx: ClientSQLiteTransactionScope;\n containerId: string;\n createIntent: ContainerCreateIntentInput;\n updatedAt: string;\n}) {\n const { containerId, createIntent, tx, updatedAt } = input;\n const id = createIntent.id ?? crypto.randomUUID();\n await tx\n .insert(localIntents)\n .values({\n id,\n lane: LOCAL_INTENT_LANES.containerCreate,\n subjectId: containerId,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n createdAt: updatedAt,\n updatedAt,\n })\n .onConflictDoUpdate({\n target: LOCAL_INTENT_SUBJECT,\n set: {\n // Timestamps can collide when a create is re-queued in one clock tick,\n // so every enqueue owns a fresh revision token too.\n id,\n targetContainerId: createIntent.parentContainerId,\n intentType: CONTAINER_CREATE_INTENT_TYPE,\n syncStatus: \"pending\",\n remoteContainerId: null,\n remoteMetadataDocumentId: null,\n remoteMetadataAccessStateHash: null,\n lastError: null,\n lastAttemptedAt: null,\n updatedAt,\n },\n })\n .run();\n}\n\nexport class ContainerCreateIntentSupersededError extends Error {\n constructor() {\n super(\"Container create intent was superseded before local settlement\");\n }\n}\n\nexport async function deleteContainerMoveIntentRevision(input: {\n containerId: string;\n expectedIntentId: string;\n expectedUpdatedAt: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const deleted = await input.tx\n .delete(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n eq(localIntents.id, input.expectedIntentId),\n eq(localIntents.updatedAt, input.expectedUpdatedAt),\n ),\n )\n .returning({ containerId: localIntents.subjectId });\n return deleted.length > 0;\n}\n\nasync function recordCreateIntentErrorAttempt(\n execSql: ExecSql,\n input: ContainerCreateIntentErrorInput,\n): Promise<void> {\n const {\n containerId,\n expectedIntentId,\n expectedUpdatedAt,\n message,\n stillCurrent,\n } = input;\n if (!message) throw new Error(\"Container create intent error is required\");\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: message,\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.subjectId, containerId),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n eq(localIntents.id, expectedIntentId),\n eq(localIntents.updatedAt, expectedUpdatedAt),\n ),\n )\n .run();\n };\n if (stillCurrent) {\n await runtime.guardedTransaction(record, stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n}\n\nasync function markMoveIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerMoveIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => {\n return deleteContainerMoveIntentRevision({ ...input, tx });\n },\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result === true;\n}\n\nasync function markCreateIntentRevisionSynced(\n execSql: ExecSql,\n input: ContainerCreateIntentRevisionInput,\n): Promise<boolean> {\n const outcome = await getClientSQLitePersistenceRuntime(\n execSql,\n ).guardedTransaction(\n async (tx) => settleContainerCreateIntentRevision({ ...input, tx }),\n input.stillCurrent,\n { behavior: \"immediate\" },\n );\n return outcome.committed && outcome.result !== \"superseded\";\n}\n\ntype ContainerIntentPersistence = Pick<\n ContainerContentsPersistence,\n | \"listPendingCreateIntents\"\n | \"listUnsyncedMoveIntents\"\n | \"recordCreateIntentRevisionError\"\n | \"recordMoveIntentError\"\n | \"markCreateIntentRevisionSynced\"\n | \"markMoveIntentRevisionSynced\"\n>;\n\nexport const containerIntentPersistence = {\n async listPendingCreateIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n syncStatus: localIntents.syncStatus,\n remoteContainerId: localIntents.remoteContainerId,\n remoteMetadataDocumentId: localIntents.remoteMetadataDocumentId,\n remoteMetadataAccessStateHash:\n localIntents.remoteMetadataAccessStateHash,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerCreate),\n eq(localIntents.syncStatus, \"pending\"),\n eq(localIntents.intentType, CONTAINER_CREATE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerCreateIntentRecord(row));\n },\n async listUnsyncedMoveIntents(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // No status filter: markMoveIntentRevisionSynced deletes settled rows,\n // so every surviving row is unsynced. Blocked intents replay too: \"blocked\"\n // names the reason the last attempt could not proceed, not a terminal\n // verdict — the missing container can appear via hydration, after which\n // the move completes — and hydration must still not revert them.\n const rows = await db\n .select({\n id: localIntents.id,\n containerId: localIntents.subjectId,\n parentContainerId: localIntents.targetContainerId,\n previousParentContainerId: localIntents.sourceContainerId,\n syncStatus: localIntents.syncStatus,\n lastError: localIntents.lastError,\n lastAttemptedAt: localIntents.lastAttemptedAt,\n createdAt: localIntents.createdAt,\n updatedAt: localIntents.updatedAt,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ),\n )\n .orderBy(asc(localIntents.createdAt));\n\n return rows.map((row) => mapContainerMoveIntentRecord(row));\n },\n recordCreateIntentRevisionError: (execSql, input) =>\n recordCreateIntentErrorAttempt(execSql, input),\n async recordMoveIntentError(execSql, input) {\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const record = async (tx: ClientSQLiteTransactionScope) => {\n const updatedAt = new Date().toISOString();\n await tx\n .update(localIntents)\n .set({\n lastAttemptedAt: updatedAt,\n lastError: input.message,\n syncStatus: input.blocked ? \"blocked\" : \"pending\",\n updatedAt,\n })\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.containerMove),\n eq(localIntents.subjectId, input.containerId),\n // Blocked rows stay updatable so a retried intent records its\n // fresh outcome and a transient failure unblocks it.\n inArray(localIntents.syncStatus, [\"pending\", \"blocked\"]),\n eq(localIntents.intentType, CONTAINER_MOVE_INTENT_TYPE),\n ...(input.expectedIntentId\n ? [eq(localIntents.id, input.expectedIntentId)]\n : []),\n ...(input.expectedUpdatedAt\n ? [eq(localIntents.updatedAt, input.expectedUpdatedAt)]\n : []),\n ),\n )\n .run();\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(record, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(record, { behavior: \"immediate\" });\n },\n markCreateIntentRevisionSynced,\n markMoveIntentRevisionSynced,\n} satisfies ContainerIntentPersistence;\n"]}
@@ -1,19 +1,20 @@
1
1
  import { type ClientSQLiteTransactionScope } from "../../sqlite/sqlitePersistenceRuntime.js";
2
2
  import { type ExecSql } from "../../sqlite/sqlSchema.js";
3
- import { type DocumentPlacementInput, type DocumentPlacementWriteOptions } from "./documentPlacement.js";
3
+ import { type DocumentPlacementInput, type DocumentPlacementWriteOptions } from "../documents/documentPlacement.js";
4
4
  /** Link rows and their tombstone holds leave together on a remote reset. */
5
5
  export declare function deleteDocumentPlacementRowsByContainerIds(tx: ClientSQLiteTransactionScope, containerIds: ReadonlyArray<string>): Promise<void>;
6
6
  export declare function deleteDocumentPlacementRowsByDocumentIds(tx: ClientSQLiteTransactionScope, documentIds: ReadonlyArray<string>): Promise<void>;
7
- /** Removes the listed (document, container) placements, 50 pairs per statement. */
8
- export declare function deleteDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, placements: ReadonlyArray<{
9
- readonly containerId: string;
10
- readonly documentId: string;
11
- }>): Promise<void>;
12
7
  /**
13
- * Removes each document's placements outside the containers its head links,
14
- * batching documents so one statement stays inside SQLite's bind budget.
8
+ * Remove the tombstoned placements and, with each head now verified, every
9
+ * remaining local link row the head does not link: those are listing-seeded
10
+ * rows, and leaving one would keep showing the document in a container the
11
+ * signed link set never named. Rows the head links are kept as they are.
12
+ * Runs inside the Document Store tombstone transaction.
15
13
  */
16
- export declare function deleteUnlinkedDocumentPlacementRowsInTransaction(tx: ClientSQLiteTransactionScope, linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>): Promise<void>;
14
+ export declare function deleteContainerDocumentTombstonePlacementRows(tx: ClientSQLiteTransactionScope, tombstones: ReadonlyArray<{
15
+ readonly containerId: string;
16
+ readonly documentId: string;
17
+ }>, verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>): Promise<void>;
17
18
  /** Removes a deleted document's queued placement intents and link targets. */
18
19
  export declare function deleteDocumentPlacementIntentsInTransaction(tx: ClientSQLiteTransactionScope, documentId: string): Promise<void>;
19
20
  /** The caller owns the open document commit and must propagate every failure. */
@@ -7,7 +7,7 @@ import { REMOTE_RESET_SQL_BATCH_SIZE, remoteResetBatches, SQLITE_BOUND_VARIABLE_
7
7
  import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
8
8
  import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
9
9
  import { deleteContainerDocumentTombstoneHoldRowsForLinks, deleteContainerDocumentTombstoneHoldsForContainers, deleteContainerDocumentTombstoneHoldsForDocuments, placementPairsMatch, } from "../documents/containerDocumentTombstoneHoldsPersistence.js";
10
- import { filterWritableDocumentPlacements, } from "./documentPlacement.js";
10
+ import { filterWritableDocumentPlacements, } from "../documents/documentPlacement.js";
11
11
  const LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(documentContainerProjection);
12
12
  /** Link rows and their tombstone holds leave together on a remote reset. */
13
13
  export async function deleteDocumentPlacementRowsByContainerIds(tx, containerIds) {
@@ -24,8 +24,19 @@ export async function deleteDocumentPlacementRowsByDocumentIds(tx, documentIds)
24
24
  .run();
25
25
  await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);
26
26
  }
27
+ /**
28
+ * Remove the tombstoned placements and, with each head now verified, every
29
+ * remaining local link row the head does not link: those are listing-seeded
30
+ * rows, and leaving one would keep showing the document in a container the
31
+ * signed link set never named. Rows the head links are kept as they are.
32
+ * Runs inside the Document Store tombstone transaction.
33
+ */
34
+ export async function deleteContainerDocumentTombstonePlacementRows(tx, tombstones, verifiedLinkedContainerIdsByDocumentId) {
35
+ await deleteDocumentPlacementRowsInTransaction(tx, tombstones);
36
+ await deleteUnlinkedDocumentPlacementRowsInTransaction(tx, verifiedLinkedContainerIdsByDocumentId);
37
+ }
27
38
  /** Removes the listed (document, container) placements, 50 pairs per statement. */
28
- export async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
39
+ async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
29
40
  for (const batch of remoteResetBatches(placements)) {
30
41
  await tx
31
42
  .delete(documentContainerProjection)
@@ -37,7 +48,7 @@ export async function deleteDocumentPlacementRowsInTransaction(tx, placements) {
37
48
  * Removes each document's placements outside the containers its head links,
38
49
  * batching documents so one statement stays inside SQLite's bind budget.
39
50
  */
40
- export async function deleteUnlinkedDocumentPlacementRowsInTransaction(tx, linkedContainerIdsByDocumentId) {
51
+ async function deleteUnlinkedDocumentPlacementRowsInTransaction(tx, linkedContainerIdsByDocumentId) {
41
52
  let batch = [];
42
53
  let binds = 0;
43
54
  const flush = async () => {
@@ -1 +1 @@
1
- {"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC9E,OAAO,EACL,6BAA6B,EAC7B,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mDAAmD,CAAC;AAC9F,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,0CAA0C,CAAC;AAC1E,OAAO,EACL,2BAA2B,EAC3B,kBAAkB,EAClB,4BAA4B,EAC5B,qBAAqB,GACtB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EACL,gDAAgD,EAChD,kDAAkD,EAClD,iDAAiD,EACjD,mBAAmB,GACpB,MAAM,yDAAyD,CAAC;AAEjE,OAAO,EAGL,gCAAgC,GACjC,MAAM,qBAAqB,CAAC;AAE7B,MAAM,sBAAsB,GAAG,qBAAqB,CAClD,2BAA2B,CAC5B,CAAC;AAEF,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,YAAmC;IAEnC,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T,CAAC;QACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import { and, asc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n documentPlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"./documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nexport async function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nexport async function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n now: () => Date,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = now().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n () => new Date(),\n options,\n );\n}\n\n/** The document container projection, bound to one executor and clock. */\nexport class DocumentContainerProjectionRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n }\n\n async listLinkedContainerIds(\n documentId: string,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n }\n\n async listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n await this.ensureSchema();\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, uniqueDocumentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n }\n\n async listDocumentIdsByContainerIds(\n containerIds: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n }\n\n async replaceDocumentLinks(\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await this.replaceDocumentLinksBatch(\n [{ documentId, containerIds }],\n options,\n );\n }\n\n async replaceDocumentLinksBatch(\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await ensureDocumentLinksSchema(this.execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, this.now, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n }\n}\n"]}
1
+ {"version":3,"file":"documentContainerProjectionPersistence.js","sourceRoot":"","sources":["documentContainerProjectionPersistence.ts"],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PlacementIntentTables,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport { documentIntentLinkTargets } from \"../../sqlite/schema/documentPlacementIntentSchema\";\nimport {\n documentContainerProjection,\n documentContainerProjectionTables,\n} from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documentTables } from \"../../sqlite/schema/documentRecordSchema\";\nimport {\n REMOTE_RESET_SQL_BATCH_SIZE,\n remoteResetBatches,\n SQLITE_BOUND_VARIABLE_BUDGET,\n sqliteInsertBatchSize,\n} from \"../../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport {\n deleteContainerDocumentTombstoneHoldRowsForLinks,\n deleteContainerDocumentTombstoneHoldsForContainers,\n deleteContainerDocumentTombstoneHoldsForDocuments,\n placementPairsMatch,\n} from \"../documents/containerDocumentTombstoneHoldsPersistence\";\n\nimport {\n type DocumentPlacementInput,\n type DocumentPlacementWriteOptions,\n filterWritableDocumentPlacements,\n} from \"../documents/documentPlacement\";\n\nconst LINK_INSERT_BATCH_SIZE = sqliteInsertBatchSize(\n documentContainerProjection,\n);\n\n/** Link rows and their tombstone holds leave together on a remote reset. */\nexport async function deleteDocumentPlacementRowsByContainerIds(\n tx: ClientSQLiteTransactionScope,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, containerIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForContainers(tx, containerIds);\n}\n\nexport async function deleteDocumentPlacementRowsByDocumentIds(\n tx: ClientSQLiteTransactionScope,\n documentIds: ReadonlyArray<string>,\n): Promise<void> {\n await tx\n .delete(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, documentIds))\n .run();\n await deleteContainerDocumentTombstoneHoldsForDocuments(tx, documentIds);\n}\n\n/**\n * Remove the tombstoned placements and, with each head now verified, every\n * remaining local link row the head does not link: those are listing-seeded\n * rows, and leaving one would keep showing the document in a container the\n * signed link set never named. Rows the head links are kept as they are.\n * Runs inside the Document Store tombstone transaction.\n */\nexport async function deleteContainerDocumentTombstonePlacementRows(\n tx: ClientSQLiteTransactionScope,\n tombstones: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n verifiedLinkedContainerIdsByDocumentId: ReadonlyMap<\n string,\n ReadonlySet<string>\n >,\n): Promise<void> {\n await deleteDocumentPlacementRowsInTransaction(tx, tombstones);\n await deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx,\n verifiedLinkedContainerIdsByDocumentId,\n );\n}\n\n/** Removes the listed (document, container) placements, 50 pairs per statement. */\nasync function deleteDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n placements: ReadonlyArray<{\n readonly containerId: string;\n readonly documentId: string;\n }>,\n): Promise<void> {\n for (const batch of remoteResetBatches(placements)) {\n await tx\n .delete(documentContainerProjection)\n .where(\n placementPairsMatch(\n batch,\n documentContainerProjection.documentId,\n documentContainerProjection.containerId,\n ),\n )\n .run();\n }\n}\n\n/**\n * Removes each document's placements outside the containers its head links,\n * batching documents so one statement stays inside SQLite's bind budget.\n */\nasync function deleteUnlinkedDocumentPlacementRowsInTransaction(\n tx: ClientSQLiteTransactionScope,\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlySet<string>>,\n): Promise<void> {\n let batch: SQL[] = [];\n let binds = 0;\n const flush = async () => {\n if (batch.length === 0) return;\n await tx\n .delete(documentContainerProjection)\n .where(or(...batch))\n .run();\n batch = [];\n binds = 0;\n };\n for (const [documentId, linked] of linkedContainerIdsByDocumentId) {\n // The document id plus one bind per linked container.\n const documentBinds = 1 + linked.size;\n if (\n batch.length >= REMOTE_RESET_SQL_BATCH_SIZE ||\n binds + documentBinds > SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await flush();\n }\n batch.push(unlinkedDocumentPlacementRows(documentId, linked));\n binds += documentBinds;\n }\n await flush();\n}\n\n/** A document's placements outside the containers its head links. */\nfunction unlinkedDocumentPlacementRows(\n documentId: string,\n linkedContainerIds: ReadonlySet<string>,\n): SQL {\n const ofDocument = eq(documentContainerProjection.documentId, documentId);\n return linkedContainerIds.size === 0\n ? ofDocument\n : (and(\n ofDocument,\n notInArray(documentContainerProjection.containerId, [\n ...linkedContainerIds,\n ]),\n ) ?? ofDocument);\n}\n\n/** Removes a deleted document's queued placement intents and link targets. */\nexport async function deleteDocumentPlacementIntentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n): Promise<void> {\n const placementIntent = and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n );\n await tx\n .delete(documentIntentLinkTargets)\n .where(\n inArray(\n documentIntentLinkTargets.intentId,\n tx\n .select({ id: localIntents.id })\n .from(localIntents)\n .where(placementIntent),\n ),\n )\n .run();\n await tx.delete(localIntents).where(placementIntent).run();\n}\n\nasync function ensureDocumentLinksSchema(execSql: ExecSql): Promise<void> {\n await ensureSqlTables(execSql, [\n ...documentContainerProjectionTables,\n ...documentPlacementIntentTables,\n ...documentTables,\n ]);\n}\n\nasync function replaceDocumentLinkRows(\n tx: ClientSQLiteTransactionScope,\n latest: ReadonlyMap<string, DocumentPlacementInput>,\n now: () => Date,\n options?: DocumentPlacementWriteOptions,\n): Promise<void> {\n const writable = await filterWritableDocumentPlacements(\n tx,\n [...latest.values()],\n options,\n );\n if (writable.length === 0) return;\n // A placement the writer re-asserts is no longer tombstoned: a\n // listing that links it again, or a local move that owns it, releases\n // the hold so the document is not hidden until the next retry.\n if (options?.moveIntentId) {\n await deleteContainerDocumentTombstoneHoldsForDocuments(\n tx,\n writable.map((input) => input.documentId),\n );\n } else {\n await deleteContainerDocumentTombstoneHoldRowsForLinks(tx, writable);\n }\n // Each document binds once; finish every deletion before inserting.\n for (\n let index = 0;\n index < writable.length;\n index += SQLITE_BOUND_VARIABLE_BUDGET\n ) {\n await tx\n .delete(documentContainerProjection)\n .where(\n inArray(\n documentContainerProjection.documentId,\n writable\n .slice(index, index + SQLITE_BOUND_VARIABLE_BUDGET)\n .map((input) => input.documentId),\n ),\n )\n .run();\n }\n const updatedAt = now().toISOString();\n const rows = writable.flatMap((input) =>\n Array.from(new Set(input.containerIds))\n .sort()\n .map((containerId) => ({\n documentId: input.documentId,\n containerId,\n updatedAt,\n })),\n );\n // A lane page of multi-link documents can carry more link rows than\n // one statement may bind.\n for (let index = 0; index < rows.length; index += LINK_INSERT_BATCH_SIZE) {\n await tx\n .insert(documentContainerProjection)\n .values(rows.slice(index, index + LINK_INSERT_BATCH_SIZE))\n .run();\n }\n}\n\n/** The caller owns the open document commit and must propagate every failure. */\nexport async function replaceDocumentLinksInTransaction(\n transactionExecSql: ExecSql,\n documentId: string,\n containerIds: readonly string[],\n options?: Omit<DocumentPlacementWriteOptions, \"stillCurrent\">,\n): Promise<void> {\n await ensureDocumentLinksSchema(transactionExecSql);\n await replaceDocumentLinkRows(\n getClientSQLitePersistenceRuntime(transactionExecSql).db,\n new Map([[documentId, { documentId, containerIds }]]),\n () => new Date(),\n options,\n );\n}\n\n/** The document container projection, bound to one executor and clock. */\nexport class DocumentContainerProjectionRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n async ensureSchema(): Promise<void> {\n await ensureSqlTables(this.execSql, documentContainerProjectionTables);\n }\n\n async listLinkedContainerIds(\n documentId: string,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({ containerId: documentContainerProjection.containerId })\n .from(documentContainerProjection)\n .where(eq(documentContainerProjection.documentId, documentId))\n .orderBy(asc(documentContainerProjection.containerId));\n\n return rows.map((row) => row.containerId);\n }\n\n async listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n await this.ensureSchema();\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n documentId: documentContainerProjection.documentId,\n containerId: documentContainerProjection.containerId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, uniqueDocumentIds))\n .orderBy(\n asc(documentContainerProjection.documentId),\n asc(documentContainerProjection.containerId),\n );\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const row of rows) {\n const linkedContainerIds =\n linkedContainerIdsByDocumentId.get(row.documentId) ?? [];\n linkedContainerIds.push(row.containerId);\n linkedContainerIdsByDocumentId.set(row.documentId, linkedContainerIds);\n }\n\n return linkedContainerIdsByDocumentId;\n }\n\n async listDocumentIdsByContainerIds(\n containerIds: ReadonlyArray<string>,\n ): Promise<ReadonlyArray<string>> {\n await this.ensureSchema();\n const uniqueContainerIds = Array.from(new Set(containerIds));\n if (uniqueContainerIds.length === 0) {\n return [];\n }\n\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .selectDistinct({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(\n inArray(documentContainerProjection.containerId, uniqueContainerIds),\n )\n .orderBy(asc(documentContainerProjection.documentId));\n\n return rows.map((row) => row.documentId);\n }\n\n async replaceDocumentLinks(\n documentId: string,\n containerIds: ReadonlyArray<string>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await this.replaceDocumentLinksBatch(\n [{ documentId, containerIds }],\n options,\n );\n }\n\n async replaceDocumentLinksBatch(\n inputs: ReadonlyArray<DocumentPlacementInput>,\n options?: DocumentPlacementWriteOptions,\n ): Promise<void> {\n await ensureDocumentLinksSchema(this.execSql);\n const latest = new Map(inputs.map((input) => [input.documentId, input]));\n if (latest.size === 0) return;\n const runtime = getClientSQLitePersistenceRuntime(this.execSql);\n const replace = (tx: ClientSQLiteTransactionScope) =>\n replaceDocumentLinkRows(tx, latest, this.now, options);\n if (options?.stillCurrent) {\n await runtime.guardedTransaction(replace, options.stillCurrent);\n return;\n }\n await runtime.transaction(replace);\n }\n}\n"]}
@@ -1,11 +1,12 @@
1
1
  import { type DiscoveredDocumentInput, type DocumentSummary } from "../../documents/documentSummary.js";
2
2
  import { type ExecSql } from "../../sqlite/sqlSchema.js";
3
+ import { type ContainerDocumentTombstonePlacementRemoval } from "./internal/containerDocumentTombstones.js";
3
4
  import type { ContainerDocumentTombstoneInput, DocumentsPersistence } from "./types.js";
4
5
  export { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
5
6
  export type { PendingUpdateRecord, QueuedPendingUpdateRecord } from "./records/index.js";
6
7
  export type { AttachmentRemovalRows, AttachmentStagingRows, ContainerDocumentTombstoneInput, DiscardDocumentToShellResult, DocumentsPersistence, LocalAttachmentRecord, PendingAttachmentRecord, PendingAttachmentUploadIdentity, PendingUpdateInsert, RelinkPersistedDocumentInput, StoredDocumentRecord, } from "./types.js";
7
8
  export declare function upsertDiscoveredDocuments(execSql: ExecSql, inputs: ReadonlyArray<DiscoveredDocumentInput>): Promise<DocumentSummary[]>;
8
- export declare function applyContainerDocumentTombstones(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>): Promise<DocumentSummary[]>;
9
+ export declare function applyContainerDocumentTombstones(execSql: ExecSql, tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>, removePlacementRows: ContainerDocumentTombstonePlacementRemoval): Promise<DocumentSummary[]>;
9
10
  export declare function listDocumentsByContainerIdsOrDocumentIds(execSql: ExecSql, input: {
10
11
  containerIds: ReadonlyArray<string>;
11
12
  documentIds: ReadonlyArray<string>;
@@ -4,7 +4,7 @@ import { documentProjection } from "../../sqlite/schema/documentProjectionSchema
4
4
  import { documents } from "../../sqlite/schema/documentRecordSchema.js";
5
5
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
6
6
  import { runSerializedSqlMutation } from "../../sqlite/sqlSchema.js";
7
- import { applyContainerDocumentTombstonesWithExec } from "./internal/containerDocumentTombstones.js";
7
+ import { applyContainerDocumentTombstonesWithExec, } from "./internal/containerDocumentTombstones.js";
8
8
  import { createStoredDocumentWithHistoryCheckpoint } from "./internal/createDocumentWithHistoryCheckpoint.js";
9
9
  import { discardStoredDocumentToShell } from "./internal/discardDocument.js";
10
10
  import { upsertDiscoveredDocumentsInTransaction } from "./internal/discoveredDocumentUpsert.js";
@@ -64,10 +64,10 @@ export async function upsertDiscoveredDocuments(execSql, inputs) {
64
64
  }, { behavior: "immediate" });
65
65
  });
66
66
  }
67
- export async function applyContainerDocumentTombstones(execSql, tombstones) {
67
+ export async function applyContainerDocumentTombstones(execSql, tombstones, removePlacementRows) {
68
68
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
69
69
  await sqlDocumentsPersistence.ensureSchema(lockedExecSql);
70
- return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones);
70
+ return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones, removePlacementRows);
71
71
  });
72
72
  }
73
73
  export async function listDocumentsByContainerIdsOrDocumentIds(execSql, input) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC/E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,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AAK;QAC3C,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,yBAAyB,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC1D,CAAC;QAED,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,KAAK,CAAC,uBAAuB,CAAC,OAAO,EAAE,KAAK;QAC1C,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,uBAAuB,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;YAC1D,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,GAAG,EAAE,CAAC,+BAA+B,CAAC,aAAa,EAAE,KAAK,CAAC,EAC3D,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { applyContainerDocumentTombstonesWithExec } from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(lockedExecSql, tombstones);\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}
1
+ {"version":3,"file":"documentsPersistence.js","sourceRoot":"","sources":["documentsPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,EAAE,EAAY,MAAM,aAAa,CAAC;AAC/E,OAAO,EAGL,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8CAA8C,CAAC;AAClF,OAAO,EAAE,SAAS,EAAE,MAAM,0CAA0C,CAAC;AACrE,OAAO,EAAE,iCAAiC,EAAE,MAAM,uCAAuC,CAAC;AAC1F,OAAO,EAAgB,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EACL,wCAAwC,GAEzC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,yCAAyC,EAAE,MAAM,gDAAgD,CAAC;AAC3G,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO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AED,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,KAAK,CAAC,uBAAuB,CAAC,OAAO,EAAE,KAAK;QAC1C,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;YAC/D,MAAM,uBAAuB,CAAC,YAAY,CAAC,aAAa,CAAC,CAAC;YAC1D,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,GAAG,EAAE,CAAC,+BAA+B,CAAC,aAAa,EAAE,KAAK,CAAC,EAC3D,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, or, type SQL } from \"drizzle-orm\";\nimport {\n type DiscoveredDocumentInput,\n type DocumentSummary,\n HIDDEN_DOCUMENT_SUMMARY_KINDS,\n} from \"../../documents/documentSummary\";\nimport { documentProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport {\n applyContainerDocumentTombstonesWithExec,\n type ContainerDocumentTombstonePlacementRemoval,\n} from \"./internal/containerDocumentTombstones\";\nimport { createStoredDocumentWithHistoryCheckpoint } from \"./internal/createDocumentWithHistoryCheckpoint\";\nimport { discardStoredDocumentToShell } from \"./internal/discardDocument\";\nimport { upsertDiscoveredDocumentsInTransaction } from \"./internal/discoveredDocumentUpsert\";\nimport {\n deleteStoredDocument,\n deleteStoredDocumentIfMatches,\n deleteStoredDocumentSideRowsIfAbsent,\n} from \"./internal/documentDeletionPersistence\";\nimport { loadStoredDocumentWithHistoryRestoreState } from \"./internal/documentHistoryStatePersistence\";\nimport {\n commitStoredDocumentMutation,\n settleStoredDocumentPendingUpdates,\n} from \"./internal/documentMutationPersistence\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionUpdatedAt,\n mapDocumentSummary,\n toDocumentSummary,\n} from \"./internal/documentProjectionRows\";\nimport { invalidateStoredDocumentPullContinuation } from \"./internal/documentPullContinuationPersistence\";\nimport {\n getDocumentScope,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n} from \"./internal/documentRows\";\nimport {\n resolvePersistedAccessStateHash,\n resolvePersistedDocumentRuntimeState,\n} from \"./internal/documentRuntimeState\";\nimport { loadStoredDocumentStoreState } from \"./internal/documentStoreStatePersistence\";\nimport { listDocumentSummaries } from \"./internal/documentSummaryQueries\";\nimport { ensureDocumentsSchema } from \"./internal/ensureDocumentsSchema\";\nimport { saveHydratedAttachment } from \"./internal/hydratedAttachmentPersistence\";\nimport {\n acknowledgeDocumentOrphanBlobReclaim,\n deleteOrphanedDocumentSideRows,\n isDocumentBlobStorageKeyReferenced,\n listDocumentOrphanBlobReclaims,\n} from \"./internal/orphanSideRows\";\nimport { mapPendingCreateLocalIds } from \"./internal/pendingCreateAdoption\";\nimport { documentRowQueryPersistence } from \"./internal/rowQueryPersistence\";\nimport { documentSyncQueuePersistence } from \"./internal/syncQueuePersistence\";\nimport { settleQueuedDocumentUpdatesInTransaction } from \"./records/documentPendingUpdatePersistence\";\nimport type {\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nexport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nexport type { PendingUpdateRecord, QueuedPendingUpdateRecord } from \"./records\";\nexport type {\n AttachmentRemovalRows,\n AttachmentStagingRows,\n ContainerDocumentTombstoneInput,\n DiscardDocumentToShellResult,\n DocumentsPersistence,\n LocalAttachmentRecord,\n PendingAttachmentRecord,\n PendingAttachmentUploadIdentity,\n PendingUpdateInsert,\n RelinkPersistedDocumentInput,\n StoredDocumentRecord,\n} from \"./types\";\n\nasync function relinkPersistedDocumentWithExec(\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n): Promise<DocumentSummary | null> {\n const existingDocument = await sqlDocumentsPersistence.loadDocument(\n execSql,\n input.localId,\n );\n if (!existingDocument) {\n return null;\n }\n\n const nextAccessEpoch = Math.max(\n existingDocument.accessEpoch,\n input.accessEpoch,\n );\n const nextDocument: StoredDocumentRecord = {\n ...existingDocument,\n accessEpoch: nextAccessEpoch,\n accessStateHash: resolvePersistedAccessStateHash(existingDocument, {\n accessEpoch: nextAccessEpoch,\n accessStateHash: input.accessStateHash,\n documentId: input.documentId,\n }),\n containerId: input.containerId,\n documentId: input.documentId,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: nextAccessEpoch,\n documentId: input.documentId,\n }),\n };\n\n await sqlDocumentsPersistence.saveDocument(execSql, nextDocument);\n\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const updatedAtRows = await db\n .select({ updatedAt: documentProjection.updatedAt })\n .from(documentProjection)\n .where(eq(documentProjection.localId, input.localId))\n .limit(1);\n\n return toDocumentSummary(\n nextDocument,\n getProjectionUpdatedAt(updatedAtRows[0]),\n );\n}\n\nexport async function upsertDiscoveredDocuments(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const pendingCreates = await mapPendingCreateLocalIds(lockedExecSql);\n return upsertDiscoveredDocumentsInTransaction(\n lockedExecSql,\n inputs,\n pendingCreates,\n tx,\n );\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function applyContainerDocumentTombstones(\n execSql: ExecSql,\n tombstones: ReadonlyArray<ContainerDocumentTombstoneInput>,\n removePlacementRows: ContainerDocumentTombstonePlacementRemoval,\n): Promise<DocumentSummary[]> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return applyContainerDocumentTombstonesWithExec(\n lockedExecSql,\n tombstones,\n removePlacementRows,\n );\n });\n}\n\nexport async function listDocumentsByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n): Promise<DocumentSummary[]> {\n const uniqueContainerIds = Array.from(new Set(input.containerIds));\n const uniqueDocumentIds = Array.from(new Set(input.documentIds));\n if (uniqueContainerIds.length === 0 && uniqueDocumentIds.length === 0) {\n return [];\n }\n\n const filters: SQL[] = [];\n if (uniqueContainerIds.length > 0) {\n filters.push(inArray(documentProjection.containerId, uniqueContainerIds));\n }\n\n if (uniqueDocumentIds.length > 0) {\n filters.push(inArray(documentProjection.documentId, uniqueDocumentIds));\n }\n\n const whereCondition = filters.length === 1 ? filters[0] : or(...filters);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n and(\n whereCondition,\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n ),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n}\n\nexport const sqlDocumentsPersistence: DocumentsPersistence = {\n orphanBlobs: {\n acknowledge: acknowledgeDocumentOrphanBlobReclaim,\n isReferenced: isDocumentBlobStorageKeyReferenced,\n list: listDocumentOrphanBlobReclaims,\n sweep: deleteOrphanedDocumentSideRows,\n },\n ...documentRowQueryPersistence,\n ...documentSyncQueuePersistence,\n supportsAtomicRecoveryHistoryPruning: true,\n saveHydratedAttachment,\n createDocumentWithHistoryCheckpoint:\n createStoredDocumentWithHistoryCheckpoint,\n commitDocumentMutation: (execSql, input, saveClientProjection) =>\n commitStoredDocumentMutation(\n execSql,\n input,\n saveClientProjection,\n sqlDocumentsPersistence.loadDocument,\n ),\n settleAcceptedPendingUpdates: (execSql, input) =>\n settleStoredDocumentPendingUpdates(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n ),\n ensureSchema: ensureDocumentsSchema,\n listDocumentSummaries,\n listDocumentsByContainerIdsOrDocumentIds,\n invalidatePullContinuation: (execSql, input) =>\n invalidateStoredDocumentPullContinuation(\n execSql,\n input,\n sqlDocumentsPersistence.loadDocument,\n sqlDocumentsPersistence.loadHistoryRestoreState,\n ),\n loadDocumentWithHistoryRestoreState: (execSql, localId) =>\n loadStoredDocumentWithHistoryRestoreState(\n execSql,\n localId,\n sqlDocumentsPersistence,\n ),\n loadDocumentStoreState: (execSql, localId) =>\n loadStoredDocumentStoreState(execSql, localId, sqlDocumentsPersistence),\n async saveDocument(execSql, document, options) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n async saveDocumentAndDeletePendingUpdates(\n execSql,\n document,\n pendingUpdateIds,\n options,\n ) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const updatedAt = await resolveDocumentSaveTimestamp({\n document,\n options,\n tx,\n });\n const saved = await saveDocumentRows({\n document,\n tx,\n updatedAt,\n });\n if (!saved) return updatedAt;\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n getDocumentScope(document.id),\n pendingUpdateIds,\n );\n return updatedAt;\n },\n { behavior: \"immediate\" },\n ),\n );\n },\n deleteDocument: deleteStoredDocument,\n deleteDocumentIfMatches: deleteStoredDocumentIfMatches,\n deleteDocumentSideRowsIfAbsent: deleteStoredDocumentSideRowsIfAbsent,\n async discardDocumentToShell(\n execSql,\n localId,\n expectedDocumentId,\n documentProjectors,\n ): Promise<DiscardDocumentToShellResult> {\n return discardStoredDocumentToShell({\n documentProjectors,\n execSql,\n expectedDocumentId,\n localId,\n persistence: sqlDocumentsPersistence,\n });\n },\n async upsertDiscoveredDocument(execSql, input) {\n const [nextSummary] = await upsertDiscoveredDocuments(execSql, [input]);\n if (!nextSummary) {\n throw new Error(\"Failed to upsert discovered document\");\n }\n\n return nextSummary;\n },\n async relinkPersistedDocument(execSql, input) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n () => relinkPersistedDocumentWithExec(lockedExecSql, input),\n { behavior: \"immediate\" },\n );\n });\n },\n};\n"]}