@tearleads/client-sdk 0.1.215 → 0.1.216

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 (28) hide show
  1. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +32 -0
  2. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +35 -28
  3. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  4. package/data/persistence/container-contents/documentPlacement.d.ts +20 -0
  5. package/index.d.ts +1 -1
  6. package/index.js +1 -1
  7. package/index.js.map +1 -1
  8. package/package.json +1 -1
  9. package/workflows/container-contents/container-state/purge/purgeTree.js +2 -2
  10. package/workflows/container-contents/container-state/purge/purgeTree.js.map +1 -1
  11. package/workflows/container-contents/documentLinks/documentLinkIntent.js +4 -4
  12. package/workflows/container-contents/documentLinks/documentLinkIntent.js.map +1 -1
  13. package/workflows/container-contents/documentLinks/index.js +4 -11
  14. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  15. package/workflows/container-contents/documentMove/documentMoveIntent.js +2 -3
  16. package/workflows/container-contents/documentMove/documentMoveIntent.js.map +1 -1
  17. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js +2 -2
  18. package/workflows/container-contents/documentMove/documentMoveVanishedRefresh.js.map +1 -1
  19. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js +3 -3
  20. package/workflows/container-contents/documentQueries/documentSubtreeQueries.js.map +1 -1
  21. package/workflows/container-contents/documentQueries/index.js +3 -3
  22. package/workflows/container-contents/documentQueries/index.js.map +1 -1
  23. package/workflows/container-contents/index.d.ts +1 -1
  24. package/workflows/container-contents/index.js +1 -1
  25. package/workflows/container-contents/index.js.map +1 -1
  26. package/workflows/container-contents/syncPause/discoveryGuard.js +2 -2
  27. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  28. package/workflows/container-contents/documentLinks/index.d.ts +0 -46
@@ -1,5 +1,5 @@
1
1
  import { uniqueSortedStrings } from "../../../data/documents/shared/readers.js";
2
- import { sqlDocumentContainerProjectionPersistence as links, replaceDocumentLinksInTransaction, } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
+ import { DocumentContainerProjectionRepository, replaceDocumentLinksInTransaction, } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
3
  import { enqueueDocumentPlacementIntentInTransaction } from "../../../data/persistence/container-contents/documentPlacementIntentEnqueue.js";
4
4
  import { defaultDocumentsPersistence } from "../../documents/index.js";
5
5
  import { relinkContainerDocumentLocally } from "./documentLocalRelink.js";
