@tearleads/client-sdk 0.1.235 → 0.1.236

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 (88) hide show
  1. package/client/containerContents/documentDiscovery.js +1 -1
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/organizations/index.js +1 -1
  4. package/client/organizations/index.js.map +1 -1
  5. package/client/organizations/organizationMemberships.d.ts +6 -5
  6. package/client/organizations/organizationMemberships.js +12 -69
  7. package/client/organizations/organizationMemberships.js.map +1 -1
  8. package/client/runtime/workflowRuntime.js +5 -1
  9. package/client/runtime/workflowRuntime.js.map +1 -1
  10. package/data/sqlite/schema/index.d.ts +0 -45
  11. package/data/sqlite/schema/organizationSyncPauseSchema.js +6 -17
  12. package/data/sqlite/schema/organizationSyncPauseSchema.js.map +1 -1
  13. package/data/sync/organizationSyncPauseReadMachine.js +29 -0
  14. package/data/sync/organizationSyncPauseReadMachine.js.map +1 -0
  15. package/data/sync/organizationSyncPauses.d.ts +23 -34
  16. package/data/sync/organizationSyncPauses.js +49 -57
  17. package/data/sync/organizationSyncPauses.js.map +1 -1
  18. package/internal/validators/operation/organizationMemberships.d.ts +3 -21
  19. package/internal/validators/operation/organizationMemberships.js +2 -3
  20. package/internal/validators/operation/organizationMemberships.js.map +1 -1
  21. package/internal/validators/response/organizationMembership.d.ts +3 -3
  22. package/internal/validators/response/organizationMembership.js +3 -3
  23. package/internal/validators/response/organizationMembership.js.map +1 -1
  24. package/package.json +1 -1
  25. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  26. package/stores/container-contents/containerContentsStore.js +0 -2
  27. package/stores/container-contents/containerContentsStore.js.map +1 -1
  28. package/stores/container-contents/syncAgent/index.js +6 -0
  29. package/stores/container-contents/syncAgent/index.js.map +1 -1
  30. package/stores/container-contents/types.d.ts +0 -6
  31. package/stores/container-contents/types.js.map +1 -1
  32. package/stores/documents/documentStore/index.js +3 -4
  33. package/stores/documents/documentStore/index.js.map +1 -1
  34. package/stores/documents/documentStore/initialization/index.js +7 -7
  35. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  36. package/stores/documents/documentStore/sync/index.js +2 -5
  37. package/stores/documents/documentStore/sync/index.js.map +1 -1
  38. package/stores/documents/documentStore/sync/syncRequest.js +9 -2
  39. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  40. package/stores/documents/registry.d.ts +1 -34
  41. package/stores/documents/registry.js +4 -78
  42. package/stores/documents/registry.js.map +1 -1
  43. package/workflows/container-contents/metadata/metadataRemoteSync.js +1 -0
  44. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  45. package/workflows/container-contents/remoteHydration/index.js +1 -1
  46. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  47. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js +2 -4
  48. package/workflows/container-contents/remoteHydration/remoteContainers/organizationSyncPauseFilter.js.map +1 -1
  49. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +3 -3
  50. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  51. package/workflows/container-contents/syncPause/discoveryGuard.js +7 -6
  52. package/workflows/container-contents/syncPause/discoveryGuard.js.map +1 -1
  53. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -2
  54. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  55. package/workflows/documents/sync/index.js +8 -0
  56. package/workflows/documents/sync/index.js.map +1 -1
  57. package/workflows/documents/sync/readOnlySync.js +6 -0
  58. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  59. package/workflows/documents/sync/remoteDocumentSyncPass.d.ts +7 -1
  60. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -1
  61. package/workflows/documents/sync/syncAttemptPlanning.js +24 -8
  62. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  63. package/workflows/documents/syncFailures/index.js +6 -3
  64. package/workflows/documents/syncFailures/index.js.map +1 -1
  65. package/workflows/documents/syncFailures/syncAbandon.js +21 -0
  66. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  67. package/workflows/organizations/index.d.ts +1 -1
  68. package/workflows/organizations/index.js +1 -1
  69. package/workflows/organizations/index.js.map +1 -1
  70. package/workflows/organizations/memberships/organizationMemberships.d.ts +10 -35
  71. package/workflows/organizations/memberships/organizationMemberships.js +27 -44
  72. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  73. package/workflows/shared/runtimeInput.d.ts +11 -1
  74. package/workflows/shared/runtimeInput.js.map +1 -1
  75. package/workflows/sync/coordination.d.ts +1 -1
  76. package/workflows/sync/coordination.js +1 -1
  77. package/workflows/sync/coordination.js.map +1 -1
  78. package/workflows/sync/index.d.ts +1 -1
  79. package/workflows/sync/index.js +1 -1
  80. package/workflows/sync/index.js.map +1 -1
  81. package/data/persistence/container-contents/exclusiveDocumentPlacements.js +0 -61
  82. package/data/persistence/container-contents/exclusiveDocumentPlacements.js.map +0 -1
  83. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +0 -76
  84. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +0 -1
  85. package/stores/documents/removedDocumentStore.js +0 -40
  86. package/stores/documents/removedDocumentStore.js.map +0 -1
  87. package/workflows/container-contents/syncPause/documentRemoval.js +0 -165
  88. package/workflows/container-contents/syncPause/documentRemoval.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.235",
3
+ "version": "0.1.236",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -2,7 +2,7 @@ import type { DomainScope } from "../../data/shared/domainScope.js";
2
2
  import { type ContainerContentsPersistence } from "../../workflows/container-contents/containerPersistence.js";
3
3
  import { type ContainerContentsStoreRuntime, createContainerContentsStoreSyncAgent } from "./syncAgent/index.js";
4
4
  import type { ContainerContentsStore, ContainerContentsStoreOptions, ContainerContentsStoreState } from "./types.js";
5
- type ContainerWriteMethods = Pick<ContainerContentsStore, "createChild" | "deleteContainer" | "emptyTrash" | "ensureSystemContainer" | "forgetOrganizationContent" | "moveContainer" | "prepareGroupRewrap" | "purgeContainer" | "renameContainer" | "setContainerIcon" | "setContainerPrimaryDocument" | "shareWithGroup" | "shareWithUser">;
5
+ type ContainerWriteMethods = Pick<ContainerContentsStore, "createChild" | "deleteContainer" | "emptyTrash" | "ensureSystemContainer" | "moveContainer" | "prepareGroupRewrap" | "purgeContainer" | "renameContainer" | "setContainerIcon" | "setContainerPrimaryDocument" | "shareWithGroup" | "shareWithUser">;
6
6
  export declare function createContainerWriteMethods(state: ContainerContentsStoreState, syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>): ContainerWriteMethods;
7
7
  export declare function createContainerContentsStore(initialRuntime: ContainerContentsStoreRuntime, persistence?: ContainerContentsPersistence, options?: ContainerContentsStoreOptions): ContainerContentsStore;
8
8
  export declare function getOrCreateContainerContentsStore(domainScope: DomainScope, runtime: ContainerContentsStoreRuntime, options?: ContainerContentsStoreOptions): ContainerContentsStore;
@@ -4,7 +4,6 @@ import { persistContainerState } from "./containerState/containerStatePersistenc
4
4
  import { createTreeRefreshMethods } from "./hydration/remoteHydrationRefresh.js";
5
5
  import { createChildContainer, deleteContainer, ensureSystemContainer, moveContainer, renameContainer, } from "./operations/index.js";
6
6
  import { emptyTrash } from "./operations/emptyTrashOperation.js";
7
- import { createForgetOrganizationContentMethod } from "./operations/forgetOrganizationContentOperation.js";
8
7
  import { prepareContainerGroupRewrap, verifyContainerGroupRewrapCurrent, } from "./operations/groupRewrapOperation.js";
9
8
  import { purgeContainer } from "./operations/purgeContainerOperation.js";
10
9
  import { chainPurgeAfterScopeMoves } from "./operations/purgeMoveSettlementOperation.js";
@@ -118,7 +117,6 @@ export function createContainerWriteMethods(state, syncAgent) {
118
117
  purgeContainer: (containerId, options) => chainPurgeAfterScopeMoves(state, syncAgent, containerId, options, (isCurrent) => purgeContainer(state, syncAgent, containerId, options, isCurrent)),
119
118
  emptyTrash: (trashContainerId, options) => chainPurgeAfterScopeMoves(state, syncAgent, trashContainerId, options, (isCurrent) => emptyTrash(state, syncAgent, trashContainerId, options, isCurrent)),
120
119
  ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),
121
- forgetOrganizationContent: createForgetOrganizationContentMethod(state, chainContainerWrite),
122
120
  moveContainer: (containerId, parentId) => chainContainerWrite(state, (isCurrent) => moveContainer(state, syncAgent, containerId, parentId, isCurrent), [containerId, parentId], containerId),
123
121
  prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),
124
122
  renameContainer: (containerId, name) => chainContainerWrite(state, (isCurrent) => renameContainer(state, syncAgent, containerId, name, isCurrent), [containerId]),
