@tearleads/client-sdk 0.1.235 → 0.1.237

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 (92) hide show
  1. package/client/containerContents/documentDiscovery.js +1 -1
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/organizations/index.js +1 -1
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationMemberships.d.ts +6 -5
  6. package/client/organizations/organizationMemberships.js +12 -69
  7. package/client/organizations/organizationMemberships.js.map +1 -1
  8. package/client/runtime/workflowRuntime.js +5 -1
  9. package/client/runtime/workflowRuntime.js.map +1 -1
  10. package/data/sqlite/schema/documentRecordSchema.js +7 -0
  11. package/data/sqlite/schema/documentRecordSchema.js.map +1 -1
  12. package/data/sqlite/schema/index.d.ts +0 -45
  13. package/data/sqlite/schema/organizationSyncPauseSchema.js +6 -17
  14. package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -1
  15. package/data/sync/organizationSyncPauseReadMachine.js +29 -0
  16. package/data/sync/organizationSyncPauseReadMachine.js.map +1 -0
  17. package/data/sync/organizationSyncPauses.d.ts +23 -34
  18. package/data/sync/organizationSyncPauses.js +49 -57
  19. package/data/sync/organizationSyncPauses.js.map +1 -1
  20. package/internal/validators/operation/organizationMemberships.d.ts +3 -21
  21. package/internal/validators/operation/organizationMemberships.js +2 -3
  22. package/internal/validators/operation/organizationMemberships.js.map +1 -1
  23. package/internal/validators/response/organizationMembership.d.ts +3 -3
  24. package/internal/validators/response/organizationMembership.js +3 -3
  25. package/internal/validators/response/organizationMembership.js.map +1 -1
  26. package/package.json +1 -1
  27. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  28. package/stores/container-contents/containerContentsStore.js +0 -2
  29. package/stores/container-contents/containerContentsStore.js.map +1 -1
  30. package/stores/container-contents/syncAgent/index.js +6 -0
  31. package/stores/container-contents/syncAgent/index.js.map +1 -1
  32. package/stores/container-contents/types.d.ts +0 -6
  33. package/stores/container-contents/types.js.map +1 -1
  34. package/stores/documents/documentStore/index.js +3 -4
  35. package/stores/documents/documentStore/index.js.map +1 -1
  36. package/stores/documents/documentStore/initialization/index.js +7 -7
  37. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  38. package/stores/documents/documentStore/sync/index.js +2 -5
  39. package/stores/documents/documentStore/sync/index.js.map +1 -1
  40. package/stores/documents/documentStore/sync/syncRequest.js +9 -2
  41. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  42. package/stores/documents/registry.d.ts +1 -34
  43. package/stores/documents/registry.js +4 -78
  44. package/stores/documents/registry.js.map +1 -1
  45. package/workflows/container-contents/metadata/metadataRemoteSync.js +1 -0
  46. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  47. package/workflows/container-contents/pendingWrites/deferredTails.js +4 -0
  48. package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
  49. package/workflows/container-contents/remoteHydration/index.js +1 -1
  50. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  51. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +2 -4
  52. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -1
  53. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +3 -3
  54. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  55. package/workflows/container-contents/syncPause/discoveryGuard.js +7 -6
  56. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  57. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -2
  58. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  59. package/workflows/documents/sync/index.js +8 -0
  60. package/workflows/documents/sync/index.js.map +1 -1
  61. package/workflows/documents/sync/readOnlySync.js +6 -0
  62. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  63. package/workflows/documents/sync/remoteDocumentSyncPass.d.ts +7 -1
  64. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -1
  65. package/workflows/documents/sync/syncAttemptPlanning.js +24 -8
  66. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  67. package/workflows/documents/syncFailures/index.js +6 -3
  68. package/workflows/documents/syncFailures/index.js.map +1 -1
  69. package/workflows/documents/syncFailures/syncAbandon.js +21 -0
  70. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  71. package/workflows/organizations/index.d.ts +1 -1
  72. package/workflows/organizations/index.js +1 -1
  73. package/workflows/organizations/index.js.map +1 -1
  74. package/workflows/organizations/memberships/organizationMemberships.d.ts +10 -35
  75. package/workflows/organizations/memberships/organizationMemberships.js +27 -44
  76. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  77. package/workflows/shared/runtimeInput.d.ts +11 -1
  78. package/workflows/shared/runtimeInput.js.map +1 -1
  79. package/workflows/sync/coordination.d.ts +1 -1
  80. package/workflows/sync/coordination.js +1 -1
  81. package/workflows/sync/coordination.js.map +1 -1
  82. package/workflows/sync/index.d.ts +1 -1
  83. package/workflows/sync/index.js +1 -1
  84. package/workflows/sync/index.js.map +1 -1
  85. package/data/persistence/container-contents/exclusiveDocumentPlacements.js +0 -61
  86. package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +0 -1
  87. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +0 -76
  88. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +0 -1
  89. package/stores/documents/removedDocumentStore.js +0 -40
  90. package/stores/documents/removedDocumentStore.js.map +0 -1
  91. package/workflows/container-contents/syncPause/documentRemoval.js +0 -165
  92. package/workflows/container-contents/syncPause/documentRemoval.js.map +0 -1
