@tearleads/client-sdk 0.1.210 → 0.1.212

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 (76) hide show
  1. package/client/organizations/index.js +5 -5
  2. package/client/organizations/index.js.map +1 -1
  3. package/client/organizations/principalMutationScope.js +7 -1
  4. package/client/organizations/principalMutationScope.js.map +1 -1
  5. package/client/organizations/principalMutations.d.ts +8 -6
  6. package/client/organizations/principalMutations.js +8 -8
  7. package/client/organizations/principalMutations.js.map +1 -1
  8. package/client/organizations/recipientAdmission.d.ts +2 -1
  9. package/client/organizations/recipientAdmission.js +2 -2
  10. package/client/organizations/recipientAdmission.js.map +1 -1
  11. package/client/runtime/workflowRuntime.d.ts +2 -1
  12. package/client/runtime/workflowRuntime.js +1 -1
  13. package/client/runtime/workflowRuntime.js.map +1 -1
  14. package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
  15. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  16. package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
  17. package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
  18. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
  19. package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
  20. package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
  21. package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
  22. package/data/persistence/documents/internal/discardDocument.js +4 -4
  23. package/data/persistence/documents/internal/discardDocument.js.map +1 -1
  24. package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
  25. package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
  26. package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
  27. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  28. package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
  29. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  30. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
  31. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  32. package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
  33. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  34. package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
  35. package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
  36. package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
  37. package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
  38. package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
  39. package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
  40. package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
  41. package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
  42. package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
  43. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
  44. package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
  45. package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
  46. package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
  47. package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
  48. package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
  49. package/data/persistence/documents/records/documentRecordRepository.js +286 -0
  50. package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
  51. package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
  52. package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
  53. package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
  54. package/data/persistence/documents/records/index.d.ts +4 -19
  55. package/data/persistence/documents/records/index.js +5 -29
  56. package/data/persistence/documents/records/index.js.map +1 -1
  57. package/package.json +1 -1
  58. package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
  59. package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
  60. package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
  61. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  62. package/stores/documents/documentStore/sync/syncShared.js +2 -2
  63. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  64. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
  65. package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
  66. package/workflows/container-contents/pendingWrites/index.js +4 -3
  67. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  68. package/workflows/container-contents/recovery/accessRestoration.js +2 -2
  69. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
  70. package/workflows/documents/index.d.ts +1 -1
  71. package/workflows/documents/index.js +1 -1
  72. package/workflows/documents/index.js.map +1 -1
  73. package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
  74. package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
  75. package/workflows/organizations/readModel/listLocalOrganizations.js +2 -2
  76. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
@@ -2,7 +2,7 @@ import { KeyingVerificationError } from "../../../../internal/crypto/index.js";
2
2
  import { DEFAULT_DOCUMENT_KIND, DOCUMENTS_APP_KIND, } from "../../../documents/documentConstants.js";
3
3
  import { loadDocumentMovePlacements, } from "../../container-contents/documentPlacement.js";
4
4
  import { hasDocumentPurgeCheckpointInTransaction, listPurgedDocumentIdsInTransaction, } from "../../keyingCheckpoints/documentPurgeCheckpointPersistence.js";
5
- import { findLocalIdByDocumentId, findLocalIdsByDocumentIds } from "../records/index.js";
5
+ import { DocumentRecordRepository } from "../records/index.js";
6
6
  import { discoveredDocumentPlacement, resolveDiscoveredDocumentPlacement, } from "./discoveredDocumentPlacement.js";
7
7
  import { toDocumentSummary } from "./documentProjectionRows.js";
8
8
  import { documentSaveTimestampFrom, resolveDocumentSaveTimestamp, saveDocumentRows, saveDocumentRowsBatch, } from "./documentRows.js";
@@ -40,7 +40,7 @@ async function upsertDiscoveredDocumentWithExec(execSql, input, pendingCreates,
40
40
  if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {
41
41
  throw purgedDocumentError();
42
42
  }
43
- const existingLocalId = await findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, input.documentId);
43
+ const existingLocalId = await new DocumentRecordRepository(execSql).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);
44
44
  const localId = existingLocalId ?? input.documentId;
45
45
  const pendingLocalId = pendingCreates.get(input.documentId);
46
46
  if (!existingLocalId && pendingLocalId) {
@@ -78,7 +78,7 @@ async function upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates,
78
78
  async function resolveDiscoveryTargets(execSql, inputs, pendingCreates, tx) {
79
79
  const documentIds = inputs.map((input) => input.documentId);
80
80
  const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);
81
- const existingLocalIds = await findLocalIdsByDocumentIds(execSql, DOCUMENTS_APP_KIND, documentIds);
81
+ const existingLocalIds = await new DocumentRecordRepository(execSql).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);
82
82
  const targets = [];
83
83
  const pendingLocalIds = new Set();