@@ -16,7 +16,7 @@ export async function addDocumentLinkLocally(input) {
16
16
  requestSync: false,
17
17
  targetContainerId: note.containerId,
18
18
  commitSideEffect: async (execSql) => {
19
- const currentLinks = await links.listLinkedContainerIds(execSql, note.documentId);
19
+ const currentLinks = await new DocumentContainerProjectionRepository(execSql).listLinkedContainerIds(note.documentId);
20
20
  linkedContainerIds = uniqueSortedStrings([
21
21
  ...currentLinks,
22
22
  note.containerId,
@@ -45,7 +45,7 @@ export async function removeDocumentLinkLocally(input) {
45
45
  const persisted = await defaultDocumentsPersistence.loadDocument(execSql, note.id);
46
46
  if (!persisted)
47
47
  return null;
48
- const currentLinks = await links.listLinkedContainerIds(execSql, note.documentId);
48
+ const currentLinks = await new DocumentContainerProjectionRepository(execSql).listLinkedContainerIds(note.documentId);
49
49
  const remaining = currentLinks.filter((id) => id !== removedContainerId);
50
50
  const nextContainerId = remaining.includes(note.containerId)
51
51
  ? note.containerId
@@ -60,7 +60,7 @@ export async function removeDocumentLinkLocally(input) {
60
60
  requestSync: false,
61
61
  targetContainerId: nextContainerId,
62
62
  commitSideEffect: async (transactionExecSql) => {
63
- linkedContainerIds = (await links.listLinkedContainerIds(transactionExecSql, note.documentId)).filter((id) => id !== removedContainerId);
63
+ linkedContainerIds = (await new DocumentContainerProjectionRepository(transactionExecSql).listLinkedContainerIds(note.documentId)).filter((id) => id !== removedContainerId);
64
64
  if (!linkedContainerIds.includes(nextContainerId))
65
65
  throw new Error("Document placement changed before unlink");
66
66
  await enqueueDocumentPlacementIntentInTransaction(transactionExecSql, {
@@ -1 +1 @@
1
- {"version":3,"file":"documentLinkIntent.js","sourceRoot":"","sources":["documentLinkIntent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EACL,yCAAyC,IAAI,KAAK,EAClD,iCAAiC,GAClC,MAAM,qFAAqF,CAAC;AAE7F,OAAO,EAAE,2CAA2C,EAAE,MAAM,6EAA6E,CAAC;AAC1I,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAO9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AAEvE,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAW,KAQtD;IACC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACnD,MAAM,SAAS,GAAG,MAAM,2BAA2B,CAAC,YAAY,CAC9D,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,IAAI,CAAC,EAAE,CACR,CAAC;IACF,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IACrC,IAAI,kBAAkB,GAAsB,EAAE,CAAC;IAC/C,MAAM,UAAU,GAAG,MAAM,8BAA8B,CAAC;QACtD,GAAG,KAAK;QACR,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,WAAW,EAAE,KAAK;QAClB,iBAAiB,EAAE,IAAI,CAAC,WAAW;QACnC,gBAAgB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YAClC,MAAM,YAAY,GAAG,MAAM,KAAK,CAAC,sBAAsB,CACrD,OAAO,EACP,IAAI,CAAC,UAAU,CAChB,CAAC;YACF,kBAAkB,GAAG,mBAAmB,CAAC;gBACvC,GAAG,YAAY;gBACf,IAAI,CAA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C,CAAC;IACH,IAAI,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAC/B,KAAK,CAAC,gCAAgC,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;IAC5E,KAAK,CAAC,YAAY,EAAE,EAAE,CAAC;IACvB,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport {\n sqlDocumentContainerProjectionPersistence as links,\n replaceDocumentLinksInTransaction,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\n\nimport { enqueueDocumentPlacementIntentInTransaction } from \"../../../data/persistence/container-contents/documentPlacementIntentEnqueue\";\nimport { defaultDocumentsPersistence } from \"../../documents\";\nimport type {\n DocumentStructuralMutationHost,\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRuntime,\n SetLinkedContainerIdsForDocument,\n} from \"../documentQueries/documentStructureTypes\";\nimport { relinkContainerDocumentLocally } from \"./documentLocalRelink\";\n\nexport async function addDocumentLinkLocally<TRuntime>(input: {\n currentDocumentStore: DocumentStructuralMutationLocalStore<TRuntime>;\n host: DocumentStructuralMutationHost<TRuntime>;\n note: DocumentSummary & { documentId: string; containerId: string };\n runtime: DocumentStructuralMutationRuntime;\n scheduleSync?: (() => void) | undefined;\n setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n targetContainerId: string;\n}): Promise<DocumentSummary | null> {\n const { note, runtime, targetContainerId } = input;\n const persisted = await defaultDocumentsPersistence.loadDocument(\n runtime.infra.execSql,\n note.id,\n );\n if (!persisted) return null;\n const intentId = crypto.randomUUID();\n let linkedContainerIds: readonly string[] = [];\n const linkedNote = await relinkContainerDocumentLocally({\n ...input,\n accessEpoch: persisted.accessEpoch,\n requestSync: false,\n targetContainerId: note.containerId,\n commitSideEffect: async (execSql) => {\n const currentLinks = await links.listLinkedContainerIds(\n execSql,\n note.documentId,\n );\n linkedContainerIds = uniqueSortedStrings([\n ...currentLinks,\n note.containerId,\n targetContainerId,\n ]);\n await enqueueDocumentPlacementIntentInTransaction(\n execSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n sourceContainerId: note.containerId,\n targetContainerId,\n },\n \"link\",\n );\n await replaceDocumentLinksInTransaction(\n execSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n });\n if (!linkedNote) return null;\n input.setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n input.scheduleSync?.();\n runtime.util.log(\n `Container contents: queued note ${note.id} link to ${targetContainerId}`,\n );\n return linkedNote;\n}\n\nexport async function removeDocumentLinkLocally<TRuntime>(\n input: Omit<\n Parameters<typeof addDocumentLinkLocally<TRuntime>>[0],\n \"targetContainerId\"\n > & { removedContainerId: string },\n): Promise<DocumentSummary | null> {\n const { note, runtime, removedContainerId } = input;\n const execSql = runtime.infra.execSql;\n const persisted = await defaultDocumentsPersistence.loadDocument(\n execSql,\n note.id,\n );\n if (!persisted) return null;\n const currentLinks = await links.listLinkedContainerIds(\n execSql,\n note.documentId,\n );\n const remaining = currentLinks.filter((id) => id !== removedContainerId);\n const nextContainerId = remaining.includes(note.containerId)\n ? note.containerId\n : remaining[0];\n if (!nextContainerId || !currentLinks.includes(removedContainerId))\n return null;\n const intentId = crypto.randomUUID();\n let linkedContainerIds: readonly string[] = [];\n const unlinkedNote = await relinkContainerDocumentLocally({\n ...input,\n accessEpoch: persisted.accessEpoch,\n requestSync: false,\n targetContainerId: nextContainerId,\n commitSideEffect: async (transactionExecSql) => {\n linkedContainerIds = (\n await links.listLinkedContainerIds(transactionExecSql, note.documentId)\n ).filter((id) => id !== removedContainerId);\n if (!linkedContainerIds.includes(nextContainerId))\n throw new Error(\"Document placement changed before unlink\");\n await enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n removedContainerId,\n targetContainerId: nextContainerId,\n },\n \"unlink\",\n );\n await replaceDocumentLinksInTransaction(\n transactionExecSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n });\n if (!unlinkedNote) return null;\n input.setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n input.scheduleSync?.();\n return unlinkedNote;\n}\n"]}
1
+ {"version":3,"file":"documentLinkIntent.js","sourceRoot":"","sources":["documentLinkIntent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EACL,qCAAqC,EACrC,iCAAiC,GAClC,MAAM,qFAAqF,CAAC;AAE7F,OAAO,EAAE,2CAA2C,EAAE,MAAM,6EAA6E,CAAC;AAC1I,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAO9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AAEvE,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAW,KAQtD;IACC,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACnD,MAAM,SAAS,GAAG,MAAM,2BAA2B,CAAC,YAAY,CAC9D,OAAO,CAAC,KAAK,CAAC,OAAO,EACrB,IAAI,CAAC,EAAE,CACR,CAAC;IACF,IAAI,CAAC,SAAS;QAAE,OAAO,IAAI,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IACrC,IAAI,kBAAkB,GAAsB,EAAE,CAAC;IAC/C,MAAM,UAAU,GAAG,MAAM,8BAA8B,CAAC;QACtD,GAAG,KAAK;QACR,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,WAAW,EAAE,KAAK;QAClB,iBAAiB,EAAE,IAAI,CAAC,WAAW;QACnC,gBAAgB,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE;YAClC,MAAM,YAAY,GAAG,MAAM,IAAI,qCAAqC,CAClE,OAAO,CACR,CAAC,sB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AAC;YACF,MAAM,iCAAiC,CACrC,kBAAkB,EAClB,IAAI,CAAC,UAAU,EACf,kBAAkB,EAClB,EAAE,YAAY,EAAE,QAAQ,EAAE,CAC3B,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;IACH,IAAI,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAC/B,KAAK,CAAC,gCAAgC,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;IAC5E,KAAK,CAAC,YAAY,EAAE,EAAE,CAAC;IACvB,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport {\n DocumentContainerProjectionRepository,\n replaceDocumentLinksInTransaction,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\n\nimport { enqueueDocumentPlacementIntentInTransaction } from \"../../../data/persistence/container-contents/documentPlacementIntentEnqueue\";\nimport { defaultDocumentsPersistence } from \"../../documents\";\nimport type {\n DocumentStructuralMutationHost,\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRuntime,\n SetLinkedContainerIdsForDocument,\n} from \"../documentQueries/documentStructureTypes\";\nimport { relinkContainerDocumentLocally } from \"./documentLocalRelink\";\n\nexport async function addDocumentLinkLocally<TRuntime>(input: {\n currentDocumentStore: DocumentStructuralMutationLocalStore<TRuntime>;\n host: DocumentStructuralMutationHost<TRuntime>;\n note: DocumentSummary & { documentId: string; containerId: string };\n runtime: DocumentStructuralMutationRuntime;\n scheduleSync?: (() => void) | undefined;\n setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n targetContainerId: string;\n}): Promise<DocumentSummary | null> {\n const { note, runtime, targetContainerId } = input;\n const persisted = await defaultDocumentsPersistence.loadDocument(\n runtime.infra.execSql,\n note.id,\n );\n if (!persisted) return null;\n const intentId = crypto.randomUUID();\n let linkedContainerIds: readonly string[] = [];\n const linkedNote = await relinkContainerDocumentLocally({\n ...input,\n accessEpoch: persisted.accessEpoch,\n requestSync: false,\n targetContainerId: note.containerId,\n commitSideEffect: async (execSql) => {\n const currentLinks = await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIds(note.documentId);\n linkedContainerIds = uniqueSortedStrings([\n ...currentLinks,\n note.containerId,\n targetContainerId,\n ]);\n await enqueueDocumentPlacementIntentInTransaction(\n execSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n sourceContainerId: note.containerId,\n targetContainerId,\n },\n \"link\",\n );\n await replaceDocumentLinksInTransaction(\n execSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n });\n if (!linkedNote) return null;\n input.setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n input.scheduleSync?.();\n runtime.util.log(\n `Container contents: queued note ${note.id} link to ${targetContainerId}`,\n );\n return linkedNote;\n}\n\nexport async function removeDocumentLinkLocally<TRuntime>(\n input: Omit<\n Parameters<typeof addDocumentLinkLocally<TRuntime>>[0],\n \"targetContainerId\"\n > & { removedContainerId: string },\n): Promise<DocumentSummary | null> {\n const { note, runtime, removedContainerId } = input;\n const execSql = runtime.infra.execSql;\n const persisted = await defaultDocumentsPersistence.loadDocument(\n execSql,\n note.id,\n );\n if (!persisted) return null;\n const currentLinks = await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIds(note.documentId);\n const remaining = currentLinks.filter((id) => id !== removedContainerId);\n const nextContainerId = remaining.includes(note.containerId)\n ? note.containerId\n : remaining[0];\n if (!nextContainerId || !currentLinks.includes(removedContainerId))\n return null;\n const intentId = crypto.randomUUID();\n let linkedContainerIds: readonly string[] = [];\n const unlinkedNote = await relinkContainerDocumentLocally({\n ...input,\n accessEpoch: persisted.accessEpoch,\n requestSync: false,\n targetContainerId: nextContainerId,\n commitSideEffect: async (transactionExecSql) => {\n linkedContainerIds = (\n await new DocumentContainerProjectionRepository(\n transactionExecSql,\n ).listLinkedContainerIds(note.documentId)\n ).filter((id) => id !== removedContainerId);\n if (!linkedContainerIds.includes(nextContainerId))\n throw new Error(\"Document placement changed before unlink\");\n await enqueueDocumentPlacementIntentInTransaction(\n transactionExecSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n removedContainerId,\n targetContainerId: nextContainerId,\n },\n \"unlink\",\n );\n await replaceDocumentLinksInTransaction(\n transactionExecSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n });\n if (!unlinkedNote) return null;\n input.setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n input.scheduleSync?.();\n return unlinkedNote;\n}\n"]}
@@ -1,18 +1,9 @@
1
1
  import { reportAndRethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
2
- import { sqlDocumentContainerProjectionPersistence } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
+ import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
3
  import { errorMessage } from "../../../data/shared/errorMessage.js";
4
4
  import { isDatabaseUnavailableError } from "../../../data/sync/databaseUnavailable.js";
5
5
  import { RemoteDocumentService, resolveDocumentCreateAuthor, } from "../../documents/index.js";
6
6
  import { createRuntimePrincipalPolicyWarmer, } from "../../principals/runtimePolicyWarmer.js";
7
- export async function initializeDocumentLinksSchema(execSql) {
8
- await sqlDocumentContainerProjectionPersistence.ensureSchema(execSql);
9
- }
10
- export async function listDocumentLinkedContainerIds(execSql, documentId) {
11
- return sqlDocumentContainerProjectionPersistence.listLinkedContainerIds(execSql, documentId);
12
- }
13
- export async function replaceDocumentLinks(execSql, documentId, containerIds) {
14
- await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(execSql, documentId, containerIds);
15
- }
16
7
  /**
17
8
  * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.
18
9
  * The caller's string-only log line stays the fallback for a host without
@@ -74,7 +65,9 @@ export async function relinkRemoteContainerDocument(input) {
74
65
  }
75
66
  if (input.isCurrent?.() === false)
76
67
  return null;
77
- await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(execSql, documentId, result.linkedContainerIds, { stillCurrent: input.isCurrent });
68
+ await new DocumentContainerProjectionRepository(execSql).replaceDocumentLinks(documentId, result.linkedContainerIds, {
69
+ stillCurrent: input.isCurrent,
70
+ });
78
71
  return result;
79
72
  }
80
73
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,yCAAyC,EAAE,MAAM,qFAAqF,CAAC;AAChJ,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAEjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EAIL,qBAAqB,EAErB,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACL,kCAAkC,GAEnC,MAAM,sCAAsC,CAAC;AA6B9C,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAgB;IAEhB,MAAM,yCAAyC,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,OAAgB,EAChB,UAAkB;IAElB,OAAO,yCAAyC,CAAC,sBAAsB,CACrE,OAAO,EACP,UAAU,CACX,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,OAAgB,EAChB,UAAkB,EAClB,YAAmC;IAEnC,MAAM,yCAAyC,CAAC,oBAAoB,CAClE,OAAO,EACP,UAAU,EACV,YAAY,CACb,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,iCAAiC,CACxC,IAA0C,EAC1C,KAAc;IAEd,uEAAuE;IACvE,8EAA8E;IAC9E,+EAA+E;IAC/E,IAAI,CAAC,IAAI,CAAC,QAAQ,IA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AAI,CAAC,CAAC,CAAC,MAAM,cAAc,iBAAiB,KAAK,OAAO,EAAE,CAC/I,CAAC;QACF,sEAAsE;QACtE,4EAA4E;QAC5E,oEAAoE;QACpE,iCAAiC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAanD;IACC,OAAO,6BAA6B,CAAC;QACnC,GAAG,KAAK;QACR,SAAS,EAAE,QAAQ;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerDocumentLinkApi = RemoteDocumentServiceApi;\ntype ContainerDocumentLinkOperation = Parameters<\n RemoteDocumentService[\"relinkRemoteDocument\"]\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\nexport interface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n}\n\nexport type { RemoteDocumentPersistedState };\n\nexport async function initializeDocumentLinksSchema(\n execSql: ExecSql,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.ensureSchema(execSql);\n}\n\nexport async function listDocumentLinkedContainerIds(\n execSql: ExecSql,\n documentId: string,\n): Promise<ReadonlyArray<string>> {\n return sqlDocumentContainerProjectionPersistence.listLinkedContainerIds(\n execSql,\n documentId,\n );\n}\n\nexport async function replaceDocumentLinks(\n execSql: ExecSql,\n documentId: string,\n containerIds: ReadonlyArray<string>,\n): Promise<void> {\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n containerIds,\n );\n}\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: targetSecretKey,\n execSql,\n });\n\n try {\n const result = await remoteDocuments.relinkRemoteDocument({\n attachmentReuse: input.attachmentReuse,\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n ),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await sqlDocumentContainerProjectionPersistence.replaceDocumentLinks(\n execSql,\n documentId,\n result.linkedContainerIds,\n { stillCurrent: input.isCurrent },\n );\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EAIL,qBAAqB,EAErB,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACL,kCAAkC,GAEnC,MAAM,sCAAsC,CAAC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AC;QACF,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,iCAAiC,SAAS,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,cAAc,iBAAiB,KAAK,OAAO,EAAE,CAC/I,CAAC;QACF,sEAAsE;QACtE,4EAA4E;QAC5E,oEAAoE;QACpE,iCAAiC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAanD;IACC,OAAO,6BAA6B,CAAC;QACnC,GAAG,KAAK;QACR,SAAS,EAAE,QAAQ;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerDocumentLinkApi = RemoteDocumentServiceApi;\ntype ContainerDocumentLinkOperation = Parameters<\n RemoteDocumentService[\"relinkRemoteDocument\"]\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\nexport interface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n}\n\nexport type { RemoteDocumentPersistedState };\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: targetSecretKey,\n execSql,\n });\n\n try {\n const result = await remoteDocuments.relinkRemoteDocument({\n attachmentReuse: input.attachmentReuse,\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n ),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinks(documentId, result.linkedContainerIds, {\n stillCurrent: input.isCurrent,\n });\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n"]}
@@ -1,15 +1,14 @@
1
1
  import { DEFAULT_DOCUMENT_ACCESS_EPOCH } from "../../../data/documents/documentConstants.js";
2
2
  import { uniqueSortedStrings } from "../../../data/documents/shared/readers.js";
3
- import { replaceDocumentLinksInTransaction } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
3
+ import { DocumentContainerProjectionRepository, replaceDocumentLinksInTransaction, } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
4
4
  import { enqueueDocumentPlacementIntentInTransaction } from "../../../data/persistence/container-contents/documentPlacementIntentEnqueue.js";
5
5
  import { defaultDocumentsPersistence } from "../../documents/index.js";
6
- import { listDocumentLinkedContainerIds } from "../documentLinks/index.js";
7
6
  import { relinkContainerDocumentLocally } from "../documentLinks/documentLocalRelink.js";
8
7
  async function resolveOptimisticDocumentMoveLinks(input) {
9
8
  if (input.replaceLinkedContainers) {
10
9
  return [input.targetContainerId];
11
10
  }
12
- const currentLinkedContainerIds = await listDocumentLinkedContainerIds(input.runtime.infra.execSql, input.documentId);
11
+ const currentLinkedContainerIds = await new DocumentContainerProjectionRepository(input.runtime.infra.execSql).listLinkedContainerIds(input.documentId);
13
12
  const linkedContainerIds = currentLinkedContainerIds.length > 0
14
13
  ? currentLinkedContainerIds
15
14
  : input.currentContainerId
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntent.js","sourceRoot":"","sources":["documentMoveIntent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAE1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EAAE,iCAAiC,EAAE,MAAM,qFAAqF,CAAC;AACxI,OAAO,EAAE,2CAA2C,EAAE,MAAM,6EAA6E,CAAC;AAC1I,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAQtF,KAAK,UAAU,kCAAkC,CAAC,KAMjD;IACC,IAAI,KAAK,CAAC,uBAAuB,EAAE,CAAC;QAClC,OAAO,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACnC,CAAC;IAED,MAAM,yBAAyB,GAAG,MAAM,8BAA8B,CACpE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC3B,KAAK,CAAC,UAAU,CACjB,CAAC;IACF,MAAM,kBAAkB,GACtB,yBAAyB,CAAC,MAAM,GAAG,CAAC;QAClC,CAAC,CAAC,yBAAyB;QAC3B,CAAC,CAAC,KAAK,CAAC,kBAAkB;YACxB,CAAC,CAAC,CAAC,KAAK,CAAC,kBAAkB,CAAC;YAC5B,CAAC,CAAC,EAAE,CAAC;IAEX,OAAO,mBAAmB,CAAC;QACzB,GAAG,kBAAkB,CAAC,MAAM,CAC1B,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,KAAK,KAAK,CAAC,kBAAkB,CAC1D;QACD,KAAK,CAAC,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,EAAE,IAAI,CAAC,WAAW;gBACnC,iBAAiB;aAClB,EACD,MAAM,CACP,CAAC;YACF,MAAM,iCAAiC,CACrC,OAAO,EACP,IAAI,CAAC,UAAU,EACf,kBAAkB,EAClB,EAAE,YAAY,EAAE,QAAQ,EAAE,CAC3B,CAAC;QACJ,CAAC;QACD,WAAW,EAAE,KAAK;QAClB,OAAO;QACP,iBAAiB;KAClB,CAAC,CAAC;IACH,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC7C,CAAC;IAED,gCAAgC,CAAC,IAAI,CAAC,UAAU,EAAE,kBAAkB,CAAC,CAAC;IACtE,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC9B,YAAY,EAAE,EAAE,CAAC;IACjB,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,mCAAmC,SAAS,CAAC,EAAE,YAAY,iBAAiB,EAAE,CAC/E,CAAC;IACF,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AACjD,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_ACCESS_EPOCH } from \"../../../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport { replaceDocumentLinksInTransaction } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { enqueueDocumentPlacementIntentInTransaction } from \"../../../data/persistence/container-contents/documentPlacementIntentEnqueue\";\nimport { defaultDocumentsPersistence } from \"../../documents\";\nimport { listDocumentLinkedContainerIds } from \"../documentLinks\";\nimport { relinkContainerDocumentLocally } from \"../documentLinks/documentLocalRelink\";\nimport type {\n DocumentStructuralMutationHost,\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRuntime,\n SetLinkedContainerIdsForDocument,\n} from \"../documentQueries/documentStructureTypes\";\n\nasync function resolveOptimisticDocumentMoveLinks(input: {\n currentContainerId: string | null;\n documentId: string;\n replaceLinkedContainers?: boolean | undefined;\n runtime: DocumentStructuralMutationRuntime;\n targetContainerId: string;\n}): Promise<string[]> {\n if (input.replaceLinkedContainers) {\n return [input.targetContainerId];\n }\n\n const currentLinkedContainerIds = await listDocumentLinkedContainerIds(\n input.runtime.infra.execSql,\n input.documentId,\n );\n const linkedContainerIds =\n currentLinkedContainerIds.length > 0\n ? currentLinkedContainerIds\n : input.currentContainerId\n ? [input.currentContainerId]\n : [];\n\n return uniqueSortedStrings([\n ...linkedContainerIds.filter(\n (containerId) => containerId !== input.currentContainerId,\n ),\n input.targetContainerId,\n ]);\n}\n\nasync function resolveLocalMoveAccessEpoch(input: {\n localId: string;\n runtime: DocumentStructuralMutationRuntime;\n}): Promise<number> {\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n input.runtime.infra.execSql,\n input.localId,\n );\n // The local relink must keep the document's current key epoch. Falling back\n // is only for partially seeded local state; downgrading synced documents\n // would make offline edits use stale access material.\n return existingDocument?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n}\n\nexport async function moveRemoteDocumentLinkLocally<TRuntime>(params: {\n currentDocumentStore: DocumentStructuralMutationLocalStore<TRuntime>;\n expandNode: (nodeId: string) => void;\n host: DocumentStructuralMutationHost<TRuntime>;\n note: DocumentSummary & { documentId: string };\n replaceLinkedContainers?: boolean | undefined;\n runtime: DocumentStructuralMutationRuntime;\n scheduleSync?: (() => void) | undefined;\n setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n targetContainerId: string;\n}): Promise<{ linksChanged: boolean; note: DocumentSummary | null }> {\n const {\n currentDocumentStore,\n expandNode,\n host,\n note,\n replaceLinkedContainers,\n runtime,\n scheduleSync,\n setLinkedContainerIdsForDocument,\n targetContainerId,\n } = params;\n const linkedContainerIds = await resolveOptimisticDocumentMoveLinks({\n currentContainerId: note.containerId,\n documentId: note.documentId,\n replaceLinkedContainers,\n runtime,\n targetContainerId,\n });\n\n // Apply the user's chosen placement locally now, then replay the signed\n // link-set mutation from this durable intent when auth/network/key context is\n // back. This mirrors container move intents: UI state should not wait on the\n // server, but the remote contract still converges through the normal writer\n // projection path.\n const intentId = crypto.randomUUID();\n\n const movedNote = await relinkContainerDocumentLocally({\n accessEpoch: await resolveLocalMoveAccessEpoch({\n localId: note.id,\n runtime,\n }),\n currentDocumentStore,\n host,\n note,\n commitSideEffect: async (execSql) => {\n await enqueueDocumentPlacementIntentInTransaction(\n execSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n replaceLinkedContainers,\n sourceContainerId: note.containerId,\n targetContainerId,\n },\n \"move\",\n );\n await replaceDocumentLinksInTransaction(\n execSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n requestSync: false,\n runtime,\n targetContainerId,\n });\n if (!movedNote) {\n return { linksChanged: false, note: null };\n }\n\n setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n expandNode(targetContainerId);\n scheduleSync?.();\n runtime.util.log(\n `Container contents: queued note ${movedNote.id} move to ${targetContainerId}`,\n );\n return { linksChanged: true, note: movedNote };\n}\n"]}
1
+ {"version":3,"file":"documentMoveIntent.js","sourceRoot":"","sources":["documentMoveIntent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,2CAA2C,CAAC;AAE1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,wCAAwC,CAAC;AAC7E,OAAO,EACL,qCAAqC,EACrC,iCAAiC,GAClC,MAAM,qFAAqF,CAAC;AAC7F,OAAO,EAAE,2CAA2C,EAAE,MAAM,6EAA6E,CAAC;AAC1I,OAAO,EAAE,2BAA2B,EAAE,MAAM,iBAAiB,CAAC;AAC9D,OAAO,EAAE,8BAA8B,EAAE,MAAM,sCAAsC,CAAC;AAQtF,KAAK,UAAU,kCAAkC,CAAC,KAMjD;IACC,IAAI,KAAK,CAAC,uBAAuB,EAAE,CAAC;QA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E,IAAI,EAAE,SAAS,EAAE,CAAC;AACjD,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_ACCESS_EPOCH } from \"../../../data/documents/documentConstants\";\nimport type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { uniqueSortedStrings } from \"../../../data/documents/shared/readers\";\nimport {\n DocumentContainerProjectionRepository,\n replaceDocumentLinksInTransaction,\n} from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { enqueueDocumentPlacementIntentInTransaction } from \"../../../data/persistence/container-contents/documentPlacementIntentEnqueue\";\nimport { defaultDocumentsPersistence } from \"../../documents\";\nimport { relinkContainerDocumentLocally } from \"../documentLinks/documentLocalRelink\";\nimport type {\n DocumentStructuralMutationHost,\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRuntime,\n SetLinkedContainerIdsForDocument,\n} from \"../documentQueries/documentStructureTypes\";\n\nasync function resolveOptimisticDocumentMoveLinks(input: {\n currentContainerId: string | null;\n documentId: string;\n replaceLinkedContainers?: boolean | undefined;\n runtime: DocumentStructuralMutationRuntime;\n targetContainerId: string;\n}): Promise<string[]> {\n if (input.replaceLinkedContainers) {\n return [input.targetContainerId];\n }\n\n const currentLinkedContainerIds =\n await new DocumentContainerProjectionRepository(\n input.runtime.infra.execSql,\n ).listLinkedContainerIds(input.documentId);\n const linkedContainerIds =\n currentLinkedContainerIds.length > 0\n ? currentLinkedContainerIds\n : input.currentContainerId\n ? [input.currentContainerId]\n : [];\n\n return uniqueSortedStrings([\n ...linkedContainerIds.filter(\n (containerId) => containerId !== input.currentContainerId,\n ),\n input.targetContainerId,\n ]);\n}\n\nasync function resolveLocalMoveAccessEpoch(input: {\n localId: string;\n runtime: DocumentStructuralMutationRuntime;\n}): Promise<number> {\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n input.runtime.infra.execSql,\n input.localId,\n );\n // The local relink must keep the document's current key epoch. Falling back\n // is only for partially seeded local state; downgrading synced documents\n // would make offline edits use stale access material.\n return existingDocument?.accessEpoch ?? DEFAULT_DOCUMENT_ACCESS_EPOCH;\n}\n\nexport async function moveRemoteDocumentLinkLocally<TRuntime>(params: {\n currentDocumentStore: DocumentStructuralMutationLocalStore<TRuntime>;\n expandNode: (nodeId: string) => void;\n host: DocumentStructuralMutationHost<TRuntime>;\n note: DocumentSummary & { documentId: string };\n replaceLinkedContainers?: boolean | undefined;\n runtime: DocumentStructuralMutationRuntime;\n scheduleSync?: (() => void) | undefined;\n setLinkedContainerIdsForDocument: SetLinkedContainerIdsForDocument;\n targetContainerId: string;\n}): Promise<{ linksChanged: boolean; note: DocumentSummary | null }> {\n const {\n currentDocumentStore,\n expandNode,\n host,\n note,\n replaceLinkedContainers,\n runtime,\n scheduleSync,\n setLinkedContainerIdsForDocument,\n targetContainerId,\n } = params;\n const linkedContainerIds = await resolveOptimisticDocumentMoveLinks({\n currentContainerId: note.containerId,\n documentId: note.documentId,\n replaceLinkedContainers,\n runtime,\n targetContainerId,\n });\n\n // Apply the user's chosen placement locally now, then replay the signed\n // link-set mutation from this durable intent when auth/network/key context is\n // back. This mirrors container move intents: UI state should not wait on the\n // server, but the remote contract still converges through the normal writer\n // projection path.\n const intentId = crypto.randomUUID();\n\n const movedNote = await relinkContainerDocumentLocally({\n accessEpoch: await resolveLocalMoveAccessEpoch({\n localId: note.id,\n runtime,\n }),\n currentDocumentStore,\n host,\n note,\n commitSideEffect: async (execSql) => {\n await enqueueDocumentPlacementIntentInTransaction(\n execSql,\n {\n id: intentId,\n documentId: note.documentId,\n localId: note.id,\n replaceLinkedContainers,\n sourceContainerId: note.containerId,\n targetContainerId,\n },\n \"move\",\n );\n await replaceDocumentLinksInTransaction(\n execSql,\n note.documentId,\n linkedContainerIds,\n { moveIntentId: intentId },\n );\n },\n requestSync: false,\n runtime,\n targetContainerId,\n });\n if (!movedNote) {\n return { linksChanged: false, note: null };\n }\n\n setLinkedContainerIdsForDocument(note.documentId, linkedContainerIds);\n expandNode(targetContainerId);\n scheduleSync?.();\n runtime.util.log(\n `Container contents: queued note ${movedNote.id} move to ${targetContainerId}`,\n );\n return { linksChanged: true, note: movedNote };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { isContainerNotFoundFailure } from "../../../data/containers/shared/mutationFailures.js";
2
2
  import { readLinkedContainerIdsFromDocumentManifest } from "../../../data/documents/shared/projection/index.js";
3
- import { listDocumentLinkedContainerIds } from "../documentLinks/index.js";
3
+ import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
4
4
  import { createDocumentMoveFailureState, recordDocumentMoveFailure, } from "./documentMoveFailure.js";
5
5
  /**
6
6
  * Every container the unlink half of the move can cite. The unlink set is
@@ -17,7 +17,7 @@ async function listMoveSourceContainerIds(input) {
17
17
  input.apiClient.getDocumentWriterProjectionResult(documentId, {
18
18
  reportErrors: false,
19
19
  }),
20
- listDocumentLinkedContainerIds(input.execSql, documentId),
20
+ new DocumentContainerProjectionRepository(input.execSql).listLinkedContainerIds(documentId),
21
21
  ]);
22
22
  const remoteLinkedContainerIds = remote.ok
23
23
  ? readLinkedContainerIdsFromDocumentManifest(remote.data)
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveVanishedRefresh.js","sourceRoot":"","sources":["documentMoveVanishedRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAC9F,OAAO,EAAE,0CAA0C,EAAE,MAAM,2CAA2C,CAAC;AAIvG,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAElE,OAAO,EACL,8BAA8B,EAE9B,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAa/B;;;;;;;;GAQG;AACH,KAAK,UAAU,0BAA0B,CAAC,KAKzC;IACC,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IACvD,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,C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qEAAqE;IACrE,2EAA2E;IAC3E,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;AACvE,CAAC","sourcesContent":["import { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport { readLinkedContainerIdsFromDocumentManifest } from \"../../../data/documents/shared/projection\";\nimport type { DocumentMoveIntentRecord } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DocumentLinkSetFailureHandler } from \"../../documents\";\nimport { listDocumentLinkedContainerIds } from \"../documentLinks\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n createDocumentMoveFailureState,\n type DocumentMoveFailureState,\n recordDocumentMoveFailure,\n} from \"./documentMoveFailure\";\n\nexport interface VanishedContainerRefreshOutcome<TMoved> {\n readonly failure: DocumentMoveFailureState;\n readonly moved: TMoved;\n /**\n * Park the intent terminally. True only when the destination itself is\n * proven gone: a coded 404 on its projection probe after eviction. No\n * mutation verdict — first attempt or retry — is ever terminal.\n */\n readonly unavailable: boolean;\n}\n\n/**\n * Every container the unlink half of the move can cite. The unlink set is\n * read off the REMOTE document manifest's link set, so that set — refetched\n * after eviction so it is current — is the authority; the local link\n * projection, the intent's source, and the document's local placement are\n * unioned in so a source known only on one side still gets its cached path\n * refreshed. A superset is harmless: an eviction only forces a refetch, and\n * nothing here decides what gets unlinked.\n */\nasync function listMoveSourceContainerIds(input: {\n apiClient: ContainerContentsWorkflowRuntime[\"apiClient\"];\n execSql: ExecSql;\n existingContainerId: string | null | undefined;\n intent: DocumentMoveIntentRecord;\n}): Promise<string[]> {\n const { documentId, targetContainerId } = input.intent;\n const [remote, local] = await Promise.all([\n input.apiClient.getDocumentWriterProjectionResult(documentId, {\n reportErrors: false,\n }),\n listDocumentLinkedContainerIds(input.execSql, documentId),\n ]);\n const remoteLinkedContainerIds = remote.ok\n ? readLinkedContainerIdsFromDocumentManifest(remote.data)\n : [];\n return Array.from(\n new Set([\n ...remoteLinkedContainerIds,\n ...local,\n input.intent.sourceContainerId,\n input.existingContainerId,\n ]),\n )\n .filter(\n (containerId): containerId is string =>\n typeof containerId === \"string\" && containerId !== targetContainerId,\n )\n .sort();\n}\n\n/**\n * A vanished-container verdict (coded container 404 or `container_unavailable`\n * 409) does not by itself doom a queued move. The deleted container may be a\n * stale ANCESTOR in a cached path — the destination or a source was moved\n * under a live parent before its former parent was deleted — and the local\n * tombstone cascade cannot rescue that intent (it retargets only intents whose\n * source or destination IS the tombstoned container). So refresh before\n * declaring terminal: evict the cached destination, document, and source\n * projections, probe the destination, and retry once with the fresh paths.\n *\n * Only the destination's fate is terminal, and only as proven by its own\n * probe. Sources are evicted, never judged: the retry's unlink set comes from\n * the verified manifest alone, so a server-asserted \"source gone\" can neither\n * skip a revoke nor complete the move — a retry whose link landed but whose\n * unlink still vanished stays partial (pending) with a live link the queue\n * keeps trying to revoke. The retry's own vanished verdict, on either side, is\n * likewise never terminal: with the destination live it can only name another\n * ancestor deleted mid-pass, which the next pass's fresh paths outrun. The\n * pass is bounded to one retry; a transient probe failure leaves the intent\n * retriable (or denied on 403) for a later pass.\n */\nexport async function moveWithVanishedContainerRefresh<TMoved>(input: {\n apiClient: ContainerContentsWorkflowRuntime[\"apiClient\"];\n attempt: (\n onFailure: DocumentLinkSetFailureHandler,\n ) => Promise<TMoved | \"abandoned\">;\n execSql: ExecSql;\n existingContainerId: string | null | undefined;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n}): Promise<VanishedContainerRefreshOutcome<TMoved> | \"abandoned\"> {\n const { apiClient, intent } = input;\n const firstFailure = createDocumentMoveFailureState();\n const first = await input.attempt((failure) =>\n recordDocumentMoveFailure(firstFailure, failure),\n );\n if (first === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!firstFailure.sawVanishedContainer) {\n return { failure: firstFailure, moved: first, unavailable: false };\n }\n\n for (const targetContainerId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n apiClient.evictContainerWriterProjection(targetContainerId);\n const destination = await apiClient.getContainerWriterProjectionResult(\n targetContainerId,\n { reportErrors: false },\n );\n apiClient.evictDocumentWriterProjection(intent.documentId);\n if (!input.isCurrent()) return \"abandoned\";\n if (!destination.ok) {\n destination.report();\n recordDocumentMoveFailure(firstFailure, destination);\n return {\n failure: firstFailure,\n moved: first,\n unavailable: isContainerNotFoundFailure(destination),\n };\n }\n }\n\n for (const sourceContainerId of await listMoveSourceContainerIds(input)) {\n apiClient.evictContainerWriterProjection(sourceContainerId);\n }\n if (!input.isCurrent()) return \"abandoned\";\n\n const retryFailure = createDocumentMoveFailureState();\n const retried = await input.attempt((failure) =>\n recordDocumentMoveFailure(retryFailure, failure),\n );\n if (retried === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n // The retry's own vanished verdict is never terminal. The destination was\n // just proven live, so a second `container_unavailable` can only name\n // another ancestor deleted during the refreshed attempt (or a source): the\n // intent stays pending with its failure recorded and the next pass starts\n // over with freshly evicted projections. One retry per pass keeps it\n // bounded; nothing in the queue backs a pending intent off between passes.\n return { failure: retryFailure, moved: retried, unavailable: false };\n}\n"]}
1
+ {"version":3,"file":"documentMoveVanishedRefresh.js","sourceRoot":"","sources":["documentMoveVanishedRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,kDAAkD,CAAC;AAC9F,OAAO,EAAE,0CAA0C,EAAE,MAAM,2CAA2C,CAAC;AACvG,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAK5I,OAAO,EACL,8BAA8B,EAE9B,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAa/B;;;;;;;;GAQG;AACH,KAAK,UAAU,0BAA0B,CAAC,KAKzC;IACC,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC;IACv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E;QAAE,OAAO,WAAW,CAAC;IACtE,0EAA0E;IAC1E,sEAAsE;IACtE,2EAA2E;IAC3E,0EAA0E;IAC1E,qEAAqE;IACrE,2EAA2E;IAC3E,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC;AACvE,CAAC","sourcesContent":["import { isContainerNotFoundFailure } from \"../../../data/containers/shared/mutationFailures\";\nimport { readLinkedContainerIdsFromDocumentManifest } from \"../../../data/documents/shared/projection\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentMoveIntentRecord } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { DocumentLinkSetFailureHandler } from \"../../documents\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n createDocumentMoveFailureState,\n type DocumentMoveFailureState,\n recordDocumentMoveFailure,\n} from \"./documentMoveFailure\";\n\nexport interface VanishedContainerRefreshOutcome<TMoved> {\n readonly failure: DocumentMoveFailureState;\n readonly moved: TMoved;\n /**\n * Park the intent terminally. True only when the destination itself is\n * proven gone: a coded 404 on its projection probe after eviction. No\n * mutation verdict — first attempt or retry — is ever terminal.\n */\n readonly unavailable: boolean;\n}\n\n/**\n * Every container the unlink half of the move can cite. The unlink set is\n * read off the REMOTE document manifest's link set, so that set — refetched\n * after eviction so it is current — is the authority; the local link\n * projection, the intent's source, and the document's local placement are\n * unioned in so a source known only on one side still gets its cached path\n * refreshed. A superset is harmless: an eviction only forces a refetch, and\n * nothing here decides what gets unlinked.\n */\nasync function listMoveSourceContainerIds(input: {\n apiClient: ContainerContentsWorkflowRuntime[\"apiClient\"];\n execSql: ExecSql;\n existingContainerId: string | null | undefined;\n intent: DocumentMoveIntentRecord;\n}): Promise<string[]> {\n const { documentId, targetContainerId } = input.intent;\n const [remote, local] = await Promise.all([\n input.apiClient.getDocumentWriterProjectionResult(documentId, {\n reportErrors: false,\n }),\n new DocumentContainerProjectionRepository(\n input.execSql,\n ).listLinkedContainerIds(documentId),\n ]);\n const remoteLinkedContainerIds = remote.ok\n ? readLinkedContainerIdsFromDocumentManifest(remote.data)\n : [];\n return Array.from(\n new Set([\n ...remoteLinkedContainerIds,\n ...local,\n input.intent.sourceContainerId,\n input.existingContainerId,\n ]),\n )\n .filter(\n (containerId): containerId is string =>\n typeof containerId === \"string\" && containerId !== targetContainerId,\n )\n .sort();\n}\n\n/**\n * A vanished-container verdict (coded container 404 or `container_unavailable`\n * 409) does not by itself doom a queued move. The deleted container may be a\n * stale ANCESTOR in a cached path — the destination or a source was moved\n * under a live parent before its former parent was deleted — and the local\n * tombstone cascade cannot rescue that intent (it retargets only intents whose\n * source or destination IS the tombstoned container). So refresh before\n * declaring terminal: evict the cached destination, document, and source\n * projections, probe the destination, and retry once with the fresh paths.\n *\n * Only the destination's fate is terminal, and only as proven by its own\n * probe. Sources are evicted, never judged: the retry's unlink set comes from\n * the verified manifest alone, so a server-asserted \"source gone\" can neither\n * skip a revoke nor complete the move — a retry whose link landed but whose\n * unlink still vanished stays partial (pending) with a live link the queue\n * keeps trying to revoke. The retry's own vanished verdict, on either side, is\n * likewise never terminal: with the destination live it can only name another\n * ancestor deleted mid-pass, which the next pass's fresh paths outrun. The\n * pass is bounded to one retry; a transient probe failure leaves the intent\n * retriable (or denied on 403) for a later pass.\n */\nexport async function moveWithVanishedContainerRefresh<TMoved>(input: {\n apiClient: ContainerContentsWorkflowRuntime[\"apiClient\"];\n attempt: (\n onFailure: DocumentLinkSetFailureHandler,\n ) => Promise<TMoved | \"abandoned\">;\n execSql: ExecSql;\n existingContainerId: string | null | undefined;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n}): Promise<VanishedContainerRefreshOutcome<TMoved> | \"abandoned\"> {\n const { apiClient, intent } = input;\n const firstFailure = createDocumentMoveFailureState();\n const first = await input.attempt((failure) =>\n recordDocumentMoveFailure(firstFailure, failure),\n );\n if (first === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!firstFailure.sawVanishedContainer) {\n return { failure: firstFailure, moved: first, unavailable: false };\n }\n\n for (const targetContainerId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n apiClient.evictContainerWriterProjection(targetContainerId);\n const destination = await apiClient.getContainerWriterProjectionResult(\n targetContainerId,\n { reportErrors: false },\n );\n apiClient.evictDocumentWriterProjection(intent.documentId);\n if (!input.isCurrent()) return \"abandoned\";\n if (!destination.ok) {\n destination.report();\n recordDocumentMoveFailure(firstFailure, destination);\n return {\n failure: firstFailure,\n moved: first,\n unavailable: isContainerNotFoundFailure(destination),\n };\n }\n }\n\n for (const sourceContainerId of await listMoveSourceContainerIds(input)) {\n apiClient.evictContainerWriterProjection(sourceContainerId);\n }\n if (!input.isCurrent()) return \"abandoned\";\n\n const retryFailure = createDocumentMoveFailureState();\n const retried = await input.attempt((failure) =>\n recordDocumentMoveFailure(retryFailure, failure),\n );\n if (retried === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n // The retry's own vanished verdict is never terminal. The destination was\n // just proven live, so a second `container_unavailable` can only name\n // another ancestor deleted during the refreshed attempt (or a source): the\n // intent stays pending with its failure recorded and the next pass starts\n // over with freshly evicted projections. One retry per pass keeps it\n // bounded; nothing in the queue backs a pending intent off between passes.\n return { failure: retryFailure, moved: retried, unavailable: false };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { sqlDocumentContainerProjectionPersistence } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
1
+ import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
2
2
  import { ContainerDocumentTombstoneHoldRepository } from "../../../data/persistence/documents/containerDocumentTombstoneHoldRepository.js";
3
3
  import { containerDocumentPlacementKey } from "../../../data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js";
4
4
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
@@ -12,7 +12,7 @@ function addContainerContentsDocumentSummaries(documentSummariesById, documentSu
12
12
  async function listContainerContentsDocumentIdsByContainerIds(execSql, containerIds) {
13
13
  const documentIds = new Set();
14
14
  for (const containerIdBatch of listContainerContentsSqlIdBatches(containerIds)) {
15
- const batchDocumentIds = await sqlDocumentContainerProjectionPersistence.listDocumentIdsByContainerIds(execSql, containerIdBatch);
15
+ const batchDocumentIds = await new DocumentContainerProjectionRepository(execSql).listDocumentIdsByContainerIds(containerIdBatch);
16
16
  for (const documentId of batchDocumentIds) {
17
17
  documentIds.add(documentId);
18
18
  }
@@ -71,7 +71,7 @@ export async function listContainerContentsDocumentsForContainers(execSql, conta
71
71
  sortDocumentSummaries: options.sortDocumentSummaries,
72
72
  });
73
73
  const documentIds = Array.from(new Set(documentSummaries.flatMap((documentSummary) => documentSummary.documentId ? [documentSummary.documentId] : [])));
74
- const linkedContainerIdsByDocumentId = withoutHeldPlacements(await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(execSql, documentIds), await new ContainerDocumentTombstoneHoldRepository(execSql).listContainerDocumentTombstoneHoldsForDocuments(documentIds));
74
+ const linkedContainerIdsByDocumentId = withoutHeldPlacements(await new DocumentContainerProjectionRepository(execSql).listLinkedContainerIdsByDocumentIds(documentIds), await new ContainerDocumentTombstoneHoldRepository(execSql).listContainerDocumentTombstoneHoldsForDocuments(documentIds));
75
75
  // An earlier link-id read can race a move. Recheck membership against the
76
76
  // summaries and final link read so a fresh trash summary cannot ride stale
77
77
  // root ids into the root view. Notification fences reject older summaries.
@@ -1 +1 @@
1
- {"version":3,"file":"documentSubtreeQueries.js","sourceRoot":"","sources":["documentSubtreeQueries.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yCAAyC,EAAE,MAAM,qFAAqF,CAAC;AAChJ,OAAO,EAAE,wCAAwC,EAAE,MAAM,8EAA8E,CAAC;AACxI,OAAO,EAAE,6BAA6B,E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,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,8BAA8B,EAAE,GACzD,MAAM,2CAA2C,CAC/C,OAAO,EACP,KAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAC9B,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAChC,CAAC;IAEJ,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC,eAAe,EAAE,EAAE;QACnD,MAAM,kBAAkB,GACtB,kDAAkD,CAAC;YACjD,eAAe;YACf,8BAA8B;YAC9B,kBAAkB;SACnB,CAAC,CAAC;QACL,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACxB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO;YACL;gBACE,UAAU,EAAE,eAAe,CAAC,UAAU;gBACtC,OAAO,EAAE,eAAe,CAAC,EAAE;gBAC3B,kBAAkB;aACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wDAAwD,CAAC,EACvE,OAAO,EACP,GAAG,KAAK,EAMT;IACC,OAAO,6CAA6C,CAAC;QACnD,GAAG,KAAK;QACR,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;KAC/B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { containerDocumentPlacementKey } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { compareContainerContentsDocumentSummaries } from \"./rows\";\nimport { listContainerContentsSqlIdBatches } from \"./sql\";\nimport type {\n ContainerContentsContainerSubtreeState,\n ContainerContentsDocumentRuntimeTarget,\n ContainerContentsSharedDocumentSummaries,\n ContainerDocumentQueriesRuntime,\n} from \"./types\";\n\nfunction addContainerContentsDocumentSummaries(\n documentSummariesById: Map<string, DocumentSummary>,\n documentSummaries: ReadonlyArray<DocumentSummary>,\n): void {\n for (const documentSummary of documentSummaries) {\n documentSummariesById.set(documentSummary.id, documentSummary);\n }\n}\n\nasync function listContainerContentsDocumentIdsByContainerIds(\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n): Promise<string[]> {\n const documentIds = new Set<string>();\n\n for (const containerIdBatch of listContainerContentsSqlIdBatches(\n containerIds,\n )) {\n const batchDocumentIds =\n await sqlDocumentContainerProjectionPersistence.listDocumentIdsByContainerIds(\n execSql,\n containerIdBatch,\n );\n for (const documentId of batchDocumentIds) {\n documentIds.add(documentId);\n }\n }\n\n return Array.from(documentIds).sort();\n}\n\nasync function listContainerContentsDocumentSummariesByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n sortDocumentSummaries: boolean;\n },\n): Promise<DocumentSummary[]> {\n const documentSummariesById = new Map<string, DocumentSummary>();\n\n for (const containerIdBatch of listContainerContentsSqlIdBatches(\n input.containerIds,\n )) {\n addContainerContentsDocumentSummaries(\n documentSummariesById,\n await sqlDocumentsPersistence.listDocumentsByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds: containerIdBatch,\n documentIds: [],\n },\n ),\n );\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n input.documentIds,\n )) {\n addContainerContentsDocumentSummaries(\n documentSummariesById,\n await sqlDocumentsPersistence.listDocumentsByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds: [],\n documentIds: documentIdBatch,\n },\n ),\n );\n }\n\n const documentSummaries = Array.from(documentSummariesById.values());\n return input.sortDocumentSummaries\n ? documentSummaries.sort(compareContainerContentsDocumentSummaries)\n : documentSummaries;\n}\n\nfunction heldPlacementKey(\n documentId: string | null,\n containerId: string,\n): string {\n return containerDocumentPlacementKey({\n containerId,\n documentId: documentId ?? \"\",\n });\n}\n\nfunction withoutHeldPlacements(\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlyArray<string>>,\n holds: ReadonlyArray<{ containerId: string; documentId: string }>,\n): {\n held: ReadonlySet<string>;\n links: ReadonlyMap<string, ReadonlyArray<string>>;\n} {\n const held = new Set(\n holds.map((hold) => heldPlacementKey(hold.documentId, hold.containerId)),\n );\n if (held.size === 0) {\n return { held, links: linkedContainerIdsByDocumentId };\n }\n return {\n held,\n links: new Map(\n Array.from(linkedContainerIdsByDocumentId, ([documentId, ids]) => [\n documentId,\n ids.filter((id) => !held.has(heldPlacementKey(documentId, id))),\n ]),\n ),\n };\n}\n\n/**\n * Shared batched read pipeline for a flat set of container ids: linked\n * document ids → document summaries → linked container ids per document.\n * Sorting is optional so device-first projection reads can skip it.\n */\nexport async function listContainerContentsDocumentsForContainers(\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n options: { sortDocumentSummaries: boolean },\n): Promise<ContainerContentsSharedDocumentSummaries> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n const linkedDocumentIds =\n await listContainerContentsDocumentIdsByContainerIds(execSql, containerIds);\n const documentSummaries =\n await listContainerContentsDocumentSummariesByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds,\n documentIds: linkedDocumentIds,\n sortDocumentSummaries: options.sortDocumentSummaries,\n },\n );\n const documentIds = Array.from(\n new Set(\n documentSummaries.flatMap((documentSummary) =>\n documentSummary.documentId ? [documentSummary.documentId] : [],\n ),\n ),\n );\n const linkedContainerIdsByDocumentId = withoutHeldPlacements(\n await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(\n execSql,\n documentIds,\n ),\n await new ContainerDocumentTombstoneHoldRepository(\n execSql,\n ).listContainerDocumentTombstoneHoldsForDocuments(documentIds),\n );\n\n // An earlier link-id read can race a move. Recheck membership against the\n // summaries and final link read so a fresh trash summary cannot ride stale\n // root ids into the root view. Notification fences reject older summaries.\n // A held placement (a listing tombstone awaiting signed evidence) is not a\n // membership here either, matching the container item and sidebar views.\n const requestedIds = new Set(containerIds);\n return {\n documentSummaries: documentSummaries.filter(\n (summary) =>\n (summary.containerId !== null &&\n requestedIds.has(summary.containerId) &&\n !linkedContainerIdsByDocumentId.held.has(\n heldPlacementKey(summary.documentId, summary.containerId),\n )) ||\n (summary.documentId !== null &&\n linkedContainerIdsByDocumentId.links\n .get(summary.documentId)\n ?.some((id) => requestedIds.has(id))),\n ),\n linkedContainerIdsByDocumentId: linkedContainerIdsByDocumentId.links,\n };\n}\n\nfunction listContainerContentsContainerSubtreeIds(\n containersById: ReadonlyMap<string, ContainerContentsContainerSubtreeState>,\n rootContainerId: string,\n): string[] {\n const childrenByParentId = new Map<string, string[]>();\n for (const containerState of containersById.values()) {\n const parentId = containerState.container.parentId;\n if (parentId === null) {\n continue;\n }\n\n const children = childrenByParentId.get(parentId);\n if (children) {\n children.push(containerState.container.id);\n } else {\n childrenByParentId.set(parentId, [containerState.container.id]);\n }\n }\n\n const subtreeIds: string[] = [];\n const stack = [rootContainerId];\n const visited = new Set<string>();\n while (stack.length > 0) {\n const containerId = stack.pop();\n if (containerId === undefined || visited.has(containerId)) {\n continue;\n }\n visited.add(containerId);\n\n if (containersById.has(containerId)) {\n subtreeIds.push(containerId);\n }\n\n const children = childrenByParentId.get(containerId);\n if (children) {\n stack.push(...children);\n }\n }\n\n return subtreeIds;\n}\n\nfunction resolveContainerContentsDocumentRuntimeContainerId(params: {\n documentSummary: Pick<DocumentSummary, \"containerId\" | \"documentId\">;\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlyArray<string>>;\n sharedContainerIds: ReadonlySet<string>;\n}): string | null {\n const {\n documentSummary,\n linkedContainerIdsByDocumentId,\n sharedContainerIds,\n } = params;\n if (\n documentSummary.containerId &&\n sharedContainerIds.has(documentSummary.containerId)\n ) {\n return documentSummary.containerId;\n }\n\n if (!documentSummary.documentId) {\n return null;\n }\n\n return (\n linkedContainerIdsByDocumentId\n .get(documentSummary.documentId)\n ?.find((containerId) => sharedContainerIds.has(containerId)) ?? null\n );\n}\n\nasync function listDocumentRuntimeTargetsForContainerSubtree(input: {\n containersById: ReadonlyMap<string, ContainerContentsContainerSubtreeState>;\n execSql: ExecSql;\n rootContainerId: string;\n}): Promise<ContainerContentsDocumentRuntimeTarget[]> {\n const { containersById, execSql, rootContainerId } = input;\n const sharedContainerIds = new Set(\n listContainerContentsContainerSubtreeIds(containersById, rootContainerId),\n );\n if (sharedContainerIds.size === 0) {\n return [];\n }\n\n const { documentSummaries, linkedContainerIdsByDocumentId } =\n await listContainerContentsDocumentsForContainers(\n execSql,\n Array.from(sharedContainerIds),\n { sortDocumentSummaries: true },\n );\n\n return documentSummaries.flatMap((documentSummary) => {\n const runtimeContainerId =\n resolveContainerContentsDocumentRuntimeContainerId({\n documentSummary,\n linkedContainerIdsByDocumentId,\n sharedContainerIds,\n });\n if (!runtimeContainerId) {\n return [];\n }\n\n return [\n {\n documentId: documentSummary.documentId,\n localId: documentSummary.id,\n runtimeContainerId,\n },\n ];\n });\n}\n\nexport function listDocumentRuntimeTargetsForContainerSubtreeFromRuntime({\n runtime,\n ...input\n}: Omit<\n Parameters<typeof listDocumentRuntimeTargetsForContainerSubtree>[0],\n \"execSql\"\n> & {\n runtime: ContainerDocumentQueriesRuntime;\n}): ReturnType<typeof listDocumentRuntimeTargetsForContainerSubtree> {\n return listDocumentRuntimeTargetsForContainerSubtree({\n ...input,\n execSql: runtime.infra.execSql,\n });\n}\n"]}
1
+ {"version":3,"file":"documentSubtreeQueries.js","sourceRoot":"","sources":["documentSubtreeQueries.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,OAAO,EAAE,wCAAwC,EAAE,MAAM,8EAA8E,C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AwC,CAAC,cAAc,EAAE,eAAe,CAAC,CAC1E,CAAC;IACF,IAAI,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,8BAA8B,EAAE,GACzD,MAAM,2CAA2C,CAC/C,OAAO,EACP,KAAK,CAAC,IAAI,CAAC,kBAAkB,CAAC,EAC9B,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAChC,CAAC;IAEJ,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC,eAAe,EAAE,EAAE;QACnD,MAAM,kBAAkB,GACtB,kDAAkD,CAAC;YACjD,eAAe;YACf,8BAA8B;YAC9B,kBAAkB;SACnB,CAAC,CAAC;QACL,IAAI,CAAC,kBAAkB,EAAE,CAAC;YACxB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,OAAO;YACL;gBACE,UAAU,EAAE,eAAe,CAAC,UAAU;gBACtC,OAAO,EAAE,eAAe,CAAC,EAAE;gBAC3B,kBAAkB;aACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,wDAAwD,CAAC,EACvE,OAAO,EACP,GAAG,KAAK,EAMT;IACC,OAAO,6CAA6C,CAAC;QACnD,GAAG,KAAK;QACR,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;KAC/B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentSummary } from \"../../../data/documents/documentSummary\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { ContainerDocumentTombstoneHoldRepository } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldRepository\";\nimport { containerDocumentPlacementKey } from \"../../../data/persistence/documents/containerDocumentTombstoneHoldsPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { compareContainerContentsDocumentSummaries } from \"./rows\";\nimport { listContainerContentsSqlIdBatches } from \"./sql\";\nimport type {\n ContainerContentsContainerSubtreeState,\n ContainerContentsDocumentRuntimeTarget,\n ContainerContentsSharedDocumentSummaries,\n ContainerDocumentQueriesRuntime,\n} from \"./types\";\n\nfunction addContainerContentsDocumentSummaries(\n documentSummariesById: Map<string, DocumentSummary>,\n documentSummaries: ReadonlyArray<DocumentSummary>,\n): void {\n for (const documentSummary of documentSummaries) {\n documentSummariesById.set(documentSummary.id, documentSummary);\n }\n}\n\nasync function listContainerContentsDocumentIdsByContainerIds(\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n): Promise<string[]> {\n const documentIds = new Set<string>();\n\n for (const containerIdBatch of listContainerContentsSqlIdBatches(\n containerIds,\n )) {\n const batchDocumentIds = await new DocumentContainerProjectionRepository(\n execSql,\n ).listDocumentIdsByContainerIds(containerIdBatch);\n for (const documentId of batchDocumentIds) {\n documentIds.add(documentId);\n }\n }\n\n return Array.from(documentIds).sort();\n}\n\nasync function listContainerContentsDocumentSummariesByContainerIdsOrDocumentIds(\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n sortDocumentSummaries: boolean;\n },\n): Promise<DocumentSummary[]> {\n const documentSummariesById = new Map<string, DocumentSummary>();\n\n for (const containerIdBatch of listContainerContentsSqlIdBatches(\n input.containerIds,\n )) {\n addContainerContentsDocumentSummaries(\n documentSummariesById,\n await sqlDocumentsPersistence.listDocumentsByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds: containerIdBatch,\n documentIds: [],\n },\n ),\n );\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n input.documentIds,\n )) {\n addContainerContentsDocumentSummaries(\n documentSummariesById,\n await sqlDocumentsPersistence.listDocumentsByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds: [],\n documentIds: documentIdBatch,\n },\n ),\n );\n }\n\n const documentSummaries = Array.from(documentSummariesById.values());\n return input.sortDocumentSummaries\n ? documentSummaries.sort(compareContainerContentsDocumentSummaries)\n : documentSummaries;\n}\n\nfunction heldPlacementKey(\n documentId: string | null,\n containerId: string,\n): string {\n return containerDocumentPlacementKey({\n containerId,\n documentId: documentId ?? \"\",\n });\n}\n\nfunction withoutHeldPlacements(\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlyArray<string>>,\n holds: ReadonlyArray<{ containerId: string; documentId: string }>,\n): {\n held: ReadonlySet<string>;\n links: ReadonlyMap<string, ReadonlyArray<string>>;\n} {\n const held = new Set(\n holds.map((hold) => heldPlacementKey(hold.documentId, hold.containerId)),\n );\n if (held.size === 0) {\n return { held, links: linkedContainerIdsByDocumentId };\n }\n return {\n held,\n links: new Map(\n Array.from(linkedContainerIdsByDocumentId, ([documentId, ids]) => [\n documentId,\n ids.filter((id) => !held.has(heldPlacementKey(documentId, id))),\n ]),\n ),\n };\n}\n\n/**\n * Shared batched read pipeline for a flat set of container ids: linked\n * document ids → document summaries → linked container ids per document.\n * Sorting is optional so device-first projection reads can skip it.\n */\nexport async function listContainerContentsDocumentsForContainers(\n execSql: ExecSql,\n containerIds: ReadonlyArray<string>,\n options: { sortDocumentSummaries: boolean },\n): Promise<ContainerContentsSharedDocumentSummaries> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n const linkedDocumentIds =\n await listContainerContentsDocumentIdsByContainerIds(execSql, containerIds);\n const documentSummaries =\n await listContainerContentsDocumentSummariesByContainerIdsOrDocumentIds(\n execSql,\n {\n containerIds,\n documentIds: linkedDocumentIds,\n sortDocumentSummaries: options.sortDocumentSummaries,\n },\n );\n const documentIds = Array.from(\n new Set(\n documentSummaries.flatMap((documentSummary) =>\n documentSummary.documentId ? [documentSummary.documentId] : [],\n ),\n ),\n );\n const linkedContainerIdsByDocumentId = withoutHeldPlacements(\n await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIdsByDocumentIds(documentIds),\n await new ContainerDocumentTombstoneHoldRepository(\n execSql,\n ).listContainerDocumentTombstoneHoldsForDocuments(documentIds),\n );\n\n // An earlier link-id read can race a move. Recheck membership against the\n // summaries and final link read so a fresh trash summary cannot ride stale\n // root ids into the root view. Notification fences reject older summaries.\n // A held placement (a listing tombstone awaiting signed evidence) is not a\n // membership here either, matching the container item and sidebar views.\n const requestedIds = new Set(containerIds);\n return {\n documentSummaries: documentSummaries.filter(\n (summary) =>\n (summary.containerId !== null &&\n requestedIds.has(summary.containerId) &&\n !linkedContainerIdsByDocumentId.held.has(\n heldPlacementKey(summary.documentId, summary.containerId),\n )) ||\n (summary.documentId !== null &&\n linkedContainerIdsByDocumentId.links\n .get(summary.documentId)\n ?.some((id) => requestedIds.has(id))),\n ),\n linkedContainerIdsByDocumentId: linkedContainerIdsByDocumentId.links,\n };\n}\n\nfunction listContainerContentsContainerSubtreeIds(\n containersById: ReadonlyMap<string, ContainerContentsContainerSubtreeState>,\n rootContainerId: string,\n): string[] {\n const childrenByParentId = new Map<string, string[]>();\n for (const containerState of containersById.values()) {\n const parentId = containerState.container.parentId;\n if (parentId === null) {\n continue;\n }\n\n const children = childrenByParentId.get(parentId);\n if (children) {\n children.push(containerState.container.id);\n } else {\n childrenByParentId.set(parentId, [containerState.container.id]);\n }\n }\n\n const subtreeIds: string[] = [];\n const stack = [rootContainerId];\n const visited = new Set<string>();\n while (stack.length > 0) {\n const containerId = stack.pop();\n if (containerId === undefined || visited.has(containerId)) {\n continue;\n }\n visited.add(containerId);\n\n if (containersById.has(containerId)) {\n subtreeIds.push(containerId);\n }\n\n const children = childrenByParentId.get(containerId);\n if (children) {\n stack.push(...children);\n }\n }\n\n return subtreeIds;\n}\n\nfunction resolveContainerContentsDocumentRuntimeContainerId(params: {\n documentSummary: Pick<DocumentSummary, \"containerId\" | \"documentId\">;\n linkedContainerIdsByDocumentId: ReadonlyMap<string, ReadonlyArray<string>>;\n sharedContainerIds: ReadonlySet<string>;\n}): string | null {\n const {\n documentSummary,\n linkedContainerIdsByDocumentId,\n sharedContainerIds,\n } = params;\n if (\n documentSummary.containerId &&\n sharedContainerIds.has(documentSummary.containerId)\n ) {\n return documentSummary.containerId;\n }\n\n if (!documentSummary.documentId) {\n return null;\n }\n\n return (\n linkedContainerIdsByDocumentId\n .get(documentSummary.documentId)\n ?.find((containerId) => sharedContainerIds.has(containerId)) ?? null\n );\n}\n\nasync function listDocumentRuntimeTargetsForContainerSubtree(input: {\n containersById: ReadonlyMap<string, ContainerContentsContainerSubtreeState>;\n execSql: ExecSql;\n rootContainerId: string;\n}): Promise<ContainerContentsDocumentRuntimeTarget[]> {\n const { containersById, execSql, rootContainerId } = input;\n const sharedContainerIds = new Set(\n listContainerContentsContainerSubtreeIds(containersById, rootContainerId),\n );\n if (sharedContainerIds.size === 0) {\n return [];\n }\n\n const { documentSummaries, linkedContainerIdsByDocumentId } =\n await listContainerContentsDocumentsForContainers(\n execSql,\n Array.from(sharedContainerIds),\n { sortDocumentSummaries: true },\n );\n\n return documentSummaries.flatMap((documentSummary) => {\n const runtimeContainerId =\n resolveContainerContentsDocumentRuntimeContainerId({\n documentSummary,\n linkedContainerIdsByDocumentId,\n sharedContainerIds,\n });\n if (!runtimeContainerId) {\n return [];\n }\n\n return [\n {\n documentId: documentSummary.documentId,\n localId: documentSummary.id,\n runtimeContainerId,\n },\n ];\n });\n}\n\nexport function listDocumentRuntimeTargetsForContainerSubtreeFromRuntime({\n runtime,\n ...input\n}: Omit<\n Parameters<typeof listDocumentRuntimeTargetsForContainerSubtree>[0],\n \"execSql\"\n> & {\n runtime: ContainerDocumentQueriesRuntime;\n}): ReturnType<typeof listDocumentRuntimeTargetsForContainerSubtree> {\n return listDocumentRuntimeTargetsForContainerSubtree({\n ...input,\n execSql: runtime.infra.execSql,\n });\n}\n"]}
@@ -2,7 +2,7 @@ import { sqlContainerContentsPersistence } from "../../../data/persistence/conta
2
2
  import { ensureContainerTables } from "../../../data/persistence/container-contents/containerPersistence.js";
3
3
  import { RECOVERY_FOLDER_MOVES_SQL, RETAINED_CONTAINER_METADATA_SQL, } from "../../../data/persistence/container-contents/containerRecoveryPersistence.js";
4
4
  import { ContainerSyncWatermarkRepository, containerContentsSyncLane, } from "../../../data/persistence/container-contents/containerSyncWatermarkPersistence.js";
5
- import { sqlDocumentContainerProjectionPersistence } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
5
+ import { DocumentContainerProjectionRepository } from "../../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
6
6
  import { loadLinkedDocumentSummaryRow } from "../../../data/persistence/container-contents/linkedDocumentSummary.js";
7
7
  import { applyContainerDocumentTombstones as applyPersistedContainerDocumentTombstones, sqlDocumentsPersistence, upsertDiscoveredDocuments, } from "../../../data/persistence/documents/documentsPersistence.js";
8
8
  import { LOCAL_INTENT_LANES, localIntentTables, } from "../../../data/sqlite/schema/index.js";
@@ -147,7 +147,7 @@ async function listContainerContentsLinkedContainerIdsByDocumentIds(execSql, doc
147
147
  linkedContainerIdsByDocumentId.set(documentId, []);
148
148
  }
149
149
  for (const documentIdBatch of listContainerContentsSqlIdBatches(uniqueDocumentIds)) {
150
- const batchLinkedContainerIdsByDocumentId = await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(execSql, documentIdBatch);
150
+ const batchLinkedContainerIdsByDocumentId = await new DocumentContainerProjectionRepository(execSql).listLinkedContainerIdsByDocumentIds(documentIdBatch);
151
151
  for (const [documentId, linkedContainerIds,] of batchLinkedContainerIdsByDocumentId.entries()) {
152
152
  linkedContainerIdsByDocumentId.set(documentId, Array.from(linkedContainerIds));
153
153
  }
@@ -199,7 +199,7 @@ export function createContainerDocumentQueriesFromRuntime(runtime) {
199
199
  return resetPendingWriteRetryState(execSql, input);
200
200
  },
201
201
  replaceDocumentLinksBatch(inputs) {
202
- return sqlDocumentContainerProjectionPersistence.replaceDocumentLinksBatch(execSql, inputs);
202
+ return new DocumentContainerProjectionRepository(execSql).replaceDocumentLinksBatch(inputs);
203
203
  },
204
204
  async saveContainerDocumentWatermark(containerId, watermark) {
205
205
  await new ContainerSyncWatermarkRepository(execSql).saveWatermark(containerContentsSyncLane(containerId), watermark);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,2EAA2E,CAAC;AACnF,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EAAE,yCAAyC,EAAE,MAAM,qFAAqF,CAAC;AAChJ,OAAO,EAAE,4BAA4B,EAAE,MAAM,oEAAoE,CAAC;AAClH,OAAO,EACL,gCAAgC,IAAI,yCAAyC,EAC7E,uBAAuB,EACvB,yBAAyB,GAC1B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAgB,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EACL,iBAAiB,EAEjB,2BAA2B,GAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,2BAA2B,GAE5B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,oBAAoB,GAErB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EACxC,mBAAmB,EACnB,uCAAuC,GACxC,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EACL,6BAA6B,EAC7B,wCAAwC,EACxC,yCAAyC,EACzC,4CAA4C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AO,EACP,eAAe,GAAG,KAAK,GACxB;YACC,OAAO,4CAA4C,CACjD,OAAO,EACP,OAAO,EACP,qBAAqB,EACrB,eAAe,CAChB,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,WAAW;YACxC,OAAO,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,aAAa,CAChE,yBAAyB,CAAC,WAAW,CAAC,CACvC,CAAC;QACJ,CAAC;QACD,mCAAmC,CAAC,WAAW;YAC7C,OAAO,oDAAoD,CACzD,OAAO,EACP,WAAW,CACZ,CAAC;QACJ,CAAC;QACD,oBAAoB;YAClB,OAAO,oBAAoB,CAAC,OAAO,CAAC,CAAC;QACvC,CAAC;QACD,iBAAiB;YACf,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QACD,qBAAqB,CAAC,KAAK;YACzB,OAAO,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,yCAAyC,CAAC,yBAAyB,CACxE,OAAO,EACP,MAAM,CACP,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,8BAA8B,CAAC,WAAW,EAAE,SAAS;YACzD,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,aAAa,CAC/D,yBAAyB,CAAC,WAAW,CAAC,EACtC,SAAS,CACV,CAAC;QACJ,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,yBAAyB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACpD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { SyncWatermark } from \"@tearleads/validators/response\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n RECOVERY_FOLDER_MOVES_SQL,\n RETAINED_CONTAINER_METADATA_SQL,\n} from \"../../../data/persistence/container-contents/containerRecoveryPersistence\";\nimport {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { sqlDocumentContainerProjectionPersistence } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { loadLinkedDocumentSummaryRow } from \"../../../data/persistence/container-contents/linkedDocumentSummary\";\nimport {\n applyContainerDocumentTombstones as applyPersistedContainerDocumentTombstones,\n sqlDocumentsPersistence,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n LOCAL_INTENT_LANES,\n localIntentTables,\n} from \"../../../data/sqlite/schema\";\nimport { type ExecSql, ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport {\n listPendingWrites,\n type PendingWriteQueueItem,\n resetPendingWriteRetryState,\n} from \"../pendingWrites\";\nimport {\n createFolderRecoveryQueries,\n type RecoveryFolder,\n} from \"../recovery/folderRecovery\";\nimport type { ContainerDocumentObjectSyncState } from \"../syncState\";\nimport { hydratedProjectionSql } from \"./hydrationSql\";\nimport {\n getOrphanedDocumentQueryBind,\n getOrphanedDocumentWhereSql,\n} from \"./orphanedDocumentSql\";\nimport {\n listPendingDownloads,\n type PendingDownloadQueueItem,\n} from \"./pendingDownloads\";\nimport {\n mapContainerContentsDocumentSummaryRow,\n mapContainerContentsDocumentSyncStateRow,\n mapContainerItemRow,\n readContainerContentsContainerItemCount,\n} from \"./rows\";\nimport { listContainerDocumentSidebarWindow } from \"./sidebarWindow\";\nimport {\n clampContainerItemWindowValue,\n getContainerContentsContainerItemOrderBy,\n getContainerContentsContainerItemsBaseSql,\n getContainerContentsDocumentPendingStateCtes,\n getContainerItemWindowLimit,\n getOrphanedDocumentExistsSql,\n getOrphanedDocumentItemsBaseSql,\n listContainerContentsSqlIdBatches,\n} from \"./sql\";\nimport type {\n ContainerDocumentLinkInput,\n ContainerDocumentQueriesRuntime,\n ContainerDocumentSidebarWindow,\n ContainerDocumentTombstone,\n ContainerItemSort,\n ContainerItemWindow,\n} from \"./types\";\n\nexport type {\n ContainerDocumentLinkInput,\n ContainerDocumentSidebarRow,\n ContainerDocumentTombstone,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"./types\";\n\ninterface ListContainerItemWindowInput {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n limit: number;\n offset: number;\n sort: ContainerItemSort;\n visibleForeignSystemContainerNames?: ReadonlyArray<string> | undefined;\n visibleSystemSlots?: ReadonlyArray<ContainerSystemSlot> | undefined;\n}\n\nexport interface ContainerDocumentQueries {\n /** Read a hydrated linked document by cross-device identity, never a local id. */\n loadContainerDocumentSummary(input: {\n containerId: string;\n documentId: string;\n }): Promise<DocumentSummary | null>;\n listRecoveryFolderMoveIds(input: {\n currentOrganizationId: string | null;\n }): Promise<string[]>;\n listRecoveryFolders(input: {\n currentOrganizationId: string | null;\n }): Promise<RecoveryFolder[]>;\n discardRecoveryFolder(\n input: Pick<RecoveryFolder, \"containerId\" | \"organizationId\" | \"revision\">,\n ): Promise<boolean>;\n applyContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n hasOrphanedDocuments(input: {\n currentOrganizationId: string | null;\n }): Promise<boolean>;\n listContainerDocumentSidebarWindow(input: {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n documentKind?: string | undefined;\n limit: number;\n offset: number;\n }): Promise<ContainerDocumentSidebarWindow>;\n listContainerItemWindow(\n input: ListContainerItemWindowInput,\n ): Promise<ContainerItemWindow>;\n loadDocumentSyncState(\n localId: string,\n ): Promise<ContainerDocumentObjectSyncState | null>;\n loadDocumentSummary(\n localId: string,\n options?: { requireHydrated?: boolean },\n ): Promise<DocumentSummary | null>;\n loadOrphanedDocumentSummary(input: {\n requireHydrated?: boolean;\n currentOrganizationId: string | null;\n localId: string;\n }): Promise<DocumentSummary | null>;\n loadContainerDocumentWatermark(\n containerId: string,\n ): Promise<SyncWatermark | null>;\n listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>>;\n listPendingDownloads(): Promise<ReadonlyArray<PendingDownloadQueueItem>>;\n listPendingWrites(): Promise<ReadonlyArray<PendingWriteQueueItem>>;\n retryPendingWriteItem(input: {\n localId: string;\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n }): Promise<void>;\n replaceDocumentLinksBatch(\n inputs: ReadonlyArray<ContainerDocumentLinkInput>,\n ): Promise<void>;\n saveContainerDocumentWatermark(\n containerId: string,\n watermark: SyncWatermark,\n ): Promise<void>;\n upsertDiscoveredDocuments(\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n}\n\nasync function listContainerItemWindow(\n execSql: ExecSql,\n input: ListContainerItemWindowInput,\n): Promise<ContainerItemWindow> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, localIntentTables);\n\n const limit = getContainerItemWindowLimit(input.limit);\n const offset = clampContainerItemWindowValue(input.offset);\n const visibleSystemSlots = Array.from(\n new Set(input.visibleSystemSlots ?? []),\n );\n const currentOrganizationId = input.currentOrganizationId || null;\n const visibleForeignSystemContainerNames = currentOrganizationId\n ? Array.from(new Set(input.visibleForeignSystemContainerNames ?? []))\n : [];\n const orphaned = input.containerId === null;\n const bind = orphaned\n ? getOrphanedDocumentQueryBind(input.currentOrganizationId)\n : [\n input.containerId,\n ...visibleSystemSlots,\n ...(visibleForeignSystemContainerNames.length > 0\n ? [currentOrganizationId, ...visibleForeignSystemContainerNames]\n : []),\n input.containerId,\n input.containerId,\n ];\n const baseSql = orphaned\n ? getOrphanedDocumentItemsBaseSql()\n : getContainerContentsContainerItemsBaseSql(\n visibleSystemSlots.length,\n visibleForeignSystemContainerNames.length,\n );\n const countRows = await execSql(\n `SELECT COUNT(*) AS total_count FROM (${baseSql})`,\n bind,\n );\n const totalCount = readContainerContentsContainerItemCount(\n countRows[0] ?? {},\n );\n\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const rows = await execSql(\n `${baseSql} ORDER BY ${getContainerContentsContainerItemOrderBy(input.sort)} LIMIT ? OFFSET ?`,\n [...bind, limit, offset],\n );\n\n return {\n rows: rows.map((row) => mapContainerItemRow(input.containerId, row)),\n totalCount,\n };\n}\n\nasync function hasOrphanedDocuments(\n execSql: ExecSql,\n currentOrganizationId: string | null,\n): Promise<boolean> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n // One statement for all three probes; the folder probes need an\n // organization, as their standalone readers do.\n const folderProbes = currentOrganizationId\n ? `OR EXISTS(${RETAINED_CONTAINER_METADATA_SQL}) OR EXISTS(${RECOVERY_FOLDER_MOVES_SQL})`\n : \"\";\n if (currentOrganizationId)\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const rows = await execSql(\n `SELECT (EXISTS(${getOrphanedDocumentExistsSql()}) ${folderProbes}) AS found`,\n [\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...(currentOrganizationId\n ? [\n currentOrganizationId,\n LOCAL_INTENT_LANES.containerMove,\n currentOrganizationId,\n ]\n : []),\n ],\n );\n return Number(Object.values(rows[0] ?? {})[0] ?? 0) !== 0;\n}\n\nasync function queryContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n scope: { bind: ReadonlyArray<string | null>; whereSql: string },\n): Promise<DocumentSummary | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n SELECT\n d.local_id AS local_id,\n d.document_id AS document_id,\n d.container_id AS container_id,\n d.document_kind AS document_kind,\n d.title AS title,\n d.updated_at AS updated_at,\n stored.access_state_hash AS access_state_hash,\n stored.effective_access_level AS effective_access_level\n FROM document_projection d\n LEFT JOIN documents stored\n ON stored.app_kind = 'documents'\n AND stored.local_id = d.local_id\n WHERE d.local_id = ?\n ${scope.whereSql}\n LIMIT 1\n `,\n [localId, ...scope.bind],\n );\n\n return mapContainerContentsDocumentSummaryRow(rows[0] ?? {});\n}\n\nfunction loadContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: [],\n whereSql: requireHydrated\n ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}`\n : \"\",\n });\n}\n\nfunction loadContainerContentsOrphanedDocumentSummary(\n execSql: ExecSql,\n localId: string,\n currentOrganizationId: string | null,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: getOrphanedDocumentQueryBind(currentOrganizationId),\n whereSql: `${requireHydrated ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}` : \"\"} AND ${getOrphanedDocumentWhereSql(\n {\n documentIdSql: \"d.document_id\",\n projectionAlias: \"d\",\n },\n )}`,\n });\n}\n\nasync function loadContainerContentsDocumentSyncState(\n execSql: ExecSql,\n localId: string,\n): Promise<ContainerDocumentObjectSyncState | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n WITH ${getContainerContentsDocumentPendingStateCtes()}\n SELECT\n d.document_id AS document_id,\n COALESCE(document_updates.pending_update_count, 0) AS pending_update_count,\n COALESCE(document_attachments.pending_attachment_count, 0) AS pending_attachment_count,\n COALESCE(document_attachments.pending_attachment_bytes, 0) AS pending_attachment_bytes,\n NULL AS sync_last_error\n FROM document_projection d\n LEFT JOIN document_pending_update_counts document_updates\n ON document_updates.local_id = d.local_id\n LEFT JOIN document_pending_attachment_counts document_attachments\n ON document_attachments.local_id = d.local_id\n WHERE d.local_id = ?\n LIMIT 1\n `,\n [localId],\n );\n const [row] = rows;\n if (!row) {\n return null;\n }\n\n return mapContainerContentsDocumentSyncStateRow(row);\n}\n\nasync function listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql: ExecSql,\n documentIds: ReadonlyArray<string>,\n): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n uniqueDocumentIds,\n )) {\n const batchLinkedContainerIdsByDocumentId =\n await sqlDocumentContainerProjectionPersistence.listLinkedContainerIdsByDocumentIds(\n execSql,\n documentIdBatch,\n );\n for (const [\n documentId,\n linkedContainerIds,\n ] of batchLinkedContainerIdsByDocumentId.entries()) {\n linkedContainerIdsByDocumentId.set(\n documentId,\n Array.from(linkedContainerIds),\n );\n }\n }\n\n return linkedContainerIdsByDocumentId;\n}\n\nexport function createContainerDocumentQueriesFromRuntime(\n runtime: ContainerDocumentQueriesRuntime,\n): ContainerDocumentQueries {\n const execSql = runtime.infra.execSql;\n return {\n ...createFolderRecoveryQueries(execSql),\n async loadContainerDocumentSummary(input) {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n return mapContainerContentsDocumentSummaryRow(\n (await loadLinkedDocumentSummaryRow(execSql, input)) ?? {},\n );\n },\n applyContainerDocumentTombstones(tombstones) {\n return applyPersistedContainerDocumentTombstones(execSql, tombstones);\n },\n hasOrphanedDocuments({ currentOrganizationId }) {\n return hasOrphanedDocuments(execSql, currentOrganizationId);\n },\n listContainerDocumentSidebarWindow(input) {\n return listContainerDocumentSidebarWindow(execSql, input);\n },\n listContainerItemWindow(input) {\n return listContainerItemWindow(execSql, input);\n },\n loadDocumentSyncState(localId) {\n return loadContainerContentsDocumentSyncState(execSql, localId);\n },\n loadDocumentSummary(localId, options) {\n return loadContainerContentsDocumentSummary(\n execSql,\n localId,\n options?.requireHydrated ?? false,\n );\n },\n loadOrphanedDocumentSummary({\n currentOrganizationId,\n localId,\n requireHydrated = false,\n }) {\n return loadContainerContentsOrphanedDocumentSummary(\n execSql,\n localId,\n currentOrganizationId,\n requireHydrated,\n );\n },\n loadContainerDocumentWatermark(containerId) {\n return new ContainerSyncWatermarkRepository(execSql).loadWatermark(\n containerContentsSyncLane(containerId),\n );\n },\n listLinkedContainerIdsByDocumentIds(documentIds) {\n return listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql,\n documentIds,\n );\n },\n listPendingDownloads() {\n return listPendingDownloads(execSql);\n },\n listPendingWrites() {\n return listPendingWrites(execSql);\n },\n retryPendingWriteItem(input) {\n return resetPendingWriteRetryState(execSql, input);\n },\n replaceDocumentLinksBatch(inputs) {\n return sqlDocumentContainerProjectionPersistence.replaceDocumentLinksBatch(\n execSql,\n inputs,\n );\n },\n async saveContainerDocumentWatermark(containerId, watermark) {\n await new ContainerSyncWatermarkRepository(execSql).saveWatermark(\n containerContentsSyncLane(containerId),\n watermark,\n );\n },\n upsertDiscoveredDocuments(inputs) {\n return upsertDiscoveredDocuments(execSql, inputs);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,qBAAqB,EAAE,MAAM,mEAAmE,CAAC;AAC1G,OAAO,EACL,yBAAyB,EACzB,+BAA+B,GAChC,MAAM,2EAA2E,CAAC;AACnF,OAAO,EACL,gCAAgC,EAChC,yBAAyB,GAC1B,MAAM,gFAAgF,CAAC;AACxF,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,O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f,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;QACpC,CAAC;QACD,qBAAqB,CAAC,KAAK;YACzB,OAAO,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACrD,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,IAAI,qCAAqC,CAC9C,OAAO,CACR,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC;QACtC,CAAC;QACD,KAAK,CAAC,8BAA8B,CAAC,WAAW,EAAE,SAAS;YACzD,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC,aAAa,CAC/D,yBAAyB,CAAC,WAAW,CAAC,EACtC,SAAS,CACV,CAAC;QACJ,CAAC;QACD,yBAAyB,CAAC,MAAM;YAC9B,OAAO,yBAAyB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACpD,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { SyncWatermark } from \"@tearleads/validators/response\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../../data/documents/documentSummary\";\nimport { sqlContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { ensureContainerTables } from \"../../../data/persistence/container-contents/containerPersistence\";\nimport {\n RECOVERY_FOLDER_MOVES_SQL,\n RETAINED_CONTAINER_METADATA_SQL,\n} from \"../../../data/persistence/container-contents/containerRecoveryPersistence\";\nimport {\n ContainerSyncWatermarkRepository,\n containerContentsSyncLane,\n} from \"../../../data/persistence/container-contents/containerSyncWatermarkPersistence\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { loadLinkedDocumentSummaryRow } from \"../../../data/persistence/container-contents/linkedDocumentSummary\";\nimport {\n applyContainerDocumentTombstones as applyPersistedContainerDocumentTombstones,\n sqlDocumentsPersistence,\n upsertDiscoveredDocuments,\n} from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n LOCAL_INTENT_LANES,\n localIntentTables,\n} from \"../../../data/sqlite/schema\";\nimport { type ExecSql, ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport {\n listPendingWrites,\n type PendingWriteQueueItem,\n resetPendingWriteRetryState,\n} from \"../pendingWrites\";\nimport {\n createFolderRecoveryQueries,\n type RecoveryFolder,\n} from \"../recovery/folderRecovery\";\nimport type { ContainerDocumentObjectSyncState } from \"../syncState\";\nimport { hydratedProjectionSql } from \"./hydrationSql\";\nimport {\n getOrphanedDocumentQueryBind,\n getOrphanedDocumentWhereSql,\n} from \"./orphanedDocumentSql\";\nimport {\n listPendingDownloads,\n type PendingDownloadQueueItem,\n} from \"./pendingDownloads\";\nimport {\n mapContainerContentsDocumentSummaryRow,\n mapContainerContentsDocumentSyncStateRow,\n mapContainerItemRow,\n readContainerContentsContainerItemCount,\n} from \"./rows\";\nimport { listContainerDocumentSidebarWindow } from \"./sidebarWindow\";\nimport {\n clampContainerItemWindowValue,\n getContainerContentsContainerItemOrderBy,\n getContainerContentsContainerItemsBaseSql,\n getContainerContentsDocumentPendingStateCtes,\n getContainerItemWindowLimit,\n getOrphanedDocumentExistsSql,\n getOrphanedDocumentItemsBaseSql,\n listContainerContentsSqlIdBatches,\n} from \"./sql\";\nimport type {\n ContainerDocumentLinkInput,\n ContainerDocumentQueriesRuntime,\n ContainerDocumentSidebarWindow,\n ContainerDocumentTombstone,\n ContainerItemSort,\n ContainerItemWindow,\n} from \"./types\";\n\nexport type {\n ContainerDocumentLinkInput,\n ContainerDocumentSidebarRow,\n ContainerDocumentTombstone,\n ContainerItemRow,\n ContainerItemSort,\n ContainerItemSortDirection,\n ContainerItemSortKey,\n} from \"./types\";\n\ninterface ListContainerItemWindowInput {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n limit: number;\n offset: number;\n sort: ContainerItemSort;\n visibleForeignSystemContainerNames?: ReadonlyArray<string> | undefined;\n visibleSystemSlots?: ReadonlyArray<ContainerSystemSlot> | undefined;\n}\n\nexport interface ContainerDocumentQueries {\n /** Read a hydrated linked document by cross-device identity, never a local id. */\n loadContainerDocumentSummary(input: {\n containerId: string;\n documentId: string;\n }): Promise<DocumentSummary | null>;\n listRecoveryFolderMoveIds(input: {\n currentOrganizationId: string | null;\n }): Promise<string[]>;\n listRecoveryFolders(input: {\n currentOrganizationId: string | null;\n }): Promise<RecoveryFolder[]>;\n discardRecoveryFolder(\n input: Pick<RecoveryFolder, \"containerId\" | \"organizationId\" | \"revision\">,\n ): Promise<boolean>;\n applyContainerDocumentTombstones(\n tombstones: ReadonlyArray<ContainerDocumentTombstone>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n hasOrphanedDocuments(input: {\n currentOrganizationId: string | null;\n }): Promise<boolean>;\n listContainerDocumentSidebarWindow(input: {\n /** Null selects the virtual orphaned-documents recovery collection. */\n containerId: string | null;\n currentOrganizationId?: string | null | undefined;\n documentKind?: string | undefined;\n limit: number;\n offset: number;\n }): Promise<ContainerDocumentSidebarWindow>;\n listContainerItemWindow(\n input: ListContainerItemWindowInput,\n ): Promise<ContainerItemWindow>;\n loadDocumentSyncState(\n localId: string,\n ): Promise<ContainerDocumentObjectSyncState | null>;\n loadDocumentSummary(\n localId: string,\n options?: { requireHydrated?: boolean },\n ): Promise<DocumentSummary | null>;\n loadOrphanedDocumentSummary(input: {\n requireHydrated?: boolean;\n currentOrganizationId: string | null;\n localId: string;\n }): Promise<DocumentSummary | null>;\n loadContainerDocumentWatermark(\n containerId: string,\n ): Promise<SyncWatermark | null>;\n listLinkedContainerIdsByDocumentIds(\n documentIds: ReadonlyArray<string>,\n ): Promise<ReadonlyMap<string, ReadonlyArray<string>>>;\n listPendingDownloads(): Promise<ReadonlyArray<PendingDownloadQueueItem>>;\n listPendingWrites(): Promise<ReadonlyArray<PendingWriteQueueItem>>;\n retryPendingWriteItem(input: {\n localId: string;\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n }): Promise<void>;\n replaceDocumentLinksBatch(\n inputs: ReadonlyArray<ContainerDocumentLinkInput>,\n ): Promise<void>;\n saveContainerDocumentWatermark(\n containerId: string,\n watermark: SyncWatermark,\n ): Promise<void>;\n upsertDiscoveredDocuments(\n inputs: ReadonlyArray<DiscoveredDocumentInput>,\n ): Promise<ReadonlyArray<DocumentSummary>>;\n}\n\nasync function listContainerItemWindow(\n execSql: ExecSql,\n input: ListContainerItemWindowInput,\n): Promise<ContainerItemWindow> {\n await ensureContainerTables(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await ensureSqlTables(execSql, localIntentTables);\n\n const limit = getContainerItemWindowLimit(input.limit);\n const offset = clampContainerItemWindowValue(input.offset);\n const visibleSystemSlots = Array.from(\n new Set(input.visibleSystemSlots ?? []),\n );\n const currentOrganizationId = input.currentOrganizationId || null;\n const visibleForeignSystemContainerNames = currentOrganizationId\n ? Array.from(new Set(input.visibleForeignSystemContainerNames ?? []))\n : [];\n const orphaned = input.containerId === null;\n const bind = orphaned\n ? getOrphanedDocumentQueryBind(input.currentOrganizationId)\n : [\n input.containerId,\n ...visibleSystemSlots,\n ...(visibleForeignSystemContainerNames.length > 0\n ? [currentOrganizationId, ...visibleForeignSystemContainerNames]\n : []),\n input.containerId,\n input.containerId,\n ];\n const baseSql = orphaned\n ? getOrphanedDocumentItemsBaseSql()\n : getContainerContentsContainerItemsBaseSql(\n visibleSystemSlots.length,\n visibleForeignSystemContainerNames.length,\n );\n const countRows = await execSql(\n `SELECT COUNT(*) AS total_count FROM (${baseSql})`,\n bind,\n );\n const totalCount = readContainerContentsContainerItemCount(\n countRows[0] ?? {},\n );\n\n if (limit === 0 || offset >= totalCount) {\n return { rows: [], totalCount };\n }\n\n const rows = await execSql(\n `${baseSql} ORDER BY ${getContainerContentsContainerItemOrderBy(input.sort)} LIMIT ? OFFSET ?`,\n [...bind, limit, offset],\n );\n\n return {\n rows: rows.map((row) => mapContainerItemRow(input.containerId, row)),\n totalCount,\n };\n}\n\nasync function hasOrphanedDocuments(\n execSql: ExecSql,\n currentOrganizationId: string | null,\n): Promise<boolean> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n // One statement for all three probes; the folder probes need an\n // organization, as their standalone readers do.\n const folderProbes = currentOrganizationId\n ? `OR EXISTS(${RETAINED_CONTAINER_METADATA_SQL}) OR EXISTS(${RECOVERY_FOLDER_MOVES_SQL})`\n : \"\";\n if (currentOrganizationId)\n await sqlContainerContentsPersistence.ensureSchema(execSql);\n const rows = await execSql(\n `SELECT (EXISTS(${getOrphanedDocumentExistsSql()}) ${folderProbes}) AS found`,\n [\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...getOrphanedDocumentQueryBind(currentOrganizationId),\n ...(currentOrganizationId\n ? [\n currentOrganizationId,\n LOCAL_INTENT_LANES.containerMove,\n currentOrganizationId,\n ]\n : []),\n ],\n );\n return Number(Object.values(rows[0] ?? {})[0] ?? 0) !== 0;\n}\n\nasync function queryContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n scope: { bind: ReadonlyArray<string | null>; whereSql: string },\n): Promise<DocumentSummary | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n SELECT\n d.local_id AS local_id,\n d.document_id AS document_id,\n d.container_id AS container_id,\n d.document_kind AS document_kind,\n d.title AS title,\n d.updated_at AS updated_at,\n stored.access_state_hash AS access_state_hash,\n stored.effective_access_level AS effective_access_level\n FROM document_projection d\n LEFT JOIN documents stored\n ON stored.app_kind = 'documents'\n AND stored.local_id = d.local_id\n WHERE d.local_id = ?\n ${scope.whereSql}\n LIMIT 1\n `,\n [localId, ...scope.bind],\n );\n\n return mapContainerContentsDocumentSummaryRow(rows[0] ?? {});\n}\n\nfunction loadContainerContentsDocumentSummary(\n execSql: ExecSql,\n localId: string,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: [],\n whereSql: requireHydrated\n ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}`\n : \"\",\n });\n}\n\nfunction loadContainerContentsOrphanedDocumentSummary(\n execSql: ExecSql,\n localId: string,\n currentOrganizationId: string | null,\n requireHydrated: boolean,\n): Promise<DocumentSummary | null> {\n return queryContainerContentsDocumentSummary(execSql, localId, {\n bind: getOrphanedDocumentQueryBind(currentOrganizationId),\n whereSql: `${requireHydrated ? `AND ${hydratedProjectionSql(\"d.local_id\", \"documents\")}` : \"\"} AND ${getOrphanedDocumentWhereSql(\n {\n documentIdSql: \"d.document_id\",\n projectionAlias: \"d\",\n },\n )}`,\n });\n}\n\nasync function loadContainerContentsDocumentSyncState(\n execSql: ExecSql,\n localId: string,\n): Promise<ContainerDocumentObjectSyncState | null> {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n\n const rows = await execSql(\n `\n WITH ${getContainerContentsDocumentPendingStateCtes()}\n SELECT\n d.document_id AS document_id,\n COALESCE(document_updates.pending_update_count, 0) AS pending_update_count,\n COALESCE(document_attachments.pending_attachment_count, 0) AS pending_attachment_count,\n COALESCE(document_attachments.pending_attachment_bytes, 0) AS pending_attachment_bytes,\n NULL AS sync_last_error\n FROM document_projection d\n LEFT JOIN document_pending_update_counts document_updates\n ON document_updates.local_id = d.local_id\n LEFT JOIN document_pending_attachment_counts document_attachments\n ON document_attachments.local_id = d.local_id\n WHERE d.local_id = ?\n LIMIT 1\n `,\n [localId],\n );\n const [row] = rows;\n if (!row) {\n return null;\n }\n\n return mapContainerContentsDocumentSyncStateRow(row);\n}\n\nasync function listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql: ExecSql,\n documentIds: ReadonlyArray<string>,\n): Promise<ReadonlyMap<string, ReadonlyArray<string>>> {\n const uniqueDocumentIds = Array.from(new Set(documentIds));\n if (uniqueDocumentIds.length === 0) {\n return new Map();\n }\n\n const linkedContainerIdsByDocumentId = new Map<string, string[]>();\n for (const documentId of uniqueDocumentIds) {\n linkedContainerIdsByDocumentId.set(documentId, []);\n }\n\n for (const documentIdBatch of listContainerContentsSqlIdBatches(\n uniqueDocumentIds,\n )) {\n const batchLinkedContainerIdsByDocumentId =\n await new DocumentContainerProjectionRepository(\n execSql,\n ).listLinkedContainerIdsByDocumentIds(documentIdBatch);\n for (const [\n documentId,\n linkedContainerIds,\n ] of batchLinkedContainerIdsByDocumentId.entries()) {\n linkedContainerIdsByDocumentId.set(\n documentId,\n Array.from(linkedContainerIds),\n );\n }\n }\n\n return linkedContainerIdsByDocumentId;\n}\n\nexport function createContainerDocumentQueriesFromRuntime(\n runtime: ContainerDocumentQueriesRuntime,\n): ContainerDocumentQueries {\n const execSql = runtime.infra.execSql;\n return {\n ...createFolderRecoveryQueries(execSql),\n async loadContainerDocumentSummary(input) {\n await sqlDocumentsPersistence.ensureSchema(execSql);\n return mapContainerContentsDocumentSummaryRow(\n (await loadLinkedDocumentSummaryRow(execSql, input)) ?? {},\n );\n },\n applyContainerDocumentTombstones(tombstones) {\n return applyPersistedContainerDocumentTombstones(execSql, tombstones);\n },\n hasOrphanedDocuments({ currentOrganizationId }) {\n return hasOrphanedDocuments(execSql, currentOrganizationId);\n },\n listContainerDocumentSidebarWindow(input) {\n return listContainerDocumentSidebarWindow(execSql, input);\n },\n listContainerItemWindow(input) {\n return listContainerItemWindow(execSql, input);\n },\n loadDocumentSyncState(localId) {\n return loadContainerContentsDocumentSyncState(execSql, localId);\n },\n loadDocumentSummary(localId, options) {\n return loadContainerContentsDocumentSummary(\n execSql,\n localId,\n options?.requireHydrated ?? false,\n );\n },\n loadOrphanedDocumentSummary({\n currentOrganizationId,\n localId,\n requireHydrated = false,\n }) {\n return loadContainerContentsOrphanedDocumentSummary(\n execSql,\n localId,\n currentOrganizationId,\n requireHydrated,\n );\n },\n loadContainerDocumentWatermark(containerId) {\n return new ContainerSyncWatermarkRepository(execSql).loadWatermark(\n containerContentsSyncLane(containerId),\n );\n },\n listLinkedContainerIdsByDocumentIds(documentIds) {\n return listContainerContentsLinkedContainerIdsByDocumentIds(\n execSql,\n documentIds,\n );\n },\n listPendingDownloads() {\n return listPendingDownloads(execSql);\n },\n listPendingWrites() {\n return listPendingWrites(execSql);\n },\n retryPendingWriteItem(input) {\n return resetPendingWriteRetryState(execSql, input);\n },\n replaceDocumentLinksBatch(inputs) {\n return new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinksBatch(inputs);\n },\n async saveContainerDocumentWatermark(containerId, watermark) {\n await new ContainerSyncWatermarkRepository(execSql).saveWatermark(\n containerContentsSyncLane(containerId),\n watermark,\n );\n },\n upsertDiscoveredDocuments(inputs) {\n return upsertDiscoveredDocuments(execSql, inputs);\n },\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
+ export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
1
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
2
3
  export { type DocumentAttributionRangesInput, type DocumentAttributionRangesPage, loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
3
4
  export { type ContainerSyncWatermarkLane, ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
4
- export { initializeDocumentLinksSchema, listDocumentLinkedContainerIds, replaceDocumentLinks, } from "./documentLinks/index.js";
5
5
  export { type ContainerDocumentLinkInput, type ContainerDocumentQueries, type ContainerDocumentSidebarRow, type ContainerDocumentTombstone, type ContainerItemRow, type ContainerItemSort, type ContainerItemSortDirection, type ContainerItemSortKey, createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
6
6
  export { activateDocumentLink, addDocumentLink, canMutateDocumentLink, canMutateLocalDocumentLink, type DocumentStructuralMutationHost, type MergeDocumentSummary, moveDocumentLink, moveLocalDocumentLink, removeDocumentLink, type SetLinkedContainerIdsForDocument, } from "./documentQueries/documentStructure.js";
7
7
  export type { PendingDownloadQueueItem } from "./documentQueries/pendingDownloads.js";
@@ -1,7 +1,7 @@
1
+ export { DocumentContainerProjectionRepository } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
1
2
  export { didRegainSyncPrerequisites, isDatabaseUnavailableError, } from "../../data/sync/syncCoordinator.js";
2
3
  export { loadDocumentAttributionRanges, } from "./attribution/documentAttributionRanges.js";
3
4
  export { ContainerSyncWatermarkRepository, createContainerContentsSyncLane, createContainerParentSyncLane, defaultContainerContentsPersistence, } from "./containerPersistence.js";
4
- export { initializeDocumentLinksSchema, listDocumentLinkedContainerIds, replaceDocumentLinks, } from "./documentLinks/index.js";
5
5
  export { createContainerDocumentQueriesFromRuntime, } from "./documentQueries/index.js";
6
6
  export { activateDocumentLink, addDocumentLink, canMutateDocumentLink, canMutateLocalDocumentLink, moveDocumentLink, moveLocalDocumentLink, removeDocumentLink, } from "./documentQueries/documentStructure.js";
7
7
  export { listBlobInfo, } from "./info/blobInfo.js";