@tearleads/client-sdk 0.1.252 → 0.1.253

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 (91) hide show
  1. package/Tearleads.js +3 -3
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/index.d.ts +2 -0
  4. package/client/containerContents/index.js +4 -9
  5. package/client/containerContents/index.js.map +1 -1
  6. package/client/containerContents/storeRuntime.d.ts +17 -0
  7. package/client/containerContents/storeRuntime.js +31 -0
  8. package/client/containerContents/storeRuntime.js.map +1 -0
  9. package/client/deviceFirst/index.d.ts +2 -3
  10. package/client/deviceFirst/index.js +44 -22
  11. package/client/deviceFirst/index.js.map +1 -1
  12. package/client/runtime/workflowRuntime.d.ts +2 -0
  13. package/client/runtime/workflowRuntime.js +13 -6
  14. package/client/runtime/workflowRuntime.js.map +1 -1
  15. package/data/sync/syncCoordinator.js +17 -10
  16. package/data/sync/syncCoordinator.js.map +1 -1
  17. package/package.json +1 -1
  18. package/stores/container-contents/containerContentsStore.d.ts +3 -9
  19. package/stores/container-contents/containerContentsStore.js +24 -21
  20. package/stores/container-contents/containerContentsStore.js.map +1 -1
  21. package/stores/container-contents/containerState/storeScope.js +6 -0
  22. package/stores/container-contents/containerState/storeScope.js.map +1 -0
  23. package/stores/container-contents/hydration/backgroundHydration.js +2 -1
  24. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  25. package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
  26. package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
  27. package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
  28. package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
  29. package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
  30. package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
  31. package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
  32. package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
  33. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  34. package/stores/container-contents/hydration/startupHydration.js +2 -9
  35. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  36. package/stores/container-contents/hydration/treeResetMachine.js +61 -0
  37. package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
  38. package/stores/container-contents/localRefresh.js +28 -12
  39. package/stores/container-contents/localRefresh.js.map +1 -1
  40. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
  41. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
  42. package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
  43. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
  44. package/stores/container-contents/state.d.ts +3 -7
  45. package/stores/container-contents/state.js +27 -16
  46. package/stores/container-contents/state.js.map +1 -1
  47. package/stores/container-contents/syncAgent/index.d.ts +7 -2
  48. package/stores/container-contents/syncAgent/index.js +77 -49
  49. package/stores/container-contents/syncAgent/index.js.map +1 -1
  50. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
  51. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  52. package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
  53. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  54. package/stores/local-projection/localProjectionStore.js +24 -15
  55. package/stores/local-projection/localProjectionStore.js.map +1 -1
  56. package/stores/local-projection/registry.js +2 -2
  57. package/stores/local-projection/registry.js.map +1 -1
  58. package/workflows/container-contents/container-state/create/createChild.js +3 -15
  59. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  60. package/workflows/container-contents/containerPersistence.d.ts +4 -8
  61. package/workflows/container-contents/containerPersistence.js +22 -12
  62. package/workflows/container-contents/containerPersistence.js.map +1 -1
  63. package/workflows/container-contents/localState.js +3 -0
  64. package/workflows/container-contents/localState.js.map +1 -1
  65. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
  66. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
  67. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
  68. package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
  69. package/workflows/container-contents/remoteHydration/index.js +17 -66
  70. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  71. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
  72. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
  73. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
  74. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  75. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
  76. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  77. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
  78. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  79. package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
  80. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  81. package/workflows/container-contents/runtime.d.ts +3 -0
  82. package/workflows/container-contents/runtime.js.map +1 -1
  83. package/workflows/container-contents/storedContainerState.js +17 -7
  84. package/workflows/container-contents/storedContainerState.js.map +1 -1
  85. package/workflows/container-contents/syncLane.d.ts +1 -0
  86. package/workflows/container-contents/syncLane.js +9 -1
  87. package/workflows/container-contents/syncLane.js.map +1 -1
  88. package/workflows/shared/runtimeInput.d.ts +2 -0
  89. package/workflows/shared/runtimeInput.js.map +1 -1
  90. package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
  91. package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,iC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ACnE,CAAC;IACJ,CAAC;CACF;AAED;;;;GAIG;AACH,KAAK,UAAU,oBAAoB,CACjC,OAA+D;IAE/D,IAAI,kBAAkB,GAAG,KAAK,CAAC;IAC/B,MAAM,OAAO,CAAC,GAAG,EAAE;QACjB,kBAAkB,GAAG,IAAI,CAAC;IAC5B,CAAC,CAAC,CAAC;IACH,IAAI,kBAAkB,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA8C,EAC9C,OAAe,EACf,KAAc;IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B;IAE/B,MAAM,KAAK,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAC7C,OAAO,uDAAuD,CAC5D,EAAE,GAAG,KAAK,EAAE,aAAa,EAAE,cAAc,CAAC,8BAA8B,EAAE,EAC1E,cAAc,CAAC,kBAAkB;IACjC,qEAAqE;IACrE,CAAC,MAAM,EAAE,WAAW,EAAE,EAAE,CACtB,qBAAqB,CACnB,cAAc,EACd,KAAK,CAAC,KAAK,CAAC,OAAO,EACnB,MAAM,EACN,WAAW,CACZ,CACJ,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n disposeDomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n} from \"../../workflows/container-contents\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentPriming/documentHydrationProbe\";\nimport type { ContainerContents } from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport { requireShareRecipient } from \"../organizations/recipientAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n for (const [domainScope, entry] of this.entriesByScope) {\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n disposeDomainSyncCoordinator(domainScope);\n }\n this.entriesByScope.clear();\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n service.start();\n\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n return entry;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) =>\n getOrCreateDomainSyncCoordinator(domainScope).registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: () =>\n refreshContainerTree((onListingUnavailable) =>\n store.getContainerStore().refresh({ onListingUnavailable }),\n ),\n refreshRootTree: () =>\n refreshContainerTree((onListingUnavailable) =>\n store.getContainerStore().refreshRootLane({ onListingUnavailable }),\n ),\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n/**\n * Runs one tree refresh and rejects if any listing request it made failed or\n * timed out: the crawl stopped short, so the tree may be stale even though\n * the refresh itself settled.\n */\nasync function refreshContainerTree(\n refresh: (onListingUnavailable: () => void) => Promise<boolean>,\n): Promise<void> {\n let listingUnavailable = false;\n await refresh(() => {\n listingUnavailable = true;\n });\n if (listingUnavailable) {\n throw new Error(\"Container tree listing was unavailable\");\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport function createDeviceFirstWorkflowRuntime(\n runtimeService: InternalRuntime,\n): ContainerContentsStoreWorkflowRuntime {\n const input = runtimeService.workflowInput();\n return createContainerContentsStoreWorkflowRuntimeFromSnapshot(\n { ...input, organizations: runtimeService.containerContentsOrganizations },\n runtimeService.adoptRootContainer,\n // Admit against the trust store of the database this runtime writes.\n (userId, accessLevel) =>\n requireShareRecipient(\n runtimeService,\n input.infra.execSql,\n userId,\n accessLevel,\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,EAChC,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,mCAAmC,EACnC,2BAA2B,EAC3B,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,mCAAmC,EACnC,qCAAqC,EACrC,6BAA6B,GAC9B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,+BAA+B,GAGhC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAG3B,yBAAyB,GAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kCAAkC,EAAE,MAAM,+EAA+E,CAAC;AACnI,OAAO,EAAE,oCAAoC,EAAE,MAAM,2EAA2E,CAAC;AACjI,OAAO,EAEL,mCAAmC,IAAI,gCAAgC,GACxE,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAElG,OAAO,EAAE,qCAAqC,EAAE,MAAM,iCAAiC,CAAC;AAgCxF,MAAM,UAAU,iBAAiB,CAC/B,cAA+B,EAC/B,iBAAoC;IAEpC,OAAO,IAAI,kBAAkB,CAAC,cAAc,EAAE,iBAAiB,CAAC,CAAC;AACnE,CAAC;AAWD,SAAS,cAAc,CAAC,KAA4B;IAClD,KAAK,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;IAC5B,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,IAA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AoB,EAAE,EAAE,CAC5C,KAAK,CAAC,iBAAiB,EAAE,CAAC,eAAe,CAAC,EAAE,oBAAoB,EAAE,CAAC,CACpE;YACH,gBAAgB,EAAE,0BAA0B;YAC5C,qEAAqE;YACrE,wEAAwE;YACxE,QAAQ,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE,CAC3B,wBAAwB,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC;SACnE,CAAC;IACJ,CAAC;CACF;AAED;;;;GAIG;AACH,KAAK,UAAU,oBAAoB,CACjC,OAA+D;IAE/D,IAAI,kBAAkB,GAAG,KAAK,CAAC;IAC/B,MAAM,OAAO,CAAC,GAAG,EAAE;QACjB,kBAAkB,GAAG,IAAI,CAAC;IAC5B,CAAC,CAAC,CAAC;IACH,IAAI,kBAAkB,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC;AAED,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,wBAAwB,CAC/B,OAA8C,EAC9C,OAAe,EACf,KAAc;IAEd,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC5D,CAAC;AAED,OAAO,EAAE,gCAAgC,EAAE,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n type DomainSyncCoordinator,\n getOrCreateDomainSyncCoordinator,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n type ContainerContentsStore,\n type ContainerContentsStoreOptions,\n isAutomaticRootCatchupContainerNode,\n isReconcilableContainerNode,\n isRemoteBackedContainerNode,\n} from \"../../stores/container-contents\";\nimport { openDocumentStore } from \"../../stores/documents\";\nimport {\n requestRegisteredDocumentRemoteSync,\n subscribeToPersistedDocumentDeletions,\n subscribeToPersistedDocuments,\n} from \"../../stores/documents/registry\";\nimport {\n getOrCreateLocalProjectionStore,\n type LocalProjectionStore,\n type LocalProjectionView,\n} from \"../../stores/local-projection\";\nimport {\n connectReconciliationTriggers,\n createReconciliationService,\n type ReconciliationHost,\n type ReconciliationService,\n systemReconciliationClock,\n} from \"../../sync/reconciliation\";\nimport {\n type ContainerContentsStoreWorkflowRuntime,\n createContainerContentsDocumentsRuntime,\n} from \"../../workflows/container-contents\";\nimport { listAllContainerDocumentIdsFromApi } from \"../../workflows/container-contents/documentDiscovery/containerDocumentListing\";\nimport { probeUndiscoveredRemoteDocumentBatch } from \"../../workflows/container-contents/documentPriming/documentHydrationProbe\";\nimport {\n type ContainerContents,\n createContainerContentsStoreRuntime as createDeviceFirstWorkflowRuntime,\n} from \"../containerContents\";\nimport { discoverContainerDocumentLanesForRuntime } from \"../containerContents/documentDiscovery\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { createReconciledDocumentContentPuller } from \"./reconciledDocumentContentPull\";\n\nexport type { LocalProjectionView } from \"../../stores/local-projection\";\n\n/** One domain scope's local read, local-write, and reconciliation handles. */\nexport interface DeviceFirstContainerContents {\n /**\n * Locally durable container tree and mutation store. Ordinary tree writes\n * update this store after local persistence and queue remote convergence in\n * the background; security-sensitive remote operations keep their explicit\n * online requirements.\n */\n readonly containerStore: ContainerContentsStore;\n /** Background remote reconciliation; never awaited for first paint. */\n readonly reconciler: ReconciliationService;\n /** Synchronously readable container/document projection. */\n readonly view: LocalProjectionView;\n}\n\n/**\n * Device-first facade. Opens a shared scope that pairs immediate local reads\n * and locally durable writes with background remote convergence.\n */\nexport interface DeviceFirst {\n /** Open all device-first handles for the current domain scope. */\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents;\n /** Stop the current scope's reconciler (if one was created) on teardown. */\n dispose(): void;\n}\n\nexport function createDeviceFirst(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n): DeviceFirst {\n return new DeviceFirstService(runtimeService, containerContents);\n}\n\ninterface DeviceFirstScopeEntry {\n retiring?: boolean;\n coordinator: DomainSyncCoordinator;\n contents: DeviceFirstContainerContents;\n disconnectReconciliationTriggers: () => void;\n unsubscribePersistedDocumentDeletions: () => void;\n unsubscribePersistedDocuments: () => void;\n}\n\nfunction stopScopeEntry(entry: DeviceFirstScopeEntry): void {\n entry.coordinator.dispose();\n entry.contents.reconciler.stop();\n entry.disconnectReconciliationTriggers();\n entry.unsubscribePersistedDocumentDeletions();\n entry.unsubscribePersistedDocuments();\n}\n\nfunction createInitialDocumentProbeHost(\n runtimeService: InternalRuntime,\n domainScope: ReconciliationHost[\"domainScope\"],\n): Pick<\n ReconciliationHost,\n | \"listContainerDocumentIds\"\n | \"probeUndiscoveredDocumentsBatch\"\n | \"reportInitialDocumentProbeComplete\"\n> {\n return {\n listContainerDocumentIds: (containerId) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return listAllContainerDocumentIdsFromApi({\n apiClient: runtime.apiClient,\n containerId,\n reportErrors: false,\n });\n },\n probeUndiscoveredDocumentsBatch: async (input) => {\n const runtime = createDeviceFirstWorkflowRuntime(runtimeService);\n return probeUndiscoveredRemoteDocumentBatch({\n ...input,\n host: {\n documentWorkflowRuntime: (containerId) =>\n createContainerContentsDocumentsRuntime(runtime, containerId),\n openDocumentStore: (target) =>\n openDocumentStore(\n domainScope,\n target.localId,\n target.runtime,\n target.documentId,\n ),\n },\n runtime,\n });\n },\n reportInitialDocumentProbeComplete: (requestedCount) => {\n runtimeService\n .workflowInput()\n .util.log(\n `Initial document hydration probe requested ${requestedCount} syncs`,\n );\n },\n };\n}\n\nclass DeviceFirstService implements DeviceFirst {\n // A real Map (not WeakMap) so dispose() can iterate every scope seen this\n // session. A running reconciler holds event subscriptions that keep an idle,\n // stale-scope service (and its scope) reachable anyway, so WeakMap bought no\n // GC here; the entries are released explicitly on dispose().\n private readonly entriesByScope = new Map<\n DomainScope,\n DeviceFirstScopeEntry\n >();\n\n constructor(\n private readonly runtimeService: InternalRuntime,\n private readonly containerContents: ContainerContents,\n ) {}\n\n open(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstContainerContents {\n return this.getOrCreateEntry(options).contents;\n }\n\n dispose(): void {\n // Stop every reconciler created this session — not just the current\n // scope's. A scope change (e.g. anonymous -> authenticated) leaves the old\n // scope's reconciler subscribed and its coordinator pump live; tear them\n // all down. Force-stop each scope's coordinator (which runs the reconciler\n // lane) alongside stopping the service.\n const entries = Array.from(this.entriesByScope);\n for (const [, entry] of entries) entry.retiring = true;\n for (const [scope, entry] of entries) this.retireEntry(scope, entry);\n }\n\n private retireEntry(scope: DomainScope, entry: DeviceFirstScopeEntry): void {\n if (this.entriesByScope.get(scope) !== entry) return;\n this.entriesByScope.delete(scope);\n stopScopeEntry(entry);\n }\n\n private workflowRuntime(): ContainerContentsStoreWorkflowRuntime {\n return createDeviceFirstWorkflowRuntime(this.runtimeService);\n }\n\n private getOrCreateEntry(\n options?: ContainerContentsStoreOptions | undefined,\n ): DeviceFirstScopeEntry {\n const runtime = this.workflowRuntime();\n const domainScope = runtime.state.domainScope;\n const existing = this.entriesByScope.get(domainScope);\n if (existing && (existing.retiring || existing.coordinator.isDisposed())) {\n this.retireEntry(domainScope, existing);\n return this.getOrCreateEntry(options);\n }\n if (existing) {\n // Do not call updateRuntime here: facade selectors run during React\n // render, and updateRuntime emits synchronously. Hosts drive runtime\n // updates through view.updateRuntime() from an effect instead.\n return existing;\n }\n\n const coordinator = getOrCreateDomainSyncCoordinator(domainScope);\n const store = getOrCreateLocalProjectionStore({\n domainScope,\n runtime,\n options,\n });\n // Opening the container store publishes its lane. A subscriber may have\n // finished opening this scope while that notification was in progress.\n if (this.entriesByScope.has(domainScope))\n return this.getOrCreateEntry(options);\n if (coordinator.isDisposed())\n throw new Error(\"Device-first scope retired during registration\");\n const service = createReconciliationService(\n this.createReconciliationHost(store, domainScope, coordinator),\n );\n const disconnectReconciliationTriggers = connectReconciliationTriggers({\n service,\n store,\n });\n const unsubscribePersistedDocumentDeletions =\n subscribeToPersistedDocumentDeletions(domainScope, (localId) => {\n store.removePersistedDocument(localId);\n });\n const unsubscribePersistedDocuments = subscribeToPersistedDocuments(\n domainScope,\n (document, change) =>\n store.refreshPersistedDocument(document, change.placementChanged),\n );\n const view: LocalProjectionView = {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n setActiveContainer: (containerId) =>\n store.setActiveContainer(containerId),\n updateRuntime: (nextRuntime) => store.updateRuntime(nextRuntime),\n };\n\n const entry: DeviceFirstScopeEntry = {\n coordinator,\n contents: {\n containerStore: store.getContainerStore(),\n reconciler: service,\n view,\n },\n disconnectReconciliationTriggers,\n unsubscribePersistedDocumentDeletions,\n unsubscribePersistedDocuments,\n };\n this.entriesByScope.set(domainScope, entry);\n service.start();\n const current = this.entriesByScope.get(domainScope);\n if (!current || current.coordinator.isDisposed()) {\n this.retireEntry(domainScope, entry);\n throw new Error(\"Device-first scope retired during registration\");\n }\n return current;\n }\n\n private createReconciliationHost(\n store: LocalProjectionStore,\n domainScope: ReconciliationHost[\"domainScope\"],\n coordinator: DomainSyncCoordinator,\n ): ReconciliationHost {\n const runtimeService = this.runtimeService;\n const containerContents = this.containerContents;\n const requestDocumentContentPull = createReconciledDocumentContentPuller({\n getContainer: (containerId) =>\n store\n .getSnapshot()\n .containers.find((container) => container.id === containerId) ?? null,\n pullDocumentContent: (input) =>\n containerContents.pullDocumentContent(input),\n requestRegisteredDocumentRemoteSync: (localId, documentId) =>\n requestRegisteredDocumentRemoteSync(domainScope, localId, documentId),\n });\n const canDiscoverContainerDocuments = (containerId: string) => {\n const container = store\n .getSnapshot()\n .containers.find((node) => node.id === containerId);\n return container ? isRemoteBackedContainerNode(container) : false;\n };\n const listKnownContainerIds = () => {\n // A local-first id is not listable yet and may still be racing its create\n // request. Once remote-backed, it participates normally; system contents\n // are especially important during rematerialization because this device\n // may not have authored them.\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isReconcilableContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n const listAutomaticRootCatchupContainerIds = () => {\n const homeOrganizationId =\n runtimeService.workflowInput().auth.organizationId;\n return store\n .getSnapshot()\n .containers.flatMap((node) =>\n isAutomaticRootCatchupContainerNode(node, homeOrganizationId)\n ? [node.id]\n : [],\n );\n };\n return {\n clock: systemReconciliationClock,\n domainScope,\n registerLane: (key, config) => coordinator.registerLane(key, config),\n canDiscoverContainerDocuments,\n getRuntimeStatus: () => {\n const input = runtimeService.workflowInput();\n return {\n dbStatus: input.infra.dbStatus,\n isAuthenticated: input.auth.isAuthenticated,\n online: input.state.online,\n };\n },\n listKnownContainerIds,\n // Root discovery can surface directly granted non-root containers, so\n // retain every regular container. Exclude only this identity's own system\n // children; cold/auth backfill and explicit full Refresh cover those.\n listAutomaticRootCatchupContainerIds,\n discoverContainerDocuments: (requests, onOutcome) =>\n discoverContainerDocumentLanesForRuntime({\n onOutcome,\n requests,\n runtimeService,\n }),\n loadContainerDelta: (containerId) =>\n store.loadContainerDelta(containerId),\n applyReconciled: (delta) => store.applyReconciled(delta),\n requestDocumentContentPull,\n ...createInitialDocumentProbeHost(runtimeService, domainScope),\n refreshTree: () =>\n refreshContainerTree((onListingUnavailable) =>\n store.getContainerStore().refresh({ onListingUnavailable }),\n ),\n refreshRootTree: () =>\n refreshContainerTree((onListingUnavailable) =>\n store.getContainerStore().refreshRootLane({ onListingUnavailable }),\n ),\n isIgnorableError: isDatabaseUnavailableError,\n // Resolve the runtime per call: it is rebuilt as the active identity\n // changes, and a reference captured here would report into a dead host.\n logError: (message, error) =>\n logReconciliationFailure(this.workflowRuntime(), message, error),\n };\n }\n}\n\n/**\n * Runs one tree refresh and rejects if any listing request it made failed or\n * timed out: the crawl stopped short, so the tree may be stale even though\n * the refresh itself settled.\n */\nasync function refreshContainerTree(\n refresh: (onListingUnavailable: () => void) => Promise<boolean>,\n): Promise<void> {\n let listingUnavailable = false;\n await refresh(() => {\n listingUnavailable = true;\n });\n if (listingUnavailable) {\n throw new Error(\"Container tree listing was unavailable\");\n }\n}\n\n// Returns the host's result: both callbacks are declared `=> void` but may be\n// async, and the lane reporter only catches a rejection it is handed.\nfunction logReconciliationFailure(\n runtime: ContainerContentsStoreWorkflowRuntime,\n message: string,\n error: unknown,\n): unknown {\n const { log, logError } = runtime.util;\n return logError ? logError(message, error) : log(message);\n}\n\nexport { createDeviceFirstWorkflowRuntime };\n"]}