84
84
  for (const input of inputs) {
@@ -1 +1 @@
1
- {"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAO9C,OAAO,EAEL,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC,kCAAkC,GACnC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAEhF,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,G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AC,MAAM,CAAC,OAAO,CAAC,EAC1B,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CACrC;KACF,CAAC,CACH,CAAC;IACF,MAAM,KAAK,GAAG,MAAM,qBAAqB,CAAC;QACxC,OAAO,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC9B,EAAE;KACH,CAAC,CAAC;IACH,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,MAAM,iBAAiB,EAAE,CAAC;IAC3D,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE;QAC5B,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS;YAAE,OAAO,MAAM,CAAC,OAAO,CAAC;QACrD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC1C,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;QACpE,OAAO,iBAAiB,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../../container-contents/documentPlacement\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { findLocalIdByDocumentId, findLocalIdsByDocumentIds } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await findLocalIdByDocumentId(\n execSql,\n DOCUMENTS_APP_KIND,\n input.documentId,\n );\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await findLocalIdsByDocumentIds(\n execSql,\n DOCUMENTS_APP_KIND,\n documentIds,\n );\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
1
+ {"version":3,"file":"discoveredDocumentUpsert.js","sourceRoot":"","sources":["discoveredDocumentUpsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,sCAAsC,CAAC;AAO9C,OAAO,EAEL,0BAA0B,GAC3B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,uCAAuC,EACvC,kCAAkC,GACnC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EACL,yBAAyB,EACzB,4BAA4B,EAC5B,gBAAgB,EAChB,qBAAqB,GACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,oCAAoC,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACnE,OAAO,EACL,uBAAuB,EACvB,wBAAwB,GAEzB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,qCAAqC,GAAG,qBAAqB,CAAC;AAEpE,SAAS,mBAAmB;IAC1B,OAAO,IAAI,uBAAuB,CAChC,UAAU,EACV,0DAA0D,CAC3D,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB;IACxB,OAAO,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAe,EACf,KAA8B,EAC9B,gBAA6C,EAC7C,SAAyD;IAEzD,OAAO;QACL,EAAE,EAAE,OAAO;QACX,UAAU,EAAE,KAAK,CAAC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CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IAC5D,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n DEFAULT_DOCUMENT_KIND,\n DOCUMENTS_APP_KIND,\n} from \"../../../documents/documentConstants\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../documents/documentSummary\";\nimport type { ClientSQLiteTransactionScope } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n type DocumentMovePlacement,\n loadDocumentMovePlacements,\n} from \"../../container-contents/documentPlacement\";\nimport {\n hasDocumentPurgeCheckpointInTransaction,\n listPurgedDocumentIdsInTransaction,\n} from \"../../keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport {\n discoveredDocumentPlacement,\n resolveDiscoveredDocumentPlacement,\n} from \"./discoveredDocumentPlacement\";\nimport { toDocumentSummary } from \"./documentProjectionRows\";\nimport {\n documentSaveTimestampFrom,\n resolveDocumentSaveTimestamp,\n saveDocumentRows,\n saveDocumentRowsBatch,\n} from \"./documentRows\";\nimport { resolvePersistedDocumentRuntimeState } from \"./documentRuntimeState\";\nimport { loadPendingCreateSummary } from \"./pendingCreateAdoption\";\nimport {\n loadStoredDocumentState,\n loadStoredDocumentStates,\n type StoredDocumentState,\n} from \"./rowQueryPersistence\";\n\nconst DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE = \"Syncing document...\";\n\nfunction purgedDocumentError(): KeyingVerificationError {\n return new KeyingVerificationError(\n \"rollback\",\n \"Document discovery targets a permanently purged document\",\n );\n}\n\nfunction fenceSkippedError(): Error {\n return new Error(\"Document recovery generation changed during discovery\");\n}\n\nfunction nextDiscoveredDocument(\n localId: string,\n input: DiscoveredDocumentInput,\n existingDocument: StoredDocumentRecord | null,\n placement: ReturnType<typeof discoveredDocumentPlacement>,\n): StoredDocumentRecord {\n return {\n id: localId,\n documentId: input.documentId,\n documentKind: existingDocument?.documentKind ?? DEFAULT_DOCUMENT_KIND,\n text: existingDocument?.text ?? \"\",\n title: existingDocument?.title ?? DISCOVERED_DOCUMENT_PLACEHOLDER_TITLE,\n snapshotEndVersion: existingDocument?.snapshotEndVersion ?? \"\",\n recoveryGeneration: existingDocument?.recoveryGeneration ?? 0,\n ...placement,\n effectiveAccessLevel:\n input.effectiveAccessLevel ??\n existingDocument?.effectiveAccessLevel ??\n null,\n ...resolvePersistedDocumentRuntimeState(existingDocument, {\n accessEpoch: placement.accessEpoch,\n documentId: input.documentId,\n }),\n };\n}\n\n/** One discovered document, read and written on its own (the per-row path). */\nasync function upsertDiscoveredDocumentWithExec(\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary> {\n if (await hasDocumentPurgeCheckpointInTransaction(tx, input.documentId)) {\n throw purgedDocumentError();\n }\n const existingLocalId = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, input.documentId);\n const localId = existingLocalId ?? input.documentId;\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n return pending;\n }\n const existingDocument =\n (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n const placement = await resolveDiscoveredDocumentPlacement(\n tx,\n existingDocument,\n input,\n );\n const nextDocument = nextDiscoveredDocument(\n localId,\n input,\n existingDocument,\n placement,\n );\n const updatedAt = await resolveDocumentSaveTimestamp({\n document: nextDocument,\n options: existingDocument ? undefined : { updatedAt: input.createdAt },\n tx,\n });\n if (!(await saveDocumentRows({ document: nextDocument, tx, updatedAt }))) {\n throw fenceSkippedError();\n }\n return toDocumentSummary(nextDocument, updatedAt);\n}\n\nasync function upsertDiscoveredDocumentsPerRow(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const summaries: DocumentSummary[] = [];\n for (const input of inputs) {\n summaries.push(\n await upsertDiscoveredDocumentWithExec(\n execSql,\n input,\n pendingCreates,\n tx,\n ),\n );\n }\n return summaries;\n}\n\ntype DiscoveryTarget =\n | { kind: \"pending\"; summary: DocumentSummary }\n | { input: DiscoveredDocumentInput; kind: \"write\"; localId: string };\n\n/**\n * Resolves every input to its pending-create summary or its target local id,\n * in input order, so the first purged or unavailable input throws exactly as\n * the per-row walk would. Returns null when one input's write could change\n * another input's reads, which only the per-row walk handles.\n */\nasync function resolveDiscoveryTargets(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DiscoveryTarget[] | null> {\n const documentIds = inputs.map((input) => input.documentId);\n const purged = await listPurgedDocumentIdsInTransaction(tx, documentIds);\n const existingLocalIds = await new DocumentRecordRepository(\n execSql,\n ).findLocalIdsByDocumentIds(DOCUMENTS_APP_KIND, documentIds);\n const targets: DiscoveryTarget[] = [];\n const pendingLocalIds = new Set<string>();\n for (const input of inputs) {\n if (purged.has(input.documentId)) throw purgedDocumentError();\n const existingLocalId = existingLocalIds.get(input.documentId);\n const pendingLocalId = pendingCreates.get(input.documentId);\n if (!existingLocalId && pendingLocalId) {\n const pending = await loadPendingCreateSummary(execSql, pendingLocalId);\n if (!pending) throw new Error(\"Pending create projection is unavailable\");\n pendingLocalIds.add(pendingLocalId);\n targets.push({ kind: \"pending\", summary: pending });\n continue;\n }\n targets.push({\n input,\n kind: \"write\",\n localId: existingLocalId ?? input.documentId,\n });\n }\n const writeLocalIds = targets.flatMap((target) =>\n target.kind === \"write\" ? [target.localId] : [],\n );\n const independent =\n new Set(writeLocalIds).size === writeLocalIds.length &&\n !writeLocalIds.some((localId) => pendingLocalIds.has(localId));\n return independent ? targets : null;\n}\n\n/**\n * Whether writing each target leaves every other target's reads unchanged: a\n * stored row at a target local id that carries a different document id would\n * be re-pointed by its write, which another input's lookup could have read.\n */\nfunction targetsReadDisjointRows(\n targets: ReadonlyArray<DiscoveryTarget>,\n states: ReadonlyMap<string, StoredDocumentState>,\n): boolean {\n return targets.every(\n (target) =>\n target.kind !== \"write\" ||\n (states.get(target.localId)?.record.documentId ??\n target.input.documentId) === target.input.documentId,\n );\n}\n\nfunction plannedDiscoveryWrite(\n target: Extract<DiscoveryTarget, { kind: \"write\" }>,\n state: StoredDocumentState | undefined,\n intent: DocumentMovePlacement | undefined,\n) {\n const existingDocument = state?.record ?? null;\n const document = nextDiscoveredDocument(\n target.localId,\n target.input,\n existingDocument,\n discoveredDocumentPlacement(existingDocument, target.input, intent),\n );\n // The joined state read is the row and projection the per-row walk reads\n // again for its timestamp; nothing earlier in this transaction writes it.\n const updatedAt = state\n ? documentSaveTimestampFrom(\n {\n projection: state.projection,\n snapshotEndVersion: state.record.snapshotEndVersion,\n },\n document,\n )\n : target.input.createdAt;\n return { document, updatedAt };\n}\n\n/**\n * Discovery as set statements: one read per table for every input, then\n * multi-row upserts. Inputs whose rows could interact (a repeated document\n * id, a shared local id, or a row another input would re-point) keep the\n * per-row walk, which reads each input after the previous one's writes.\n */\nexport async function upsertDiscoveredDocumentsInTransaction(\n execSql: ExecSql,\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n pendingCreates: ReadonlyMap<string, string>,\n tx: ClientSQLiteTransactionScope,\n): Promise<DocumentSummary[]> {\n const documentIds = inputs.map((input) => input.documentId);\n if (new Set(documentIds).size !== documentIds.length) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const targets = await resolveDiscoveryTargets(\n execSql,\n inputs,\n pendingCreates,\n tx,\n );\n if (!targets) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const writes = targets.flatMap((target) =>\n target.kind === \"write\" ? [target] : [],\n );\n if (writes.length === 0) {\n return targets.flatMap((target) =>\n target.kind === \"pending\" ? [target.summary] : [],\n );\n }\n const states = await loadStoredDocumentStates(\n execSql,\n writes.map((target) => target.localId),\n );\n if (!targetsReadDisjointRows(targets, states)) {\n return upsertDiscoveredDocumentsPerRow(execSql, inputs, pendingCreates, tx);\n }\n const intents = await loadDocumentMovePlacements(\n tx,\n writes.map((target) => target.input.documentId),\n );\n const planned = new Map(\n writes.map((target) => [\n target.localId,\n plannedDiscoveryWrite(\n target,\n states.get(target.localId),\n intents.get(target.input.documentId),\n ),\n ]),\n );\n const saved = await saveDocumentRowsBatch({\n entries: [...planned.values()],\n tx,\n });\n if (saved.size !== planned.size) throw fenceSkippedError();\n return targets.map((target) => {\n if (target.kind === \"pending\") return target.summary;\n const write = planned.get(target.localId);\n if (!write) throw new Error(\"Discovered document write is missing\");\n return toDocumentSummary(write.document, write.updatedAt);\n });\n}\n"]}
@@ -6,8 +6,7 @@ import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
6
6
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
7
7
  import { ensureSqlTables, runSerializedSqlMutation, } from "../../../sqlite/sqlSchema.js";
8
8
  import { deleteDocumentPlacementIntentsInTransaction, deleteDocumentPlacementRowsByDocumentIds, } from "../../container-contents/documentContainerProjectionPersistence.js";
9
- import { clearDocumentSyncFailure, deleteDocumentRecord, loadDocumentRecord, } from "../records/index.js";
10
- import { deleteDocumentHistory } from "../records/documentHistoryPersistence.js";
9
+ import { DocumentRecordRepository } from "../records/index.js";
11
10
  import { sameCanonicalDocumentSecurityIdentity } from "./documentRecordIdentity.js";
12
11
  import { getDocumentScope } from "./documentRows.js";
13
12
  import { queueDocumentAttachmentBlobReclaims } from "./orphanSideRows.js";
@@ -40,9 +39,10 @@ async function deleteStoredDocumentRows(input) {
40
39
  await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);
41
40
  }
42
41
  const scope = getDocumentScope(localId);
43
- await deleteDocumentHistory(lockedExecSql, scope);
44
- await clearDocumentSyncFailure(lockedExecSql, scope);
45
- await deleteDocumentRecord(lockedExecSql, scope);
42
+ const records = new DocumentRecordRepository(lockedExecSql);
43
+ await records.deleteDocumentHistory(scope);
44
+ await records.clearDocumentSyncFailure(scope);
45
+ await records.deleteDocumentRecord(scope);
46
46
  }
47
47
  async function ensureDocumentDeletionTables(execSql) {
48
48
  // Move intents live in the container-contents schema, which document-only
@@ -61,7 +61,7 @@ export async function deleteStoredDocument(execSql, localId) {
61
61
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
62
62
  await ensureDocumentDeletionTables(lockedExecSql);
63
63
  await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
64
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
64
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
65
65
  appKind: DOCUMENTS_APP_KIND,
66
66
  localId,
67
67
  });
@@ -78,7 +78,7 @@ export async function deleteStoredDocumentIfMatches(execSql, expectedRecord, del
78
78
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
79
79
  await ensureDocumentDeletionTables(lockedExecSql);
80
80
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
81
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
81
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
82
82
  appKind: DOCUMENTS_APP_KIND,
83
83
  localId: expectedRecord.id,
84
84
  });