@@ -1,61 +0,0 @@
1
- import { and, eq, inArray } from "drizzle-orm";
2
- import { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
3
- import { documentContainerProjection } from "../../sqlite/schema/documentProjectionSchema.js";
4
- import { documents } from "../../sqlite/schema/documentRecordSchema.js";
5
- import { SQLITE_BOUND_VARIABLE_BUDGET } from "../../sqlite/sqliteBindBudget.js";
6
- import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
7
- // Leave room for the fixed binds each statement adds beside its id list.
8
- const ID_BATCH_SIZE = SQLITE_BOUND_VARIABLE_BUDGET - 8;
9
- function batches(values) {
10
- const result = [];
11
- for (let index = 0; index < values.length; index += ID_BATCH_SIZE) {
12
- result.push(values.slice(index, index + ID_BATCH_SIZE));
13
- }
14
- return result;
15
- }
16
- /**
17
- * Local ids of the documents whose every placement is one of `containerIds`.
18
- * A document also placed in a container outside the set stays: removing these
19
- * containers must not take a document another folder still shows.
20
- */
21
- export async function listDocumentLocalIdsPlacedOnlyIn(execSql, containerIds) {
22
- const targets = new Set(containerIds);
23
- if (targets.size === 0)
24
- return [];
25
- const { db } = getClientSQLitePersistenceRuntime(execSql);
26
- const placedDocumentIds = new Set();
27
- for (const batch of batches([...targets])) {
28
- const rows = await db
29
- .select({ documentId: documentContainerProjection.documentId })
30
- .from(documentContainerProjection)
31
- .where(inArray(documentContainerProjection.containerId, batch));
32
- for (const row of rows)
33
- placedDocumentIds.add(row.documentId);
34
- }
35
- const exclusiveDocumentIds = new Set(placedDocumentIds);
36
- for (const batch of batches([...placedDocumentIds])) {
37
- const rows = await db
38
- .select({
39
- containerId: documentContainerProjection.containerId,
40
- documentId: documentContainerProjection.documentId,
41
- })
42
- .from(documentContainerProjection)
43
- .where(inArray(documentContainerProjection.documentId, batch));
44
- for (const row of rows) {
45
- if (!targets.has(row.containerId)) {
46
- exclusiveDocumentIds.delete(row.documentId);
47
- }
48
- }
49
- }
50
- const localIds = [];
51
- for (const batch of batches([...exclusiveDocumentIds])) {
52
- const rows = await db
53
- .select({ localId: documents.localId })
54
- .from(documents)
55
- .where(and(eq(documents.appKind, DOCUMENTS_APP_KIND), inArray(documents.documentId, batch)));
56
- for (const row of rows)
57
- localIds.push(row.localId);
58
- }
59
- return localIds.sort();
60
- }
61
- //# sourceMapping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AAI,CAAC,SAAS,CAAC;aACf,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC,EACzC,OAAO,CAAC,SAAS,CAAC,UAAU,EAAE,KAAK,CAAC,CACrC,CACF,CAAC;QACJ,KAAK,MAAM,GAAG,IAAI,IAAI;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nimport { documentContainerProjection } from \"../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../sqlite/schema/documentRecordSchema\";\nimport { SQLITE_BOUND_VARIABLE_BUDGET } from \"../../sqlite/sqliteBindBudget\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n// Leave room for the fixed binds each statement adds beside its id list.\nconst ID_BATCH_SIZE = SQLITE_BOUND_VARIABLE_BUDGET - 8;\n\nfunction batches<T>(values: readonly T[]): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += ID_BATCH_SIZE) {\n result.push(values.slice(index, index + ID_BATCH_SIZE));\n }\n return result;\n}\n\n/**\n * Local ids of the documents whose every placement is one of `containerIds`.\n * A document also placed in a container outside the set stays: removing these\n * containers must not take a document another folder still shows.\n */\nexport async function listDocumentLocalIdsPlacedOnlyIn(\n execSql: ExecSql,\n containerIds: readonly string[],\n): Promise<string[]> {\n const targets = new Set(containerIds);\n if (targets.size === 0) return [];\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const placedDocumentIds = new Set<string>();\n for (const batch of batches([...targets])) {\n const rows = await db\n .select({ documentId: documentContainerProjection.documentId })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.containerId, batch));\n for (const row of rows) placedDocumentIds.add(row.documentId);\n }\n\n const exclusiveDocumentIds = new Set(placedDocumentIds);\n for (const batch of batches([...placedDocumentIds])) {\n const rows = await db\n .select({\n containerId: documentContainerProjection.containerId,\n documentId: documentContainerProjection.documentId,\n })\n .from(documentContainerProjection)\n .where(inArray(documentContainerProjection.documentId, batch));\n for (const row of rows) {\n if (!targets.has(row.containerId)) {\n exclusiveDocumentIds.delete(row.documentId);\n }\n }\n }\n\n const localIds: string[] = [];\n for (const batch of batches([...exclusiveDocumentIds])) {\n const rows = await db\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, batch),\n ),\n );\n for (const row of rows) localIds.push(row.localId);\n }\n return localIds.sort();\n}\n"]}
@@ -1,76 +0,0 @@
1
- import { removeOrganizationContentUnlessPending } from "../../../workflows/container-contents/syncPause/documentRemoval.js";
2
- import { reclaimDocumentOrphanBlobs } from "../../../workflows/documents/index.js";
3
- import { getOrCreateOrganizationSyncPauses, isRetainedWhileSyncPaused, } from "../../../workflows/sync/coordination.js";
4
- import { emitPersistedDocumentDeletion, hasQueuedDocumentStoreWrites, restoreDocumentStore, retireDocumentStore, } from "../../documents/registry.js";
5
- import { updateContainerContentsSnapshot } from "../state.js";
6
- /** The local containers forgetting an organization's content removes. */
7
- function listForgettableOrganizationContainerIds(state, organizationId) {
8
- return [...state.containersById.values()].flatMap(({ container }) => container.organizationId === organizationId &&
9
- !isRetainedWhileSyncPaused(container)
10
- ? [container.id]
11
- : []);
12
- }
13
- /**
14
- * Removes one organization's content from this device after its sync was
15
- * paused: every container except its retained metadata root, and every
16
- * document placed only in those containers. Nothing changes on the server, so
17
- * resuming downloads it again.
18
- *
19
- * Unsynced work is never removed: the removal refuses while any pending write
20
- * touches the organization, checked under the same lock as the deletions, and
21
- * while an open store holds edits for any of its documents that have not
22
- * reached SQLite. It also refuses the session's active organization, whose
23
- * root the session still writes to. Returns whether nothing is left to retry.
24
- */
25
- async function forgetOrganizationContent(state, organizationId, isCurrent) {
26
- if (state.runtime.infra.dbStatus !== "ready" || !state.snapshot.ready) {
27
- return false;
28
- }
29
- if (state.runtime.auth.organizationId === organizationId)
30
- return false;
31
- const containerIds = listForgettableOrganizationContainerIds(state, organizationId);
32
- const { documentProjectors, execSql } = state.runtime.infra;
33
- const { domainScope } = state.runtime.state;
34
- // Switching into the organization mid-removal stops it before any deletion.
35
- const stillCurrent = () => isCurrent() && state.runtime.auth.organizationId !== organizationId;
36
- await state.persistence.ensureSchema(execSql);
37
- const pauses = getOrCreateOrganizationSyncPauses(domainScope);
38
- const removal = await removeOrganizationContentUnlessPending({
39
- containerIds,
40
- deleteContainers: (lockedExecSql, removals) => state.persistence.deleteContainers(lockedExecSql, removals, {
41
- stillCurrent,
42
- }),
43
- documentProjectors,
44
- execSql,
45
- hasQueuedWrites: (localId) => hasQueuedDocumentStoreWrites(domainScope, localId),
46
- organizationId,
47
- restoreDocument: (localId) => restoreDocumentStore(domainScope, localId),
48
- retireDocument: (localId) => retireDocumentStore(domainScope, localId, () => pauses.isOrganizationPaused(organizationId)),
49
- stillCurrent,
50
- });
51
- for (const localId of removal.deletedLocalIds) {
52
- emitPersistedDocumentDeletion(domainScope, localId);
53
- }
54
- if (removal.deletedLocalIds.length > 0) {
55
- void reclaimDocumentOrphanBlobs(state.runtime);
56
- }
57
- for (const containerId of removal.deletedContainerIds) {
58
- state.containersById.delete(containerId);
59
- }
60
- if (removal.deletedContainerIds.length > 0 && state.initialized) {
61
- updateContainerContentsSnapshot(state);
62
- }
63
- return removal.status === "removed";
64
- }
65
- /** Runs `forgetOrganizationContent` in the store's container write chain. */
66
- export function createForgetOrganizationContentMethod(state, chainContainerWrite) {
67
- return async (organizationId) => {
68
- let forgotten = false;
69
- await chainContainerWrite(state, async (isCurrent) => {
70
- forgotten = await forgetOrganizationContent(state, organizationId, isCurrent);
71
- return null;
72
- }, listForgettableOrganizationContainerIds(state, organizationId));
73
- return forgotten;
74
- };
75
- }
76
- //# sourceMappingURL=forgetOrganizationContentOperation.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"forgetOrganizationContentOperation.js","sourceRoot":"","sources":["forgetOrganizationContentOperation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sCAAsC,EAAE,MAAM,iEAAiE,CAAC;AACzH,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EACL,iCAAiC,EACjC,yBAAyB,GAC1B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,0BAA0B,CAAC;AAElC,OAAO,EAAE,+BAA+B,EAAE,MAAM,UAAU,CAAC;AAG3D,yEAAyE;AACzE,SAAS,uCAAuC,CAC9C,KAA0D,EAC1D,cAAsB;IAEtB,OAAO,CAAC,GAAG,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,CAClE,SAAS,CAAC,cAAc,KAAK,cAAc;QAC3C,CAAC,yBAAyB,CAAC,SAAS,CAAC;QACnC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC;QAChB,CAAC,CAAC,EAAE,CACP,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;GAWG;AACH,KAAK,UAAU,yBAAyB,CACtC,KAAkC,EAClC,cAAsB,EACtB,SAA8B;IAE9B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QACtE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,KAAK,cAAc;QAAE,OAAO,KAAK,CAAC;IACvE,MAAM,YAAY,GAAG,uCAAuC,CAC1D,KAAK,EACL,cAAc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K,0BAA0B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,WAAW,IAAI,OAAO,CAAC,mBAAmB,EAAE,CAAC;QACtD,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC3C,CAAC;IACD,IAAI,OAAO,CAAC,mBAAmB,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAChE,+BAA+B,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IACD,OAAO,OAAO,CAAC,MAAM,KAAK,SAAS,CAAC;AACtC,CAAC;AAQD,6EAA6E;AAC7E,MAAM,UAAU,qCAAqC,CACnD,KAAkC,EAClC,mBAAwC;IAExC,OAAO,KAAK,EAAE,cAAc,EAAE,EAAE;QAC9B,IAAI,SAAS,GAAG,KAAK,CAAC;QACtB,MAAM,mBAAmB,CACvB,KAAK,EACL,KAAK,EAAE,SAAS,EAAE,EAAE;YAClB,SAAS,GAAG,MAAM,yBAAyB,CACzC,KAAK,EACL,cAAc,EACd,SAAS,CACV,CAAC;YACF,OAAO,IAAI,CAAC;QACd,CAAC,EACD,uCAAuC,CAAC,KAAK,EAAE,cAAc,CAAC,CAC/D,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { removeOrganizationContentUnlessPending } from \"../../../workflows/container-contents/syncPause/documentRemoval\";\nimport { reclaimDocumentOrphanBlobs } from \"../../../workflows/documents\";\nimport {\n getOrCreateOrganizationSyncPauses,\n isRetainedWhileSyncPaused,\n} from \"../../../workflows/sync/coordination\";\nimport {\n emitPersistedDocumentDeletion,\n hasQueuedDocumentStoreWrites,\n restoreDocumentStore,\n retireDocumentStore,\n} from \"../../documents/registry\";\nimport type { ContainerWriteGuard } from \"../remoteWrites/writeGeneration\";\nimport { updateContainerContentsSnapshot } from \"../state\";\nimport type { ContainerContentsStoreState } from \"../types\";\n\n/** The local containers forgetting an organization's content removes. */\nfunction listForgettableOrganizationContainerIds(\n state: Pick<ContainerContentsStoreState, \"containersById\">,\n organizationId: string,\n): string[] {\n return [...state.containersById.values()].flatMap(({ container }) =>\n container.organizationId === organizationId &&\n !isRetainedWhileSyncPaused(container)\n ? [container.id]\n : [],\n );\n}\n\n/**\n * Removes one organization's content from this device after its sync was\n * paused: every container except its retained metadata root, and every\n * document placed only in those containers. Nothing changes on the server, so\n * resuming downloads it again.\n *\n * Unsynced work is never removed: the removal refuses while any pending write\n * touches the organization, checked under the same lock as the deletions, and\n * while an open store holds edits for any of its documents that have not\n * reached SQLite. It also refuses the session's active organization, whose\n * root the session still writes to. Returns whether nothing is left to retry.\n */\nasync function forgetOrganizationContent(\n state: ContainerContentsStoreState,\n organizationId: string,\n isCurrent: ContainerWriteGuard,\n): Promise<boolean> {\n if (state.runtime.infra.dbStatus !== \"ready\" || !state.snapshot.ready) {\n return false;\n }\n if (state.runtime.auth.organizationId === organizationId) return false;\n const containerIds = listForgettableOrganizationContainerIds(\n state,\n organizationId,\n );\n const { documentProjectors, execSql } = state.runtime.infra;\n const { domainScope } = state.runtime.state;\n // Switching into the organization mid-removal stops it before any deletion.\n const stillCurrent = () =>\n isCurrent() && state.runtime.auth.organizationId !== organizationId;\n await state.persistence.ensureSchema(execSql);\n const pauses = getOrCreateOrganizationSyncPauses(domainScope);\n const removal = await removeOrganizationContentUnlessPending({\n containerIds,\n deleteContainers: (lockedExecSql, removals) =>\n state.persistence.deleteContainers(lockedExecSql, removals, {\n stillCurrent,\n }),\n documentProjectors,\n execSql,\n hasQueuedWrites: (localId) =>\n hasQueuedDocumentStoreWrites(domainScope, localId),\n organizationId,\n restoreDocument: (localId) => restoreDocumentStore(domainScope, localId),\n retireDocument: (localId) =>\n retireDocumentStore(domainScope, localId, () =>\n pauses.isOrganizationPaused(organizationId),\n ),\n stillCurrent,\n });\n for (const localId of removal.deletedLocalIds) {\n emitPersistedDocumentDeletion(domainScope, localId);\n }\n if (removal.deletedLocalIds.length > 0) {\n void reclaimDocumentOrphanBlobs(state.runtime);\n }\n for (const containerId of removal.deletedContainerIds) {\n state.containersById.delete(containerId);\n }\n if (removal.deletedContainerIds.length > 0 && state.initialized) {\n updateContainerContentsSnapshot(state);\n }\n return removal.status === \"removed\";\n}\n\ntype ContainerWriteChain = (\n state: ContainerContentsStoreState,\n work: (isCurrent: () => boolean) => ContainerContentsStoreState[\"writeChain\"],\n changedIds: readonly string[],\n) => ContainerContentsStoreState[\"writeChain\"];\n\n/** Runs `forgetOrganizationContent` in the store's container write chain. */\nexport function createForgetOrganizationContentMethod(\n state: ContainerContentsStoreState,\n chainContainerWrite: ContainerWriteChain,\n): (organizationId: string) => Promise<boolean> {\n return async (organizationId) => {\n let forgotten = false;\n await chainContainerWrite(\n state,\n async (isCurrent) => {\n forgotten = await forgetOrganizationContent(\n state,\n organizationId,\n isCurrent,\n );\n return null;\n },\n listForgettableOrganizationContainerIds(state, organizationId),\n );\n return forgotten;\n };\n}\n"]}
@@ -1,40 +0,0 @@
1
- const REMOVED_DOCUMENT_MESSAGE = "This document was removed while its organization's sync is paused";
2
- /**
3
- * Stands in for a store whose document a paused organization's cleanup
4
- * removed. It keeps showing the last snapshot, read-only, and does nothing
5
- * else, so an open editor neither recreates the document nor downloads it
6
- * while the pause lasts.
7
- */
8
- export function createRemovedDocumentStore(lastSnapshot) {
9
- const snapshot = {
10
- ...lastSnapshot,
11
- canAttach: false,
12
- canWrite: false,
13
- syncing: false,
14
- };
15
- const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));
16
- return {
17
- addRow: refuse,
18
- assertCanRotateContentKey: refuse,
19
- attachFiles: () => undefined,
20
- discardLocalState: async () => false,
21
- ensureInitialized: async () => false,
22
- getSnapshot: () => snapshot,
23
- hasQueuedWrites: () => false,
24
- hasUnsavedLocalEdits: () => false,
25
- removeAttachment: () => undefined,
26
- removeRow: refuse,
27
- replaceAttachment: refuse,
28
- requestRemoteSync: () => undefined,
29
- requestRemoteSyncAndWait: async () => false,
30
- requestSync: () => undefined,
31
- relink: async () => null,
32
- restoreContent: async () => false,
33
- setStructuredFields: refuse,
34
- setText: refuse,
35
- subscribe: () => () => undefined,
36
- updateRowFields: refuse,
37
- updateRuntime: () => undefined,
38
- };
39
- }
40
- //# sourceMappingURL=removedDocumentStore.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"removedDocumentStore.js","sourceRoot":"","sources":["removedDocumentStore.ts"],"names":[],"mappings":"AAEA,MAAM,wBAAwB,GAC5B,mEAAmE,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CACxC,YAA8B;IAE9B,MAAM,QAAQ,GAAqB;QACjC,GAAG,YAAY;QACf,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;QACf,OAAO,EAAE,KAAK;KACf,CAAC;IACF,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC,CAAC;IACzE,OAAO;QACL,MAAM,EAAE,MAAM;QACd,yBAAyB,EAAE,MAAM;QACjC,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,iBAAiB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACpC,WAAW,EAAE,GAAG,EAAE,CAAC,QAAQ;QAC3B,eAAe,EAAE,GAAG,EAAE,CAAC,KAAK;QAC5B,oBAAoB,EAAE,GAAG,EAAE,CAAC,KAAK;QACjC,gBAAgB,EAAE,GAAG,EAAE,CAAC,SAAS;QACjC,SAAS,EAAE,MAAM;QACjB,iBAAiB,EAAE,MAAM;QACzB,iBAAiB,EAAE,GAAG,EAAE,CAAC,SAAS;QAClC,wBAAwB,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QAC3C,WAAW,EAAE,GAAG,EAAE,CAAC,SAAS;QAC5B,MAAM,EAAE,KAAK,IAAI,EAAE,CAAC,IAAI;QACxB,cAAc,EAAE,KAAK,IAAI,EAAE,CAAC,KAAK;QACjC,mBAAmB,EAAE,MAAM;QAC3B,OAAO,EAAE,MAAM;QACf,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,CAAC,SAAS;QAChC,eAAe,EAAE,MAAM;QACvB,aAAa,EAAE,GAAG,EAAE,CAAC,SAAS;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["import type { DocumentSnapshot, DocumentStore } from \"./types\";\n\nconst REMOVED_DOCUMENT_MESSAGE =\n \"This document was removed while its organization's sync is paused\";\n\n/**\n * Stands in for a store whose document a paused organization's cleanup\n * removed. It keeps showing the last snapshot, read-only, and does nothing\n * else, so an open editor neither recreates the document nor downloads it\n * while the pause lasts.\n */\nexport function createRemovedDocumentStore(\n lastSnapshot: DocumentSnapshot,\n): DocumentStore {\n const snapshot: DocumentSnapshot = {\n ...lastSnapshot,\n canAttach: false,\n canWrite: false,\n syncing: false,\n };\n const refuse = () => Promise.reject(new Error(REMOVED_DOCUMENT_MESSAGE));\n return {\n addRow: refuse,\n assertCanRotateContentKey: refuse,\n attachFiles: () => undefined,\n discardLocalState: async () => false,\n ensureInitialized: async () => false,\n getSnapshot: () => snapshot,\n hasQueuedWrites: () => false,\n hasUnsavedLocalEdits: () => false,\n removeAttachment: () => undefined,\n removeRow: refuse,\n replaceAttachment: refuse,\n requestRemoteSync: () => undefined,\n requestRemoteSyncAndWait: async () => false,\n requestSync: () => undefined,\n relink: async () => null,\n restoreContent: async () => false,\n setStructuredFields: refuse,\n setText: refuse,\n subscribe: () => () => undefined,\n updateRowFields: refuse,\n updateRuntime: () => undefined,\n };\n}\n"]}
@@ -1,165 +0,0 @@
1
- import { deleteDocumentPlacements } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
- import { listDocumentLocalIdsPlacedOnlyIn } from "../../../data/persistence/container-contents/exclusiveDocumentPlacements.js";
3
- import { runSerializedSqlMutation } from "../../../data/sqlite/sqlExec.js";
4
- import { registerClientSQLiteCommitGuard } from "../../../data/sqlite/sqliteCommitGuards.js";
5
- import { defaultDocumentsPersistence, deletePersistedDocument, } from "../../documents/index.js";
6
- import { OrganizationSyncPauseRepository } from "../../sync/coordination.js";
7
- import { carriesLocalWrites, listPendingWrites } from "../pendingWrites/index.js";
8
- // The deletion cascade binds several values per container across its
9
- // statements (its tombstone row alone binds a value per column), so a large
10
- // organization is removed in batches that stay within SQLite's bind budget.
11
- const CONTAINER_REMOVAL_BATCH_SIZE = 50;
12
- const refused = (status) => ({
13
- deletedContainerIds: [],
14
- deletedLocalIds: [],
15
- status,
16
- });
17
- /** Stops at the first batch that is no longer current. */
18
- async function deleteContainersInBatches(lockedExecSql, containerIds, deleteContainers) {
19
- const removedAt = new Date().toISOString();
20
- const deleted = [];
21
- for (let index = 0; index < containerIds.length; index += CONTAINER_REMOVAL_BATCH_SIZE) {
22
- const batch = containerIds.slice(index, index + CONTAINER_REMOVAL_BATCH_SIZE);
23
- const removed = await deleteContainers(lockedExecSql, batch.map((containerId) => ({
24
- containerId,
25
- reason: "access_revoked",
26
- updatedAt: removedAt,
27
- })));
28
- deleted.push(...removed);
29
- if (removed.length !== batch.length)
30
- break;
31
- }
32
- return deleted;
33
- }
34
- class DocumentRemovalNotCurrent extends Error {
35
- }
36
- /**
37
- * Deletes one document unless the removal stopped being current or a store
38
- * queued a write for it. The check runs as a commit guard, in the same
39
- * synchronous slice as the COMMIT, so an edit queued while the rows were being
40
- * deleted rolls the deletion back. When the COMMIT-time check passes, the
41
- * document's store is retired in that same slice, so an open editor turns
42
- * read-only before the deletion commits and no later edit can be accepted and
43
- * lost; a COMMIT that then fails restores it.
44
- */
45
- async function deleteDocumentUnlessEdited(input) {
46
- const expectedRecord = await defaultDocumentsPersistence.loadDocument(input.execSql, input.localId);
47
- if (!expectedRecord)
48
- return false;
49
- // The guard runs once when registered and again right before the COMMIT;
50
- // only that last run retires the store.
51
- let guardRuns = 0;
52
- let retired = false;
53
- try {
54
- const deleted = await deletePersistedDocument({
55
- beforeDeleteInTransaction: async (transactionExecSql) => {
56
- await new OrganizationSyncPauseRepository(transactionExecSql).recordPauseRemovedDocument({
57
- localId: input.localId,
58
- organizationId: input.organizationId,
59
- });
60
- registerClientSQLiteCommitGuard(transactionExecSql, () => {
61
- if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {
62
- throw new DocumentRemovalNotCurrent();
63
- }
64
- guardRuns += 1;
65
- if (guardRuns > 1) {
66
- retired = true;
67
- input.retireDocument(input.localId);
68
- }
69
- });
70
- },
71
- deleteDocumentPlacements,
72
- documentProjectors: input.documentProjectors,
73
- execSql: input.execSql,
74
- expectedRecord,
75
- localId: input.localId,
76
- persistence: defaultDocumentsPersistence,
77
- });
78
- if (!deleted && retired)
79
- input.restoreDocument(input.localId);
80
- return deleted;
81
- }
82
- catch (error) {
83
- if (retired)
84
- input.restoreDocument(input.localId);
85
- if (error instanceof DocumentRemovalNotCurrent)
86
- return false;
87
- throw error;
88
- }
89
- }
90
- /**
91
- * Removes a paused organization's containers and the documents placed only in
92
- * them, unless a persisted pending write (a queued update, a deferred tail, an
93
- * intent, or an attachment upload) touches the organization, those
94
- * containers, or those documents. The scan and every deletion hold one SQLite
95
- * mutation lock, so no persisted write can land between them.
96
- *
97
- * An open store may also hold edits that have not reached SQLite yet, so
98
- * the removal refuses while any targeted document has queued writes; they
99
- * persist as pending writes and upload, and a later pass removes the rest.
100
- * The containers go first, under `stillCurrent`; documents are deleted only
101
- * after every container was, each under a commit guard against an edit
102
- * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local
103
- * copy, like any document whose container this device lost. Documents that
104
- * were already detached are never touched: they may be the only copy of work
105
- * a recovery still needs.
106
- */
107
- /** Deletes documents in order until the removal stops being current. */
108
- async function deleteUneditedDocuments(input, lockedExecSql, localIds) {
109
- const deletedLocalIds = [];
110
- for (const localId of localIds) {
111
- if (!input.stillCurrent())
112
- break;
113
- if (await deleteDocumentUnlessEdited({
114
- documentProjectors: input.documentProjectors,
115
- execSql: lockedExecSql,
116
- hasQueuedWrites: input.hasQueuedWrites,
117
- localId,
118
- organizationId: input.organizationId,
119
- restoreDocument: input.restoreDocument,
120
- retireDocument: input.retireDocument,
121
- stillCurrent: input.stillCurrent,
122
- })) {
123
- deletedLocalIds.push(localId);
124
- }
125
- }
126
- return deletedLocalIds;
127
- }
128
- export async function removeOrganizationContentUnlessPending(input) {
129
- return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {
130
- const containerIds = new Set(input.containerIds);
131
- const localIds = await listDocumentLocalIdsPlacedOnlyIn(lockedExecSql, input.containerIds);
132
- if (containerIds.size === 0 && localIds.length === 0) {
133
- return {
134
- deletedContainerIds: [],
135
- deletedLocalIds: [],
136
- status: "removed",
137
- };
138
- }
139
- const documentIds = new Set(localIds);
140
- const pending = await listPendingWrites(lockedExecSql);
141
- if (pending.some((item) => carriesLocalWrites(item) &&
142
- (item.organizationId === input.organizationId ||
143
- (item.containerId !== null && containerIds.has(item.containerId)) ||
144
- documentIds.has(item.localId)))) {
145
- return refused("pending-writes");
146
- }
147
- if (localIds.some(input.hasQueuedWrites))
148
- return refused("queued-edits");
149
- const deletedContainerIds = await deleteContainersInBatches(lockedExecSql, [...containerIds], input.deleteContainers);
150
- if (deletedContainerIds.length !== containerIds.size) {
151
- return {
152
- deletedContainerIds,
153
- deletedLocalIds: [],
154
- status: "interrupted",
155
- };
156
- }
157
- const deletedLocalIds = await deleteUneditedDocuments(input, lockedExecSql, localIds);
158
- return {
159
- deletedContainerIds,
160
- deletedLocalIds,
161
- status: deletedLocalIds.length === localIds.length ? "removed" : "interrupted",
162
- };
163
- });
164
- }
165
- //# sourceMappingURL=documentRemoval.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"documentRemoval.js","sourceRoot":"","sources":["documentRemoval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qFAAqF,CAAC;AAC/H,OAAO,EAAE,gCAAgC,E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tB,CAAC;QACJ,CAAC;QACD,MAAM,eAAe,GAAG,MAAM,uBAAuB,CACnD,KAAK,EACL,aAAa,EACb,QAAQ,CACT,CAAC;QACF,OAAO;YACL,mBAAmB;YACnB,eAAe;YACf,MAAM,EACJ,eAAe,CAAC,MAAM,KAAK,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa;SACzE,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deleteDocumentPlacements } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { listDocumentLocalIdsPlacedOnlyIn } from \"../../../data/persistence/container-contents/exclusiveDocumentPlacements\";\nimport { runSerializedSqlMutation } from \"../../../data/sqlite/sqlExec\";\nimport { registerClientSQLiteCommitGuard } from \"../../../data/sqlite/sqliteCommitGuards\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n defaultDocumentsPersistence,\n deletePersistedDocument,\n} from \"../../documents\";\nimport { OrganizationSyncPauseRepository } from \"../../sync/coordination\";\nimport { carriesLocalWrites, listPendingWrites } from \"../pendingWrites\";\nimport type { ContainerContentsWorkflowRuntimeInfra } from \"../runtime\";\n\nexport interface OrganizationContentRemoval {\n /**\n * `removed` when every targeted container and document is gone.\n * `pending-writes` and `queued-edits` refused before deleting anything.\n * `interrupted` stopped part way: the removal stopped being current, or a\n * document was edited while it ran and stayed.\n */\n readonly status:\n | \"removed\"\n | \"pending-writes\"\n | \"queued-edits\"\n | \"interrupted\";\n readonly deletedContainerIds: readonly string[];\n readonly deletedLocalIds: readonly string[];\n}\n\n// The deletion cascade binds several values per container across its\n// statements (its tombstone row alone binds a value per column), so a large\n// organization is removed in batches that stay within SQLite's bind budget.\nconst CONTAINER_REMOVAL_BATCH_SIZE = 50;\n\nconst refused = (\n status: \"pending-writes\" | \"queued-edits\",\n): OrganizationContentRemoval => ({\n deletedContainerIds: [],\n deletedLocalIds: [],\n status,\n});\n\ninterface ContainerRemoval {\n readonly containerId: string;\n readonly reason: \"access_revoked\";\n readonly updatedAt: string;\n}\n\n/** Stops at the first batch that is no longer current. */\nasync function deleteContainersInBatches(\n lockedExecSql: ExecSql,\n containerIds: readonly string[],\n deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>,\n): Promise<string[]> {\n const removedAt = new Date().toISOString();\n const deleted: string[] = [];\n for (\n let index = 0;\n index < containerIds.length;\n index += CONTAINER_REMOVAL_BATCH_SIZE\n ) {\n const batch = containerIds.slice(\n index,\n index + CONTAINER_REMOVAL_BATCH_SIZE,\n );\n const removed = await deleteContainers(\n lockedExecSql,\n batch.map((containerId) => ({\n containerId,\n reason: \"access_revoked\",\n updatedAt: removedAt,\n })),\n );\n deleted.push(...removed);\n if (removed.length !== batch.length) break;\n }\n return deleted;\n}\n\nclass DocumentRemovalNotCurrent extends Error {}\n\n/**\n * Deletes one document unless the removal stopped being current or a store\n * queued a write for it. The check runs as a commit guard, in the same\n * synchronous slice as the COMMIT, so an edit queued while the rows were being\n * deleted rolls the deletion back. When the COMMIT-time check passes, the\n * document's store is retired in that same slice, so an open editor turns\n * read-only before the deletion commits and no later edit can be accepted and\n * lost; a COMMIT that then fails restores it.\n */\nasync function deleteDocumentUnlessEdited(input: {\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly localId: string;\n readonly organizationId: string;\n readonly restoreDocument: (localId: string) => void;\n readonly retireDocument: (localId: string) => void;\n readonly stillCurrent: () => boolean;\n}): Promise<boolean> {\n const expectedRecord = await defaultDocumentsPersistence.loadDocument(\n input.execSql,\n input.localId,\n );\n if (!expectedRecord) return false;\n // The guard runs once when registered and again right before the COMMIT;\n // only that last run retires the store.\n let guardRuns = 0;\n let retired = false;\n try {\n const deleted = await deletePersistedDocument({\n beforeDeleteInTransaction: async (transactionExecSql) => {\n await new OrganizationSyncPauseRepository(\n transactionExecSql,\n ).recordPauseRemovedDocument({\n localId: input.localId,\n organizationId: input.organizationId,\n });\n registerClientSQLiteCommitGuard(transactionExecSql, () => {\n if (!input.stillCurrent() || input.hasQueuedWrites(input.localId)) {\n throw new DocumentRemovalNotCurrent();\n }\n guardRuns += 1;\n if (guardRuns > 1) {\n retired = true;\n input.retireDocument(input.localId);\n }\n });\n },\n deleteDocumentPlacements,\n documentProjectors: input.documentProjectors,\n execSql: input.execSql,\n expectedRecord,\n localId: input.localId,\n persistence: defaultDocumentsPersistence,\n });\n if (!deleted && retired) input.restoreDocument(input.localId);\n return deleted;\n } catch (error) {\n if (retired) input.restoreDocument(input.localId);\n if (error instanceof DocumentRemovalNotCurrent) return false;\n throw error;\n }\n}\n\n/**\n * Removes a paused organization's containers and the documents placed only in\n * them, unless a persisted pending write (a queued update, a deferred tail, an\n * intent, or an attachment upload) touches the organization, those\n * containers, or those documents. The scan and every deletion hold one SQLite\n * mutation lock, so no persisted write can land between them.\n *\n * An open store may also hold edits that have not reached SQLite yet, so\n * the removal refuses while any targeted document has queued writes; they\n * persist as pending writes and upload, and a later pass removes the rest.\n * The containers go first, under `stillCurrent`; documents are deleted only\n * after every container was, each under a commit guard against an edit\n * queued meanwhile or the removal no longer applying. A document edited mid-removal stays as a detached local\n * copy, like any document whose container this device lost. Documents that\n * were already detached are never touched: they may be the only copy of work\n * a recovery still needs.\n */\n/** Deletes documents in order until the removal stops being current. */\nasync function deleteUneditedDocuments(\n input: Parameters<typeof removeOrganizationContentUnlessPending>[0],\n lockedExecSql: ExecSql,\n localIds: readonly string[],\n): Promise<string[]> {\n const deletedLocalIds: string[] = [];\n for (const localId of localIds) {\n if (!input.stillCurrent()) break;\n if (\n await deleteDocumentUnlessEdited({\n documentProjectors: input.documentProjectors,\n execSql: lockedExecSql,\n hasQueuedWrites: input.hasQueuedWrites,\n localId,\n organizationId: input.organizationId,\n restoreDocument: input.restoreDocument,\n retireDocument: input.retireDocument,\n stillCurrent: input.stillCurrent,\n })\n ) {\n deletedLocalIds.push(localId);\n }\n }\n return deletedLocalIds;\n}\n\nexport async function removeOrganizationContentUnlessPending(input: {\n readonly containerIds: readonly string[];\n readonly deleteContainers: (\n lockedExecSql: ExecSql,\n removals: readonly ContainerRemoval[],\n ) => Promise<readonly string[]>;\n readonly documentProjectors: ContainerContentsWorkflowRuntimeInfra[\"documentProjectors\"];\n readonly execSql: ExecSql;\n /** Whether an open store holds writes for the document not yet in SQLite. */\n readonly hasQueuedWrites: (localId: string) => boolean;\n readonly organizationId: string;\n /** Undoes retireDocument when the deletion did not commit. */\n readonly restoreDocument: (localId: string) => void;\n /** Retires a deleted document's store; see deleteDocumentUnlessEdited. */\n readonly retireDocument: (localId: string) => void;\n /** Whether the removal still applies, e.g. the session did not switch in. */\n readonly stillCurrent: () => boolean;\n}): Promise<OrganizationContentRemoval> {\n return runSerializedSqlMutation(input.execSql, async (lockedExecSql) => {\n const containerIds = new Set(input.containerIds);\n const localIds = await listDocumentLocalIdsPlacedOnlyIn(\n lockedExecSql,\n input.containerIds,\n );\n if (containerIds.size === 0 && localIds.length === 0) {\n return {\n deletedContainerIds: [],\n deletedLocalIds: [],\n status: \"removed\",\n };\n }\n const documentIds = new Set(localIds);\n const pending = await listPendingWrites(lockedExecSql);\n if (\n pending.some(\n (item) =>\n carriesLocalWrites(item) &&\n (item.organizationId === input.organizationId ||\n (item.containerId !== null && containerIds.has(item.containerId)) ||\n documentIds.has(item.localId)),\n )\n ) {\n return refused(\"pending-writes\");\n }\n if (localIds.some(input.hasQueuedWrites)) return refused(\"queued-edits\");\n\n const deletedContainerIds = await deleteContainersInBatches(\n lockedExecSql,\n [...containerIds],\n input.deleteContainers,\n );\n if (deletedContainerIds.length !== containerIds.size) {\n return {\n deletedContainerIds,\n deletedLocalIds: [],\n status: \"interrupted\",\n };\n }\n const deletedLocalIds = await deleteUneditedDocuments(\n input,\n lockedExecSql,\n localIds,\n );\n return {\n deletedContainerIds,\n deletedLocalIds,\n status:\n deletedLocalIds.length === localIds.length ? \"removed\" : \"interrupted\",\n };\n });\n}\n"]}