@@ -39,6 +39,8 @@ export interface InternalRuntime {
39
39
  identityLinks: Pick<TrustedUserIdentityService, "createLink" | "createLinkFor" | "verifyLink" | "loadAdmissionPin" | "resolvePinned" | "resolveVerified" | "requireVerified">;
40
40
  retirePrincipalHistoryProtection(): void;
41
41
  readonly sessionGeneration: number;
42
+ /** Storage and session custody, stable through transport token renewal. */
43
+ readonly scopeGeneration: number;
42
44
  readonly adoptRootContainer: ContainerContentsRootAdopter;
43
45
  readonly deleteDocumentPlacements: DocumentPlacementCleanup;
44
46
  readonly containerContentsOrganizations: ContainerContentsOrganizationHost;
@@ -65,11 +65,8 @@ function sessionExecutor(dependencies) {
65
65
  ? sessionLifetime(dependencies.session).bind(execSql)
66
66
  : null;
67
67
  }
68
- export function createRuntime(dependencies) {
69
- const readyExecSql = () => sessionExecutor(dependencies);
70
- const runtimeSubscription = createRuntimeSubscription(dependencies);
71
- const { trustedUserIdentityService, resolveTrustedUserIdentity } = createRuntimeIdentityResolution(dependencies, readyExecSql, () => runtimeSubscription.recoveryGeneration);
72
- const historyProtection = createPrincipalHistoryProtectionCustody({
68
+ function createRuntimeHistoryProtection(dependencies, readGeneration) {
69
+ return createPrincipalHistoryProtectionCustody({
73
70
  keyProvider: dependencies.principalHistoryKeyProvider,
74
71
  readScope: () => {
75
72
  const signingFingerprint = dependencies.identity.signingFingerprint;
@@ -82,15 +79,24 @@ export function createRuntime(dependencies) {
82
79
  signingFingerprint,
83
80
  identityTrustDomain,
84
81
  database: dependencies.database.requireExecSql("principal history protection"),
85
- generation: runtimeSubscription.recoveryGeneration,
82
+ generation: readGeneration(),
86
83
  };
87
84
  },
88
85
  });
86
+ }
87
+ export function createRuntime(dependencies) {
88
+ const readyExecSql = () => sessionExecutor(dependencies);
89
+ const runtimeSubscription = createRuntimeSubscription(dependencies);
90
+ const { trustedUserIdentityService, resolveTrustedUserIdentity } = createRuntimeIdentityResolution(dependencies, readyExecSql, () => runtimeSubscription.recoveryGeneration);
91
+ const historyProtection = createRuntimeHistoryProtection(dependencies, () => runtimeSubscription.recoveryGeneration);
89
92
  const runtimeInput = createRuntimeInputFactory(dependencies, bindSessionIdentityResolver(resolveTrustedUserIdentity, sessionLifetime(dependencies.session)), historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration, () => runtimeSubscription.sessionGeneration).bind);
90
93
  return {
91
94
  identityTrustDomain: dependencies.identityTrustDomain,
92
95
  identityLinks: trustedUserIdentityService,
93
96
  retirePrincipalHistoryProtection: historyProtection.retire,
97
+ get scopeGeneration() {
98
+ return runtimeSubscription.mutationGeneration;
99
+ },
94
100
  get sessionGeneration() {
95
101
  return runtimeSubscription.sessionGeneration;
96
102
  },
@@ -181,6 +187,7 @@ function createRuntimeInputFactory(dependencies, bindIdentityResolver, bindHisto
181
187
  // connectivity signal for host/UI. See Session.syncEnabled.
182
188
  online: dependencies.network.online && dependencies.session.syncEnabled,
183
189
  peerScope: dependencies.peerScope ?? null,
190
+ serverEventsConnected: dependencies.events.connected,
184
191
  serverEventsConnectionGeneration: dependencies.events.connectionGeneration,
185
192
  serverEventsPendingConnectAttempt: dependencies.events.pendingConnectAttempt,
186
193
  });
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAA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Q,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { createContainerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { sessionLifetime } from \"../session\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport {\n bindSessionIdentityResolver,\n createRuntimeIdentityResolution,\n} from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport { createRuntimeSubscription } from \"./runtimeSubscription\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n readSessionGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n readSessionGeneration,\n signIn: sessionLifetime(dependencies.session),\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: sessionLifetime(dependencies.session).bind(\n dependencies.database.requireExecSql(\"principal mutation\"),\n ),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nfunction sessionExecutor(\n dependencies: WorkflowRuntimeDependencies,\n): ExecSql | null {\n const execSql = dependencies.database.execSql;\n return dependencies.database.status === \"ready\" && execSql\n ? sessionLifetime(dependencies.session).bind(execSql)\n : null;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () => sessionExecutor(dependencies);\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.database.requireExecSql(\n \"principal history protection\",\n ),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n bindSessionIdentityResolver(\n resolveTrustedUserIdentity,\n sessionLifetime(dependencies.session),\n ),\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n () => runtimeSubscription.sessionGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: createContainerContentsOrganizationHost(\n () => runtimeSubscription.sessionGeneration,\n ),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate, assertCurrent) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () =>\n trustedUserIdentityService.pinLocal(userId, candidate, assertCurrent),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n bindIdentityResolver: () => TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql = sessionExecutor(dependencies) ?? unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: sessionLifetime(dependencies.session).bindBlobStore(\n dependencies.blobs.store,\n ),\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n const resolveTrustedUserIdentity = bindIdentityResolver();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAI5H,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAgB,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAEL,sBAAsB,GAGvB,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,uCAAuC,EAAE,MAAM,qDAAqD,CAAC;AAC9G,OAAO,EAAE,sBAAsB,EAAE,MAAM,mDAAmD,CAAC;AAC3F,OAAO,EACL,4BAA4B,GAE7B,MAAM,qDAAqD,C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ads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../../data/documents/documentKinds\";\nimport { deleteDocumentPlacements } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport type { DocumentPlacementCleanup } from \"../../data/persistence/documents/documentsPersistence\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport { type ExecSql, unavailableExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type LocalUserIdentityCandidate,\n loadPinnedUserIdentity,\n type TrustedUserIdentityResolver,\n type TrustedUserIdentityService,\n} from \"../../data/trustedUserIdentity\";\nimport type {\n ContainerContentsOrganizationHost,\n ContainerContentsRootAdopter,\n} from \"../../workflows/container-contents\";\nimport { createContainerContentsOrganizationHost } from \"../../workflows/organizations/containerContentsHost\";\nimport { PrincipalPolicyService } from \"../../workflows/principals/principalPolicyService\";\nimport {\n createProvisionedStatePrimer,\n type ProvisionedStatePrimer,\n} from \"../../workflows/registration/provisionedStatePrimer\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../../workflows/shared/runtimeInput\";\nimport { getOrCreateOrganizationSyncPauses } from \"../../workflows/sync/coordination\";\nimport type { Blobs } from \"../blobs\";\nimport type { Identity } from \"../identity\";\nimport { sessionLifetime } from \"../session\";\nimport { acknowledgedSessionRoot } from \"../session/sessionRootAuthority\";\nimport type { Session } from \"../session/sessionTypes\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport {\n bindSessionIdentityResolver,\n createRuntimeIdentityResolution,\n} from \"./runtimeIdentityResolution\";\nimport { reuseIfShallowEqual } from \"./runtimeInputReuse\";\nimport { createRuntimeSubscription } from \"./runtimeSubscription\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** Bound to this snapshot's API client, executor, and history custody. */\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nexport interface InternalRuntime {\n /** Resolved once by the composition root; constant for the client's life. */\n readonly identityTrustDomain: string | null;\n identityLinks: Pick<\n TrustedUserIdentityService,\n | \"createLink\"\n | \"createLinkFor\"\n | \"verifyLink\"\n | \"loadAdmissionPin\"\n | \"resolvePinned\"\n | \"resolveVerified\"\n | \"requireVerified\"\n >;\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n /** Storage and session custody, stable through transport token renewal. */\n readonly scopeGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly deleteDocumentPlacements: DocumentPlacementCleanup;\n readonly containerContentsOrganizations: ContainerContentsOrganizationHost;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n assertCurrent?: () => void,\n ): Promise<void>;\n readonly primeProvisionedState: ProvisionedStatePrimer;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n readSessionGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n readSessionGeneration,\n signIn: sessionLifetime(dependencies.session),\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: sessionLifetime(dependencies.session).bind(\n dependencies.database.requireExecSql(\"principal mutation\"),\n ),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\n/** Priming reads the runtime's database, identity and trust pins; it pins nothing. */\nfunction createRuntimeProvisioningPrimer(\n dependencies: WorkflowRuntimeDependencies,\n bindLease: () => PrincipalHistoryProtectionLease | undefined,\n readyExecSql: () => ExecSql | null,\n): ProvisionedStatePrimer {\n return createProvisionedStatePrimer({\n bindLease,\n execSqlFor: (database) =>\n dependencies.database.client === database ? readyExecSql() : null,\n loadPinnedIdentity: async (execSql, userId) =>\n dependencies.identityTrustDomain\n ? loadPinnedUserIdentity({\n execSql,\n identityTrustDomain: dependencies.identityTrustDomain,\n userId,\n })\n : null,\n logError: dependencies.logError,\n signingFingerprint: () => dependencies.identity.signingFingerprint,\n });\n}\n\nfunction sessionExecutor(\n dependencies: WorkflowRuntimeDependencies,\n): ExecSql | null {\n const execSql = dependencies.database.execSql;\n return dependencies.database.status === \"ready\" && execSql\n ? sessionLifetime(dependencies.session).bind(execSql)\n : null;\n}\n\nfunction createRuntimeHistoryProtection(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.database.requireExecSql(\n \"principal history protection\",\n ),\n generation: readGeneration(),\n };\n },\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const readyExecSql = () => sessionExecutor(dependencies);\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const { trustedUserIdentityService, resolveTrustedUserIdentity } =\n createRuntimeIdentityResolution(\n dependencies,\n readyExecSql,\n () => runtimeSubscription.recoveryGeneration,\n );\n const historyProtection = createRuntimeHistoryProtection(\n dependencies,\n () => runtimeSubscription.recoveryGeneration,\n );\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n bindSessionIdentityResolver(\n resolveTrustedUserIdentity,\n sessionLifetime(dependencies.session),\n ),\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n () => runtimeSubscription.sessionGeneration,\n ).bind,\n );\n\n return {\n identityTrustDomain: dependencies.identityTrustDomain,\n identityLinks: trustedUserIdentityService,\n retirePrincipalHistoryProtection: historyProtection.retire,\n get scopeGeneration() {\n return runtimeSubscription.mutationGeneration;\n },\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n deleteDocumentPlacements,\n containerContentsOrganizations: createContainerContentsOrganizationHost(\n () => runtimeSubscription.sessionGeneration,\n ),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate, assertCurrent) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () =>\n trustedUserIdentityService.pinLocal(userId, candidate, assertCurrent),\n );\n },\n primeProvisionedState: createRuntimeProvisioningPrimer(\n dependencies,\n historyProtection.bind,\n readyExecSql,\n ),\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\nfunction runtimeInputUtilities(\n dependencies: WorkflowRuntimeDependencies,\n util: WorkflowRuntimeUtilInput | undefined,\n): WorkflowRuntimeUtilInput {\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId, direction = \"push\") =>\n getOrCreateOrganizationSyncPauses(\n dependencies.getDomainScope(),\n ).holdsSync(organizationId) ||\n (direction === \"push\" &&\n (dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ??\n false)),\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n return util;\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n bindIdentityResolver: () => TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql = sessionExecutor(dependencies) ?? unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: sessionLifetime(dependencies.session).bindBlobStore(\n dependencies.blobs.store,\n ),\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnected: dependencies.events.connected,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n serverEventsPendingConnectAttempt:\n dependencies.events.pendingConnectAttempt,\n });\n util = runtimeInputUtilities(dependencies, util);\n\n const apiClient = bindMutationApi();\n const resolveTrustedUserIdentity = bindIdentityResolver();\n return {\n apiClient,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n // Binds this snapshot's lease now; work on an older snapshot keeps its own.\n principalPolicies: new PrincipalPolicyService({\n apiClient,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n }),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n principalPolicies: _principalPolicies,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { createListenerSet } from "../shared/listenerSet.js";
1
2
  import { requestAllPumpDrivenLanes, requestLaneSync, requestLaneSyncAfter, waitForIdleLanes, } from "./coordinatorPump.js";
2
3
  import { hasPendingLaneWork, INITIAL_SYNC_LANE_RUN_STATE, publishSyncCoordinatorSnapshot, } from "./coordinatorState.js";
3
4
  import { transitionSyncLaneRequest } from "./syncLaneMachine.js";
@@ -9,6 +10,8 @@ import { beginUploadLane } from "./uploadLane.js";
9
10
  export { isDatabaseUnavailableError } from "../sqlite/availability/databaseUnavailable.js";
10
11
  export { didRegainSyncPrerequisites, } from "./syncPrerequisites.js";
11
12
  const coordinatorsByScope = new WeakMap();
13
+ // A host watching a domain follows its replacement coordinator until it unsubscribes.
14
+ const observersByScope = new WeakMap();
12
15
  function createSyncLaneHandle(coordinatorState, lane) {
13
16
  return {
14
17
  isDisposed: () => coordinatorState.disposed,
@@ -16,11 +19,11 @@ function createSyncLaneHandle(coordinatorState, lane) {
16
19
  requestSyncAfter: (delayMs) => requestLaneSyncAfter(coordinatorState, lane, delayMs),
17
20
  };
18
21
  }
19
- function createDomainSyncCoordinator() {
22
+ function createDomainSyncCoordinator(domainScope) {
20
23
  const coordinatorState = {
21
24
  disposed: false,
22
25
  lanes: new Map(),
23
- listeners: new Set(),
26
+ listeners: new Set([() => observersByScope.get(domainScope)?.notify()]),
24
27
  nextRegistrationIndex: 0,
25
28
  nextRunOrder: 0,
26
29
  wakePump: null,
@@ -36,7 +39,11 @@ function createDomainSyncCoordinator() {
36
39
  return beginUploadLane(coordinatorState, key, options);
37
40
  },
38
41
  dispose() {
42
+ if (coordinatorState.disposed)
43
+ return;
39
44
  coordinatorState.disposed = true;
45
+ // A disposal listener can synchronously reopen this scope.
46
+ coordinatorsByScope.delete(domainScope);
40
47
  // Drop queued work so waitForIdle reports settled immediately and a
41
48
  // lane left re-requested by an in-flight run does not survive teardown.
42
49
  for (const lane of coordinatorState.lanes.values()) {
@@ -118,7 +125,7 @@ export function getOrCreateDomainSyncCoordinator(domainScope) {
118
125
  if (existingCoordinator) {
119
126
  return existingCoordinator;
120
127
  }
121
- const nextCoordinator = createDomainSyncCoordinator();
128
+ const nextCoordinator = createDomainSyncCoordinator(domainScope);
122
129
  coordinatorsByScope.set(domainScope, nextCoordinator);
123
130
  return nextCoordinator;
124
131
  }
@@ -138,18 +145,18 @@ export function requestDomainSyncLane(domainScope, key) {
138
145
  // Stop admitting work and remove this scope's coordinator. Active callbacks
139
146
  // drain under their existing watchdogs; getOrCreate builds a fresh coordinator.
140
147
  export function disposeDomainSyncCoordinator(domainScope) {
141
- const coordinator = coordinatorsByScope.get(domainScope);
142
- if (!coordinator) {
143
- return;
144
- }
145
- coordinator.dispose();
146
- coordinatorsByScope.delete(domainScope);
148
+ coordinatorsByScope.get(domainScope)?.dispose();
147
149
  }
148
150
  export function getDomainSyncCoordinatorSnapshot(domainScope) {
149
151
  return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();
150
152
  }
151
153
  export function subscribeToDomainSyncCoordinator(domainScope, listener) {
152
- return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);
154
+ let observers = observersByScope.get(domainScope);
155
+ if (!observers) {
156
+ observers = createListenerSet();
157
+ observersByScope.set(domainScope, observers);
158
+ }
159
+ return observers.subscribe(listener);
153
160
  }
154
161
  export function beginDomainSyncUploadLane(domainScope, key, options) {
155
162
  return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(key, options);
@@ -1 +1 @@
1
- {"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kBAAkB,EAClB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAE9D,OAAO,EAAE,wBAAwB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,+EAA+E;AAC/E,6EAA6E;AAC7E,kCAAkC;AAClC,OAAO,EAAE,0BAA0B,EAAE,MAAM,4CAA4C,CAAC;AAGxF,OAAO,EACL,0BAA0B,GAE3B,MAAM,qBAAqB,CAAC;AAgC7B,MAAM,mBAAmB,GAAG,IAAI,OA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O,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set(),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n coordinatorState.disposed = true;\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator();\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n const coordinator = coordinatorsByScope.get(domainScope);\n if (!coordinator) {\n return;\n }\n\n coordinator.dispose();\n coordinatorsByScope.delete(domainScope);\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n return getOrCreateDomainSyncCoordinator(domainScope).subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\n );\n}\n"]}
1
+ {"version":3,"file":"syncCoordinator.js","sourceRoot":"","sources":["syncCoordinator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,oBAAoB,EAEpB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,kB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;AAClD,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,WAAwB;IAExB,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,WAAW,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,WAAwB,EACxB,QAAoB;IAEpB,IAAI,SAAS,GAAG,gBAAgB,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAClD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,SAAS,GAAG,iBAAiB,EAAE,CAAC;QAChC,gBAAgB,CAAC,GAAG,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAC/C,CAAC;IACD,OAAO,SAAS,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,yBAAyB,CACvC,WAAwB,EACxB,GAAW,EACX,OAA+B;IAE/B,OAAO,gCAAgC,CAAC,WAAW,CAAC,CAAC,eAAe,CAClE,GAAG,EACH,OAAO,CACR,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,WAAwB,EACxB,OAAyB;IAEzB,OAAO,CACL,mBAAmB,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,WAAW,CAAC,OAAO,CAAC;QAC1D,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACtB,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../shared/domainScope\";\nimport { createListenerSet } from \"../shared/listenerSet\";\nimport {\n requestAllPumpDrivenLanes,\n requestLaneSync,\n requestLaneSyncAfter,\n type SyncIdleOptions,\n waitForIdleLanes,\n} from \"./coordinatorPump\";\nimport type {\n DomainSyncCoordinatorState,\n SyncLaneState,\n} from \"./coordinatorState\";\nimport {\n hasPendingLaneWork,\n INITIAL_SYNC_LANE_RUN_STATE,\n publishSyncCoordinatorSnapshot,\n} from \"./coordinatorState\";\nimport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nimport { transitionSyncLaneRequest } from \"./syncLaneMachine\";\nimport type { DomainSyncSnapshot } from \"./syncTelemetry\";\nimport { createDomainSyncSnapshot, createSyncTimestamp } from \"./syncTelemetry\";\nimport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\nimport { beginUploadLane } from \"./uploadLane\";\n\n// Re-exported here because lanes reach it as a shouldIgnoreError alongside the\n// rest of the coordinator surface; it lives beside this coordinator with the\n// error type it discriminates on.\nexport { isDatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nexport type { SyncIdleOptions } from \"./coordinatorPump\";\nexport type { SyncLane, SyncLaneConfig } from \"./syncLaneConfig\";\nexport {\n didRegainSyncPrerequisites,\n type SyncRuntimeStatus,\n} from \"./syncPrerequisites\";\nexport type {\n DomainSyncSnapshot,\n SyncLaneLastAction,\n SyncLanePhase,\n SyncLaneProgress,\n SyncLaneSnapshot,\n SyncLaneStatus,\n} from \"./syncTelemetry\";\nexport type { UploadSyncLane, UploadSyncLaneOptions } from \"./uploadLane\";\n\nexport interface DomainSyncCoordinator {\n beginUploadLane: (\n key: string,\n options?: UploadSyncLaneOptions,\n ) => UploadSyncLane;\n // Drop queued work and refuse new runs; active callbacks retain ownership.\n dispose: () => void;\n getSnapshot: () => DomainSyncSnapshot;\n registerLane: (key: string, config: SyncLaneConfig) => SyncLane;\n // Re-request every pump-driven lane — a manual \"sync now\" that re-drives\n // durable owners stranded by a transient failure. Observational upload rows\n // are updated only by those owners' real attachment upload attempts.\n requestAllLanes: () => void;\n // Request one registered pump lane without re-driving unrelated owners.\n requestLane: (key: string) => void;\n hasPendingWork: () => boolean;\n isDisposed: () => boolean;\n subscribe: (listener: () => void) => () => void;\n waitForIdle: (options?: SyncIdleOptions) => Promise<boolean>;\n}\n\nconst coordinatorsByScope = new WeakMap<DomainScope, DomainSyncCoordinator>();\n\n// A host watching a domain follows its replacement coordinator until it unsubscribes.\nconst observersByScope = new WeakMap<\n DomainScope,\n ReturnType<typeof createListenerSet<[]>>\n>();\n\nfunction createSyncLaneHandle(\n coordinatorState: DomainSyncCoordinatorState,\n lane: SyncLaneState,\n): SyncLane {\n return {\n isDisposed: () => coordinatorState.disposed,\n requestSync: () => requestLaneSync(coordinatorState, lane),\n requestSyncAfter: (delayMs) =>\n requestLaneSyncAfter(coordinatorState, lane, delayMs),\n };\n}\n\nfunction createDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const coordinatorState: DomainSyncCoordinatorState = {\n disposed: false,\n lanes: new Map<string, SyncLaneState>(),\n listeners: new Set([() => observersByScope.get(domainScope)?.notify()]),\n nextRegistrationIndex: 0,\n nextRunOrder: 0,\n wakePump: null,\n pump: null,\n snapshot: createDomainSyncSnapshot({\n hasPendingWork: false,\n lanes: [],\n pumpActive: false,\n }),\n };\n\n return {\n beginUploadLane(key: string, options: UploadSyncLaneOptions = {}) {\n return beginUploadLane(coordinatorState, key, options);\n },\n dispose() {\n if (coordinatorState.disposed) return;\n coordinatorState.disposed = true;\n // A disposal listener can synchronously reopen this scope.\n coordinatorsByScope.delete(domainScope);\n // Drop queued work so waitForIdle reports settled immediately and a\n // lane left re-requested by an in-flight run does not survive teardown.\n for (const lane of coordinatorState.lanes.values()) {\n lane.request = transitionSyncLaneRequest(lane.request, {\n type: \"clear\",\n });\n }\n // Publish the final settled snapshot, then release listener closures:\n // the coordinator is dropped from the registry and a remount subscribes\n // to a fresh one.\n publishSyncCoordinatorSnapshot(coordinatorState);\n coordinatorState.listeners.clear();\n },\n getSnapshot() {\n return coordinatorState.snapshot;\n },\n hasPendingWork() {\n return (\n !!coordinatorState.pump ||\n hasPendingLaneWork(coordinatorState.lanes.values())\n );\n },\n isDisposed() {\n return coordinatorState.disposed;\n },\n registerLane(key: string, config: SyncLaneConfig): SyncLane {\n const existingLane = coordinatorState.lanes.get(key);\n if (existingLane) {\n existingLane.config = config;\n existingLane.blobStorageKey = null;\n existingLane.pumpDriven = true;\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, existingLane);\n }\n\n const registeredAt = createSyncTimestamp();\n const nextLane: SyncLaneState = {\n ...INITIAL_SYNC_LANE_RUN_STATE,\n blobStorageKey: null,\n config,\n errorCount: 0,\n key,\n lastAction: \"registered\",\n lastActionAt: registeredAt,\n lastCompletedAt: null,\n lastError: null,\n lastFailedAt: null,\n lastRequestedAt: null,\n lastStartedAt: null,\n progress: null,\n pumpDriven: true,\n registrationIndex: coordinatorState.nextRegistrationIndex,\n requestCount: 0,\n };\n coordinatorState.nextRegistrationIndex += 1;\n coordinatorState.lanes.set(key, nextLane);\n publishSyncCoordinatorSnapshot(coordinatorState);\n return createSyncLaneHandle(coordinatorState, nextLane);\n },\n requestAllLanes() {\n requestAllPumpDrivenLanes(coordinatorState);\n },\n requestLane(key: string) {\n const lane = coordinatorState.lanes.get(key);\n if (lane?.pumpDriven) {\n requestLaneSync(coordinatorState, lane);\n }\n },\n subscribe(listener: () => void) {\n coordinatorState.listeners.add(listener);\n return () => {\n coordinatorState.listeners.delete(listener);\n };\n },\n waitForIdle(options?: SyncIdleOptions) {\n return waitForIdleLanes(coordinatorState, options);\n },\n };\n}\n\nexport function getOrCreateDomainSyncCoordinator(\n domainScope: DomainScope,\n): DomainSyncCoordinator {\n const existingCoordinator = coordinatorsByScope.get(domainScope);\n if (existingCoordinator) {\n return existingCoordinator;\n }\n\n const nextCoordinator = createDomainSyncCoordinator(domainScope);\n coordinatorsByScope.set(domainScope, nextCoordinator);\n return nextCoordinator;\n}\n\nexport function hasDomainSyncCoordinatorPendingWork(\n domainScope: DomainScope,\n): boolean {\n return coordinatorsByScope.get(domainScope)?.hasPendingWork() ?? false;\n}\n\n// Re-request every pump-driven lane for a scope: a user-driven \"sync now\" that\n// retries durable work stranded by a transient failure. Observational upload\n// telemetry is never directly pumped. A no-op when no coordinator exists yet\n// (nothing has been synced) or it has been disposed.\nexport function requestAllDomainSyncLanes(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.requestAllLanes();\n}\n\nexport function requestDomainSyncLane(\n domainScope: DomainScope,\n key: string,\n): void {\n coordinatorsByScope.get(domainScope)?.requestLane(key);\n}\n\n// Stop admitting work and remove this scope's coordinator. Active callbacks\n// drain under their existing watchdogs; getOrCreate builds a fresh coordinator.\nexport function disposeDomainSyncCoordinator(domainScope: DomainScope): void {\n coordinatorsByScope.get(domainScope)?.dispose();\n}\n\nexport function getDomainSyncCoordinatorSnapshot(\n domainScope: DomainScope,\n): DomainSyncSnapshot {\n return getOrCreateDomainSyncCoordinator(domainScope).getSnapshot();\n}\n\nexport function subscribeToDomainSyncCoordinator(\n domainScope: DomainScope,\n listener: () => void,\n): () => void {\n let observers = observersByScope.get(domainScope);\n if (!observers) {\n observers = createListenerSet();\n observersByScope.set(domainScope, observers);\n }\n return observers.subscribe(listener);\n}\n\nexport function beginDomainSyncUploadLane(\n domainScope: DomainScope,\n key: string,\n options?: UploadSyncLaneOptions,\n): UploadSyncLane {\n return getOrCreateDomainSyncCoordinator(domainScope).beginUploadLane(\n key,\n options,\n );\n}\n\nexport function waitForDomainSyncCoordinatorToSettle(\n domainScope: DomainScope,\n options?: SyncIdleOptions,\n): Promise<boolean> {\n return (\n coordinatorsByScope.get(domainScope)?.waitForIdle(options) ??\n Promise.resolve(true)\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.252",
3
+ "version": "0.1.253",
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": {
@@ -1,18 +1,12 @@
1
1
  import type { DomainScope } from "../../data/shared/domainScope.js";
2
2
  import { type ContainerContentsPersistence } from "../../workflows/container-contents/containerPersistence.js";
3
- import { type ContainerContentsStoreRuntime, createContainerContentsStoreSyncAgent } from "./syncAgent/index.js";
3
+ import { type ContainerContentsStoreRuntime, type createContainerContentsStoreSyncAgent } from "./syncAgent/index.js";
4
4
  import type { ContainerContentsStore, ContainerContentsStoreOptions, ContainerContentsStoreState } from "./types.js";
5
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;
9
- /**
10
- * Arm the next structural pass's document-priming scan for a domain scope.
11
- * Priming normally re-arms only on store creation and topology changes, so a
12
- * caller that just tore down a document's local state uses this to have the
13
- * still-listed server document re-created without waiting for an app
14
- * restart. Returns false when the scope has no container-contents store yet;
15
- * the startup priming pass covers that case.
16
- */
9
+ /** Re-arm priming after a local deletion so the next pass re-creates still-listed documents.
10
+ * A new store already primes its documents on startup. */
17
11
  export declare function requestContainerContentsDocumentPriming(domainScope: DomainScope): boolean;
18
12
  export {};
@@ -1,5 +1,6 @@
1
1
  import { getCachedContainerWriterProjection } from "../../workflows/container-contents/container-state/projectionCache.js";
2
2
  import { defaultContainerContentsPersistence, } from "../../workflows/container-contents/containerPersistence.js";
3
+ import { getOrCreateDomainSyncCoordinator } from "../../workflows/sync/coordination.js";
3
4
  import { persistContainerState } from "./containerState/containerStatePersistence.js";
4
5
  import { createTreeRefreshMethods } from "./hydration/remoteHydrationRefresh.js";
5
6
  import { createChildContainer, deleteContainer, ensureSystemContainer, moveContainer, renameContainer, } from "./operations/index.js";
@@ -14,7 +15,7 @@ import { chainContainerWrite } from "./remoteWrites/localWriteQueue.js";
14
15
  import { chainRemoteContainerTask } from "./remoteWrites/remoteWriteQueue.js";
15
16
  import { captureContainerWriteGeneration } from "./remoteWrites/writeGeneration.js";
16
17
  import { createContainerContentsStoreState, subscribeToContainerContentsStore, updateContainerContentsSnapshot, updateContainerContentsStorePersistence, updateContainerContentsStoreRuntime, } from "./state.js";
17
- import { createContainerContentsStoreSyncAgent, } from "./syncAgent/index.js";
18
+ import { prepareContainerContentsStoreSyncAgent, } from "./syncAgent/index.js";
18
19
  import { oweContainerMetadataRead } from "./syncAgent/metadataRevalidation.js";
19
20
  import { findRootContainerState } from "./systemContainers/systemContainerLookup.js";
20
21
  const containerContentsStoresByScope = new WeakMap();
@@ -26,12 +27,6 @@ function applyContainerContentsStoreOptions(state, syncAgent, options) {
26
27
  updateContainerContentsStorePersistence(state, options.persistence ?? defaultContainerContentsPersistence, syncAgent);
27
28
  }
28
29
  }
29
- function getCachedContainerWriterProjectionForStore(state, containerId) {
30
- const containerState = state.containersById.get(containerId);
31
- return containerState
32
- ? getCachedContainerWriterProjection(containerState)
33
- : null;
34
- }
35
30
  function createContainerContentsStoreSyncHost(state) {
36
31
  return {
37
32
  persistContainerState: (containerState, patch, updateView, saveOptions, mutationOptions) => persistContainerState(state, containerState, {
@@ -128,12 +123,15 @@ export function createContainerWriteMethods(state, syncAgent) {
128
123
  }
129
124
  function createContainerContentsStoreEntry(initialRuntime, persistence = defaultContainerContentsPersistence, options = {}) {
130
125
  const state = createContainerContentsStoreState(initialRuntime, options.persistence ?? persistence, options.logLabel);
131
- const syncAgent = createContainerContentsStoreSyncAgent({
126
+ const { agent: syncAgent, registerLane } = prepareContainerContentsStoreSyncAgent({
132
127
  host: createContainerContentsStoreSyncHost(state),
133
128
  state,
134
129
  });
130
+ const coordinator = getOrCreateDomainSyncCoordinator(initialRuntime.state.domainScope);
135
131
  const writeMethods = createContainerWriteMethods(state, syncAgent);
136
132
  return {
133
+ registerLane,
134
+ isDisposed: coordinator.isDisposed,
137
135
  requestDocumentPriming: () => {
138
136
  state.documentStoresNeedPriming = true;
139
137
  syncAgent.scheduleSync();
@@ -149,7 +147,10 @@ function createContainerContentsStoreEntry(initialRuntime, persistence = default
149
147
  return syncAgent.refreshLocalContainers();
150
148
  },
151
149
  requestSync: () => syncAgent.scheduleSync(),
152
- getCachedContainerWriterProjection: (containerId) => getCachedContainerWriterProjectionForStore(state, containerId),
150
+ getCachedContainerWriterProjection: (containerId) => {
151
+ const container = state.containersById.get(containerId);
152
+ return container ? getCachedContainerWriterProjection(container) : null;
153
+ },
153
154
  getSnapshot: () => state.snapshot,
154
155
  subscribe: (listener) => subscribeToContainerContentsStore(state, listener),
155
156
  updateRuntime: (runtime) => updateContainerContentsStoreRuntime(state, runtime, syncAgent),
@@ -158,27 +159,29 @@ function createContainerContentsStoreEntry(initialRuntime, persistence = default
158
159
  };
159
160
  }
160
161
  export function createContainerContentsStore(initialRuntime, persistence = defaultContainerContentsPersistence, options = {}) {
161
- return createContainerContentsStoreEntry(initialRuntime, persistence, options)
162
- .store;
162
+ const entry = createContainerContentsStoreEntry(initialRuntime, persistence, options);
163
+ entry.registerLane();
164
+ if (entry.isDisposed())
165
+ throw new Error("Container scope retired during registration");
166
+ return entry.store;
163
167
  }
164
168
  export function getOrCreateContainerContentsStore(domainScope, runtime, options = {}) {
165
169
  const existingEntry = containerContentsStoresByScope.get(domainScope);
166
- if (existingEntry) {
170
+ if (existingEntry && !existingEntry.isDisposed()) {
167
171
  existingEntry.updateOptions(options);
168
172
  return existingEntry.store;
169
173
  }
170
174
  const nextEntry = createContainerContentsStoreEntry(runtime, defaultContainerContentsPersistence, options);
171
175
  containerContentsStoresByScope.set(domainScope, nextEntry);
172
- return nextEntry.store;
176
+ // Registering the lane publishes a snapshot and can synchronously reopen this tree.
177
+ nextEntry.registerLane();
178
+ const current = containerContentsStoresByScope.get(domainScope);
179
+ if (!current || current.isDisposed())
180
+ throw new Error("Container scope retired during registration");
181
+ return current.store;
173
182
  }
174
- /**
175
- * Arm the next structural pass's document-priming scan for a domain scope.
176
- * Priming normally re-arms only on store creation and topology changes, so a
177
- * caller that just tore down a document's local state uses this to have the
178
- * still-listed server document re-created without waiting for an app
179
- * restart. Returns false when the scope has no container-contents store yet;
180
- * the startup priming pass covers that case.
181
- */
183
+ /** Re-arm priming after a local deletion so the next pass re-creates still-listed documents.
184
+ * A new store already primes its documents on startup. */
182
185
  export function requestContainerContentsDocumentPriming(domainScope) {
183
186
  const entry = containerContentsStoresByScope.get(domainScope);
184
187
  if (!entry) {