@@ -1 +1 @@
1
- {"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,aAAa,EACb,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,gBAA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E;QACD,aAAa,EAAE,CAAC,WAAW,EAAE,EAAE,CAC7B,kCAAkC,CAAC,KAAK,EAAE,SAAS,EAAE,WAAW,CAAC;KACpE,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,4BAA4B,CAC1C,cAA6C,EAC7C,cAA4C,mCAAmC,EAC/E,UAAyC,EAAE;IAE3C,OAAO,iCAAiC,CAAC,cAAc,EAAE,WAAW,EAAE,OAAO,CAAC;SAC3E,KAAK,CAAC;AACX,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,WAAwB,EACxB,OAAsC,EACtC,UAAyC,EAAE;IAE3C,MAAM,aAAa,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IACtE,IAAI,aAAa,EAAE,CAAC;QAClB,aAAa,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;QACrC,OAAO,aAAa,CAAC,KAAK,CAAC;IAC7B,CAAC;IAED,MAAM,SAAS,GAAG,iCAAiC,CACjD,OAAO,EACP,mCAAmC,EACnC,OAAO,CACR,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport { createTreeRefreshMethods } from \"./hydration/remoteHydrationRefresh\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport { createForgetOrganizationContentMethod } from \"./operations/forgetOrganizationContentOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { chainPurgeAfterScopeMoves } from \"./operations/purgeMoveSettlementOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport { setContainerPrimaryDocument } from \"./operations/setContainerPrimaryDocumentOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { chainContainerWrite } from \"./remoteWrites/localWriteQueue\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"forgetOrganizationContent\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId, accessLevel) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n async (isCurrent) => {\n // Sharing admits the recipient, so a pin observed on first sight is\n // not enough: a verified identity link (or this device's keys) must\n // have established it, or the full-bundle signed roster. The\n // check runs inside the write scope, which must still be current\n // once it returns.\n await state.runtime.requireVerifiedRecipient(userId, accessLevel);\n if (!isCurrent()) return false;\n return shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n accessLevel,\n isCurrent,\n );\n },\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n containerId,\n options,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n ),\n emptyTrash: (trashContainerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n trashContainerId,\n options,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n forgetOrganizationContent: createForgetOrganizationContentMethod(\n state,\n chainContainerWrite,\n ),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerPrimaryDocument: (containerId, documentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerPrimaryDocument(\n state,\n syncAgent,\n containerId,\n documentId,\n isCurrent,\n ),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n ...createTreeRefreshMethods(state, syncAgent),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
1
+ {"version":3,"file":"containerContentsStore.js","sourceRoot":"","sources":["containerContentsStore.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kCAAkC,EAAE,MAAM,oEAAoE,CAAC;AACxH,OAAO,EAEL,mCAAmC,GACpC,MAAM,yDAAyD,CAAC;AACjE,OAAO,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,oCAAoC,CAAC;AAC9E,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,aAAa,EACb,eAAe,GAChB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,iCAAiC,GAClC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AACtF,OAAO,EAAE,gBAAgB,EAAE,MAAM,wCAAwC,CAAC;AAC1E,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAChG,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,+BAA+B,EAAE,MAAM,gCAAgC,CAAC;AACjF,OAAO,EACL,iCAAiC,EACjC,iCAAiC,EACjC,+BAA+B,EAC/B,uCAAuC,EACvC,mCAAmC,GACpC,MAAM,SAAS,CAAC;AACjB,OAAO,EAGL,qCAAqC,GACtC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,0CAA0C,CAAC;AAOlF,MAAM,8BAA8B,GAAG,IAAI,OAAO,EAG/C,CAAC;AAQJ,S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,CAAC;IACF,8BAA8B,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC3D,OAAO,SAAS,CAAC,KAAK,CAAC;AACzB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uCAAuC,CACrD,WAAwB;IAExB,MAAM,KAAK,GAAG,8BAA8B,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC9D,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,CAAC,sBAAsB,EAAE,CAAC;IAC/B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport { getCachedContainerWriterProjection } from \"../../workflows/container-contents/container-state/projectionCache\";\nimport {\n type ContainerContentsPersistence,\n defaultContainerContentsPersistence,\n} from \"../../workflows/container-contents/containerPersistence\";\nimport { persistContainerState } from \"./containerState/containerStatePersistence\";\nimport { createTreeRefreshMethods } from \"./hydration/remoteHydrationRefresh\";\nimport {\n createChildContainer,\n deleteContainer,\n ensureSystemContainer,\n moveContainer,\n renameContainer,\n} from \"./operations\";\nimport { emptyTrash } from \"./operations/emptyTrashOperation\";\nimport {\n prepareContainerGroupRewrap,\n verifyContainerGroupRewrapCurrent,\n} from \"./operations/groupRewrapOperation\";\nimport { purgeContainer } from \"./operations/purgeContainerOperation\";\nimport { chainPurgeAfterScopeMoves } from \"./operations/purgeMoveSettlementOperation\";\nimport { setContainerIcon } from \"./operations/setContainerIconOperation\";\nimport { setContainerPrimaryDocument } from \"./operations/setContainerPrimaryDocumentOperation\";\nimport {\n shareContainerWithGroup,\n shareContainerWithUser,\n} from \"./operations/shareOperations\";\nimport { chainContainerWrite } from \"./remoteWrites/localWriteQueue\";\nimport { chainRemoteContainerTask } from \"./remoteWrites/remoteWriteQueue\";\nimport { captureContainerWriteGeneration } from \"./remoteWrites/writeGeneration\";\nimport {\n createContainerContentsStoreState,\n subscribeToContainerContentsStore,\n updateContainerContentsSnapshot,\n updateContainerContentsStorePersistence,\n updateContainerContentsStoreRuntime,\n} from \"./state\";\nimport {\n type ContainerContentsStoreRuntime,\n type ContainerContentsStoreSyncAgent,\n createContainerContentsStoreSyncAgent,\n} from \"./syncAgent\";\nimport { findRootContainerState } from \"./systemContainers/systemContainerLookup\";\nimport type {\n ContainerContentsStore,\n ContainerContentsStoreOptions,\n ContainerContentsStoreState,\n} from \"./types\";\n\nconst containerContentsStoresByScope = new WeakMap<\n DomainScope,\n ContainerContentsStoreEntry\n>();\n\ninterface ContainerContentsStoreEntry {\n requestDocumentPriming: () => void;\n store: ContainerContentsStore;\n updateOptions: (options: ContainerContentsStoreOptions) => void;\n}\n\nfunction applyContainerContentsStoreOptions(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n options: ContainerContentsStoreOptions,\n): void {\n if (\"logLabel\" in options) {\n state.logLabel = options.logLabel;\n }\n\n if (\"persistence\" in options) {\n updateContainerContentsStorePersistence(\n state,\n options.persistence ?? defaultContainerContentsPersistence,\n syncAgent,\n );\n }\n}\n\nfunction getCachedContainerWriterProjectionForStore(\n state: ContainerContentsStoreState,\n containerId: string,\n) {\n const containerState = state.containersById.get(containerId);\n return containerState\n ? getCachedContainerWriterProjection(containerState)\n : null;\n}\n\nfunction createContainerContentsStoreSyncHost(\n state: ContainerContentsStoreState,\n): Parameters<typeof createContainerContentsStoreSyncAgent>[0][\"host\"] {\n return {\n persistContainerState: (\n containerState,\n patch,\n updateView,\n saveOptions,\n mutationOptions,\n ) =>\n persistContainerState(state, containerState, {\n patch,\n updateView,\n saveOptions,\n ...mutationOptions,\n }),\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n },\n updateSnapshot: () => updateContainerContentsSnapshot(state),\n };\n}\n\ntype ContainerWriteMethods = Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"prepareGroupRewrap\"\n | \"purgeContainer\"\n | \"renameContainer\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n>;\n\n// The group-rewrap builder verifies any required existing grant before capturing\n// the container KEK, then returns a check/rewrap pair. A verified non-match is\n// distinct from an unavailable preparation so security-critical callers can\n// no-op unrelated groups without failing open for a real grant.\nfunction createPrepareGroupRewrapMethod(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerContentsStore[\"prepareGroupRewrap\"] {\n return async (containerId, groupId, accessLevel, options) => {\n const preparation = await chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n prepareContainerGroupRewrap(\n state,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n );\n return preparation?.status === \"prepared\"\n ? {\n isCurrent: (\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n ) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n verifyContainerGroupRewrapCurrent(\n state,\n containerId,\n groupId,\n accessLevel,\n expectedGroupHead,\n expectedContainerId,\n expectedOrganizationId,\n isCurrent,\n ),\n containerId,\n ),\n rewrap: () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n {\n ...options,\n knownContainerKeks: preparation.knownContainerKeks,\n // A prepared re-wrap is grant-preserving by definition, so\n // it never mints a grant and never needs the chosen name.\n requireExistingGrant: true,\n },\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n status: \"prepared\" as const,\n }\n : (preparation ?? null);\n };\n}\n\nfunction createContainerSharingMethods(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): Pick<ContainerWriteMethods, \"shareWithUser\" | \"shareWithGroup\"> {\n return {\n shareWithUser: (containerId, userId, accessLevel) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n async (isCurrent) => {\n // Sharing admits the recipient, so a pin observed on first sight is\n // not enough: a verified identity link (or this device's keys) must\n // have established it, or the full-bundle signed roster. The\n // check runs inside the write scope, which must still be current\n // once it returns.\n await state.runtime.requireVerifiedRecipient(userId, accessLevel);\n if (!isCurrent()) return false;\n return shareContainerWithUser(\n state,\n syncAgent,\n containerId,\n userId,\n accessLevel,\n isCurrent,\n );\n },\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n shareWithGroup: (containerId, groupId, accessLevel, options) =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n false,\n (isCurrent) =>\n shareContainerWithGroup(\n state,\n syncAgent,\n containerId,\n groupId,\n accessLevel,\n options,\n isCurrent,\n ),\n containerId,\n { preserveResultOnLocalWrite: true },\n ),\n };\n}\n\nfunction createDeleteContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"deleteContainer\"] {\n return (containerId) => {\n const current = captureContainerWriteGeneration(state);\n const remoteDelete = () =>\n chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n (isCurrent) =>\n deleteContainer(state, syncAgent, containerId, isCurrent),\n containerId,\n ).then((node) => node !== null);\n if (state.containersById.get(containerId)?.record.documentId)\n return remoteDelete();\n let promoted = false;\n return chainContainerWrite(\n state,\n (isCurrent) => {\n // Promotion can win while this local operation was queued. Hand it to\n // the remote queue after releasing the local chain, before any HTTP I/O.\n promoted = Boolean(\n state.containersById.get(containerId)?.record.documentId,\n );\n return promoted\n ? Promise.resolve(null)\n : deleteContainer(state, syncAgent, containerId, isCurrent);\n },\n [containerId],\n ).then((node) => (promoted && current() ? remoteDelete() : node !== null));\n };\n}\n\nfunction createEnsureSystemContainerMethod(\n state: ContainerContentsStoreState,\n syncAgent: ContainerContentsStoreSyncAgent,\n): ContainerContentsStore[\"ensureSystemContainer\"] {\n return (systemSlot, name, options) => {\n const work = (isCurrent: () => boolean) =>\n ensureSystemContainer(\n state,\n syncAgent,\n systemSlot,\n name,\n options,\n isCurrent,\n );\n const rootId = findRootContainerState(state)?.container.id;\n return options?.deferRemoteBootstrap\n ? chainContainerWrite(state, work, [])\n : chainRemoteContainerTask(\n state,\n syncAgent,\n null,\n work,\n rootId ? { rootId, systemSlot } : undefined,\n );\n };\n}\n\nexport function createContainerWriteMethods(\n state: ContainerContentsStoreState,\n syncAgent: ReturnType<typeof createContainerContentsStoreSyncAgent>,\n): ContainerWriteMethods {\n return {\n ...createContainerSharingMethods(state, syncAgent),\n createChild: (parentId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n createChildContainer(state, syncAgent, parentId, name, isCurrent),\n [parentId],\n ),\n deleteContainer: createDeleteContainerMethod(state, syncAgent),\n purgeContainer: (containerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n containerId,\n options,\n (isCurrent) =>\n purgeContainer(state, syncAgent, containerId, options, isCurrent),\n ),\n emptyTrash: (trashContainerId, options) =>\n chainPurgeAfterScopeMoves(\n state,\n syncAgent,\n trashContainerId,\n options,\n (isCurrent) =>\n emptyTrash(state, syncAgent, trashContainerId, options, isCurrent),\n ),\n ensureSystemContainer: createEnsureSystemContainerMethod(state, syncAgent),\n moveContainer: (containerId, parentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n moveContainer(state, syncAgent, containerId, parentId, isCurrent),\n [containerId, parentId],\n containerId,\n ),\n prepareGroupRewrap: createPrepareGroupRewrapMethod(state, syncAgent),\n renameContainer: (containerId, name) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n renameContainer(state, syncAgent, containerId, name, isCurrent),\n [containerId],\n ),\n setContainerPrimaryDocument: (containerId, documentId) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerPrimaryDocument(\n state,\n syncAgent,\n containerId,\n documentId,\n isCurrent,\n ),\n [containerId],\n ),\n setContainerIcon: (containerId, icon) =>\n chainContainerWrite(\n state,\n (isCurrent) =>\n setContainerIcon(state, syncAgent, containerId, icon, isCurrent),\n [containerId],\n ),\n };\n}\n\nfunction createContainerContentsStoreEntry(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStoreEntry {\n const state = createContainerContentsStoreState(\n initialRuntime,\n options.persistence ?? persistence,\n options.logLabel,\n );\n const syncAgent = createContainerContentsStoreSyncAgent({\n host: createContainerContentsStoreSyncHost(state),\n state,\n });\n const writeMethods = createContainerWriteMethods(state, syncAgent);\n\n return {\n requestDocumentPriming: () => {\n state.documentStoresNeedPriming = true;\n syncAgent.scheduleSync();\n },\n store: {\n ...writeMethods,\n ...createTreeRefreshMethods(state, syncAgent),\n // Force an on-demand local SQLite re-read (see the interface doc): arm the\n // gate refreshLocalContainerStates otherwise requires, which the runtime\n // auto-arms only on a context transition an on-demand caller cannot rely on.\n refreshLocalContainers: () => {\n state.localContainersNeedRefresh = true;\n return syncAgent.refreshLocalContainers();\n },\n requestSync: () => syncAgent.scheduleSync(),\n getCachedContainerWriterProjection: (containerId) =>\n getCachedContainerWriterProjectionForStore(state, containerId),\n getSnapshot: () => state.snapshot,\n subscribe: (listener) =>\n subscribeToContainerContentsStore(state, listener),\n updateRuntime: (runtime) =>\n updateContainerContentsStoreRuntime(state, runtime, syncAgent),\n },\n updateOptions: (nextOptions) =>\n applyContainerContentsStoreOptions(state, syncAgent, nextOptions),\n };\n}\n\nexport function createContainerContentsStore(\n initialRuntime: ContainerContentsStoreRuntime,\n persistence: ContainerContentsPersistence = defaultContainerContentsPersistence,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n return createContainerContentsStoreEntry(initialRuntime, persistence, options)\n .store;\n}\n\nexport function getOrCreateContainerContentsStore(\n domainScope: DomainScope,\n runtime: ContainerContentsStoreRuntime,\n options: ContainerContentsStoreOptions = {},\n): ContainerContentsStore {\n const existingEntry = containerContentsStoresByScope.get(domainScope);\n if (existingEntry) {\n existingEntry.updateOptions(options);\n return existingEntry.store;\n }\n\n const nextEntry = createContainerContentsStoreEntry(\n runtime,\n defaultContainerContentsPersistence,\n options,\n );\n containerContentsStoresByScope.set(domainScope, nextEntry);\n return nextEntry.store;\n}\n\n/**\n * Arm the next structural pass's document-priming scan for a domain scope.\n * Priming normally re-arms only on store creation and topology changes, so a\n * caller that just tore down a document's local state uses this to have the\n * still-listed server document re-created without waiting for an app\n * restart. Returns false when the scope has no container-contents store yet;\n * the startup priming pass covers that case.\n */\nexport function requestContainerContentsDocumentPriming(\n domainScope: DomainScope,\n): boolean {\n const entry = containerContentsStoresByScope.get(domainScope);\n if (!entry) {\n return false;\n }\n\n entry.requestDocumentPriming();\n return true;\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { loadLocalContainerStates } from "../../../workflows/container-contents/localState.js";
2
2
  import { isDatabaseUnavailableError, registerContainerContentsSyncLane, } from "../../../workflows/container-contents/syncLane.js";
3
+ import { loadOrganizationSyncPausesBeforeSync } from "../../../workflows/sync/coordination.js";
3
4
  import { createRestoredAccessReconciler } from "../accessRestorationSweep.js";
4
5
  import { primeStoreDocumentSubtree } from "../documentWork/documentRecovery.js";
5
6
  import { observeContainerBackgroundHydration } from "../hydration/backgroundHydration.js";
@@ -22,6 +23,11 @@ async function initializeContainerContentsStore(input) {
22
23
  if (loadRuntime.infra.dbStatus !== "ready") {
23
24
  return;
24
25
  }
26
+ await loadOrganizationSyncPausesBeforeSync({
27
+ domainScope: loadRuntime.state.domainScope,
28
+ execSql: loadRuntime.infra.execSql,
29
+ log: loadRuntime.util.log,
30
+ });
25
31
  const localContainerStates = await loadLocalContainerStates({
26
32
  persistence,
27
33
  runtime: loadRuntime,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAE5F,OAAO,EACL,0BAA0B,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EAAE,CACvB,sCAAsC,CAAC;YACrC,IAAI;YACJ,eAAe;YACf,uBAAuB;YACvB,2BAA2B,EAAE,CAAC,iBAAiB,EAAE,EAAE;gBACjD,iBAAiB,CAAC;oBAChB,2BAA2B,EAAE,KAAK;oBAClC,SAAS,EAAE,CAAC,iBAAiB,CAAC;iBAC/B,CAAC,CAAC;YACL,CAAC;YACD,KAAK;SACN,CAAC;KACL,CAAC,CAAC;IAEH,OAAO;QACL,iBAAiB,EAAE,GAAG,EAAE;YACtB,uCAAuC,CAAC;gBACtC,kBAAkB;gBAClB,IAAI;gBACJ,qBAAqB,EAAE,OAAO;gBAC9B,kBAAkB;gBAClB,YAAY;gBACZ,KAAK;aACN,CAAC,CAAC;YACH,KAAK,kBAAkB,EAAE,CAAC;QAC5B,CAAC;QACD,kBAAkB;QAClB,qBAAqB,EAAE,wBAAwB,CAAC,MAAM;QACtD,8BAA8B,EAAE,CAAC,eAAe,EAAE,SAAS,EAAE,EAAE,CAC7D,yBAAyB,CAAC,KAAK,EAAE,eAAe,EAAE,SAAS,CAAC;QAC9D,sBAAsB,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAC1E,OAAO;QACP,eAAe,EAAE,CAAC,OAAO,EAAE,EAAE,CAC3B,0BAA0B,CAAC;YACzB,0BAA0B,EAAE,OAAO,EAAE,0BAA0B;YAC/D,SAAS,EAAE,OAAO,EAAE,SAAS;YAC7B,gBAAgB,EAAE,uBAAuB;YACzC,KAAK;SACN,CAAC;QACJ,sBAAsB,EAAE,gBAAgB;QACxC,uBAAuB,EAAE,iBAAiB;QAC1C,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import { loadLocalContainerStates } from \"../../../workflows/container-contents/localState\";\nimport type { RemoteContainerHydrationHost } from \"../../../workflows/container-contents/remoteHydration\";\nimport {\n isDatabaseUnavailableError,\n registerContainerContentsSyncLane,\n} from \"../../../workflows/container-contents/syncLane\";\nimport { createRestoredAccessReconciler } from \"../accessRestorationSweep\";\nimport { primeStoreDocumentSubtree } from \"../documentWork/documentRecovery\";\nimport { observeContainerBackgroundHydration } from \"../hydration/backgroundHydration\";\nimport {\n type RemoteHydrationRefreshOptions,\n refreshAllRemoteHydration,\n refreshRootRemoteHydration,\n} from \"../hydration/remoteHydrationRefresh\";\nimport { requestContainerContentsRemoteHydration } from \"../hydration/remoteHydrationRequest\";\nimport {\n hasStartupContainerSyncWork,\n scheduleStaleStartupRemoteHydration,\n} from \"../hydration/startupHydration\";\nimport { refreshLocalContainerStates } from \"../localRefresh\";\nimport { getContainerContentsStoreLogLabel } from \"../logLabel\";\nimport { createRemoteContainerIngestionController } from \"../remoteEvents/remoteContainerIngestion\";\nimport { handleContainerContentsRemoteEvents } from \"../remoteEvents/remoteEventSync\";\nimport { consumePendingContainerContentsReconnectRefresh } from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\nimport { runContainerContentsStoreSyncIteration } from \"./syncLaneIteration\";\n\nexport type { ContainerState } from \"../../../workflows/container-contents/remoteHydration\";\nexport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgentTypes\";\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nasync function initializeContainerContentsStore(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const {\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n } = input;\n const persistence = state.persistence;\n const loadRuntime = state.runtime;\n if (loadRuntime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n const localContainerStates = await loadLocalContainerStates({\n persistence,\n runtime: loadRuntime,\n });\n if (!isCurrent()) {\n return;\n }\n\n for (const containerState of localContainerStates) {\n state.containersById.set(containerState.container.id, containerState);\n }\n\n state.initialized = true;\n\n const shouldScheduleStaleRootRecovery =\n await scheduleStaleStartupRemoteHydration({\n isCurrent,\n requestHydration: () =>\n requestContainerContentsRemoteHydration({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n }),\n state,\n });\n if (!isCurrent()) {\n return;\n }\n const runtime = state.runtime;\n const hasPendingRestorationSweep =\n typeof runtime.auth.userId === \"string\" &&\n (\n await persistence.listDormantMetadataSweepRequests(\n loadRuntime.infra.execSql,\n runtime.auth.userId,\n )\n ).length > 0;\n if (!isCurrent()) {\n return;\n }\n\n host.updateSnapshot();\n handleRemoteEvents();\n\n runtime.util.log(\n `${getContainerContentsStoreLogLabel(state)}: loaded ${state.containersById.size} container(s)`,\n );\n\n const currentRuntime = state.runtime;\n if (currentRuntime.auth.isAuthenticated && currentRuntime.state.online) {\n const hasStartupWork =\n shouldScheduleStaleRootRecovery ||\n hasPendingRestorationSweep ||\n (await hasStartupContainerSyncWork(state));\n if (!isCurrent() || !hasStartupWork) {\n return;\n }\n currentRuntime.util.log(\n shouldScheduleStaleRootRecovery\n ? `${getContainerContentsStoreLogLabel(state)}: startup detected stale root recovery; scheduling lane pass`\n : `${getContainerContentsStoreLogLabel(state)}: startup detected durable sync work; scheduling lane pass`,\n );\n scheduleSync();\n }\n}\n\nfunction waitForStaleLocalRefreshBeforeInitialization(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): boolean {\n const { state } = input;\n const activeRefresh = state.localContainerRefreshPromise;\n if (\n !activeRefresh ||\n (state.localContainerRefreshGeneration === state.lifecycleGeneration &&\n state.localContainerRefreshStructuralGeneration ===\n state.structuralGeneration)\n ) {\n return false;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n state.initializeGeneration = lifecycleGeneration;\n const releaseInitializationBarrier = () => {\n if (state.initializePromise !== initializationBarrier) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n };\n const initializationBarrier = activeRefresh.then(\n releaseInitializationBarrier,\n releaseInitializationBarrier,\n );\n state.initializePromise = initializationBarrier;\n return true;\n}\n\nfunction ensureContainerContentsStoreInitialized(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const { handleRemoteEvents, host, resumeRecoveryWork, scheduleSync, state } =\n input;\n if (state.initialized || state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n if (state.initializePromise) {\n return;\n }\n if (waitForStaleLocalRefreshBeforeInitialization(input)) {\n return;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n const persistence = state.persistence;\n const execSql = state.runtime.infra.execSql;\n const isCurrent = () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.persistence === persistence &&\n state.runtime.infra.execSql === execSql;\n state.initializeGeneration = lifecycleGeneration;\n const initializePromise = initializeContainerContentsStore({\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n })\n .catch((error: unknown) => {\n if (!isCurrent() || isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n if (state.initializePromise !== initializePromise) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (isCurrent()) {\n consumePendingContainerContentsReconnectRefresh(\n state,\n input.refreshAfterReconnect,\n );\n } else if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n });\n state.initializePromise = initializePromise;\n}\n\n// Read the runtime lazily: updateRuntime replaces state.runtime, so a\n// reference captured at lane registration would report into a dead identity's\n// host. Returns the host's result: both callbacks are declared `=> void` but\n// may be async, and the lane reporter only catches a rejection it is handed.\nfunction logSyncLaneFailure(\n state: ContainerContentsStoreSyncState,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = state.runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nfunction createHydrationRequester(input: {\n host: RemoteContainerHydrationHost;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent[\"requestRemoteHydration\"] {\n return (options = {}) =>\n requestContainerContentsRemoteHydration({\n ...input,\n followDiscoveredParentLanes: options.followDiscoveredParentLanes,\n parentIds: options.parentIds,\n resetAllLaneWatermarks: options.resetAllLaneWatermarks,\n });\n}\n\nexport function createContainerContentsStoreSyncAgent(input: {\n host: RemoteContainerHydrationHost;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent {\n const { host, state } = input;\n const scheduleSync = () => requestContainerContentsStoreSync(state);\n const remoteContainerIngestion = createRemoteContainerIngestionController({\n host,\n scheduleSync,\n state,\n });\n const resumeRecoveryWork = remoteContainerIngestion.resumeInterruptedWork;\n\n const requestHydration = createHydrationRequester({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const requestRefreshHydration = (options: RemoteHydrationRefreshOptions) =>\n requestContainerContentsRemoteHydration({\n ...options,\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const scheduleHydration = (\n options?: Parameters<typeof requestHydration>[0],\n ) => observeContainerBackgroundHydration(state, requestHydration(options));\n const refresh: ContainerContentsStoreSyncAgent[\"refresh\"] = (options) =>\n refreshAllRemoteHydration({\n // Explicit user refresh must rediscover children hidden by unsigned hints.\n resetAllLaneWatermarks: options?.resetAllLaneWatermarks,\n requestHydration: requestRefreshHydration,\n state,\n });\n const handleRemoteEvents = () =>\n handleContainerContentsRemoteEvents({\n requestHydration,\n scheduleSync,\n state,\n });\n const reconcileRestoredAccess = createRestoredAccessReconciler({\n requestHydration: requestRefreshHydration,\n state,\n });\n\n state.syncLane = registerContainerContentsSyncLane({\n domainScope: state.runtime.state.domainScope,\n logError: (message, error) => logSyncLaneFailure(state, message, error),\n run: (policyOperation) =>\n runContainerContentsStoreSyncIteration({\n host,\n policyOperation,\n reconcileRestoredAccess,\n requestRemoteReconciliation: (parentContainerId) => {\n scheduleHydration({\n followDiscoveredParentLanes: false,\n parentIds: [parentContainerId],\n });\n },\n state,\n }),\n });\n\n return {\n ensureInitialized: () => {\n ensureContainerContentsStoreInitialized({\n handleRemoteEvents,\n host,\n refreshAfterReconnect: refresh,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n void resumeRecoveryWork();\n },\n handleRemoteEvents,\n ingestRemoteContainer: remoteContainerIngestion.ingest,\n primeDocumentsForSharedSubtree: (rootContainerId, isCurrent) =>\n primeStoreDocumentSubtree(state, rootContainerId, isCurrent),\n refreshLocalContainers: () => refreshLocalContainerStates({ host, state }),\n refresh,\n refreshRootLane: (options) =>\n refreshRootRemoteHydration({\n includeActiveRootChildLane: options?.includeActiveRootChildLane,\n parentIds: options?.parentIds,\n requestHydration: requestRefreshHydration,\n state,\n }),\n requestRemoteHydration: requestHydration,\n scheduleRemoteHydration: scheduleHydration,\n scheduleSync,\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAE5F,OAAO,EACL,0BAA0B,EAC1B,iCAAiC,GAClC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,oCAAoC,EAAE,MAAM,sCAAsC,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC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sCAAsC,CAAC;YACrC,IAAI;YACJ,eAAe;YACf,uBAAuB;YACvB,2BAA2B,EAAE,CAAC,iBAAiB,EAAE,EAAE;gBACjD,iBAAiB,CAAC;oBAChB,2BAA2B,EAAE,KAAK;oBAClC,SAAS,EAAE,CAAC,iBAAiB,CAAC;iBAC/B,CAAC,CAAC;YACL,CAAC;YACD,KAAK;SACN,CAAC;KACL,CAAC,CAAC;IAEH,OAAO;QACL,iBAAiB,EAAE,GAAG,EAAE;YACtB,uCAAuC,CAAC;gBACtC,kBAAkB;gBAClB,IAAI;gBACJ,qBAAqB,EAAE,OAAO;gBAC9B,kBAAkB;gBAClB,YAAY;gBACZ,KAAK;aACN,CAAC,CAAC;YACH,KAAK,kBAAkB,EAAE,CAAC;QAC5B,CAAC;QACD,kBAAkB;QAClB,qBAAqB,EAAE,wBAAwB,CAAC,MAAM;QACtD,8BAA8B,EAAE,CAAC,eAAe,EAAE,SAAS,EAAE,EAAE,CAC7D,yBAAyB,CAAC,KAAK,EAAE,eAAe,EAAE,SAAS,CAAC;QAC9D,sBAAsB,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAC1E,OAAO;QACP,eAAe,EAAE,CAAC,OAAO,EAAE,EAAE,CAC3B,0BAA0B,CAAC;YACzB,0BAA0B,EAAE,OAAO,EAAE,0BAA0B;YAC/D,SAAS,EAAE,OAAO,EAAE,SAAS;YAC7B,gBAAgB,EAAE,uBAAuB;YACzC,KAAK;SACN,CAAC;QACJ,sBAAsB,EAAE,gBAAgB;QACxC,uBAAuB,EAAE,iBAAiB;QAC1C,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import { loadLocalContainerStates } from \"../../../workflows/container-contents/localState\";\nimport type { RemoteContainerHydrationHost } from \"../../../workflows/container-contents/remoteHydration\";\nimport {\n isDatabaseUnavailableError,\n registerContainerContentsSyncLane,\n} from \"../../../workflows/container-contents/syncLane\";\nimport { loadOrganizationSyncPausesBeforeSync } from \"../../../workflows/sync/coordination\";\nimport { createRestoredAccessReconciler } from \"../accessRestorationSweep\";\nimport { primeStoreDocumentSubtree } from \"../documentWork/documentRecovery\";\nimport { observeContainerBackgroundHydration } from \"../hydration/backgroundHydration\";\nimport {\n type RemoteHydrationRefreshOptions,\n refreshAllRemoteHydration,\n refreshRootRemoteHydration,\n} from \"../hydration/remoteHydrationRefresh\";\nimport { requestContainerContentsRemoteHydration } from \"../hydration/remoteHydrationRequest\";\nimport {\n hasStartupContainerSyncWork,\n scheduleStaleStartupRemoteHydration,\n} from \"../hydration/startupHydration\";\nimport { refreshLocalContainerStates } from \"../localRefresh\";\nimport { getContainerContentsStoreLogLabel } from \"../logLabel\";\nimport { createRemoteContainerIngestionController } from \"../remoteEvents/remoteContainerIngestion\";\nimport { handleContainerContentsRemoteEvents } from \"../remoteEvents/remoteEventSync\";\nimport { consumePendingContainerContentsReconnectRefresh } from \"../state\";\nimport type {\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n} from \"./syncAgentTypes\";\nimport { runContainerContentsStoreSyncIteration } from \"./syncLaneIteration\";\n\nexport type { ContainerState } from \"../../../workflows/container-contents/remoteHydration\";\nexport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncAgent,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgentTypes\";\n\nfunction requestContainerContentsStoreSync(\n state: ContainerContentsStoreSyncState,\n) {\n state.syncLane?.requestSync();\n}\n\nasync function initializeContainerContentsStore(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n isCurrent: () => boolean;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const {\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n } = input;\n const persistence = state.persistence;\n const loadRuntime = state.runtime;\n if (loadRuntime.infra.dbStatus !== \"ready\") {\n return;\n }\n\n await loadOrganizationSyncPausesBeforeSync({\n domainScope: loadRuntime.state.domainScope,\n execSql: loadRuntime.infra.execSql,\n log: loadRuntime.util.log,\n });\n const localContainerStates = await loadLocalContainerStates({\n persistence,\n runtime: loadRuntime,\n });\n if (!isCurrent()) {\n return;\n }\n\n for (const containerState of localContainerStates) {\n state.containersById.set(containerState.container.id, containerState);\n }\n\n state.initialized = true;\n\n const shouldScheduleStaleRootRecovery =\n await scheduleStaleStartupRemoteHydration({\n isCurrent,\n requestHydration: () =>\n requestContainerContentsRemoteHydration({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n }),\n state,\n });\n if (!isCurrent()) {\n return;\n }\n const runtime = state.runtime;\n const hasPendingRestorationSweep =\n typeof runtime.auth.userId === \"string\" &&\n (\n await persistence.listDormantMetadataSweepRequests(\n loadRuntime.infra.execSql,\n runtime.auth.userId,\n )\n ).length > 0;\n if (!isCurrent()) {\n return;\n }\n\n host.updateSnapshot();\n handleRemoteEvents();\n\n runtime.util.log(\n `${getContainerContentsStoreLogLabel(state)}: loaded ${state.containersById.size} container(s)`,\n );\n\n const currentRuntime = state.runtime;\n if (currentRuntime.auth.isAuthenticated && currentRuntime.state.online) {\n const hasStartupWork =\n shouldScheduleStaleRootRecovery ||\n hasPendingRestorationSweep ||\n (await hasStartupContainerSyncWork(state));\n if (!isCurrent() || !hasStartupWork) {\n return;\n }\n currentRuntime.util.log(\n shouldScheduleStaleRootRecovery\n ? `${getContainerContentsStoreLogLabel(state)}: startup detected stale root recovery; scheduling lane pass`\n : `${getContainerContentsStoreLogLabel(state)}: startup detected durable sync work; scheduling lane pass`,\n );\n scheduleSync();\n }\n}\n\nfunction waitForStaleLocalRefreshBeforeInitialization(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): boolean {\n const { state } = input;\n const activeRefresh = state.localContainerRefreshPromise;\n if (\n !activeRefresh ||\n (state.localContainerRefreshGeneration === state.lifecycleGeneration &&\n state.localContainerRefreshStructuralGeneration ===\n state.structuralGeneration)\n ) {\n return false;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n state.initializeGeneration = lifecycleGeneration;\n const releaseInitializationBarrier = () => {\n if (state.initializePromise !== initializationBarrier) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n };\n const initializationBarrier = activeRefresh.then(\n releaseInitializationBarrier,\n releaseInitializationBarrier,\n );\n state.initializePromise = initializationBarrier;\n return true;\n}\n\nfunction ensureContainerContentsStoreInitialized(input: {\n handleRemoteEvents: () => void;\n host: RemoteContainerHydrationHost;\n refreshAfterReconnect: () => Promise<boolean>;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}) {\n const { handleRemoteEvents, host, resumeRecoveryWork, scheduleSync, state } =\n input;\n if (state.initialized || state.runtime.infra.dbStatus !== \"ready\") {\n return;\n }\n if (state.initializePromise) {\n return;\n }\n if (waitForStaleLocalRefreshBeforeInitialization(input)) {\n return;\n }\n\n const lifecycleGeneration = state.lifecycleGeneration;\n const persistence = state.persistence;\n const execSql = state.runtime.infra.execSql;\n const isCurrent = () =>\n state.lifecycleGeneration === lifecycleGeneration &&\n state.persistence === persistence &&\n state.runtime.infra.execSql === execSql;\n state.initializeGeneration = lifecycleGeneration;\n const initializePromise = initializeContainerContentsStore({\n handleRemoteEvents,\n host,\n isCurrent,\n resumeRecoveryWork,\n scheduleSync,\n state,\n })\n .catch((error: unknown) => {\n if (!isCurrent() || isDatabaseUnavailableError(error)) {\n return;\n }\n\n throw error;\n })\n .finally(() => {\n if (state.initializePromise !== initializePromise) {\n return;\n }\n state.initializePromise = null;\n state.initializeGeneration = null;\n if (isCurrent()) {\n consumePendingContainerContentsReconnectRefresh(\n state,\n input.refreshAfterReconnect,\n );\n } else if (state.runtime.infra.dbStatus === \"ready\") {\n ensureContainerContentsStoreInitialized(input);\n }\n });\n state.initializePromise = initializePromise;\n}\n\n// Read the runtime lazily: updateRuntime replaces state.runtime, so a\n// reference captured at lane registration would report into a dead identity's\n// host. Returns the host's result: both callbacks are declared `=> void` but\n// may be async, and the lane reporter only catches a rejection it is handed.\nfunction logSyncLaneFailure(\n state: ContainerContentsStoreSyncState,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = state.runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nfunction createHydrationRequester(input: {\n host: RemoteContainerHydrationHost;\n resumeRecoveryWork: () => Promise<void>;\n scheduleSync: () => void;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent[\"requestRemoteHydration\"] {\n return (options = {}) =>\n requestContainerContentsRemoteHydration({\n ...input,\n followDiscoveredParentLanes: options.followDiscoveredParentLanes,\n parentIds: options.parentIds,\n resetAllLaneWatermarks: options.resetAllLaneWatermarks,\n });\n}\n\nexport function createContainerContentsStoreSyncAgent(input: {\n host: RemoteContainerHydrationHost;\n state: ContainerContentsStoreSyncState;\n}): ContainerContentsStoreSyncAgent {\n const { host, state } = input;\n const scheduleSync = () => requestContainerContentsStoreSync(state);\n const remoteContainerIngestion = createRemoteContainerIngestionController({\n host,\n scheduleSync,\n state,\n });\n const resumeRecoveryWork = remoteContainerIngestion.resumeInterruptedWork;\n\n const requestHydration = createHydrationRequester({\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const requestRefreshHydration = (options: RemoteHydrationRefreshOptions) =>\n requestContainerContentsRemoteHydration({\n ...options,\n host,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n const scheduleHydration = (\n options?: Parameters<typeof requestHydration>[0],\n ) => observeContainerBackgroundHydration(state, requestHydration(options));\n const refresh: ContainerContentsStoreSyncAgent[\"refresh\"] = (options) =>\n refreshAllRemoteHydration({\n // Explicit user refresh must rediscover children hidden by unsigned hints.\n resetAllLaneWatermarks: options?.resetAllLaneWatermarks,\n requestHydration: requestRefreshHydration,\n state,\n });\n const handleRemoteEvents = () =>\n handleContainerContentsRemoteEvents({\n requestHydration,\n scheduleSync,\n state,\n });\n const reconcileRestoredAccess = createRestoredAccessReconciler({\n requestHydration: requestRefreshHydration,\n state,\n });\n\n state.syncLane = registerContainerContentsSyncLane({\n domainScope: state.runtime.state.domainScope,\n logError: (message, error) => logSyncLaneFailure(state, message, error),\n run: (policyOperation) =>\n runContainerContentsStoreSyncIteration({\n host,\n policyOperation,\n reconcileRestoredAccess,\n requestRemoteReconciliation: (parentContainerId) => {\n scheduleHydration({\n followDiscoveredParentLanes: false,\n parentIds: [parentContainerId],\n });\n },\n state,\n }),\n });\n\n return {\n ensureInitialized: () => {\n ensureContainerContentsStoreInitialized({\n handleRemoteEvents,\n host,\n refreshAfterReconnect: refresh,\n resumeRecoveryWork,\n scheduleSync,\n state,\n });\n void resumeRecoveryWork();\n },\n handleRemoteEvents,\n ingestRemoteContainer: remoteContainerIngestion.ingest,\n primeDocumentsForSharedSubtree: (rootContainerId, isCurrent) =>\n primeStoreDocumentSubtree(state, rootContainerId, isCurrent),\n refreshLocalContainers: () => refreshLocalContainerStates({ host, state }),\n refresh,\n refreshRootLane: (options) =>\n refreshRootRemoteHydration({\n includeActiveRootChildLane: options?.includeActiveRootChildLane,\n parentIds: options?.parentIds,\n requestHydration: requestRefreshHydration,\n state,\n }),\n requestRemoteHydration: requestHydration,\n scheduleRemoteHydration: scheduleHydration,\n scheduleSync,\n };\n}\n"]}
@@ -64,12 +64,6 @@ export interface ContainerContentsStore {
64
64
  moveContainer: (containerId: string, parentId: string) => Promise<ContainerNode | null>;
65
65
  purgeContainer: (containerId: string, options?: PurgeOptions) => Promise<boolean>;
66
66
  emptyTrash: (trashContainerId: string, options?: PurgeOptions) => Promise<boolean>;
67
- /**
68
- * Removes a paused organization's content from this device: every container
69
- * except its metadata root, and every document placed only in them. Local
70
- * only; the caller first confirms the organization has no unsynced writes.
71
- */
72
- forgetOrganizationContent: (organizationId: string) => Promise<boolean>;
73
67
  prepareGroupRewrap: (containerId: string, groupId: string, accessLevel: ContainerContentsShareAccessLevel, options?: {
74
68
  requireExistingGrant?: boolean;
75
69
  } | undefined) => Promise<ContainerGroupRewrapPreparation | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PurgeOptions } from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nimport type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport type { ContainerDocumentObjectSyncState } from \"../../workflows/container-contents/syncState\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgent/syncAgentTypes\";\n\n// Reuse the canonical access-level union from the crypto layer (the same source\n// `ContainerShareAccessLevel` chains to) rather than re-spelling the literals,\n// so the two can't drift.\nexport type ContainerContentsShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerContentsStoreOptions {\n logLabel?: string | undefined;\n persistence?: ContainerContentsPersistence | undefined;\n}\n\n/** Lets an explicit tree refresh learn that it may have stopped short. */\nexport interface ContainerTreeRefreshObserver {\n /**\n * Called once the refresh settles if any container listing request failed\n * or timed out while it ran, so lanes may have stayed unlisted. A refused\n * or unverifiable item is not reported: retrying cannot fix it.\n */\n readonly onListingUnavailable?: (() => void) | undefined;\n}\n\nexport interface ContainerNode {\n systemSlot?: ContainerSystemSlot | null;\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | undefined;\n id: string;\n icon?: string | null;\n metadataDocumentId?: string | null;\n /** False while a discovered remote folder has no local metadata content. */\n metadataReady?: boolean;\n /** Canonical document id stored in encrypted metadata; never a device-local id. */\n primaryDocumentId?: string | null;\n organizationId: string;\n name: string;\n parentId: string | null;\n syncState: ContainerDocumentObjectSyncState;\n kind: \"container\";\n updatedAt?: string | null;\n}\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation/refresh methods, spelled as a Pick so the two can't drift.\nexport type ContainerContentsContextValue = ContainerContentsSnapshot &\n Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"purgeContainer\"\n | \"refresh\"\n | \"refreshRootLane\"\n | \"renameContainer\"\n | \"requestSync\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n >;\n\nexport interface ContainerContentsSnapshot {\n nodes: ReadonlyArray<ContainerNode>;\n ready: boolean;\n}\n\nexport type ContainerGroupRewrapPreparation =\n | {\n status: \"not-granted\";\n }\n | {\n isCurrent(\n expectedGroupHead: ReferencedPrincipalHead,\n expectedContainerId: string,\n expectedOrganizationId: string,\n ): Promise<boolean>;\n rewrap(): Promise<boolean>;\n status: \"prepared\";\n };\n\n/**\n * Shared per-scope container tree and mutation store.\n *\n * Ordinary metadata/topology writes (`createChild`, `moveContainer`,\n * `renameContainer`, and `setContainerIcon`) commit to local persistence and\n * update subscribers before their queued remote sync converges. Destructive\n * and access-control operations retain their explicit remote-authority gates.\n */\nexport interface ContainerContentsStore {\n createChild: (\n parentId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n deleteContainer: (containerId: string) => Promise<boolean>;\n ensureSystemContainer: (\n systemSlot: ContainerSystemSlot,\n name: string,\n options?: EnsureSystemContainerOptions | undefined,\n ) => Promise<ContainerNode | null>;\n moveContainer: (\n containerId: string,\n parentId: string,\n ) => Promise<ContainerNode | null>;\n purgeContainer: (\n containerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n emptyTrash: (\n trashContainerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n /**\n * Removes a paused organization's content from this device: every container\n * except its metadata root, and every document placed only in them. Local\n * only; the caller first confirms the organization has no unsynced writes.\n */\n forgetOrganizationContent: (organizationId: string) => Promise<boolean>;\n // `options.requireExistingGrant` gates the preparation check only. The\n // prepared `rewrap` is always grant-preserving: it re-wraps a signed grant\n // and never mints one, so it carries no chosen group name, and it throws\n // (rather than healing through a policy mutation) when the container\n // manifest grants the group but the verified policy has no matching grant.\n prepareGroupRewrap: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options?: { requireExistingGrant?: boolean } | undefined,\n ) => Promise<ContainerGroupRewrapPreparation | null>;\n refresh: (options?: ContainerTreeRefreshObserver) => Promise<boolean>;\n refreshRootLane: (\n options?: RefreshRootLaneOptions & ContainerTreeRefreshObserver,\n ) => Promise<boolean>;\n // Re-read root-lane containers from local SQLite into the snapshot with NO\n // server round-trip. Surfaces a just-persisted container — e.g. the Trash bin\n // that registration/org-creation provisioned server-side and wrote to SQLite\n // via persistRegistrationBootstrap — instantly, instead of waiting for the\n // remote root-lane pull. Idempotent with a later remote pull: the merge is\n // keyed by container id, so the pull reconciles in place rather than duplicating.\n refreshLocalContainers: () => Promise<void>;\n requestSync: () => void;\n renameContainer: (\n containerId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n /** Null clears the preference. Target must be hydrated, linked and synced once. */\n setContainerPrimaryDocument: (\n containerId: string,\n documentId: string | null,\n ) => Promise<ContainerNode | null>;\n setContainerIcon: (\n containerId: string,\n icon: string | null,\n ) => Promise<ContainerNode | null>;\n shareWithGroup: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options: {\n /**\n * The display name the group was chosen by. Required: the share fails\n * closed if the verified group policy commits a different name. Signed\n * names are unique within an organization by construction (enforced at\n * group creation), so the target's own name identifies it.\n */\n expectedGroupName: string;\n },\n ) => Promise<boolean>;\n shareWithUser: (\n containerId: string,\n userId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n ) => Promise<boolean>;\n getCachedContainerWriterProjection: (\n containerId: string,\n ) => ContainerWriterProjectionResponse | null;\n getSnapshot: () => ContainerContentsSnapshot;\n subscribe: (listener: () => void) => () => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n}\n\nexport interface EnsureSystemContainerOptions {\n icon?: string | null | undefined;\n skipAdvancedManagedRoot?: boolean | undefined;\n // For local-first bootstrap paths where slow remote I/O must not block the\n // caller from creating the deterministic local system container.\n deferRemoteBootstrap?: boolean | undefined;\n // Create the deterministic local system container without queuing the remote\n // create. A later ensureSystemContainer call without this flag promotes the\n // local slot into the sync queue.\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface ContainerContentsStoreState\n extends ContainerContentsStoreSyncState {\n listeners: Set<() => void>;\n snapshot: ContainerContentsSnapshot;\n writeChain: Promise<ContainerNode | null>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PurgeOptions } from \"../../workflows/container-contents/container-state/purge/purgeProgress\";\nimport type { ContainerContentsPersistence } from \"../../workflows/container-contents/containerPersistence\";\nimport type { ContainerDocumentObjectSyncState } from \"../../workflows/container-contents/syncState\";\nimport type {\n ContainerContentsStoreRuntime,\n ContainerContentsStoreSyncState,\n RefreshRootLaneOptions,\n} from \"./syncAgent/syncAgentTypes\";\n\n// Reuse the canonical access-level union from the crypto layer (the same source\n// `ContainerShareAccessLevel` chains to) rather than re-spelling the literals,\n// so the two can't drift.\nexport type ContainerContentsShareAccessLevel = ContainerAccessLevel;\n\nexport interface ContainerContentsStoreOptions {\n logLabel?: string | undefined;\n persistence?: ContainerContentsPersistence | undefined;\n}\n\n/** Lets an explicit tree refresh learn that it may have stopped short. */\nexport interface ContainerTreeRefreshObserver {\n /**\n * Called once the refresh settles if any container listing request failed\n * or timed out while it ran, so lanes may have stayed unlisted. A refused\n * or unverifiable item is not reported: retrying cannot fix it.\n */\n readonly onListingUnavailable?: (() => void) | undefined;\n}\n\nexport interface ContainerNode {\n systemSlot?: ContainerSystemSlot | null;\n createdAt?: string | null;\n effectiveAccessLevel?: ContainerAccessLevel | undefined;\n id: string;\n icon?: string | null;\n metadataDocumentId?: string | null;\n /** False while a discovered remote folder has no local metadata content. */\n metadataReady?: boolean;\n /** Canonical document id stored in encrypted metadata; never a device-local id. */\n primaryDocumentId?: string | null;\n organizationId: string;\n name: string;\n parentId: string | null;\n syncState: ContainerDocumentObjectSyncState;\n kind: \"container\";\n updatedAt?: string | null;\n}\n\n// The store surface exposed through context: the snapshot fields plus the\n// store's mutation/refresh methods, spelled as a Pick so the two can't drift.\nexport type ContainerContentsContextValue = ContainerContentsSnapshot &\n Pick<\n ContainerContentsStore,\n | \"createChild\"\n | \"deleteContainer\"\n | \"emptyTrash\"\n | \"ensureSystemContainer\"\n | \"moveContainer\"\n | \"purgeContainer\"\n | \"refresh\"\n | \"refreshRootLane\"\n | \"renameContainer\"\n | \"requestSync\"\n | \"setContainerIcon\"\n | \"setContainerPrimaryDocument\"\n | \"shareWithGroup\"\n | \"shareWithUser\"\n >;\n\nexport interface ContainerContentsSnapshot {\n nodes: ReadonlyArray<ContainerNode>;\n ready: boolean;\n}\n\nexport type ContainerGroupRewrapPreparation =\n | {\n status: \"not-granted\";\n }\n | {\n isCurrent(\n expectedGroupHead: ReferencedPrincipalHead,\n expectedContainerId: string,\n expectedOrganizationId: string,\n ): Promise<boolean>;\n rewrap(): Promise<boolean>;\n status: \"prepared\";\n };\n\n/**\n * Shared per-scope container tree and mutation store.\n *\n * Ordinary metadata/topology writes (`createChild`, `moveContainer`,\n * `renameContainer`, and `setContainerIcon`) commit to local persistence and\n * update subscribers before their queued remote sync converges. Destructive\n * and access-control operations retain their explicit remote-authority gates.\n */\nexport interface ContainerContentsStore {\n createChild: (\n parentId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n deleteContainer: (containerId: string) => Promise<boolean>;\n ensureSystemContainer: (\n systemSlot: ContainerSystemSlot,\n name: string,\n options?: EnsureSystemContainerOptions | undefined,\n ) => Promise<ContainerNode | null>;\n moveContainer: (\n containerId: string,\n parentId: string,\n ) => Promise<ContainerNode | null>;\n purgeContainer: (\n containerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n emptyTrash: (\n trashContainerId: string,\n options?: PurgeOptions,\n ) => Promise<boolean>;\n // `options.requireExistingGrant` gates the preparation check only. The\n // prepared `rewrap` is always grant-preserving: it re-wraps a signed grant\n // and never mints one, so it carries no chosen group name, and it throws\n // (rather than healing through a policy mutation) when the container\n // manifest grants the group but the verified policy has no matching grant.\n prepareGroupRewrap: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options?: { requireExistingGrant?: boolean } | undefined,\n ) => Promise<ContainerGroupRewrapPreparation | null>;\n refresh: (options?: ContainerTreeRefreshObserver) => Promise<boolean>;\n refreshRootLane: (\n options?: RefreshRootLaneOptions & ContainerTreeRefreshObserver,\n ) => Promise<boolean>;\n // Re-read root-lane containers from local SQLite into the snapshot with NO\n // server round-trip. Surfaces a just-persisted container — e.g. the Trash bin\n // that registration/org-creation provisioned server-side and wrote to SQLite\n // via persistRegistrationBootstrap — instantly, instead of waiting for the\n // remote root-lane pull. Idempotent with a later remote pull: the merge is\n // keyed by container id, so the pull reconciles in place rather than duplicating.\n refreshLocalContainers: () => Promise<void>;\n requestSync: () => void;\n renameContainer: (\n containerId: string,\n name: string,\n ) => Promise<ContainerNode | null>;\n /** Null clears the preference. Target must be hydrated, linked and synced once. */\n setContainerPrimaryDocument: (\n containerId: string,\n documentId: string | null,\n ) => Promise<ContainerNode | null>;\n setContainerIcon: (\n containerId: string,\n icon: string | null,\n ) => Promise<ContainerNode | null>;\n shareWithGroup: (\n containerId: string,\n groupId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n options: {\n /**\n * The display name the group was chosen by. Required: the share fails\n * closed if the verified group policy commits a different name. Signed\n * names are unique within an organization by construction (enforced at\n * group creation), so the target's own name identifies it.\n */\n expectedGroupName: string;\n },\n ) => Promise<boolean>;\n shareWithUser: (\n containerId: string,\n userId: string,\n accessLevel: ContainerContentsShareAccessLevel,\n ) => Promise<boolean>;\n getCachedContainerWriterProjection: (\n containerId: string,\n ) => ContainerWriterProjectionResponse | null;\n getSnapshot: () => ContainerContentsSnapshot;\n subscribe: (listener: () => void) => () => void;\n updateRuntime: (runtime: ContainerContentsStoreRuntime) => void;\n}\n\nexport interface EnsureSystemContainerOptions {\n icon?: string | null | undefined;\n skipAdvancedManagedRoot?: boolean | undefined;\n // For local-first bootstrap paths where slow remote I/O must not block the\n // caller from creating the deterministic local system container.\n deferRemoteBootstrap?: boolean | undefined;\n // Create the deterministic local system container without queuing the remote\n // create. A later ensureSystemContainer call without this flag promotes the\n // local slot into the sync queue.\n deferRemoteSync?: boolean | undefined;\n}\n\nexport interface ContainerContentsStoreState\n extends ContainerContentsStoreSyncState {\n listeners: Set<() => void>;\n snapshot: ContainerContentsSnapshot;\n writeChain: Promise<ContainerNode | null>;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { DEFAULT_DOCUMENT_KIND } from "../../../data/documents/documentConstants.js";
2
2
  import { createDocumentProjectionUserKeyResolver, defaultDocumentsPersistence, didDocumentProjectionKeyRuntimeChange, didRegainSyncPrerequisites, requestDocumentSyncLaneAndWait, } from "../../../workflows/documents/index.js";
3
- import { createDocumentStoreFacade, emitPersistedDocument, getOrCreateDocumentStoreRegistry, registerDocumentStore, registerDocumentStoreIdentity, requestDocumentStoreSync, resolveDocumentStoreKey, takeRegisteredDocumentStore, } from "../registry.js";
3
+ import { createDocumentStoreFacade, emitPersistedDocument, getOrCreateDocumentStoreRegistry, registerDocumentStore, registerDocumentStoreIdentity, requestDocumentStoreSync, resolveDocumentStoreKey, } from "../registry.js";
4
4
  import { attachFilesToDocumentStore, replaceAttachmentInDocumentStore, } from "./attachments/index.js";
5
5
  import { removeAttachmentFromDocumentStore } from "./attachments/attachmentRemoval.js";
6
6
  import { discardDocumentStoreLocalState } from "./discard.js";
@@ -199,13 +199,12 @@ export function createDocumentStore(localId, initialRuntime, persistence = defau
199
199
  }
200
200
  export function getOrCreateDocumentStore(domainScope, localId, runtime, initialDocumentId = null, initialText = "", initialDocumentKind = DEFAULT_DOCUMENT_KIND, options = {}) {
201
201
  const registry = getOrCreateDocumentStoreRegistry(domainScope);
202
- const createBacking = () => createBackingDocumentStore(localId, runtime, defaultDocumentsPersistence, initialDocumentId, initialText, initialDocumentKind, options);
203
- const existingStore = takeRegisteredDocumentStore(registry, resolveDocumentStoreKey(registry, localId, initialDocumentId), createBacking);
202
+ const existingStore = registry.storesByKey.get(resolveDocumentStoreKey(registry, localId, initialDocumentId));
204
203
  if (existingStore) {
205
204
  registerDocumentStore(domainScope, localId, existingStore, initialDocumentId);
206
205
  return existingStore;
207
206
  }
208
- const nextStore = createDocumentStoreFacade(createBacking());
207
+ const nextStore = createDocumentStore(localId, runtime, defaultDocumentsPersistence, initialDocumentId, initialText, initialDocumentKind, options);
209
208
  registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);
210
209
  return nextStore;
211
210
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAGlF,OAAO,EACL,uCAAuC,EAEvC,2BAA2B,EAC3B,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,EACvB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W,GAAG,EAAE,EAChB,sBAA0C,qBAAqB,EAC/D,UAAoC,EAAE;IAEtC,MAAM,KAAK,GAAG,wBAAwB,CACpC,WAAW,EACX,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n takeRegisteredDocumentStore,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport { restoreDocumentStoreContent } from \"./history/restoreContent\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport { createRowWrites } from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n ...createRowWrites(state, scheduleSync, liveWrite),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n restoreContent: (content, options) =>\n liveWrite(() =>\n restoreDocumentStoreContent(state, scheduleSync, content, options),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const createBacking = () =>\n createBackingDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n const existingStore = takeRegisteredDocumentStore(\n registry,\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n createBacking,\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStoreFacade(createBacking());\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAGlF,OAAO,EACL,uCAAuC,EAEvC,2BAA2B,EAC3B,qCAAqC,EACrC,0BAA0B,EAC1B,8BAA8B,GAC/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,yBAAyB,EACzB,qBAAqB,EACrB,gCAAgC,EAChC,qBAAqB,EACrB,6BAA6B,EAC7B,wBAAwB,EACxB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AAQrB,OAAO,EACL,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,EACL,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,GACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,4BAA4B,EAAE,MAAM,iCAAiC,CAAC;AAC/E,OAAO,EAAE,8BAA8B,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,EACL,wBAAwB,EAExB,4BAA4B,EAC5B,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,SA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ACb,iBAAiB,CAClB,CAAC;QACF,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,MAAM,SAAS,GAAG,mBAAmB,CACnC,OAAO,EACP,OAAO,EACP,2BAA2B,EAC3B,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,qBAAqB,CAAC,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAC1E,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,WAAwB,EACxB,OAAe,EACf,OAAyB,EACzB,oBAAmC,IAAI,EACvC,WAAW,GAAG,EAAE,EAChB,sBAA0C,qBAAqB,EAC/D,UAAoC,EAAE;IAEtC,MAAM,KAAK,GAAG,wBAAwB,CACpC,WAAW,EACX,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,WAAW,EACX,mBAAmB,EACnB,OAAO,CACR,CAAC;IACF,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;IAC7B,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { DEFAULT_DOCUMENT_KIND } from \"../../../data/documents/documentConstants\";\nimport type { StoredDocumentKind } from \"../../../data/documents/documentKinds\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport {\n createDocumentProjectionUserKeyResolver,\n type DocumentsPersistence,\n defaultDocumentsPersistence,\n didDocumentProjectionKeyRuntimeChange,\n didRegainSyncPrerequisites,\n requestDocumentSyncLaneAndWait,\n} from \"../../../workflows/documents\";\nimport {\n createDocumentStoreFacade,\n emitPersistedDocument,\n getOrCreateDocumentStoreRegistry,\n registerDocumentStore,\n registerDocumentStoreIdentity,\n requestDocumentStoreSync,\n resolveDocumentStoreKey,\n} from \"../registry\";\nimport type {\n DocumentAttachmentUpload,\n DocumentStore,\n DocumentStoreFacade,\n DocumentStoreOpenOptions,\n DocumentsRuntime,\n} from \"../types\";\nimport {\n attachFilesToDocumentStore,\n replaceAttachmentInDocumentStore,\n} from \"./attachments\";\nimport { removeAttachmentFromDocumentStore } from \"./attachments/attachmentRemoval\";\nimport { discardDocumentStoreLocalState } from \"./discard\";\nimport { restoreDocumentStoreContent } from \"./history/restoreContent\";\nimport {\n ensureDocumentStoreInitialized,\n ensureDocumentStoreReady,\n relinkDocumentStore,\n} from \"./initialization\";\nimport { assertInitialContentFitsKind } from \"./initialization/initialContent\";\nimport { registerInternalDocumentRelink } from \"./internalRelink\";\nimport { countQueuedWrite } from \"./localWriteQueue\";\nimport { setDocumentStructuredFields, setDocumentText } from \"./mutations\";\nimport { assertLoadedDocumentStoreCanRotate } from \"./rotation/rotationPreflight\";\nimport { createRowWrites } from \"./rows\";\nimport {\n createDocumentStoreState,\n type DocumentStoreState,\n refreshAttachabilitySnapshot,\n resetDocumentStore,\n subscribeToDocumentStore,\n} from \"./state\";\nimport { registerDocumentStoreSyncLane } from \"./sync\";\nimport { logRevalidationScheduled } from \"./sync/remoteRevalidationTelemetry\";\nimport { settleDeferredStartupProbe } from \"./sync/startupProbeDeferral\";\nimport {\n allowDocumentStoreRemoteSync,\n captureDocumentStoreRemoteSyncRequestGeneration,\n captureDocumentStoreSyncLaneGeneration,\n type DocumentStoreRemoteSyncRequestGeneration,\n type DocumentStoreSyncLaneGeneration,\n didDocumentStoreRemoteSyncRequestComplete,\n hasPendingIndependentDocumentStoreRemoteSync,\n invalidateDocumentStoreRemoteSync,\n invalidateDocumentStoreSyncLane,\n isDocumentStoreRemoteSyncBlocked,\n isDocumentStoreRemoteSyncRequestGenerationCurrent,\n markDocumentStoreRemoteSyncPending,\n registerDocumentStoreRemoteSyncWaiter,\n} from \"./sync/syncGeneration\";\nimport { handleDocumentRemoteEvents } from \"./sync/syncRemoteSignals\";\n\nexport {\n discardRegisteredDocumentLocalState,\n requestDomainDocumentSync,\n subscribeToPersistedDocuments,\n} from \"../registry\";\n\nfunction refreshDocumentStoreSyncLane(\n state: DocumentStoreState,\n force = false,\n): void {\n if (!force && state.syncLane && !state.syncLane.isDisposed?.()) {\n return;\n }\n if (state.syncLane) {\n invalidateDocumentStoreSyncLane(state);\n }\n let syncLaneGeneration: DocumentStoreSyncLaneGeneration | null = null;\n state.syncLane = registerDocumentStoreSyncLane(\n state,\n () => syncLaneGeneration,\n );\n syncLaneGeneration = captureDocumentStoreSyncLaneGeneration(state);\n}\n\nfunction updateDocumentStoreRuntime(\n state: DocumentStoreState,\n nextRuntime: DocumentsRuntime,\n scheduleSync: () => void,\n) {\n const previousRuntime = state.runtime;\n const serverEventsReconnected =\n (nextRuntime.state.serverEventsConnectionGeneration ?? 0) >\n (previousRuntime.state.serverEventsConnectionGeneration ?? 0);\n const domainScopeChanged =\n previousRuntime.state.domainScope !== nextRuntime.state.domainScope;\n const projectionKeyRuntimeChanged = didDocumentProjectionKeyRuntimeChange(\n previousRuntime,\n nextRuntime,\n );\n if (projectionKeyRuntimeChanged) {\n state.resolveProjectionUserKey =\n createDocumentProjectionUserKeyResolver(nextRuntime);\n state.writerProjection = null;\n }\n state.runtime = nextRuntime;\n refreshDocumentStoreSyncLane(state, domainScopeChanged);\n if (domainScopeChanged) {\n state.locallyAcceptedUpdateIds = new Set();\n state.remoteUpdatePending = false;\n state.writerProjection = null;\n }\n\n if (nextRuntime.infra.dbStatus !== \"ready\") {\n if (state.snapshot.ready || state.initialized || state.initializePromise) {\n resetDocumentStore(state);\n }\n state.lastEventCount = nextRuntime.state.events.length;\n return;\n }\n\n refreshAttachabilitySnapshot(state);\n ensureDocumentStoreInitialized(state, scheduleSync);\n handleDocumentRemoteEvents(state, scheduleSync);\n\n if (state.snapshot.ready) {\n settleDeferredStartupProbe(state, serverEventsReconnected, scheduleSync);\n if (serverEventsReconnected) {\n // The invalidation stream is lossy while disconnected. Once the server\n // has acknowledged this socket's authoritative interest declaration,\n // every already-open remote document needs one HTTP probe to cover peer\n // writes made during the gap. This also closes iOS background/resume reconnects where the\n // native network source remained online throughout.\n requestRemoteDocumentStoreSync(state, scheduleSync);\n logRevalidationScheduled(state.runtime, \"reconnect\");\n } else if (didRegainSyncPrerequisites(previousRuntime, state.runtime)) {\n scheduleSync();\n }\n }\n}\n\nfunction requestRemoteDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n owner: \"independent\" | \"waiter\" = \"independent\",\n): number {\n allowDocumentStoreRemoteSync(state);\n const signalSequence = markDocumentStoreRemoteSyncPending(state, owner);\n scheduleSync();\n return signalSequence;\n}\n\nfunction requestOrdinaryDocumentStoreSync(\n state: DocumentStoreState,\n scheduleSync: () => void,\n): void {\n // A normal UI reopen is a fresh owner for remote-only work. It may recover\n // a probe that an earlier, now-unmounted owner aborted.\n if (isDocumentStoreRemoteSyncBlocked(state)) {\n requestRemoteDocumentStoreSync(state, scheduleSync);\n return;\n }\n scheduleSync();\n}\n\nfunction requestRemoteDocumentStoreSyncAndWait(\n state: DocumentStoreState,\n scheduleSync: () => void,\n signal?: AbortSignal,\n): Promise<boolean> {\n let requestGeneration: DocumentStoreRemoteSyncRequestGeneration | null = null;\n let requestedSignalSequence = 0;\n let releaseWaiter: (() => boolean) | null = null;\n const releaseRemoteSyncWaiter = (invalidate: boolean) => {\n const releasedLastWaiter = releaseWaiter?.() ?? false;\n if (\n invalidate &&\n releasedLastWaiter &&\n requestGeneration !== null &&\n isDocumentStoreRemoteSyncRequestGenerationCurrent(\n state,\n requestGeneration,\n ) &&\n !hasPendingIndependentDocumentStoreRemoteSync(state)\n ) {\n invalidateDocumentStoreRemoteSync(state);\n }\n };\n // A coordinator can be disposed and recreated while this same-scope store\n // remains registered. Refresh its handle before requesting work.\n refreshDocumentStoreSyncLane(state);\n return requestDocumentSyncLaneAndWait({\n didCompleteRequest: () =>\n requestGeneration !== null &&\n didDocumentStoreRemoteSyncRequestComplete(\n state,\n requestGeneration,\n requestedSignalSequence,\n ),\n domainScope: state.runtime.state.domainScope,\n localId: state.localId,\n request: () => {\n requestGeneration =\n captureDocumentStoreRemoteSyncRequestGeneration(state);\n releaseWaiter = registerDocumentStoreRemoteSyncWaiter(\n state,\n requestGeneration,\n );\n requestedSignalSequence = requestRemoteDocumentStoreSync(\n state,\n scheduleSync,\n \"waiter\",\n );\n },\n onInvalidated: () => releaseRemoteSyncWaiter(true),\n signal,\n }).then(\n (completed) => {\n releaseRemoteSyncWaiter(!completed);\n return completed;\n },\n (error: unknown) => {\n releaseRemoteSyncWaiter(true);\n throw error;\n },\n );\n}\n\nasync function discardBackingDocumentStoreLocalState(\n state: DocumentStoreState,\n scheduleSync: () => void,\n expectedDocumentId: string,\n) {\n try {\n return await discardDocumentStoreLocalState(state, expectedDocumentId);\n } finally {\n // Restart hydration whenever the attempt reset the store. This runs outside\n // its identity-chained task because initialization also chains writes.\n ensureDocumentStoreInitialized(state, scheduleSync);\n scheduleSync();\n }\n}\n\nfunction createLiveSyncLaneRequest(state: DocumentStoreState) {\n return <Result>(request: () => Result): Result => {\n refreshDocumentStoreSyncLane(state);\n return request();\n };\n}\n\nfunction registerBackingStoreInternalRelink(input: {\n scheduleSync: () => void;\n state: DocumentStoreState;\n store: DocumentStore;\n withLiveSyncLane: ReturnType<typeof createLiveSyncLaneRequest>;\n}): DocumentStore {\n registerInternalDocumentRelink(input.store, (relinkInput, commitSideEffect) =>\n input.withLiveSyncLane(() =>\n relinkDocumentStore(\n input.state,\n relinkInput,\n input.scheduleSync,\n commitSideEffect,\n ),\n ),\n );\n return input.store;\n}\n\nfunction createBackingStoreContext(\n localId: string,\n runtime: DocumentsRuntime,\n persistence: DocumentsPersistence,\n documentId: string | null,\n text: string,\n documentKind: StoredDocumentKind,\n options: DocumentStoreOpenOptions,\n) {\n const state = createDocumentStoreState(\n localId,\n runtime,\n persistence,\n {\n emitPersistedDocument,\n registerDocumentIdentity: registerDocumentStoreIdentity,\n },\n documentId,\n text,\n documentKind,\n (options.remoteSyncMode ?? \"startup\") === \"startup\",\n );\n if (options.deferInitialUpdate) state.deferInitialUpdate = true;\n const { initialRows, initialStructuredFields } = options;\n assertInitialContentFitsKind({ initialStructuredFields }, documentKind);\n state.initialContent = { initialRows, initialStructuredFields };\n refreshDocumentStoreSyncLane(state);\n const scheduleSync = () => requestDocumentStoreSync(state);\n return {\n scheduleSync,\n state,\n withLiveSyncLane: createLiveSyncLaneRequest(state),\n };\n}\n\nfunction createBackingDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n openOptions: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const context = createBackingStoreContext(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n openOptions,\n );\n\n const { scheduleSync, state, withLiveSyncLane } = context;\n // Local writes count as queued from the call, readiness wait included.\n const liveWrite = <Result>(write: () => Promise<Result>) =>\n withLiveSyncLane(() => countQueuedWrite(state, write()));\n const store: DocumentStore = {\n ...createRowWrites(state, scheduleSync, liveWrite),\n assertCanRotateContentKey: (proof) =>\n withLiveSyncLane(() =>\n assertLoadedDocumentStoreCanRotate(state, scheduleSync, proof),\n ),\n attachFiles: (files: ReadonlyArray<DocumentAttachmentUpload>) =>\n liveWrite(() => attachFilesToDocumentStore(state, scheduleSync, files)),\n discardLocalState: (expectedDocumentId: string) =>\n withLiveSyncLane(() =>\n discardBackingDocumentStoreLocalState(\n state,\n scheduleSync,\n expectedDocumentId,\n ),\n ),\n ensureInitialized: () =>\n withLiveSyncLane(() => ensureDocumentStoreReady(state, scheduleSync)),\n getSnapshot: () => state.snapshot,\n hasQueuedWrites: () => state.queuedWrites > 0,\n hasUnsavedLocalEdits: () => state.unsavedLocalEdits,\n removeAttachment: (slotId: string) =>\n liveWrite(() =>\n removeAttachmentFromDocumentStore(state, scheduleSync, slotId),\n ),\n replaceAttachment: (slotId: string, file: DocumentAttachmentUpload) =>\n liveWrite(() =>\n replaceAttachmentInDocumentStore(state, scheduleSync, slotId, file),\n ),\n requestRemoteSync: () =>\n withLiveSyncLane(() =>\n requestRemoteDocumentStoreSync(state, scheduleSync),\n ),\n restoreContent: (content, options) =>\n liveWrite(() =>\n restoreDocumentStoreContent(state, scheduleSync, content, options),\n ),\n requestRemoteSyncAndWait: (signal) =>\n requestRemoteDocumentStoreSyncAndWait(state, scheduleSync, signal),\n requestSync: () =>\n withLiveSyncLane(() =>\n requestOrdinaryDocumentStoreSync(state, scheduleSync),\n ),\n relink: (input) =>\n withLiveSyncLane(() => relinkDocumentStore(state, input, scheduleSync)),\n setStructuredFields: (kind, patch, options) =>\n liveWrite(() =>\n setDocumentStructuredFields(state, scheduleSync, kind, patch, options),\n ),\n setText: (value: string) =>\n liveWrite(() => setDocumentText(state, scheduleSync, value)),\n subscribe: (listener) => subscribeToDocumentStore(state, listener),\n updateRuntime: (runtime: DocumentsRuntime) =>\n updateDocumentStoreRuntime(state, runtime, scheduleSync),\n };\n return registerBackingStoreInternalRelink({ ...context, store });\n}\n\nexport function createDocumentStore(\n localId: string,\n initialRuntime: DocumentsRuntime,\n persistence: DocumentsPersistence = defaultDocumentsPersistence,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStoreFacade {\n return createDocumentStoreFacade(\n createBackingDocumentStore(\n localId,\n initialRuntime,\n persistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n ),\n );\n}\n\nexport function getOrCreateDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const registry = getOrCreateDocumentStoreRegistry(domainScope);\n const existingStore = registry.storesByKey.get(\n resolveDocumentStoreKey(registry, localId, initialDocumentId),\n );\n if (existingStore) {\n registerDocumentStore(\n domainScope,\n localId,\n existingStore,\n initialDocumentId,\n );\n return existingStore;\n }\n\n const nextStore = createDocumentStore(\n localId,\n runtime,\n defaultDocumentsPersistence,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n registerDocumentStore(domainScope, localId, nextStore, initialDocumentId);\n return nextStore;\n}\n\nexport function openDocumentStore(\n domainScope: DomainScope,\n localId: string,\n runtime: DocumentsRuntime,\n initialDocumentId: string | null = null,\n initialText = \"\",\n initialDocumentKind: StoredDocumentKind = DEFAULT_DOCUMENT_KIND,\n options: DocumentStoreOpenOptions = {},\n): DocumentStore {\n const store = getOrCreateDocumentStore(\n domainScope,\n localId,\n runtime,\n initialDocumentId,\n initialText,\n initialDocumentKind,\n options,\n );\n store.updateRuntime(runtime);\n return store;\n}\n"]}
@@ -4,7 +4,7 @@ import { DEFAULT_DOCUMENT_ACCESS_EPOCH, DEFAULT_DOCUMENT_KIND, } from "../../../
4
4
  import { initializeStoredDocumentKind, readStoredDocumentState, } from "../../../../data/documents/documentKinds.js";
5
5
  import { createPendingUpdateFields } from "../../../../data/documents/documentSync.js";
6
6
  import { isDatabaseUnavailableError, loadPersistedDocumentStoreState, } from "../../../../workflows/documents/index.js";
7
- import { OrganizationSyncPauseRepository } from "../../../../workflows/sync/coordination.js";
7
+ import { loadOrganizationSyncPausesBeforeSync } from "../../../../workflows/sync/coordination.js";
8
8
  import { chainIdentityWrite } from "../identityWriteChain.js";
9
9
  import { runDocumentOrphanMaintenance } from "../orphanMaintenance.js";
10
10
  import { advancePendingBaseVersion, documentSummaryFromRecord, persistDocument, saveDocumentRecord, } from "../persistence.js";
@@ -155,12 +155,12 @@ async function initializeDocumentStore(state, scheduleSync) {
155
155
  if (state.localWriteGeneration !== initializeGeneration) {
156
156
  return;
157
157
  }
158
- // A paused organization's cleanup removed it; creating it again would
159
- // download the organization's content while the pause lasts. A later open
160
- // retries, so it loads once the organization resumes.
161
- if (!persistedState.document &&
162
- (await new OrganizationSyncPauseRepository(state.runtime.infra.execSql).isPauseRemovedDocument(state.localId))) {
163
- state.initializePromise = null;
158
+ await loadOrganizationSyncPausesBeforeSync({
159
+ domainScope: state.runtime.state.domainScope,
160
+ execSql: state.runtime.infra.execSql,
161
+ log: state.runtime.util.log,
162
+ });
163
+ if (state.localWriteGeneration !== initializeGeneration) {
164
164
  return;
165
165
  }
166
166
  const restored = await restoreOrCreateInitialDocument({