@@ -116,7 +116,7 @@ export async function deleteStoredDocumentSideRowsIfAbsent(execSql, localId, exp
116
116
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
117
117
  await ensureDocumentDeletionTables(lockedExecSql);
118
118
  return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async (tx) => {
119
- const existingDocument = await loadDocumentRecord(lockedExecSql, {
119
+ const existingDocument = await new DocumentRecordRepository(lockedExecSql).loadDocumentRecord({
120
120
  appKind: DOCUMENTS_APP_KIND,
121
121
  localId,
122
122
  });
@@ -1 +1 @@
1
- {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,2CAA2C,EAC3C,wCAAwC,GACzC,MAAM,iEAAiE,CAAC;AACzE,OAAO,EACL,wBAAwB,EACxB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAE9E,OAAO,EAAE,qCAAqC,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,KAAK,UAAU,wBAAwB,CAAC,KAKvC;IACC,MAAM,EAAE,kBAAkB,EAAE,OAAO,EAAE,aAAa,EAAE,EAAE,EAAE,GAAG,KAAK,CAAC;IACjE,MAAM,mCAAmC,CAAC;QACxC,UAAU,EAAE,EAAE,CAAC,gCAAgC,CAAC,OAA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ACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,OAAgB,EAChB,OAAe,EACf,kBAAiC,EACjC,sBAAsE;IAEtE,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAC/D,MAAM,4BAA4B,CAAC,aAAa,CAAC,CAAC;QAClD,OAAO,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,KAAK,EAAE,EAAE,EAAE,EAAE;YACX,MAAM,gBAAgB,GAAG,MAAM,kBAAkB,CAAC,aAAa,EAAE;gBAC/D,OAAO,EAAE,kBAAkB;gBAC3B,OAAO;aACR,CAAC,CAAC;YACH,IAAI,gBAAgB;gBAAE,OAAO,KAAK,CAAC;YACnC,IACE,kBAAkB;gBAClB,CAAC,MAAM,uBAAuB,CAAC;oBAC7B,UAAU,EAAE,kBAAkB;oBAC9B,OAAO;oBACP,EAAE;iBACH,CAAC,CAAC,EACH,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,MAAM,wBAAwB,CAAC;gBAC7B,kBAAkB,EAAE,kBAAkB;gBACtC,OAAO;gBACP,aAAa;gBACb,EAAE;aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementIntentsInTransaction,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport {\n clearDocumentSyncFailure,\n deleteDocumentRecord,\n loadDocumentRecord,\n} from \"../records\";\nimport { deleteDocumentHistory } from \"../records/documentHistoryPersistence\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n // Placement rows and their tombstone holds, then queued placement intents.\n await deleteDocumentPlacementRowsByDocumentIds(tx, [existingDocumentId]);\n await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n await deleteDocumentHistory(lockedExecSql, scope);\n await clearDocumentSyncFailure(lockedExecSql, scope);\n await deleteDocumentRecord(lockedExecSql, scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await loadDocumentRecord(lockedExecSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
1
+ {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,GAC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iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CACjE,KAAK,EAAE,EAAE,EAAE,EAAE;YACX,MAAM,gBAAgB,GAAG,MAAM,IAAI,wBAAwB,CACzD,aAAa,CACd,CAAC,kBAAkB,CAAC;gBACnB,OAAO,EAAE,kBAAkB;gBAC3B,OAAO;aACR,CAAC,CAAC;YACH,IAAI,gBAAgB;gBAAE,OAAO,KAAK,CAAC;YACnC,IACE,kBAAkB;gBAClB,CAAC,MAAM,uBAAuB,CAAC;oBAC7B,UAAU,EAAE,kBAAkB;oBAC9B,OAAO;oBACP,EAAE;iBACH,CAAC,CAAC,EACH,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,MAAM,wBAAwB,CAAC;gBAC7B,kBAAkB,EAAE,kBAAkB;gBACtC,OAAO;gBACP,aAAa;gBACb,EAAE;aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementIntentsInTransaction,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n // Placement rows and their tombstone holds, then queued placement intents.\n await deleteDocumentPlacementRowsByDocumentIds(tx, [existingDocumentId]);\n await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(scope);\n await records.clearDocumentSyncFailure(scope);\n await records.deleteDocumentRecord(scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
@@ -6,7 +6,7 @@ import { documentSyncPullContinuationsEqual } from "../../../documents/shared/sy
6
6
  import { documentHistoryUpdates } from "../../../sqlite/schema/documentRecordSchema.js";
7
7
  import { getClientSQLitePersistenceRuntime, } from "../../../sqlite/sqlitePersistenceRuntime.js";
8
8
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
9
- import { appendDocumentHistoryUpdates, replaceDocumentHistoryCheckpoint, } from "../records/documentHistoryPersistence.js";
9
+ import { DocumentRecordRepository } from "../records/index.js";
10
10
  import { insertDocumentPendingUpdateWithHistoryInTransaction, settleQueuedDocumentUpdatesInTransaction, } from "../records/documentPendingUpdatePersistence.js";
11
11
  import { applyStoredAttachmentRemoval, upsertStoredAttachmentStagingRows, } from "./attachmentStagingPersistence.js";
12
12
  import { sameDocumentSecurityIdentity, sameDocumentSettlementIdentity, sameNullableDocumentValue, } from "./documentRecordIdentity.js";
@@ -59,6 +59,7 @@ function assertRecoveryCoversLocalState(coveredLocalState) {
59
59
  }
60
60
  }
61
61
  async function appendMutationHistory(execSql, input, tx) {
62
+ const records = new DocumentRecordRepository(execSql);
62
63
  if (input.historyCheckpoint) {
63
64
  const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState
64
65
  ? await findCoveredRecoveryLocalState(tx, input.document.id, input.historyCheckpoint.snapshot)
@@ -75,7 +76,7 @@ async function appendMutationHistory(execSql, input, tx) {
75
76
  // A queued rotation baseline the recovery snapshot covers is unqueued
76
77
  // first so the replacement below can delete it with the covered tail.
77
78
  await deleteAcceptedPendingUpdates(tx, input.document.id, coveredLocalState.checkpointIds);
78
- const checkpointReplaced = await replaceDocumentHistoryCheckpoint(execSql, { appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, {
79
+ const checkpointReplaced = await records.replaceDocumentHistoryCheckpoint({ appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, {
79
80
  ...input.historyCheckpoint,
80
81
  coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState
81
82
  ? coveredLocalState.tailIds
@@ -86,7 +87,7 @@ async function appendMutationHistory(execSql, input, tx) {
86
87
  }
87
88
  }
88
89
  if (input.historyUpdates && input.historyUpdates.length > 0) {
89
- await appendDocumentHistoryUpdates(execSql, { appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, input.historyUpdates, input.historyUpdateOrigin ?? "local");
90
+ await records.appendDocumentHistoryUpdates({ appKind: DOCUMENTS_APP_KIND, localId: input.document.id }, input.historyUpdates, input.historyUpdateOrigin ?? "local");
90
91
  }
91
92
  }
92
93
  async function findCoveredRecoveryLocalState(tx, localId, recoverySnapshot) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentMutationPersistence.js","sourceRoot":"","sources":["documentMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,cAAc,EACd,4BAA4B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MA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AC5E,KAA0E,EAC1E,YAAkD;IAElD,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,EAAE,EAAE,EAAE,EAAE;QACX,MAAM,aAAa,GAAG,MAAM,YAAY,CACtC,aAAa,EACb,KAAK,CAAC,cAAc,CAAC,EAAE,CACxB,CAAC;QACF,IACE,aAAa;YACb,8BAA8B,CAAC,aAAa,EAAE,KAAK,CAAC,cAAc,CAAC;YACnE,sBAAsB,CAAC,aAAa,EAAE,KAAK,CAAC,cAAc,CAAC,EAC3D,CAAC;YACD,MAAM,4BAA4B,CAChC,EAAE,EACF,KAAK,CAAC,cAAc,CAAC,EAAE,EACvB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n importSnapshot,\n updateMatchesDocumentHistory,\n} from \"@tearleads/loro\";\nimport { and, eq } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { documentSyncPullContinuationsEqual } from \"../../../documents/shared/sync/pullContinuation\";\nimport { documentHistoryUpdates } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport {\n appendDocumentHistoryUpdates,\n replaceDocumentHistoryCheckpoint,\n} from \"../records/documentHistoryPersistence\";\nimport {\n insertDocumentPendingUpdateWithHistoryInTransaction,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n applyStoredAttachmentRemoval,\n upsertStoredAttachmentStagingRows,\n} from \"./attachmentStagingPersistence\";\nimport {\n sameDocumentSecurityIdentity,\n sameDocumentSettlementIdentity,\n sameNullableDocumentValue,\n} from \"./documentRecordIdentity\";\nimport { documentSaveTimestampFrom, saveDocumentRows } from \"./documentRows\";\nimport { loadStoredDocumentState } from \"./rowQueryPersistence\";\n\nfunction sameRecoveryGeneration(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n (current.recoveryGeneration ?? 0) === (expected.recoveryGeneration ?? 0)\n );\n}\n\nfunction sameExpectedDocumentRecord(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n sameDocumentSecurityIdentity(current, expected) &&\n sameRecoveryGeneration(current, expected) &&\n sameNullableDocumentValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n sameNullableDocumentValue(\n current.pendingBaseVersion,\n expected.pendingBaseVersion,\n ) &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired) &&\n (current.documentKind ?? null) === (expected.documentKind ?? null) &&\n current.text === expected.text &&\n (current.title ?? null) === (expected.title ?? null)\n );\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n { appKind: DOCUMENTS_APP_KIND, localId },\n ids,\n );\n}\n\nasync function insertPendingUpdate(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n pendingUpdate: Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"pendingUpdate\"],\n): Promise<void> {\n if (!pendingUpdate) return;\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: documentId },\n tx,\n });\n}\n\nasync function settleMutationConflict(input: {\n currentRecord: StoredDocumentRecord | null;\n mutation: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (\n input.currentRecord &&\n input.mutation.settleAcceptedPendingOnConflict &&\n sameDocumentSettlementIdentity(\n input.currentRecord,\n input.mutation.expectedRecord,\n ) &&\n sameRecoveryGeneration(input.currentRecord, input.mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n input.tx,\n input.mutation.document.id,\n input.mutation.acceptedPendingUpdateIds,\n );\n }\n}\n\nfunction assertRecoveryCoversLocalState(coveredLocalState: {\n readonly hasOrdinaryPendingUpdates: boolean;\n readonly hasUnprunablePendingUpdates: boolean;\n readonly hasUnverifiedHistoryTail: boolean;\n}): void {\n if (\n coveredLocalState.hasOrdinaryPendingUpdates ||\n coveredLocalState.hasUnprunablePendingUpdates\n ) {\n throw new Error(\n \"Document recovery found unproven pending updates before installation\",\n );\n }\n if (coveredLocalState.hasUnverifiedHistoryTail) {\n throw new Error(\n \"Document recovery found unverified history tail before installation\",\n );\n }\n}\n\nasync function appendMutationHistory(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1],\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n if (input.historyCheckpoint) {\n const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState\n ? await findCoveredRecoveryLocalState(\n tx,\n input.document.id,\n input.historyCheckpoint.snapshot,\n )\n : {\n checkpointIds: [],\n hasOrdinaryPendingUpdates: false,\n hasUnprunablePendingUpdates: false,\n hasUnverifiedHistoryTail: false,\n tailIds: [],\n };\n if (input.historyCheckpoint.pruneCoveredLocalState) {\n assertRecoveryCoversLocalState(coveredLocalState);\n }\n // A queued rotation baseline the recovery snapshot covers is unqueued\n // first so the replacement below can delete it with the covered tail.\n await deleteAcceptedPendingUpdates(\n tx,\n input.document.id,\n coveredLocalState.checkpointIds,\n );\n const checkpointReplaced = await replaceDocumentHistoryCheckpoint(\n execSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n {\n ...input.historyCheckpoint,\n coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState\n ? coveredLocalState.tailIds\n : input.historyCheckpoint.coveredTailIds,\n },\n );\n if (input.historyCheckpoint.pruneCoveredLocalState && !checkpointReplaced) {\n throw new Error(\n \"Document recovery checkpoint was superseded before installation\",\n );\n }\n }\n if (input.historyUpdates && input.historyUpdates.length > 0) {\n await appendDocumentHistoryUpdates(\n execSql,\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n input.historyUpdates,\n input.historyUpdateOrigin ?? \"local\",\n );\n }\n}\n\nasync function findCoveredRecoveryLocalState(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n recoverySnapshot: string,\n): Promise<{\n checkpointIds: string[];\n hasOrdinaryPendingUpdates: boolean;\n hasUnprunablePendingUpdates: boolean;\n hasUnverifiedHistoryTail: boolean;\n tailIds: string[];\n}> {\n const recoveredDocument = await createDocument(\n `recovery-tail-verification:${localId}`,\n );\n try {\n importSnapshot(recoveredDocument, base64ToBytes(recoverySnapshot));\n const rows = await tx\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n updateData: documentHistoryUpdates.updateData,\n updateId: documentHistoryUpdates.updateId,\n })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n eq(documentHistoryUpdates.localId, localId),\n ),\n );\n const pendingUpdates = rows.filter((row) => row.updateId !== null);\n const tail = rows.filter((row) => row.origin !== \"outbox\");\n const checkpointUpdateData = new Set(\n pendingUpdates.flatMap((row) =>\n row.sourceVersionVector === null ? [] : [row.updateData],\n ),\n );\n let hasUnverifiedHistoryTail = false;\n const tailIds = tail.flatMap((row) => {\n if (row.id === null) {\n // An unverifiable row identity cannot participate in the guarded\n // delete, so accepting it would leave a stale recovery redirect.\n hasUnverifiedHistoryTail = true;\n return [];\n }\n if (checkpointUpdateData.has(row.updateData)) return [row.id];\n try {\n if (\n updateMatchesDocumentHistory(\n recoveredDocument,\n base64ToBytes(row.updateData),\n )\n ) {\n return [row.id];\n }\n } catch {\n // Fall through: malformed history is not proven by the rebuild.\n }\n hasUnverifiedHistoryTail = true;\n return [];\n });\n return {\n checkpointIds: pendingUpdates.flatMap((row) =>\n row.updateId !== null && row.sourceVersionVector !== null\n ? [row.updateId]\n : [],\n ),\n hasOrdinaryPendingUpdates: pendingUpdates.some(\n (row) => row.sourceVersionVector === null,\n ),\n hasUnprunablePendingUpdates: pendingUpdates.some(\n (row) => row.id === null,\n ),\n hasUnverifiedHistoryTail,\n tailIds,\n };\n } finally {\n recoveredDocument.free();\n }\n}\n\ntype CommitDocumentMutationInput = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[1];\ntype SaveClientProjection = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[2];\n\nasync function applyStoredDocumentMutation(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { lockedExecSql, mutation, tx } = input;\n const currentState = await loadStoredDocumentState(\n lockedExecSql,\n mutation.document.id,\n );\n const currentRecord = currentState?.record ?? null;\n if (mutation.stillCurrent && !mutation.stillCurrent()) {\n return { committed: false as const, currentRecord };\n }\n if (\n !currentRecord ||\n !sameExpectedDocumentRecord(currentRecord, mutation.expectedRecord)\n ) {\n await settleMutationConflict({ currentRecord, mutation, tx });\n return { committed: false as const, currentRecord };\n }\n\n if (mutation.attachmentRemoval) {\n await applyStoredAttachmentRemoval({\n localId: mutation.document.id,\n removal: mutation.attachmentRemoval,\n tx,\n });\n }\n if (mutation.attachmentStaging) {\n await upsertStoredAttachmentStagingRows({\n createdAt: new Date().toISOString(),\n localId: mutation.document.id,\n staging: mutation.attachmentStaging,\n tx,\n });\n }\n await appendMutationHistory(lockedExecSql, mutation, tx);\n await insertPendingUpdate(tx, mutation.document.id, mutation.pendingUpdate);\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.document.id,\n mutation.acceptedPendingUpdateIds,\n );\n // Nothing above writes the document or projection rows, so the state read\n // at the top of this transaction still decides the save timestamp.\n const updatedAt =\n mutation.updatedAt ||\n documentSaveTimestampFrom(\n {\n projection: currentState?.projection ?? null,\n snapshotEndVersion: currentRecord.snapshotEndVersion,\n },\n mutation.document,\n );\n if (\n !(await saveDocumentRows({\n clearSyncFailure: mutation.clearSyncFailure === true,\n document: mutation.document,\n tx,\n updatedAt,\n }))\n ) {\n throw new Error(\n \"Document recovery generation changed before mutation save\",\n );\n }\n await input.saveClientProjection(lockedExecSql, updatedAt);\n return { committed: true as const, updatedAt };\n}\n\nasync function runStoredDocumentMutationTransaction(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n loadDocument: DocumentsPersistence[\"loadDocument\"];\n}) {\n const outcome = await getClientSQLitePersistenceRuntime(\n input.lockedExecSql,\n ).guardedTransaction(\n (tx) => applyStoredDocumentMutation({ ...input, tx }),\n () => !input.mutation.stillCurrent || input.mutation.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentRecord: await input.loadDocument(\n input.lockedExecSql,\n input.mutation.document.id,\n ),\n };\n}\n\nexport async function commitStoredDocumentMutation(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: CommitDocumentMutationInput,\n saveClientProjection: SaveClientProjection,\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n runStoredDocumentMutationTransaction({\n lockedExecSql,\n loadDocument,\n mutation: input,\n saveClientProjection,\n }),\n );\n}\n\nexport async function settleStoredDocumentPendingUpdates(\n execSql: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[0],\n input: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const currentRecord = await loadDocument(\n lockedExecSql,\n input.expectedRecord.id,\n );\n if (\n currentRecord &&\n sameDocumentSettlementIdentity(currentRecord, input.expectedRecord) &&\n sameRecoveryGeneration(currentRecord, input.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.expectedRecord.id,\n input.pendingUpdateIds,\n );\n }\n return currentRecord;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"documentMutationPersistence.js","sourceRoot":"","sources":["documentMutationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,cAAc,EACd,cAAc,EACd,4BAA4B,GAC7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,iDAAiD,CAAC;AACrG,OAAO,EAAE,sBAAsB,EAAE,MAAM,6CAA6C,CAAC;AACrF,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EACL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CAAC,aAAa,EAAE,KAAK,CAAC,cAAc,CAAC;YACnE,sBAAsB,CAAC,aAAa,EAAE,KAAK,CAAC,cAAc,CAAC,EAC3D,CAAC;YACD,MAAM,4BAA4B,CAChC,EAAE,EACF,KAAK,CAAC,cAAc,CAAC,EAAE,EACvB,KAAK,CAAC,gBAAgB,CACvB,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { base64ToBytes } from \"@tearleads/encoding\";\nimport {\n createDocument,\n importSnapshot,\n updateMatchesDocumentHistory,\n} from \"@tearleads/loro\";\nimport { and, eq } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { documentSyncPullContinuationsEqual } from \"../../../documents/shared/sync/pullContinuation\";\nimport { documentHistoryUpdates } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport {\n insertDocumentPendingUpdateWithHistoryInTransaction,\n settleQueuedDocumentUpdatesInTransaction,\n} from \"../records/documentPendingUpdatePersistence\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n applyStoredAttachmentRemoval,\n upsertStoredAttachmentStagingRows,\n} from \"./attachmentStagingPersistence\";\nimport {\n sameDocumentSecurityIdentity,\n sameDocumentSettlementIdentity,\n sameNullableDocumentValue,\n} from \"./documentRecordIdentity\";\nimport { documentSaveTimestampFrom, saveDocumentRows } from \"./documentRows\";\nimport { loadStoredDocumentState } from \"./rowQueryPersistence\";\n\nfunction sameRecoveryGeneration(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n (current.recoveryGeneration ?? 0) === (expected.recoveryGeneration ?? 0)\n );\n}\n\nfunction sameExpectedDocumentRecord(\n current: StoredDocumentRecord,\n expected: StoredDocumentRecord,\n): boolean {\n return (\n sameDocumentSecurityIdentity(current, expected) &&\n sameRecoveryGeneration(current, expected) &&\n sameNullableDocumentValue(current.lastCommitLsn, expected.lastCommitLsn) &&\n current.snapshotEndVersion === expected.snapshotEndVersion &&\n sameNullableDocumentValue(\n current.pendingBaseVersion,\n expected.pendingBaseVersion,\n ) &&\n documentSyncPullContinuationsEqual(\n current.pullContinuation,\n expected.pullContinuation,\n ) &&\n Boolean(current.pullContinuationRecoveryRequired) ===\n Boolean(expected.pullContinuationRecoveryRequired) &&\n (current.documentKind ?? null) === (expected.documentKind ?? null) &&\n current.text === expected.text &&\n (current.title ?? null) === (expected.title ?? null)\n );\n}\n\nasync function deleteAcceptedPendingUpdates(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n ids: readonly string[],\n): Promise<void> {\n await settleQueuedDocumentUpdatesInTransaction(\n tx,\n { appKind: DOCUMENTS_APP_KIND, localId },\n ids,\n );\n}\n\nasync function insertPendingUpdate(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n pendingUpdate: Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n >[1][\"pendingUpdate\"],\n): Promise<void> {\n if (!pendingUpdate) return;\n await insertDocumentPendingUpdateWithHistoryInTransaction({\n createdAt: new Date().toISOString(),\n pendingUpdate,\n scope: { appKind: DOCUMENTS_APP_KIND, localId: documentId },\n tx,\n });\n}\n\nasync function settleMutationConflict(input: {\n currentRecord: StoredDocumentRecord | null;\n mutation: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1];\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n if (\n input.currentRecord &&\n input.mutation.settleAcceptedPendingOnConflict &&\n sameDocumentSettlementIdentity(\n input.currentRecord,\n input.mutation.expectedRecord,\n ) &&\n sameRecoveryGeneration(input.currentRecord, input.mutation.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n input.tx,\n input.mutation.document.id,\n input.mutation.acceptedPendingUpdateIds,\n );\n }\n}\n\nfunction assertRecoveryCoversLocalState(coveredLocalState: {\n readonly hasOrdinaryPendingUpdates: boolean;\n readonly hasUnprunablePendingUpdates: boolean;\n readonly hasUnverifiedHistoryTail: boolean;\n}): void {\n if (\n coveredLocalState.hasOrdinaryPendingUpdates ||\n coveredLocalState.hasUnprunablePendingUpdates\n ) {\n throw new Error(\n \"Document recovery found unproven pending updates before installation\",\n );\n }\n if (coveredLocalState.hasUnverifiedHistoryTail) {\n throw new Error(\n \"Document recovery found unverified history tail before installation\",\n );\n }\n}\n\nasync function appendMutationHistory(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[1],\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const records = new DocumentRecordRepository(execSql);\n if (input.historyCheckpoint) {\n const coveredLocalState = input.historyCheckpoint.pruneCoveredLocalState\n ? await findCoveredRecoveryLocalState(\n tx,\n input.document.id,\n input.historyCheckpoint.snapshot,\n )\n : {\n checkpointIds: [],\n hasOrdinaryPendingUpdates: false,\n hasUnprunablePendingUpdates: false,\n hasUnverifiedHistoryTail: false,\n tailIds: [],\n };\n if (input.historyCheckpoint.pruneCoveredLocalState) {\n assertRecoveryCoversLocalState(coveredLocalState);\n }\n // A queued rotation baseline the recovery snapshot covers is unqueued\n // first so the replacement below can delete it with the covered tail.\n await deleteAcceptedPendingUpdates(\n tx,\n input.document.id,\n coveredLocalState.checkpointIds,\n );\n const checkpointReplaced = await records.replaceDocumentHistoryCheckpoint(\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n {\n ...input.historyCheckpoint,\n coveredTailIds: input.historyCheckpoint.pruneCoveredLocalState\n ? coveredLocalState.tailIds\n : input.historyCheckpoint.coveredTailIds,\n },\n );\n if (input.historyCheckpoint.pruneCoveredLocalState && !checkpointReplaced) {\n throw new Error(\n \"Document recovery checkpoint was superseded before installation\",\n );\n }\n }\n if (input.historyUpdates && input.historyUpdates.length > 0) {\n await records.appendDocumentHistoryUpdates(\n { appKind: DOCUMENTS_APP_KIND, localId: input.document.id },\n input.historyUpdates,\n input.historyUpdateOrigin ?? \"local\",\n );\n }\n}\n\nasync function findCoveredRecoveryLocalState(\n tx: ClientSQLiteTransactionScope,\n localId: string,\n recoverySnapshot: string,\n): Promise<{\n checkpointIds: string[];\n hasOrdinaryPendingUpdates: boolean;\n hasUnprunablePendingUpdates: boolean;\n hasUnverifiedHistoryTail: boolean;\n tailIds: string[];\n}> {\n const recoveredDocument = await createDocument(\n `recovery-tail-verification:${localId}`,\n );\n try {\n importSnapshot(recoveredDocument, base64ToBytes(recoverySnapshot));\n const rows = await tx\n .select({\n id: documentHistoryUpdates.id,\n origin: documentHistoryUpdates.origin,\n sourceVersionVector: documentHistoryUpdates.sourceVersionVector,\n updateData: documentHistoryUpdates.updateData,\n updateId: documentHistoryUpdates.updateId,\n })\n .from(documentHistoryUpdates)\n .where(\n and(\n eq(documentHistoryUpdates.appKind, DOCUMENTS_APP_KIND),\n eq(documentHistoryUpdates.localId, localId),\n ),\n );\n const pendingUpdates = rows.filter((row) => row.updateId !== null);\n const tail = rows.filter((row) => row.origin !== \"outbox\");\n const checkpointUpdateData = new Set(\n pendingUpdates.flatMap((row) =>\n row.sourceVersionVector === null ? [] : [row.updateData],\n ),\n );\n let hasUnverifiedHistoryTail = false;\n const tailIds = tail.flatMap((row) => {\n if (row.id === null) {\n // An unverifiable row identity cannot participate in the guarded\n // delete, so accepting it would leave a stale recovery redirect.\n hasUnverifiedHistoryTail = true;\n return [];\n }\n if (checkpointUpdateData.has(row.updateData)) return [row.id];\n try {\n if (\n updateMatchesDocumentHistory(\n recoveredDocument,\n base64ToBytes(row.updateData),\n )\n ) {\n return [row.id];\n }\n } catch {\n // Fall through: malformed history is not proven by the rebuild.\n }\n hasUnverifiedHistoryTail = true;\n return [];\n });\n return {\n checkpointIds: pendingUpdates.flatMap((row) =>\n row.updateId !== null && row.sourceVersionVector !== null\n ? [row.updateId]\n : [],\n ),\n hasOrdinaryPendingUpdates: pendingUpdates.some(\n (row) => row.sourceVersionVector === null,\n ),\n hasUnprunablePendingUpdates: pendingUpdates.some(\n (row) => row.id === null,\n ),\n hasUnverifiedHistoryTail,\n tailIds,\n };\n } finally {\n recoveredDocument.free();\n }\n}\n\ntype CommitDocumentMutationInput = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[1];\ntype SaveClientProjection = Parameters<\n DocumentsPersistence[\"commitDocumentMutation\"]\n>[2];\n\nasync function applyStoredDocumentMutation(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n tx: ClientSQLiteTransactionScope;\n}) {\n const { lockedExecSql, mutation, tx } = input;\n const currentState = await loadStoredDocumentState(\n lockedExecSql,\n mutation.document.id,\n );\n const currentRecord = currentState?.record ?? null;\n if (mutation.stillCurrent && !mutation.stillCurrent()) {\n return { committed: false as const, currentRecord };\n }\n if (\n !currentRecord ||\n !sameExpectedDocumentRecord(currentRecord, mutation.expectedRecord)\n ) {\n await settleMutationConflict({ currentRecord, mutation, tx });\n return { committed: false as const, currentRecord };\n }\n\n if (mutation.attachmentRemoval) {\n await applyStoredAttachmentRemoval({\n localId: mutation.document.id,\n removal: mutation.attachmentRemoval,\n tx,\n });\n }\n if (mutation.attachmentStaging) {\n await upsertStoredAttachmentStagingRows({\n createdAt: new Date().toISOString(),\n localId: mutation.document.id,\n staging: mutation.attachmentStaging,\n tx,\n });\n }\n await appendMutationHistory(lockedExecSql, mutation, tx);\n await insertPendingUpdate(tx, mutation.document.id, mutation.pendingUpdate);\n await deleteAcceptedPendingUpdates(\n tx,\n mutation.document.id,\n mutation.acceptedPendingUpdateIds,\n );\n // Nothing above writes the document or projection rows, so the state read\n // at the top of this transaction still decides the save timestamp.\n const updatedAt =\n mutation.updatedAt ||\n documentSaveTimestampFrom(\n {\n projection: currentState?.projection ?? null,\n snapshotEndVersion: currentRecord.snapshotEndVersion,\n },\n mutation.document,\n );\n if (\n !(await saveDocumentRows({\n clearSyncFailure: mutation.clearSyncFailure === true,\n document: mutation.document,\n tx,\n updatedAt,\n }))\n ) {\n throw new Error(\n \"Document recovery generation changed before mutation save\",\n );\n }\n await input.saveClientProjection(lockedExecSql, updatedAt);\n return { committed: true as const, updatedAt };\n}\n\nasync function runStoredDocumentMutationTransaction(input: {\n lockedExecSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0];\n mutation: CommitDocumentMutationInput;\n saveClientProjection: SaveClientProjection;\n loadDocument: DocumentsPersistence[\"loadDocument\"];\n}) {\n const outcome = await getClientSQLitePersistenceRuntime(\n input.lockedExecSql,\n ).guardedTransaction(\n (tx) => applyStoredDocumentMutation({ ...input, tx }),\n () => !input.mutation.stillCurrent || input.mutation.stillCurrent(),\n { behavior: \"immediate\" },\n );\n if (outcome.committed && outcome.result) {\n return outcome.result;\n }\n return {\n committed: false as const,\n currentRecord: await input.loadDocument(\n input.lockedExecSql,\n input.mutation.document.id,\n ),\n };\n}\n\nexport async function commitStoredDocumentMutation(\n execSql: Parameters<DocumentsPersistence[\"commitDocumentMutation\"]>[0],\n input: CommitDocumentMutationInput,\n saveClientProjection: SaveClientProjection,\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n runStoredDocumentMutationTransaction({\n lockedExecSql,\n loadDocument,\n mutation: input,\n saveClientProjection,\n }),\n );\n}\n\nexport async function settleStoredDocumentPendingUpdates(\n execSql: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[0],\n input: Parameters<DocumentsPersistence[\"settleAcceptedPendingUpdates\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const currentRecord = await loadDocument(\n lockedExecSql,\n input.expectedRecord.id,\n );\n if (\n currentRecord &&\n sameDocumentSettlementIdentity(currentRecord, input.expectedRecord) &&\n sameRecoveryGeneration(currentRecord, input.expectedRecord)\n ) {\n await deleteAcceptedPendingUpdates(\n tx,\n input.expectedRecord.id,\n input.pendingUpdateIds,\n );\n }\n return currentRecord;\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { DOCUMENTS_APP_KIND } from "../../../documents/documentConstants.js";
2
2
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
3
3
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
4
- import { invalidateDocumentSyncPullContinuation } from "../records/index.js";
4
+ import { DocumentRecordRepository } from "../records/index.js";
5
5
  export async function invalidateStoredDocumentPullContinuation(execSql, input, loadDocument, loadHistoryRestoreState) {
6
6
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => getClientSQLitePersistenceRuntime(lockedExecSql).transaction(async () => {
7
- const invalidated = await invalidateDocumentSyncPullContinuation(lockedExecSql, {
7
+ const invalidated = await new DocumentRecordRepository(lockedExecSql).invalidateDocumentSyncPullContinuation({
8
8
  ...input,
9
9
  appKind: DOCUMENTS_APP_KIND,
10
10
  });
@@ -1 +1 @@
1
- {"version":3,"file":"documentPullContinuationPersistence.js","sourceRoot":"","sources":["documentPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,sCAAsC,EAAE,MAAM,YAAY,CAAC;AAGpE,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,OAA0E,EAC1E,KAAwE,EACxE,YAAkD,EAClD,uBAAwE;IAExE,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,IAAI,EAAE;QACT,MAAM,WAAW,GAAG,MAAM,sCAAsC,CAC9D,aAAa,EACb;YACE,GAAG,KAAK;YACR,OAAO,EAAE,kBAAkB;SAC5B,CACF,CAAC;QACF,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,MAAM,mBAAmB,GAAG,MAAM,uBAAuB,CACvD,aAAa,EACb,KAAK,CAAC,OAAO,CACd,CAAC;QACF,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,CAAC;IACzC,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { invalidateDocumentSyncPullContinuation } from \"../records\";\nimport type { DocumentsPersistence } from \"../types\";\n\nexport async function invalidateStoredDocumentPullContinuation(\n execSql: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[0],\n input: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n loadHistoryRestoreState: DocumentsPersistence[\"loadHistoryRestoreState\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async () => {\n const invalidated = await invalidateDocumentSyncPullContinuation(\n lockedExecSql,\n {\n ...input,\n appKind: DOCUMENTS_APP_KIND,\n },\n );\n if (!invalidated) return null;\n const record = await loadDocument(lockedExecSql, input.localId);\n if (!record) return null;\n const historyRestoreState = await loadHistoryRestoreState(\n lockedExecSql,\n input.localId,\n );\n return { historyRestoreState, record };\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"documentPullContinuationPersistence.js","sourceRoot":"","sources":["documentPullContinuationPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAGtD,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,OAA0E,EAC1E,KAAwE,EACxE,YAAkD,EAClD,uBAAwE;IAExE,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE,CAC/D,iCAAiC,CAAC,aAAa,CAAC,CAAC,WAAW,CAC1D,KAAK,IAAI,EAAE;QACT,MAAM,WAAW,GAAG,MAAM,IAAI,wBAAwB,CACpD,aAAa,CACd,CAAC,sCAAsC,CAAC;YACvC,GAAG,KAAK;YACR,OAAO,EAAE,kBAAkB;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,WAAW;YAAE,OAAO,IAAI,CAAC;QAC9B,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QACzB,MAAM,mBAAmB,GAAG,MAAM,uBAAuB,CACvD,aAAa,EACb,KAAK,CAAC,OAAO,CACd,CAAC;QACF,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,CAAC;IACzC,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport { runSerializedSqlMutation } from \"../../../sqlite/sqlSchema\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { DocumentsPersistence } from \"../types\";\n\nexport async function invalidateStoredDocumentPullContinuation(\n execSql: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[0],\n input: Parameters<DocumentsPersistence[\"invalidatePullContinuation\"]>[1],\n loadDocument: DocumentsPersistence[\"loadDocument\"],\n loadHistoryRestoreState: DocumentsPersistence[\"loadHistoryRestoreState\"],\n) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async () => {\n const invalidated = await new DocumentRecordRepository(\n lockedExecSql,\n ).invalidateDocumentSyncPullContinuation({\n ...input,\n appKind: DOCUMENTS_APP_KIND,\n });\n if (!invalidated) return null;\n const record = await loadDocument(lockedExecSql, input.localId);\n if (!record) return null;\n const historyRestoreState = await loadHistoryRestoreState(\n lockedExecSql,\n input.localId,\n );\n return { historyRestoreState, record };\n },\n { behavior: \"immediate\" },\n ),\n );\n}\n"]}
@@ -5,7 +5,7 @@ import { documentProjection, documentProjectionText, } from "../../../sqlite/sch
5
5
  import { documents } from "../../../sqlite/schema/documentRecordSchema.js";
6
6
  import { sqliteRowsPerStatement } from "../../../sqlite/sqliteBindBudget.js";
7
7
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
8
- import { documentRecordSelection, findLocalIdByDocumentId, loadDocumentRecord, mapSelectedDocumentRecord, } from "../records/index.js";
8
+ import { DocumentRecordRepository, documentRecordSelection, mapSelectedDocumentRecord, } from "../records/index.js";
9
9
  import { documentSummaryJoin, documentSummarySelection, getProjectionContainerId, getProjectionDocumentKind, getProjectionText, getProjectionTitle, mapDocumentSummary, } from "./documentProjectionRows.js";
10
10
  import { getDocumentScope, hasDocumentRow } from "./documentRows.js";
11
11
  const storedDocumentStateSelection = {
@@ -106,12 +106,12 @@ export const documentRowQueryPersistence = {
106
106
  .map((row) => row.localId)
107
107
  .filter((localId) => localId !== null);
108
108
  },
109
- findLocalIdByDocumentId: (execSql, documentId) => findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),
109
+ findLocalIdByDocumentId: (execSql, documentId) => new DocumentRecordRepository(execSql).findLocalIdByDocumentId(DOCUMENTS_APP_KIND, documentId),
110
110
  async hasDocument(execSql, localId) {
111
111
  return hasDocumentRow(execSql, localId);
112
112
  },
113
113
  async documentIdentityMatches(execSql, localId, expectedDocumentId, expectedRecoveryGeneration) {
114
- const record = await loadDocumentRecord(execSql, getDocumentScope(localId));
114
+ const record = await new DocumentRecordRepository(execSql).loadDocumentRecord(getDocumentScope(localId));
115
115
  return (record?.documentId === expectedDocumentId &&
116
116
  (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration);
117
117
  },
@@ -1 +1 @@
1
- {"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAY,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAE1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,kBA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B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,MAAM,IAAI,IAAI,CAAC;IAC3E,CAAC;IACD,KAAK,CAAC,qBAAqB,CAAC,OAAO,EAAE,OAAO;QAC1C,MAAM,EAAE,EAAE,EAAE,GAAG,iCAAiC,CAAC,OAAO,CAAC,CAAC;QAC1D,2EAA2E;QAC3E,4EAA4E;QAC5E,6EAA6E;QAC7E,kEAAkE;QAClE,MAAM,cAAc,GAAG,MAAM,EAAE;aAC5B,MAAM,CAAC,EAAE,WAAW,EAAE,kBAAkB,CAAC,WAAW,EAAE,CAAC;aACvD,IAAI,CAAC,kBAAkB,CAAC;aACxB,KAAK,CAAC,EAAE,CAAC,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;aAC9C,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,MAAM,aAAa,GAAG,cAAc,CAAC,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,EAAE,WAAW,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, type SQL } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n documentRecordSelection,\n findLocalIdByDocumentId,\n loadDocumentRecord,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\nconst storedDocumentStateSelection = {\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n};\n\nexport interface StoredDocumentState {\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n}\n\nfunction storedDocumentStateQuery(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: SQL | undefined,\n) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(storedDocumentStateSelection)\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));\n}\n\nfunction mapStoredDocumentState(\n row: Awaited<ReturnType<typeof storedDocumentStateQuery>>[number],\n): StoredDocumentState {\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<StoredDocumentState | null> {\n const [row] = await storedDocumentStateQuery(\n execSql,\n eq(documents.localId, localId),\n ).limit(1);\n return row ? mapStoredDocumentState(row) : null;\n}\n\n/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */\nexport async function loadStoredDocumentStates(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: ReadonlyArray<string>,\n): Promise<Map<string, StoredDocumentState>> {\n const states = new Map<string, StoredDocumentState>();\n const unique = Array.from(new Set(localIds));\n // One bind for the app kind; the rest carry local ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await storedDocumentStateQuery(\n execSql,\n inArray(documents.localId, unique.slice(offset, offset + chunkSize)),\n );\n for (const row of rows) states.set(row.id, mapStoredDocumentState(row));\n }\n return states;\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n findLocalIdByDocumentId(execSql, DOCUMENTS_APP_KIND, documentId),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await loadDocumentRecord(execSql, getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
1
+ {"version":3,"file":"rowQueryPersistence.js","sourceRoot":"","sources":["rowQueryPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAY,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAE1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACnF,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,iCAAiC,EAAE,MAAM,0CAA0C,CAAC;AAC7F,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,mBAAmB,EACnB,wBAAwB,EACxB,wBAAwB,EACxB,yBAAyB,EACzB,iBAAiB,EACjB,kBAAkB,EAClB,kBAAkB,GACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAUlE,MAAM,4BAA4B,GAAG;IACnC,GAAG,uBAAuB;IAC1B,qBAAqB,EAAE,kBAAkB,CAAC,WAAW;IACrD,sBAAsB,EAAE,kBAAkB,CAAC,YAAY;IACvD,cAAc,EAAE,sBAAsB,CAAC,IAAI;IAC3C,eAAe,EAAE,kBAAkB,CAAC,KAAK;IACzC,mBAAmB,EAAE,kBAAkB,CAAC,SAAS;CAClD,CAAC;AAOF,SAAS,wBAAwB,CAC/B,OAA4D,EAC5D,QAAyB;IAEzB,MAAM,EAAE,EAAE,EAAE,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c,CAAC,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,aAAa,EAAE,CAAC;YACnB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,EAAE,WAAW,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC;IACpD,CAAC;CACF,CAAC","sourcesContent":["import { and, desc, eq, inArray, notInArray, type SQL } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../documents/documentKinds\";\nimport { HIDDEN_DOCUMENT_SUMMARY_KINDS } from \"../../../documents/documentSummary\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport { sqliteRowsPerStatement } from \"../../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n DocumentRecordRepository,\n documentRecordSelection,\n mapSelectedDocumentRecord,\n} from \"../records\";\nimport type { DocumentsPersistence, StoredDocumentRecord } from \"../types\";\nimport {\n documentSummaryJoin,\n documentSummarySelection,\n getProjectionContainerId,\n getProjectionDocumentKind,\n getProjectionText,\n getProjectionTitle,\n mapDocumentSummary,\n} from \"./documentProjectionRows\";\nimport { getDocumentScope, hasDocumentRow } from \"./documentRows\";\n\n/** The projection columns a stored record was loaded with, if any. */\nexport interface StoredDocumentProjectionState {\n documentKind: StoredDocumentKind;\n text: string | null;\n title: string;\n updatedAt: string;\n}\n\nconst storedDocumentStateSelection = {\n ...documentRecordSelection,\n projectionContainerId: documentProjection.containerId,\n projectionDocumentKind: documentProjection.documentKind,\n projectionText: documentProjectionText.text,\n projectionTitle: documentProjection.title,\n projectionUpdatedAt: documentProjection.updatedAt,\n};\n\nexport interface StoredDocumentState {\n projection: StoredDocumentProjectionState | null;\n record: StoredDocumentRecord;\n}\n\nfunction storedDocumentStateQuery(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: SQL | undefined,\n) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n return db\n .select(storedDocumentStateSelection)\n .from(documents)\n .leftJoin(\n documentProjection,\n eq(documentProjection.localId, documents.localId),\n )\n .leftJoin(\n documentProjectionText,\n eq(documentProjectionText.localId, documentProjection.localId),\n )\n .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), localIds));\n}\n\nfunction mapStoredDocumentState(\n row: Awaited<ReturnType<typeof storedDocumentStateQuery>>[number],\n): StoredDocumentState {\n const {\n projectionContainerId,\n projectionDocumentKind,\n projectionText,\n projectionTitle,\n projectionUpdatedAt,\n ...recordRow\n } = row;\n // Projection columns are NOT NULL, so they are null exactly when the\n // projection row is absent.\n const projectionRow =\n projectionDocumentKind !== null &&\n projectionTitle !== null &&\n projectionUpdatedAt !== null\n ? {\n containerId: projectionContainerId,\n documentKind: projectionDocumentKind,\n text: projectionText,\n title: projectionTitle,\n }\n : undefined;\n return {\n projection:\n projectionRow && projectionUpdatedAt !== null\n ? { ...projectionRow, updatedAt: projectionUpdatedAt }\n : null,\n record: {\n ...mapSelectedDocumentRecord(recordRow),\n containerId: getProjectionContainerId(projectionRow),\n documentKind: getProjectionDocumentKind(projectionRow),\n text: getProjectionText(projectionRow),\n title: getProjectionTitle(projectionRow),\n },\n };\n}\n\n/**\n * The canonical record and its projection from ONE joined statement, so the\n * pair comes from one snapshot and a save inside the same transaction can\n * reuse the projection instead of reading it again.\n */\nexport async function loadStoredDocumentState(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localId: string,\n): Promise<StoredDocumentState | null> {\n const [row] = await storedDocumentStateQuery(\n execSql,\n eq(documents.localId, localId),\n ).limit(1);\n return row ? mapStoredDocumentState(row) : null;\n}\n\n/** `loadStoredDocumentState` for many local ids, one joined read per chunk. */\nexport async function loadStoredDocumentStates(\n execSql: Parameters<DocumentsPersistence[\"loadDocument\"]>[0],\n localIds: ReadonlyArray<string>,\n): Promise<Map<string, StoredDocumentState>> {\n const states = new Map<string, StoredDocumentState>();\n const unique = Array.from(new Set(localIds));\n // One bind for the app kind; the rest carry local ids.\n const chunkSize = sqliteRowsPerStatement(1, 1);\n for (let offset = 0; offset < unique.length; offset += chunkSize) {\n const rows = await storedDocumentStateQuery(\n execSql,\n inArray(documents.localId, unique.slice(offset, offset + chunkSize)),\n );\n for (const row of rows) states.set(row.id, mapStoredDocumentState(row));\n }\n return states;\n}\n\ntype DocumentRowQueryPersistence = Pick<\n DocumentsPersistence,\n | \"listDocuments\"\n | \"findDocumentLocalIdsByContainerId\"\n | \"findLocalIdByDocumentId\"\n | \"hasDocument\"\n | \"documentIdentityMatches\"\n | \"loadDocument\"\n | \"loadDocumentContainer\"\n>;\n\nexport const documentRowQueryPersistence: DocumentRowQueryPersistence = {\n async listDocuments(execSql) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select(documentSummarySelection)\n .from(documentProjection)\n .leftJoin(documents, documentSummaryJoin)\n .where(\n notInArray(documentProjection.documentKind, [\n ...HIDDEN_DOCUMENT_SUMMARY_KINDS,\n ]),\n )\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n\n return rows.map(mapDocumentSummary);\n },\n async findDocumentLocalIdsByContainerId(execSql, containerId) {\n // Unlike `listDocumentsByContainerIdsOrDocumentIds`, this deliberately does\n // NOT drop `HIDDEN_DOCUMENT_SUMMARY_KINDS` — it exists to reach the hidden\n // `organization_profile` document by the container it is linked to, which is\n // how a *foreign* org's display name is found on a member who synced the doc\n // under its server documentId rather than the provisioner-only local alias.\n // `documentProjection` is written and deleted in lockstep with the\n // `documents` rows (all DOCUMENTS_APP_KIND), so filtering by containerId\n // alone is sufficient — no join to `documents` is needed to select localId.\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const rows = await db\n .select({ localId: documentProjection.localId })\n .from(documentProjection)\n .where(eq(documentProjection.containerId, containerId))\n .orderBy(\n desc(documentProjection.updatedAt),\n desc(documentProjection.localId),\n );\n return rows\n .map((row) => row.localId)\n .filter((localId): localId is string => localId !== null);\n },\n findLocalIdByDocumentId: (execSql, documentId) =>\n new DocumentRecordRepository(execSql).findLocalIdByDocumentId(\n DOCUMENTS_APP_KIND,\n documentId,\n ),\n async hasDocument(execSql, localId) {\n return hasDocumentRow(execSql, localId);\n },\n async documentIdentityMatches(\n execSql,\n localId,\n expectedDocumentId,\n expectedRecoveryGeneration,\n ) {\n const record = await new DocumentRecordRepository(\n execSql,\n ).loadDocumentRecord(getDocumentScope(localId));\n return (\n record?.documentId === expectedDocumentId &&\n (record.recoveryGeneration ?? 0) === expectedRecoveryGeneration\n );\n },\n async loadDocument(execSql, localId) {\n return (await loadStoredDocumentState(execSql, localId))?.record ?? null;\n },\n async loadDocumentContainer(execSql, localId) {\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n // Select the row itself, not just its container, so an existing row with a\n // null container is reported as `{ containerId: null }` while a missing row\n // is reported as `undefined` — the caller relies on that distinction to know\n // whether the projection has authoritative placement to defer to.\n const projectionRows = await db\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .limit(1);\n const projectionRow = projectionRows[0];\n if (!projectionRow) {\n return undefined;\n }\n\n return { containerId: projectionRow.containerId };\n },\n};\n"]}
@@ -2,17 +2,16 @@ import { and, eq, isNull } from "drizzle-orm";
2
2
  import { documentAttachmentBlobProjection, documentPendingAttachments, } from "../../../sqlite/schema/index.js";
3
3
  import { getClientSQLitePersistenceRuntime } from "../../../sqlite/sqlitePersistenceRuntime.js";
4
4
  import { runSerializedSqlMutation } from "../../../sqlite/sqlSchema.js";
5
- import { enqueueDocumentPendingUpdateWithHistory, listDocumentPendingUpdates, rekeyDocumentPendingUpdate, replaceDocumentQueuedUpdates, settleDocumentPendingUpdate, unqueueDocumentPendingUpdates, } from "../records/index.js";
6
- import { appendDocumentHistoryUpdates, listDocumentHistoryTailEntries, loadDocumentHistoryRestoreState, readDocumentHistoryTailSize, replaceDocumentHistoryCheckpoint, } from "../records/documentHistoryPersistence.js";
5
+ import { DocumentRecordRepository } from "../records/index.js";
7
6
  import { buildPendingAttachmentRow, mapLocalAttachmentRecord, mapPendingAttachmentRecord, } from "./attachmentRows.js";
8
7
  import { getDocumentScope } from "./documentRows.js";
9
8
  import { queueDocumentAttachmentStorageKeys } from "./orphanSideRows.js";
10
9
  export const documentSyncQueuePersistence = {
11
10
  async listPendingUpdates(execSql, localId) {
12
- return listDocumentPendingUpdates(execSql, getDocumentScope(localId));
11
+ return new DocumentRecordRepository(execSql).listDocumentPendingUpdates(getDocumentScope(localId));
13
12
  },
14
13
  async rekeyPendingUpdate(execSql, id) {
15
- return rekeyDocumentPendingUpdate(execSql, id);
14
+ return new DocumentRecordRepository(execSql).rekeyDocumentPendingUpdate(id);
16
15
  },
17
16
  async listPendingAttachments(execSql, localId) {
18
17
  const { db } = getClientSQLitePersistenceRuntime(execSql);
@@ -59,19 +58,19 @@ export const documentSyncQueuePersistence = {
59
58
  return rows.map(mapLocalAttachmentRecord);
60
59
  },
61
60
  async appendHistoryUpdates(execSql, input) {
62
- await appendDocumentHistoryUpdates(execSql, getDocumentScope(input.localId), input.updates, input.origin);
61
+ await new DocumentRecordRepository(execSql).appendDocumentHistoryUpdates(getDocumentScope(input.localId), input.updates, input.origin);
63
62
  },
64
63
  async loadHistoryRestoreState(execSql, localId) {
65
- return loadDocumentHistoryRestoreState(execSql, getDocumentScope(localId));
64
+ return new DocumentRecordRepository(execSql).loadDocumentHistoryRestoreState(getDocumentScope(localId));
66
65
  },
67
66
  async readHistoryTailSize(execSql, localId) {
68
- return readDocumentHistoryTailSize(execSql, getDocumentScope(localId));
67
+ return new DocumentRecordRepository(execSql).readDocumentHistoryTailSize(getDocumentScope(localId));
69
68
  },
70
69
  async listHistoryTailEntries(execSql, localId) {
71
- return listDocumentHistoryTailEntries(execSql, getDocumentScope(localId));
70
+ return new DocumentRecordRepository(execSql).listDocumentHistoryTailEntries(getDocumentScope(localId));
72
71
  },
73
72
  async replaceHistoryCheckpoint(execSql, input) {
74
- await replaceDocumentHistoryCheckpoint(execSql, getDocumentScope(input.localId), {
73
+ await new DocumentRecordRepository(execSql).replaceDocumentHistoryCheckpoint(getDocumentScope(input.localId), {
75
74
  coveredTailIds: input.coveredTailIds,
76
75
  endVersionVector: input.endVersionVector,
77
76
  ...(input.force === undefined ? {} : { force: input.force }),
@@ -83,12 +82,12 @@ export const documentSyncQueuePersistence = {
83
82
  },
84
83
  async enqueuePendingUpdate(execSql, pendingUpdate, options) {
85
84
  return runSerializedSqlMutation(execSql, async (lockedExecSql) => {
86
- const pendingUpdateId = await enqueueDocumentPendingUpdateWithHistory(lockedExecSql, getDocumentScope(pendingUpdate.localId), pendingUpdate, options);
85
+ const pendingUpdateId = await new DocumentRecordRepository(lockedExecSql).enqueueDocumentPendingUpdateWithHistory(getDocumentScope(pendingUpdate.localId), pendingUpdate, options);
87
86
  return pendingUpdateId !== null;
88
87
  });
89
88
  },
90
89
  async replaceQueuedPendingUpdates(execSql, { localId, ...replacement }) {
91
- return runSerializedSqlMutation(execSql, (lockedExecSql) => replaceDocumentQueuedUpdates(lockedExecSql, getDocumentScope(localId), replacement));
90
+ return runSerializedSqlMutation(execSql, (lockedExecSql) => new DocumentRecordRepository(lockedExecSql).replaceDocumentQueuedUpdates(getDocumentScope(localId), replacement));
92
91
  },
93
92
  async saveLocalAttachment(execSql, attachment) {
94
93
  const updatedAt = new Date().toISOString();
@@ -172,12 +171,12 @@ export const documentSyncQueuePersistence = {
172
171
  },
173
172
  async deletePendingUpdate(execSql, id) {
174
173
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
175
- await settleDocumentPendingUpdate(lockedExecSql, id);
174
+ await new DocumentRecordRepository(lockedExecSql).settleDocumentPendingUpdate(id);
176
175
  });
177
176
  },
178
177
  async deletePendingUpdates(execSql, localId) {
179
178
  await runSerializedSqlMutation(execSql, async (lockedExecSql) => {
180
- await unqueueDocumentPendingUpdates(lockedExecSql, getDocumentScope(localId));
179
+ await new DocumentRecordRepository(lockedExecSql).unqueueDocumentPendingUpdates(getDocumentScope(localId));
181
180
  });
182
181
  },
183
182
  async deletePendingAttachment(execSql, localId, slotId, storageKey) {