@tearleads/client-sdk 0.1.251 → 0.1.252

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 (141) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +14 -25
  3. package/Tearleads.js.map +1 -1
  4. package/client/organizations/organizationReadModelPresentation.js +7 -4
  5. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  6. package/client/organizations/organizationReadModels.js +6 -5
  7. package/client/organizations/organizationReadModels.js.map +1 -1
  8. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  9. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  10. package/client/runtime/principalMutationApi.d.ts +4 -0
  11. package/client/runtime/principalMutationApi.js +9 -5
  12. package/client/runtime/principalMutationApi.js.map +1 -1
  13. package/client/runtime/runtimeIdentityResolution.js +23 -0
  14. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  15. package/client/runtime/runtimeSubscription.js +68 -0
  16. package/client/runtime/runtimeSubscription.js.map +1 -0
  17. package/client/runtime/workflowRuntime.d.ts +1 -1
  18. package/client/runtime/workflowRuntime.js +20 -77
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/client/session/authenticationMachine.js +47 -0
  21. package/client/session/authenticationMachine.js.map +1 -0
  22. package/client/session/index.js +75 -93
  23. package/client/session/index.js.map +1 -1
  24. package/client/session/sessionBlobStore.js +39 -0
  25. package/client/session/sessionBlobStore.js.map +1 -0
  26. package/client/session/sessionContext.js +11 -0
  27. package/client/session/sessionContext.js.map +1 -1
  28. package/client/session/sessionIdentityTrust.d.ts +2 -1
  29. package/client/session/sessionIdentityTrust.js +8 -4
  30. package/client/session/sessionIdentityTrust.js.map +1 -1
  31. package/client/session/sessionLifetime.js +87 -0
  32. package/client/session/sessionLifetime.js.map +1 -0
  33. package/client/session/sessionLogin.js +114 -0
  34. package/client/session/sessionLogin.js.map +1 -0
  35. package/client/session/sessionOrganizationCreation.js +3 -2
  36. package/client/session/sessionOrganizationCreation.js.map +1 -1
  37. package/client/session/sessionPurgeRecovery.js +11 -3
  38. package/client/session/sessionPurgeRecovery.js.map +1 -1
  39. package/client/session/sessionTypes.d.ts +6 -2
  40. package/client/session/sessionTypes.js.map +1 -1
  41. package/data/blobs/blobContracts.d.ts +4 -3
  42. package/data/blobs/blobContracts.js.map +1 -1
  43. package/data/blobs/createBlobStore.js +1 -8
  44. package/data/blobs/createBlobStore.js.map +1 -1
  45. package/data/blobs/encryptedBlobStore.js +17 -12
  46. package/data/blobs/encryptedBlobStore.js.map +1 -1
  47. package/data/blobs/memoryBlobStore.js +8 -5
  48. package/data/blobs/memoryBlobStore.js.map +1 -1
  49. package/data/blobs/opfsBlobFile.js +36 -0
  50. package/data/blobs/opfsBlobFile.js.map +1 -0
  51. package/data/blobs/opfsBlobStore.d.ts +1 -1
  52. package/data/blobs/opfsBlobStore.js +91 -21
  53. package/data/blobs/opfsBlobStore.js.map +1 -1
  54. package/data/principals/principalPolicyCoordinator.js +8 -17
  55. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  56. package/data/shared/domainScope.d.ts +2 -0
  57. package/data/shared/domainScope.js +2 -1
  58. package/data/shared/domainScope.js.map +1 -1
  59. package/data/shared/keyedQueue.js +15 -0
  60. package/data/shared/keyedQueue.js.map +1 -0
  61. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  62. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  63. package/data/sqlite/sqlExec.d.ts +6 -0
  64. package/data/sqlite/sqlExec.js +64 -13
  65. package/data/sqlite/sqlExec.js.map +1 -1
  66. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  67. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  68. package/data/trustedUserIdentity/service.js +2 -1
  69. package/data/trustedUserIdentity/service.js.map +1 -1
  70. package/data/trustedUserIdentity/types.d.ts +1 -1
  71. package/data/trustedUserIdentity/types.js.map +1 -1
  72. package/internal/api-client/ApiClient.d.ts +4 -1
  73. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  74. package/internal/api-client/apiRequestRuntime.js +86 -101
  75. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  76. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  77. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  78. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  79. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  80. package/internal/api-client/client/blobs.d.ts +1 -0
  81. package/internal/api-client/client/blobs.js +12 -3
  82. package/internal/api-client/client/blobs.js.map +1 -1
  83. package/internal/api-client/client/laneListingRequest.js +4 -0
  84. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  85. package/internal/api-client/client/session.d.ts +5 -1
  86. package/internal/api-client/client/session.js +12 -4
  87. package/internal/api-client/client/session.js.map +1 -1
  88. package/internal/api-client/client/writerProjections.js +12 -13
  89. package/internal/api-client/client/writerProjections.js.map +1 -1
  90. package/internal/api-client/operationResponse.d.ts +1 -1
  91. package/internal/api-client/operationResponse.js +10 -23
  92. package/internal/api-client/operationResponse.js.map +1 -1
  93. package/internal/api-client/operationTransport.js +2 -1
  94. package/internal/api-client/operationTransport.js.map +1 -1
  95. package/internal/api-client/principalHistoryRequest.js +25 -20
  96. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  97. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  98. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  99. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  100. package/internal/api-client/principalPolicyPages.js +4 -2
  101. package/internal/api-client/principalPolicyPages.js.map +1 -1
  102. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  103. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  104. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  105. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  106. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  107. package/internal/api-client/routes/blobs/get.js +9 -67
  108. package/internal/api-client/routes/blobs/get.js.map +1 -1
  109. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  110. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  111. package/internal/api-client/sessionRefresh.js +1 -1
  112. package/internal/api-client/sessionRefresh.js.map +1 -1
  113. package/internal/api-client/sessionRenewal.d.ts +31 -0
  114. package/internal/api-client/sessionRenewal.js +91 -6
  115. package/internal/api-client/sessionRenewal.js.map +1 -1
  116. package/internal/api-client/sessionRequestInit.js +22 -0
  117. package/internal/api-client/sessionRequestInit.js.map +1 -0
  118. package/internal/api-client/sessionResponse.js +39 -0
  119. package/internal/api-client/sessionResponse.js.map +1 -0
  120. package/internal/api-client/types.d.ts +1 -0
  121. package/internal/api-client/types.js.map +1 -1
  122. package/internal/api-client/webSocketTickets.d.ts +1 -0
  123. package/internal/api-client/webSocketTickets.js +4 -0
  124. package/internal/api-client/webSocketTickets.js.map +1 -1
  125. package/internal/sqlite-worker/client.d.ts +1 -1
  126. package/internal/sqlite-worker/client.js +6 -1
  127. package/internal/sqlite-worker/client.js.map +1 -1
  128. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  129. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  130. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  131. package/internal/sqlite-worker/types.d.ts +4 -0
  132. package/internal/sqlite-worker/types.js.map +1 -1
  133. package/package.json +1 -1
  134. package/sqlite/worker.js +1 -1
  135. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  136. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  137. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  138. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  139. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  140. package/workflows/registration/registerIdentity.js +2 -0
  141. package/workflows/registration/registerIdentity.js.map +1 -1
package/Tearleads.d.ts CHANGED
@@ -52,7 +52,6 @@ export declare class Tearleads {
52
52
  private readonly logHandler;
53
53
  private autoIdentityProvisioned;
54
54
  private autoIdentityProvisioningPromise;
55
- private expiredSessionLoginPromise;
56
55
  private pinLocalUserIdentity;
57
56
  private primeProvisionedState;
58
57
  private boundUserId;
@@ -86,6 +85,5 @@ export declare class Tearleads {
86
85
  * fresh state.
87
86
  */
88
87
  dispose(): void;
89
- private loginAfterSessionExpired;
90
88
  private startAutomaticIdentityProvisioning;
91
89
  }
package/Tearleads.js CHANGED
@@ -15,7 +15,7 @@ import { Network } from "./client/runtime/network.js";
15
15
  import { SyncBillingGate } from "./client/runtime/syncBillingGate.js";
16
16
  import { createRuntime, } from "./client/runtime/workflowRuntime.js";
17
17
  import { createSecurityIncidentService, } from "./client/securityIncidents/index.js";
18
- import { createSession } from "./client/session/index.js";
18
+ import { createSession, sessionLifetime } from "./client/session/index.js";
19
19
  import { resolveDocumentProjectorRegistry, } from "./data/documents/documentKinds.js";
20
20
  import { heldDirectoryCitations } from "./data/persistence/principalPolicy/heldOrganizationDirectories.js";
21
21
  import { createVerifiedManifestCitations } from "./data/persistence/verifiedManifestBundlePersistence.js";
@@ -54,13 +54,12 @@ export class Tearleads {
54
54
  retirePrincipalHistoryProtection = () => { };
55
55
  // Tracks the storage/identity pair that owns domain-scoped runtime state.
56
56
  domainScopeKey = null;
57
- // Recreated when the storage database or signing identity changes.
57
+ // Recreated when the storage database, signing identity, or sign-in changes.
58
58
  domainScopeValue = createDomainScope();
59
59
  logErrorHandler;
60
60
  logHandler;
61
61
  autoIdentityProvisioned = false;
62
62
  autoIdentityProvisioningPromise = null;
63
- expiredSessionLoginPromise = null;
64
63
  // Rebound to the workflow runtime once it exists; the session is created first.
65
64
  pinLocalUserIdentity = async () => {
66
65
  throw new Error("Trusted user identity runtime is not initialized");
@@ -114,6 +113,12 @@ export class Tearleads {
114
113
  });
115
114
  this.containerContents = createContainerContents(runtime);
116
115
  this.deviceFirst = createDeviceFirst(runtime, this.containerContents);
116
+ sessionLifetime(session).onBoundary = () => {
117
+ const previous = this.domainScopeValue;
118
+ this.deviceFirst.dispose();
119
+ disposeDomainSyncCoordinator(previous);
120
+ this.events.clear();
121
+ };
117
122
  this.organizations = createOrganizations(runtime, this.containerContents, () => this.deviceFirst.open().reconciler);
118
123
  this.root = createRoot(rootRuntimeOf(runtime, this.session));
119
124
  this.userIdentities = createUserIdentities({
@@ -137,7 +142,7 @@ export class Tearleads {
137
142
  }
138
143
  /** Trust callbacks reach the workflow runtime, which is created later. */
139
144
  createClientSession(options, reportSecurityIncident, identityTrustDomain) {
140
- return createSession({
145
+ const session = createSession({
141
146
  identityTrustDomain,
142
147
  api: this.apiClient,
143
148
  database: this.database,
@@ -146,11 +151,13 @@ export class Tearleads {
146
151
  log: this.log,
147
152
  logError: this.logError,
148
153
  boundUserIdForSigningKey: (signingKeyFingerprint) => this.boundUserId(signingKeyFingerprint),
149
- onUserIdentityAvailable: (userId, candidate) => this.pinLocalUserIdentity(userId, candidate),
154
+ onUserIdentityAvailable: (...args) => this.pinLocalUserIdentity(...args),
150
155
  primeProvisionedState: (input) => this.primeProvisionedState(input),
151
156
  provisionedSystemContainers: options.provisionedSystemContainers,
152
157
  reportSecurityIncident,
153
158
  });
159
+ this.apiClient.setOnSessionExpired(session.renewExpired);
160
+ return session;
154
161
  }
155
162
  createApiClient(apiBaseUrl, probeNetworkFailures) {
156
163
  return new ApiClient(apiBaseUrl, {
@@ -167,7 +174,7 @@ export class Tearleads {
167
174
  bindTrustedIdentityRuntime(runtime) {
168
175
  this.retirePrincipalHistoryProtection =
169
176
  runtime.retirePrincipalHistoryProtection;
170
- this.pinLocalUserIdentity = (userId, candidate) => runtime.pinLocalUserIdentity(userId, candidate);
177
+ this.pinLocalUserIdentity = runtime.pinLocalUserIdentity;
171
178
  this.primeProvisionedState = runtime.primeProvisionedState;
172
179
  this.boundUserId = (signingKeyFingerprint) => runtime.boundUserId(signingKeyFingerprint);
173
180
  }
@@ -183,7 +190,6 @@ export class Tearleads {
183
190
  this.apiClient.setOnNetworkSuccess(() => this.network.reportReachability(true));
184
191
  this.apiClient.setOnApiVersion((version) => this.apiVersion.observe(version));
185
192
  this.apiClient.setOnNetworkFailure((error) => this.apiNetworkFailures.notify(error.details));
186
- this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());
187
193
  this.apiClient.setOnPaymentRequired((organizationId) => this.syncBillingGate.notifyPaymentRequired(organizationId));
188
194
  }
189
195
  createWorkflowRuntime(identityTrustDomain, options, reportSecurityIncident) {
@@ -230,6 +236,7 @@ export class Tearleads {
230
236
  const nextScopeKey = JSON.stringify([
231
237
  this.database.id,
232
238
  this.identity.signingFingerprint,
239
+ sessionLifetime(this.session).epoch,
233
240
  ]);
234
241
  if (this.domainScopeKey !== nextScopeKey) {
235
242
  this.domainScopeKey = nextScopeKey;
@@ -251,24 +258,6 @@ export class Tearleads {
251
258
  this.deviceFirst.dispose();
252
259
  disposeDomainSyncCoordinator(domainScope);
253
260
  }
254
- loginAfterSessionExpired() {
255
- if (!this.session.authToken || !this.identity.signingKeyPair) {
256
- this.session.logout();
257
- return Promise.resolve(false);
258
- }
259
- // The API client replays requests the expired session sent, so a login is
260
- // their renewal only when the loaded keys authenticate that known user.
261
- const expiredUserId = this.session.userId;
262
- this.expiredSessionLoginPromise ??= this.session
263
- .login()
264
- .then((renewed) => renewed &&
265
- expiredUserId !== null &&
266
- this.session.userId === expiredUserId)
267
- .finally(() => {
268
- this.expiredSessionLoginPromise = null;
269
- });
270
- return this.expiredSessionLoginPromise;
271
- }
272
261
  startAutomaticIdentityProvisioning() {
273
262
  let unsubscribe = null;
274
263
  const stopProvisioningListener = () => {
package/Tearleads.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAET,iBAAiB,EACjB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,C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\n} from \"@tearleads/api-client\";\nimport { Blobs } from \"./client/blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./client/containerContents\";\nimport { createDeviceFirst, type DeviceFirst } from \"./client/deviceFirst\";\nimport { createDocuments, type Documents } from \"./client/documents\";\nimport { logErrorToConsole } from \"./client/host/logger\";\nimport { createIdentity, type Identity } from \"./client/identity\";\nimport {\n createUserIdentities,\n type UserIdentities,\n} from \"./client/identity/userIdentities\";\nimport {\n createOrganizations,\n type Organizations,\n} from \"./client/organizations\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./client/root\";\nimport { ApiVersion } from \"./client/runtime/apiVersion\";\nimport { Database } from \"./client/runtime/database\";\nimport { Events } from \"./client/runtime/events\";\nimport { Network } from \"./client/runtime/network\";\nimport { SyncBillingGate } from \"./client/runtime/syncBillingGate\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./client/runtime/workflowRuntime\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidents,\n} from \"./client/securityIncidents\";\nimport { createSession } from \"./client/session\";\nimport type { Session } from \"./client/session/sessionTypes\";\nimport {\n type DocumentProjectorRegistry,\n resolveDocumentProjectorRegistry,\n} from \"./data/documents/documentKinds\";\nimport { heldDirectoryCitations } from \"./data/persistence/principalPolicy/heldOrganizationDirectories\";\nimport { createVerifiedManifestCitations } from \"./data/persistence/verifiedManifestBundlePersistence\";\nimport { createDomainScope, type DomainScope } from \"./data/shared/domainScope\";\nimport { createListenerSet } from \"./data/shared/listenerSet\";\nimport type { SecurityIncidentReporter } from \"./data/shared/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"./data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"./data/trustedUserIdentity\";\nimport type { TearleadsOptions } from \"./TearleadsOptions\";\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n private readonly apiNetworkFailures =\n createListenerSet<[ApiNetworkFailureDetails]>();\n /**\n * Every API request that got no response (plain cancellations excluded),\n * with the transport's secret-free details; hosts forward them to\n * diagnostics. Returns the unsubscribe handle.\n */\n readonly subscribeApiNetworkFailures = (\n listener: (details: ApiNetworkFailureDetails) => void,\n ): (() => void) => this.apiNetworkFailures.subscribe(listener);\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database or signing identity changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n private expiredSessionLoginPromise: Promise<boolean> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedState: InternalRuntime[\"primeProvisionedState\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: TearleadsOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(\n apiBaseUrl,\n options.probeApiNetworkFailures === true,\n );\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl,\n identityTrustDomain: options.identityTrustDomain,\n });\n const security = this.createSecurityIncidents(identityTrustDomain, options);\n this.securityIncidents = security.incidents;\n this.disposeSecurityIncidents = security.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(options.identity, this.blobs, this.log, {\n assertReadyForGeneration: () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n },\n bootstrapLocalRootContainer: async (isCurrent) => {\n if (!session) {\n throw new Error(\"identity.generate requires an initialized session.\");\n }\n\n return session.bootstrapLocalRootContainer(isCurrent);\n },\n getUserId: () => session?.userId ?? null,\n });\n session = this.createClientSession(\n options,\n security.report,\n identityTrustDomain,\n );\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n identityTrustDomain,\n options,\n security.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n this.organizations = createOrganizations(\n runtime,\n this.containerContents,\n () => this.deviceFirst.open().reconciler,\n );\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n getOrganizationId: () => this.session.organizationId,\n reportSecurityIncident: security.report,\n identityLinks: runtime.identityLinks,\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Durable incident records in this database, reported to the host's listener. */\n private createSecurityIncidents(\n trustDomain: string | null,\n options: TearleadsOptions,\n ) {\n return createSecurityIncidentService({\n database: this.database,\n logError: this.logError,\n onIncident: options.onSecurityIncident,\n trustDomain,\n });\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n identityTrustDomain: string | null,\n ): Session {\n return createSession({\n identityTrustDomain,\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (userId, candidate) =>\n this.pinLocalUserIdentity(userId, candidate),\n primeProvisionedState: (input) => this.primeProvisionedState(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n }\n\n private createApiClient(\n apiBaseUrl: string,\n probeNetworkFailures: boolean,\n ): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n // A native source beats a WebView's navigator.onLine (Android misreports it).\n isOnline: () => this.network.authoritativeOnline,\n networkFailureProbe: probeNetworkFailures\n ? createApiReachabilityProbe()\n : null,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = (userId, candidate) =>\n runtime.pinLocalUserIdentity(userId, candidate);\n this.primeProvisionedState = runtime.primeProvisionedState;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already\n // verified, and the organization directories its policy bundles hold.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(\n () => this.database.execSql,\n heldDirectoryCitations,\n ),\n );\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnNetworkFailure((error) =>\n this.apiNetworkFailures.notify(error.details),\n );\n this.apiClient.setOnSessionExpired(() => this.loginAfterSessionExpired());\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. Pass it to {@link openServerEventsSocket}.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n /** Opens the API's server-events socket for a ticket; the API client owns the URL shape. */\n openServerEventsSocket(wsUrl: string, ticket: string): WebSocket {\n return openServerEventsSocket(wsUrl, ticket);\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private loginAfterSessionExpired(): Promise<boolean> {\n if (!this.session.authToken || !this.identity.signingKeyPair) {\n this.session.logout();\n return Promise.resolve(false);\n }\n\n // The API client replays requests the expired session sent, so a login is\n // their renewal only when the loaded keys authenticate that known user.\n const expiredUserId = this.session.userId;\n this.expiredSessionLoginPromise ??= this.session\n .login()\n .then(\n (renewed) =>\n renewed &&\n expiredUserId !== null &&\n this.session.userId === expiredUserId,\n )\n .finally(() => {\n this.expiredSessionLoginPromise = null;\n });\n return this.expiredSessionLoginPromise;\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
1
+ {"version":3,"file":"Tearleads.js","sourceRoot":"","sources":["Tearleads.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EAET,iBAAiB,EACjB,0BAA0B,EAC1B,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAEL,uBAAuB,GACxB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAoB,MAAM,sBAAsB,CAAC;AAC3E,OAAO,EAAE,eAAe,EAAkB,MAAM,oBAAoB,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAiB,MAAM,mBAAmB,CAAC;AAClE,OAAO,EACL,oBAAoB,GAErB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,mBAAmB,GAEpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,UAAU,EAAa,aAAa,EAAE,MAAM,eAAe,CAAC;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AACrD,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EACL,aAAa,GAGd,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,6BAA6B,GAE9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;A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AChB,WAAW,GAAG,IAAI,CAAC;QACrB,CAAC,CAAC;QACF,MAAM,sBAAsB,GAAG,GAAG,EAAE;YAClC,IAAI,IAAI,CAAC,uBAAuB,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,CAAC;gBACjE,wBAAwB,EAAE,CAAC;gBAC3B,OAAO;YACT,CAAC;YAED,IACE,IAAI,CAAC,+BAA+B;gBACpC,IAAI,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO,EAChC,CAAC;gBACD,OAAO;YACT,CAAC;YAED,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC,QAAQ;iBACjD,QAAQ,EAAE;iBACV,IAAI,CAAC,GAAG,EAAE;gBACT,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC;gBACpC,wBAAwB,EAAE,CAAC;YAC7B,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACxB,IAAI,CAAC;oBACH,IAAI,CAAC,QAAQ,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;gBACjE,CAAC;gBAAC,MAAM,CAAC;oBACP,gFAAgF;gBAClF,CAAC;YACH,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,IAAI,CAAC,+BAA+B,GAAG,IAAI,CAAC;YAC9C,CAAC,CAAC,CAAC;QACP,CAAC,CAAC;QAEF,WAAW,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACtD,CAAC;CACF","sourcesContent":["import {\n ApiClient,\n type ApiNetworkFailureDetails,\n ApiRequestMetrics,\n createApiReachabilityProbe,\n openServerEventsSocket,\n} from \"@tearleads/api-client\";\nimport { Blobs } from \"./client/blobs\";\nimport {\n type ContainerContents,\n createContainerContents,\n} from \"./client/containerContents\";\nimport { createDeviceFirst, type DeviceFirst } from \"./client/deviceFirst\";\nimport { createDocuments, type Documents } from \"./client/documents\";\nimport { logErrorToConsole } from \"./client/host/logger\";\nimport { createIdentity, type Identity } from \"./client/identity\";\nimport {\n createUserIdentities,\n type UserIdentities,\n} from \"./client/identity/userIdentities\";\nimport {\n createOrganizations,\n type Organizations,\n} from \"./client/organizations\";\nimport { createRoot, type Root, rootRuntimeOf } from \"./client/root\";\nimport { ApiVersion } from \"./client/runtime/apiVersion\";\nimport { Database } from \"./client/runtime/database\";\nimport { Events } from \"./client/runtime/events\";\nimport { Network } from \"./client/runtime/network\";\nimport { SyncBillingGate } from \"./client/runtime/syncBillingGate\";\nimport {\n createRuntime,\n type InternalRuntime,\n type Runtime,\n} from \"./client/runtime/workflowRuntime\";\nimport {\n createSecurityIncidentService,\n type SecurityIncidents,\n} from \"./client/securityIncidents\";\nimport { createSession, sessionLifetime } from \"./client/session\";\nimport type { Session } from \"./client/session/sessionTypes\";\nimport {\n type DocumentProjectorRegistry,\n resolveDocumentProjectorRegistry,\n} from \"./data/documents/documentKinds\";\nimport { heldDirectoryCitations } from \"./data/persistence/principalPolicy/heldOrganizationDirectories\";\nimport { createVerifiedManifestCitations } from \"./data/persistence/verifiedManifestBundlePersistence\";\nimport { createDomainScope, type DomainScope } from \"./data/shared/domainScope\";\nimport { createListenerSet } from \"./data/shared/listenerSet\";\nimport type { SecurityIncidentReporter } from \"./data/shared/securityIncidents\";\nimport { disposeDomainSyncCoordinator } from \"./data/sync/syncCoordinator\";\nimport { resolveIdentityTrustDomain } from \"./data/trustedUserIdentity\";\nimport type { TearleadsOptions } from \"./TearleadsOptions\";\n\nexport class Tearleads {\n readonly apiVersion = new ApiVersion();\n private readonly apiNetworkFailures =\n createListenerSet<[ApiNetworkFailureDetails]>();\n /**\n * Every API request that got no response (plain cancellations excluded),\n * with the transport's secret-free details; hosts forward them to\n * diagnostics. Returns the unsubscribe handle.\n */\n readonly subscribeApiNetworkFailures = (\n listener: (details: ApiNetworkFailureDetails) => void,\n ): (() => void) => this.apiNetworkFailures.subscribe(listener);\n readonly apiRequests: ApiRequestMetrics;\n readonly blobs: Blobs;\n readonly database: Database;\n readonly deviceFirst: DeviceFirst;\n readonly documents: Documents;\n readonly events: Events;\n readonly containerContents: ContainerContents;\n readonly identity: Identity;\n readonly network: Network;\n readonly organizations: Organizations;\n readonly root: Root;\n readonly runtime: Runtime;\n readonly securityIncidents: SecurityIncidents;\n readonly session: Session;\n readonly syncBillingGate: SyncBillingGate;\n readonly userIdentities: UserIdentities;\n\n private readonly apiClient: ApiClient;\n private readonly documentProjectors: DocumentProjectorRegistry;\n private readonly disposeSecurityIncidents: () => void;\n private retirePrincipalHistoryProtection = () => {};\n // Tracks the storage/identity pair that owns domain-scoped runtime state.\n private domainScopeKey: string | null = null;\n // Recreated when the storage database, signing identity, or sign-in changes.\n private domainScopeValue: DomainScope = createDomainScope();\n private readonly logErrorHandler: (\n message: string | Error,\n cause?: unknown,\n ) => void;\n private readonly logHandler: (message: string) => void;\n private autoIdentityProvisioned = false;\n private autoIdentityProvisioningPromise: Promise<void> | null = null;\n // Rebound to the workflow runtime once it exists; the session is created first.\n private pinLocalUserIdentity: InternalRuntime[\"pinLocalUserIdentity\"] =\n async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n private primeProvisionedState: InternalRuntime[\"primeProvisionedState\"] =\n async () => undefined;\n private boundUserId: InternalRuntime[\"boundUserId\"] = async () => {\n throw new Error(\"Trusted user identity runtime is not initialized\");\n };\n\n constructor(options: TearleadsOptions = {}) {\n const apiBaseUrl = options.apiBaseUrl ?? \"\";\n this.apiRequests = options.apiRequestMetrics ?? new ApiRequestMetrics();\n this.apiClient = this.createApiClient(\n apiBaseUrl,\n options.probeApiNetworkFailures === true,\n );\n this.blobs = new Blobs(options.blobStore, options.blobStoreFactory);\n this.database = new Database(options.database);\n this.documentProjectors = resolveDocumentProjectorRegistry(\n options.documentProjectors,\n );\n this.events = new Events(options.events, () =>\n this.apiClient.clearWriterProjectionCaches(),\n );\n this.logHandler = options.logger?.log ?? (() => undefined);\n this.logErrorHandler = options.logger?.logError ?? logErrorToConsole;\n const identityTrustDomain = resolveIdentityTrustDomain({\n apiBaseUrl,\n identityTrustDomain: options.identityTrustDomain,\n });\n const security = this.createSecurityIncidents(identityTrustDomain, options);\n this.securityIncidents = security.incidents;\n this.disposeSecurityIncidents = security.dispose;\n this.network = new Network(options.online);\n this.syncBillingGate = new SyncBillingGate();\n let session: Session | null = null;\n this.identity = createIdentity(options.identity, this.blobs, this.log, {\n assertReadyForGeneration: () => {\n if (this.database.status !== \"ready\") {\n throw new Error(\n \"identity.generate requires a ready SQLite database.\",\n );\n }\n },\n bootstrapLocalRootContainer: async (isCurrent) => {\n if (!session) {\n throw new Error(\"identity.generate requires an initialized session.\");\n }\n\n return session.bootstrapLocalRootContainer(isCurrent);\n },\n getUserId: () => session?.userId ?? null,\n });\n session = this.createClientSession(\n options,\n security.report,\n identityTrustDomain,\n );\n this.session = session;\n const runtime = this.createWorkflowRuntime(\n identityTrustDomain,\n options,\n security.report,\n );\n this.bindTrustedIdentityRuntime(runtime);\n this.runtime = runtime.publicRuntime;\n this.documents = createDocuments({\n getDefaultContainerId: () => this.session.containerId,\n runtime,\n });\n this.containerContents = createContainerContents(runtime);\n this.deviceFirst = createDeviceFirst(runtime, this.containerContents);\n sessionLifetime(session).onBoundary = () => {\n const previous = this.domainScopeValue;\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(previous);\n this.events.clear();\n };\n this.organizations = createOrganizations(\n runtime,\n this.containerContents,\n () => this.deviceFirst.open().reconciler,\n );\n this.root = createRoot(rootRuntimeOf(runtime, this.session));\n this.userIdentities = createUserIdentities({\n getOrganizationId: () => this.session.organizationId,\n reportSecurityIncident: security.report,\n identityLinks: runtime.identityLinks,\n });\n\n this.configureApiClientCallbacks();\n\n if (options.identityProvisioning === \"auto\") {\n this.startAutomaticIdentityProvisioning();\n }\n }\n\n /** Durable incident records in this database, reported to the host's listener. */\n private createSecurityIncidents(\n trustDomain: string | null,\n options: TearleadsOptions,\n ) {\n return createSecurityIncidentService({\n database: this.database,\n logError: this.logError,\n onIncident: options.onSecurityIncident,\n trustDomain,\n });\n }\n\n /** Trust callbacks reach the workflow runtime, which is created later. */\n private createClientSession(\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n identityTrustDomain: string | null,\n ) {\n const session = createSession({\n identityTrustDomain,\n api: this.apiClient,\n database: this.database,\n documentProjectors: this.documentProjectors,\n identity: this.identity,\n log: this.log,\n logError: this.logError,\n boundUserIdForSigningKey: (signingKeyFingerprint) =>\n this.boundUserId(signingKeyFingerprint),\n onUserIdentityAvailable: (...args) => this.pinLocalUserIdentity(...args),\n primeProvisionedState: (input) => this.primeProvisionedState(input),\n provisionedSystemContainers: options.provisionedSystemContainers,\n reportSecurityIncident,\n });\n this.apiClient.setOnSessionExpired(session.renewExpired);\n return session;\n }\n\n private createApiClient(\n apiBaseUrl: string,\n probeNetworkFailures: boolean,\n ): ApiClient {\n return new ApiClient(apiBaseUrl, {\n metrics: this.apiRequests,\n getIdentity: () => this.identity.signingFingerprint,\n // A native source beats a WebView's navigator.onLine (Android misreports it).\n isOnline: () => this.network.authoritativeOnline,\n networkFailureProbe: probeNetworkFailures\n ? createApiReachabilityProbe()\n : null,\n });\n }\n\n /** Rebinds the session's trust callbacks once the runtime exists. */\n private bindTrustedIdentityRuntime(runtime: InternalRuntime): void {\n this.retirePrincipalHistoryProtection =\n runtime.retirePrincipalHistoryProtection;\n this.pinLocalUserIdentity = runtime.pinLocalUserIdentity;\n this.primeProvisionedState = runtime.primeProvisionedState;\n this.boundUserId = (signingKeyFingerprint) =>\n runtime.boundUserId(signingKeyFingerprint);\n }\n\n private configureApiClientCallbacks(): void {\n // Projection reads cite bundles this identity's database already\n // verified, and the organization directories its policy bundles hold.\n this.apiClient.setVerifiedManifestCitations(\n createVerifiedManifestCitations(\n () => this.database.execSql,\n heldDirectoryCitations,\n ),\n );\n this.apiClient.setOnError((message) => this.logError(message));\n // An authoritative host source owns connectivity. Without one, request\n // outcomes remain reachability hints. Browser and native app bindings both\n // install authoritative sources so a backend outage cannot stop retries.\n this.apiClient.setOnNetworkError(() =>\n this.network.reportReachability(false),\n );\n this.apiClient.setOnNetworkSuccess(() =>\n this.network.reportReachability(true),\n );\n this.apiClient.setOnApiVersion((version) =>\n this.apiVersion.observe(version),\n );\n this.apiClient.setOnNetworkFailure((error) =>\n this.apiNetworkFailures.notify(error.details),\n );\n this.apiClient.setOnPaymentRequired((organizationId) =>\n this.syncBillingGate.notifyPaymentRequired(organizationId),\n );\n }\n\n private createWorkflowRuntime(\n identityTrustDomain: string | null,\n options: TearleadsOptions,\n reportSecurityIncident: SecurityIncidentReporter,\n ): InternalRuntime {\n return createRuntime({\n api: this.apiClient,\n blobs: this.blobs,\n database: this.database,\n documentProjectors: this.documentProjectors,\n events: this.events,\n getDomainScope: () => this.domainScope,\n identity: this.identity,\n identityTrustDomain,\n log: this.log,\n logError: this.logError,\n network: this.network,\n peerScope: options.peerScope ?? null,\n principalHistoryKeyProvider: options.principalHistoryKeyProvider,\n principalMutationTimeoutMs: options.principalMutationTimeoutMs,\n reportSecurityIncident,\n session: this.session,\n syncBillingGate: this.syncBillingGate,\n });\n }\n\n log = (message: string): void => {\n this.logHandler(message);\n };\n\n // Preserve the host's return value so best-effort callers can also catch\n // rejected promises from async loggers accepted by the void callback type.\n logError = (message: string | Error, cause?: unknown): void =>\n this.logErrorHandler(message, cause);\n\n /**\n * A single-use ticket to authenticate the server-events websocket handshake\n * (which cannot carry the bearer header): the one login returned for the\n * first connect of that session, otherwise a freshly minted one. Returns\n * null when no session is active. Pass it to {@link openServerEventsSocket}.\n */\n requestWebSocketTicket(): Promise<string | null> {\n return this.apiClient.requestWebSocketTicket();\n }\n\n /** Opens the API's server-events socket for a ticket; the API client owns the URL shape. */\n openServerEventsSocket(wsUrl: string, ticket: string): WebSocket {\n return openServerEventsSocket(wsUrl, ticket);\n }\n\n get domainScope(): DomainScope {\n const nextScopeKey = JSON.stringify([\n this.database.id,\n this.identity.signingFingerprint,\n sessionLifetime(this.session).epoch,\n ]);\n if (this.domainScopeKey !== nextScopeKey) {\n this.domainScopeKey = nextScopeKey;\n this.domainScopeValue = createDomainScope();\n }\n\n return this.domainScopeValue;\n }\n\n /**\n * Tear down background work for the active domain scope: stop the reconciler\n * and force-stop the sync coordinator pump, then drop the coordinator from\n * its registry. Hosts call this from unmount/cleanup so a pump cannot outlive\n * the React tree that created it. A later access for the same scope rebuilds\n * fresh state.\n */\n dispose(): void {\n const domainScope = this.domainScope;\n this.disposeSecurityIncidents();\n this.retirePrincipalHistoryProtection();\n this.deviceFirst.dispose();\n disposeDomainSyncCoordinator(domainScope);\n }\n\n private startAutomaticIdentityProvisioning(): void {\n let unsubscribe: (() => void) | null = null;\n const stopProvisioningListener = () => {\n unsubscribe?.();\n unsubscribe = null;\n };\n const maybeProvisionIdentity = () => {\n if (this.autoIdentityProvisioned || this.identity.signingKeyPair) {\n stopProvisioningListener();\n return;\n }\n\n if (\n this.autoIdentityProvisioningPromise ||\n this.database.status !== \"ready\"\n ) {\n return;\n }\n\n this.autoIdentityProvisioningPromise = this.identity\n .generate()\n .then(() => {\n this.autoIdentityProvisioned = true;\n stopProvisioningListener();\n })\n .catch((error: unknown) => {\n try {\n this.logError(\"Automatic identity provisioning failed\", error);\n } catch {\n // Keep background provisioning failures from surfacing as unhandled rejections.\n }\n })\n .finally(() => {\n this.autoIdentityProvisioningPromise = null;\n });\n };\n\n unsubscribe = this.database.subscribe(maybeProvisionIdentity);\n void Promise.resolve().then(maybeProvisionIdentity);\n }\n}\n"]}
@@ -7,7 +7,7 @@ import { isOrganizationDataRuntimeCurrent, } from "./organizationWorkflowRuntime
7
7
  /**
8
8
  * Run one read-model pass for the scope, then present what it applied: access
9
9
  * recovery when the pass restored a server-denied scope, group names, and
10
- * verified leave requests. Resolves `null` once the scope is no longer current.
10
+ * verified leave requests. A superseded pass resolves without a result.
11
11
  */
12
12
  export function presentOrganizationReadModelPass(runtimeService, active, pass, passIsCurrent = () => true) {
13
13
  // Snapshot the server-denied flag before reconciling. A reconcile that
@@ -26,9 +26,12 @@ export function presentOrganizationReadModelPass(runtimeService, active, pass, p
26
26
  const domainScope = active.runtime.state.domainScope;
27
27
  const stillCurrent = () => isOrganizationDataRuntimeCurrent(runtimeService, active, domainScope) &&
28
28
  passIsCurrent();
29
+ const obsolete = () => runtimeService.workflowInput().state.domainScope === domainScope
30
+ ? null
31
+ : undefined;
29
32
  return pass().then(async (directoryAndGroups) => {
30
33
  if (!stillCurrent())
31
- return null;
34
+ return obsolete();
32
35
  // Feed success restores retry eligibility even if name decryption fails.
33
36
  const accessWasRestored = accessWasDenied &&
34
37
  directoryAndGroups !== null &&
@@ -42,10 +45,10 @@ export function presentOrganizationReadModelPass(runtimeService, active, pass, p
42
45
  userId: active.userId,
43
46
  });
44
47
  if (!stillCurrent())
45
- return null;
48
+ return obsolete();
46
49
  const presented = await withVerifiedLeaveRequests(await hydrateOrganizationGroupNamesForRuntime(runtimeService, active, domainScope, directoryAndGroups), leaveRequestVerifier(runtimeService, active.runtime, active));
47
50
  // A transition during presentation publishes nothing for the old scope.
48
- return stillCurrent() ? presented : null;
51
+ return stillCurrent() ? presented : obsolete();
49
52
  });
50
53
  }
51
54
  //# sourceMappingURL=organizationReadModelPresentation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModelPresentation.js","sourceRoot":"","sources":["organizationReadModelPresentation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAE1G,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,+CAA+C,EAAE,MAAM,6EAA6E,CAAC;AAE9I,OAAO,EAAE,uCAAuC,EAAE,MAAM,kCAAkC,CAAC;AAC3F,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAEL,gCAAgC,GACjC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3C,cAAc,EACd,MAAM,EACN,WAAW,EACX,kBAAkB,CACnB,EACD,oBAAoB,CAAC,cAAc,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAC7D,CAAC;QACF,wEAAwE;QACxE,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport type { OrganizationDirectoryAndGroups } from \"../../workflows/organizations\";\nimport { withVerifiedLeaveRequests } from \"../../workflows/organizations\";\nimport { wasOrganizationPresentationAccessDeniedByServer } from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { leaveRequestVerifier } from \"./organizationLeaveRequestVerifier\";\nimport {\n type ActiveOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\n/**\n * Run one read-model pass for the scope, then present what it applied: access\n * recovery when the pass restored a server-denied scope, group names, and\n * verified leave requests. Resolves `null` once the scope is no longer current.\n */\nexport function presentOrganizationReadModelPass(\n runtimeService: InternalRuntime,\n active: ActiveOrganizationDataRuntime,\n pass: () => Promise<OrganizationDirectoryAndGroups | null | undefined>,\n passIsCurrent: () => boolean = () => true,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(runtimeService, active, domainScope) &&\n passIsCurrent();\n\n return pass().then(async (directoryAndGroups) => {\n if (!stillCurrent()) return null;\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return null;\n const presented = await withVerifiedLeaveRequests(\n await hydrateOrganizationGroupNamesForRuntime(\n runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n ),\n leaveRequestVerifier(runtimeService, active.runtime, active),\n );\n // A transition during presentation publishes nothing for the old scope.\n return stillCurrent() ? presented : null;\n });\n}\n"]}
1
+ {"version":3,"file":"organizationReadModelPresentation.js","sourceRoot":"","sources":["organizationReadModelPresentation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+DAA+D,CAAC;AAE1G,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,+CAA+C,EAAE,MAAM,6EAA6E,CAAC;AAE9I,OAAO,EAAE,uCAAuC,EAAE,MAAM,kCAAkC,CAAC;AAC3F,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAEL,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC;;;;GAIG;AACH,MAAM,UAAU,gCAAgC,CAC9C,cAA+B,EAC/B,MAAqC,EACrC,IAAsE,EACtE,gBAA+B,GAAG,EAAE,CAAC,IAAI;IAEzC,uEAAuE;IACvE,yEAAyE;IACzE,8DAA8D;IAC9D,0EAA0E;IAC1E,qEAAqE;IACrE,y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oBAAoB,CAAC,cAAc,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAC7D,CAAC;QACF,wEAAwE;QACxE,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;IACjD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { recoverOrganizationAccess } from \"../../workflows/container-contents/recovery/accessRestoration\";\nimport type { OrganizationDirectoryAndGroups } from \"../../workflows/organizations\";\nimport { withVerifiedLeaveRequests } from \"../../workflows/organizations\";\nimport { wasOrganizationPresentationAccessDeniedByServer } from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { hydrateOrganizationGroupNamesForRuntime } from \"./organizationGroupNameHydration\";\nimport { leaveRequestVerifier } from \"./organizationLeaveRequestVerifier\";\nimport {\n type ActiveOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\n/**\n * Run one read-model pass for the scope, then present what it applied: access\n * recovery when the pass restored a server-denied scope, group names, and\n * verified leave requests. A superseded pass resolves without a result.\n */\nexport function presentOrganizationReadModelPass(\n runtimeService: InternalRuntime,\n active: ActiveOrganizationDataRuntime,\n pass: () => Promise<OrganizationDirectoryAndGroups | null | undefined>,\n passIsCurrent: () => boolean = () => true,\n): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n // Snapshot the server-denied flag before reconciling. A reconcile that\n // flips it back to readable means org access was just restored (e.g. the\n // user was re-added to a group), and any write lanes idled by\n // permission-denied submissions have no self re-arm — regaining access is\n // their retry signal, mirroring how billing recovery re-requests all\n // lanes. Only a genuine server denial counts: a local session reset also\n // marks scopes denied, and re-arming on its first reconcile would race the\n // startup sync passes (e.g. pending-create adoption between panes).\n const accessWasDenied = wasOrganizationPresentationAccessDeniedByServer(\n {\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n requesterUserId: active.userId,\n },\n \"readModel\",\n );\n const domainScope = active.runtime.state.domainScope;\n const stillCurrent = () =>\n isOrganizationDataRuntimeCurrent(runtimeService, active, domainScope) &&\n passIsCurrent();\n\n const obsolete = () =>\n runtimeService.workflowInput().state.domainScope === domainScope\n ? null\n : undefined;\n return pass().then(async (directoryAndGroups) => {\n if (!stillCurrent()) return obsolete();\n // Feed success restores retry eligibility even if name decryption fails.\n const accessWasRestored =\n accessWasDenied &&\n directoryAndGroups !== null &&\n directoryAndGroups !== undefined;\n if (accessWasRestored)\n await recoverOrganizationAccess({\n domainScope,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n stillCurrent,\n userId: active.userId,\n });\n if (!stillCurrent()) return obsolete();\n const presented = await withVerifiedLeaveRequests(\n await hydrateOrganizationGroupNamesForRuntime(\n runtimeService,\n active,\n domainScope,\n directoryAndGroups,\n ),\n leaveRequestVerifier(runtimeService, active.runtime, active),\n );\n // A transition during presentation publishes nothing for the old scope.\n return stillCurrent() ? presented : obsolete();\n });\n}\n"]}
@@ -75,23 +75,21 @@ class OrganizationReadModelCoordinatorImpl {
75
75
  if (!active || groupId.length === 0) {
76
76
  return null;
77
77
  }
78
- const domainScope = active.runtime.state.domainScope;
79
78
  return loadBoundedOrganizationGroupHistory({
80
79
  active,
81
80
  groupId,
82
81
  beforeVersion,
83
- stillCurrent: () => isOrganizationDataRuntimeCurrent(this.runtimeService, active, domainScope),
82
+ stillCurrent: () => isOrganizationDataRuntimeCurrent(this.runtimeService, active),
84
83
  });
85
84
  }
86
85
  async loadOrganizationPolicyHistory(organizationId, beforeVersion) {
87
86
  const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
88
87
  if (!active)
89
88
  return null;
90
- const domainScope = active.runtime.state.domainScope;
91
89
  return loadBoundedOrganizationHistory({
92
90
  active,
93
91
  beforeVersion,
94
- stillCurrent: () => isOrganizationDataRuntimeCurrent(this.runtimeService, active, domainScope),
92
+ stillCurrent: () => isOrganizationDataRuntimeCurrent(this.runtimeService, active),
95
93
  });
96
94
  }
97
95
  async loadLocalUserDetail(userId, organizationId) {
@@ -126,6 +124,7 @@ class OrganizationReadModelCoordinatorImpl {
126
124
  execSql: active.runtime.infra.execSql,
127
125
  logError: active.runtime.util.logError,
128
126
  organizationId: active.organizationId,
127
+ stillCurrent: () => isOrganizationDataRuntimeCurrent(this.runtimeService, active),
129
128
  }));
130
129
  }
131
130
  /** Run one projection pass for the scope, then present what it applied. */
@@ -163,7 +162,9 @@ class OrganizationReadModelCoordinatorImpl {
163
162
  return undefined;
164
163
  }
165
164
  await this.settleInFlightReconcile(active);
166
- return this.reconcile(active.organizationId);
165
+ return isOrganizationDataRuntimeCurrent(this.runtimeService, active)
166
+ ? this.reconcile(active.organizationId)
167
+ : undefined;
167
168
  }
168
169
  async applyCommittedReadModel(organizationId, delta) {
169
170
  const active = activeOrganizationDataRuntime(this.runtimeService, organizationId);
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AAGxG,OAAO,EACL,mCAAmC,EACnC,6BAA6B,EAG7B,4BAA4B,EAC5B,mCAAmC,EACnC,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAE/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,6EAA6E,CAAC;AAEzH,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAK1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EACL,cAAc,EAEd,sBAAsB,EACtB,SAAS,EACT,gBA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I,CAAC,YAAY,EAAE;gBAAE,OAAO,IAAI,CAAC;YACjC,MAAM,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC,OAAO,EAAE,EAAE,CACjE,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,OAAO,EAAE,iBAAiB,CAAC,CAC3D,CAAC;QACJ,CAAC;QACD,MAAM,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;QAC3C,MAAM,OAAO,GAAG,MAAM,sBAAsB,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACvE,oEAAoE;QACpE,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IAEO,KAAK,CAAC,uBAAuB,CACnC,MAAqC;QAErC,MAAM,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC;aACjC,GAAG,CAAC,0BAA0B,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;YACtE,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;CACF;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { organizationReadModelCursorPosition } from \"@tearleads/validators/organizationReadModelCursor\";\nimport type { OrganizationReadModelDeltaResponse } from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n applyCommittedOrganizationReadModel,\n awaitCommittedReadModelOffers,\n type CommittedReadModelOffer,\n type CommittedReadModelOutcome,\n claimCommittedReadModelOffer,\n loadHeldOrganizationReadModelCursor,\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationDirectoryAndGroups,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { organizationAccessScopeKey } from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport { leaveRequestVerifier } from \"./organizationLeaveRequestVerifier\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nexport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nimport { presentOrganizationReadModelPass } from \"./organizationReadModelPresentation\";\nimport {\n committedScope,\n type InFlightReadModelPass,\n presentedAppliedCursor,\n scopedMap,\n sessionIsCurrent,\n} from \"./organizationReadModelScopes\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n // The pass in flight per requester: a feed read, or a committed delta's\n // local apply, which a feed refresh waits out instead of joining.\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, InFlightReadModelPass>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n const domainScope = active.runtime.state.domainScope;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(\n this.runtimeService,\n active,\n domainScope,\n ),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n const inFlight = this.reconciliationMap(active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n // A delta's apply reflects its commit, not this request: read after it,\n // for this scope only.\n if (inFlight?.kind === \"delta\") {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n return inFlight.promise\n .catch(() => null)\n .then(() =>\n stillCurrent() ? this.reconcile(active.organizationId) : null,\n );\n }\n return this.presentReconciliation(active, \"feed\", () =>\n reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n }),\n );\n }\n\n /** Run one projection pass for the scope, then present what it applied. */\n private presentReconciliation(\n active: ActiveOrganizationDataRuntime,\n kind: InFlightReadModelPass[\"kind\"],\n pass: () => Promise<OrganizationDirectoryAndGroups | null | undefined>,\n passIsCurrent?: () => boolean,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing.promise;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n const reconciliation = presentOrganizationReadModelPass(\n this.runtimeService,\n active,\n pass,\n passIsCurrent,\n )\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n // A delta that did not apply leaves what was presented standing.\n else if (kind === \"feed\") presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key)?.promise === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, { kind, promise: reconciliation });\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return this.reconcile(active.organizationId);\n }\n\n async applyCommittedReadModel(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n ): Promise<CommittedReadModelOutcome> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !delta) return undefined;\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n // A hint's cursor check may have claimed this delta first; share its apply.\n const outcome = await claimCommittedReadModelOffer(\n committedScope(active, sessionGeneration),\n delta,\n (offer) => this.applyClaimedOffer(active, offer, sessionGeneration),\n );\n if (!stillCurrent()) return undefined;\n if (!outcome) return outcome;\n // An apply that finished earlier stands only while nothing replaced it: a\n // later feed pass or purge leaves the caller to read instead. The mutation\n // already committed, so a failed check is only a missed delta.\n const presented = await presentedAppliedCursor(\n active,\n scopedMap(this.presentedCursorsByScope, active),\n ).catch(() => null);\n return stillCurrent() && presented === outcome.readModelCursor\n ? outcome\n : undefined;\n }\n\n private async applyClaimedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<CommittedReadModelOutcome> {\n // Distinct offers apply one after another: each waits out every pass in\n // flight, so none joins another's apply and is consumed unapplied.\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n while (this.reconciliationMap(active).has(key))\n await this.settleInFlightReconcile(active);\n return this.applyCommittedOffer(active, offer, sessionGeneration);\n }\n\n /**\n * Present an offer while the projection holds its sent cursor and the scope\n * and session are the ones that waited; a failure only forgoes it.\n */\n private applyCommittedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n return this.presentReconciliation(\n active,\n \"delta\",\n async () => {\n const held = await loadHeldOrganizationReadModelCursor(\n committedScope(active, sessionGeneration),\n );\n if (held !== offer.heldCursor || !stillCurrent()) return undefined;\n return applyCommittedOrganizationReadModel({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n requestedCursor: offer.heldCursor,\n response: offer.delta,\n stillCurrent,\n });\n },\n stillCurrent,\n ).catch((error: unknown) => {\n active.runtime.util.logError(\n \"Failed to apply a committed organization read-model delta\",\n error,\n );\n return undefined;\n });\n }\n\n sessionGuard(organizationId?: string): () => boolean {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n return active\n ? sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n )\n : () => false;\n }\n\n async reconcileAfterOwnMutation(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n startedIn: () => boolean = () => true,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !startedIn()) return undefined;\n const current = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n const stillCurrent = () => current() && startedIn();\n const applied = await this.applyCommittedReadModel(organizationId, delta);\n if (applied) return applied;\n // The fallback reads for the session that committed, or not at all.\n await this.settleInFlightReconcile(active);\n return stillCurrent() ? this.reconcile(active.organizationId) : undefined;\n }\n\n async loadAppliedCursor(\n hintPosition?: bigint,\n organizationId?: string,\n ): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n // The check belongs to the session it started in, before any await.\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n // A hint the presentation already covers waits for nothing.\n const presented = await presentedAppliedCursor(active, presentedCursors);\n if (!stillCurrent()) return null;\n if (\n hintPosition !== undefined &&\n presented !== null &&\n (organizationReadModelCursorPosition(presented, active.organizationId) ??\n -1n) >= hintPosition\n )\n return presented;\n // Otherwise this scope's own mutations that could be the hint's commit\n // settle first, and the deltas they carried apply, so a hint naming one of\n // those commits needs no read.\n const scope = committedScope(active, sessionGeneration);\n for (const offer of await awaitCommittedReadModelOffers(\n scope,\n hintPosition,\n )) {\n if (!stillCurrent()) return null;\n await claimCommittedReadModelOffer(scope, offer.delta, (claimed) =>\n this.applyClaimedOffer(active, claimed, sessionGeneration),\n );\n }\n await this.settleInFlightReconcile(active);\n const applied = await presentedAppliedCursor(active, presentedCursors);\n // A replacement session's cursor never answers this session's hint.\n return stillCurrent() ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.promise.catch(() => null);\n }\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
1
+ {"version":3,"file":"organizationReadModels.js","sourceRoot":"","sources":["organizationReadModels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AAGxG,OAAO,EACL,mCAAmC,EACnC,6BAA6B,EAG7B,4BAA4B,EAC5B,mCAAmC,EACnC,oCAAoC,EACpC,uCAAuC,EACvC,oCAAoC,EACpC,iCAAiC,EACjC,+BAA+B,EAE/B,uCAAuC,EACvC,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,6EAA6E,CAAC;AAEzH,OAAO,EAAE,mCAAmC,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAK1E,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EACL,cAAc,EAEd,sBAAsB,EACtB,SAAS,EACT,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAEL,6BAA6B,EAC7B,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AAEvC,MAAM,qBAAqB,GAAG,IAAI,OAAO,EAGtC,CAAC;AAEJ,MAAM,oCAAoC;IAiBX;IAd7B,wEAAwE;IACxE,kEAAkE;IACjD,sBAAsB,GAAG,IAAI,OAAO,EAGlD,CAAC;IACJ,uEA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B,CAAC,MAAM,CAAC,CAAC;QAC3C,MAAM,OAAO,GAAG,MAAM,sBAAsB,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACvE,oEAAoE;QACpE,OAAO,YAAY,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IACzC,CAAC;IAEO,KAAK,CAAC,uBAAuB,CACnC,MAAqC;QAErC,MAAM,IAAI,CAAC,iBAAiB,CAAC,MAAM,CAAC;aACjC,GAAG,CAAC,0BAA0B,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;YACtE,EAAE,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;CACF;AAED,MAAM,UAAU,sCAAsC,CACpD,cAA+B;IAE/B,MAAM,QAAQ,GAAG,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,MAAM,WAAW,GAAG,IAAI,oCAAoC,CAAC,cAAc,CAAC,CAAC;IAC7E,qBAAqB,CAAC,GAAG,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IACvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { organizationReadModelCursorPosition } from \"@tearleads/validators/organizationReadModelCursor\";\nimport type { OrganizationReadModelDeltaResponse } from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../data/shared/domainScope\";\nimport {\n applyCommittedOrganizationReadModel,\n awaitCommittedReadModelOffers,\n type CommittedReadModelOffer,\n type CommittedReadModelOutcome,\n claimCommittedReadModelOffer,\n loadHeldOrganizationReadModelCursor,\n loadLocalOrganizationContainerGrants,\n loadLocalOrganizationDirectoryAndGroups,\n loadLocalOrganizationGroupContainers,\n loadLocalOrganizationGroupMembers,\n loadLocalOrganizationUserDetail,\n type OrganizationDirectoryAndGroups,\n reconcileOrganizationDirectoryAndGroups,\n withVerifiedLeaveRequests,\n withVerifiedUserLeaveRequest,\n} from \"../../workflows/organizations\";\nimport { organizationAccessScopeKey } from \"../../workflows/organizations/readModel/organizationPresentationAccessState\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { loadBoundedOrganizationGroupHistory } from \"./organizationGroupHistory\";\nimport { loadBoundedOrganizationHistory } from \"./organizationHistory\";\nimport { leaveRequestVerifier } from \"./organizationLeaveRequestVerifier\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nexport type { OrganizationReadModelCoordinator } from \"./organizationReadModelCoordinator\";\n\nimport { presentOrganizationReadModelPass } from \"./organizationReadModelPresentation\";\nimport {\n committedScope,\n type InFlightReadModelPass,\n presentedAppliedCursor,\n scopedMap,\n sessionIsCurrent,\n} from \"./organizationReadModelScopes\";\nimport {\n type ActiveOrganizationDataRuntime,\n activeOrganizationDataRuntime,\n isOrganizationDataRuntimeCurrent,\n} from \"./organizationWorkflowRuntime\";\n\nconst coordinatorsByRuntime = new WeakMap<\n InternalRuntime,\n OrganizationReadModelCoordinator\n>();\n\nclass OrganizationReadModelCoordinatorImpl\n implements OrganizationReadModelCoordinator\n{\n // The pass in flight per requester: a feed read, or a committed delta's\n // local apply, which a feed refresh waits out instead of joining.\n private readonly reconciliationsByScope = new WeakMap<\n DomainScope,\n Map<string, InFlightReadModelPass>\n >();\n // The cursor each requester's last reconcile fully presented: applied,\n // group names hydrated and leave requests verified. A stored cursor whose\n // presentation work failed does not count as applied, so the next hint\n // reconciles and retries that work.\n private readonly presentedCursorsByScope = new WeakMap<\n DomainScope,\n Map<string, string>\n >();\n constructor(private readonly runtimeService: InternalRuntime) {}\n\n private reconciliationMap(active: ActiveOrganizationDataRuntime) {\n return scopedMap(this.reconciliationsByScope, active);\n }\n\n async loadLocal(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return withVerifiedLeaveRequests(\n await loadLocalOrganizationDirectoryAndGroups({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n }),\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n async loadLocalGrants(organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) {\n return null;\n }\n return loadLocalOrganizationContainerGrants({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupContainers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupContainers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadLocalGroupMembers(groupId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadLocalOrganizationGroupMembers({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n groupId,\n organizationId: active.organizationId,\n });\n }\n\n async loadGroupPolicyHistory(\n groupId: string,\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || groupId.length === 0) {\n return null;\n }\n return loadBoundedOrganizationGroupHistory({\n active,\n groupId,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(this.runtimeService, active),\n });\n }\n\n async loadOrganizationPolicyHistory(\n organizationId?: string,\n beforeVersion?: number,\n ) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n return loadBoundedOrganizationHistory({\n active,\n beforeVersion,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(this.runtimeService, active),\n });\n }\n\n async loadLocalUserDetail(userId: string, organizationId?: string) {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || userId.length === 0) {\n return null;\n }\n return withVerifiedUserLeaveRequest(\n await loadLocalOrganizationUserDetail({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n organizationId: active.organizationId,\n userId,\n }),\n active.organizationId,\n leaveRequestVerifier(this.runtimeService, active.runtime, active),\n );\n }\n\n reconcile(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return Promise.resolve(undefined);\n }\n const inFlight = this.reconciliationMap(active).get(\n organizationAccessScopeKey(active.organizationId, active.userId),\n );\n // A delta's apply reflects its commit, not this request: read after it,\n // for this scope only.\n if (inFlight?.kind === \"delta\") {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n return inFlight.promise\n .catch(() => null)\n .then(() =>\n stillCurrent() ? this.reconcile(active.organizationId) : null,\n );\n }\n return this.presentReconciliation(active, \"feed\", () =>\n reconcileOrganizationDirectoryAndGroups({\n apiClient: active.runtime.apiClient,\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n stillCurrent: () =>\n isOrganizationDataRuntimeCurrent(this.runtimeService, active),\n }),\n );\n }\n\n /** Run one projection pass for the scope, then present what it applied. */\n private presentReconciliation(\n active: ActiveOrganizationDataRuntime,\n kind: InFlightReadModelPass[\"kind\"],\n pass: () => Promise<OrganizationDirectoryAndGroups | null | undefined>,\n passIsCurrent?: () => boolean,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const byKey = this.reconciliationMap(active);\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n const existing = byKey.get(key);\n if (existing) {\n return existing.promise;\n }\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n\n const reconciliation = presentOrganizationReadModelPass(\n this.runtimeService,\n active,\n pass,\n passIsCurrent,\n )\n .then(\n (presented) => {\n if (presented) presentedCursors.set(key, presented.readModelCursor);\n // A delta that did not apply leaves what was presented standing.\n else if (kind === \"feed\") presentedCursors.delete(key);\n return presented;\n },\n (error: unknown) => {\n presentedCursors.delete(key);\n throw error;\n },\n )\n .finally(() => {\n if (byKey.get(key)?.promise === reconciliation) {\n byKey.delete(key);\n }\n });\n byKey.set(key, { kind, promise: reconciliation });\n return reconciliation;\n }\n\n async reconcileAfterMutation(\n organizationId?: string,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active?.runtime.state.online) {\n return undefined;\n }\n await this.settleInFlightReconcile(active);\n return isOrganizationDataRuntimeCurrent(this.runtimeService, active)\n ? this.reconcile(active.organizationId)\n : undefined;\n }\n\n async applyCommittedReadModel(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n ): Promise<CommittedReadModelOutcome> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !delta) return undefined;\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n // A hint's cursor check may have claimed this delta first; share its apply.\n const outcome = await claimCommittedReadModelOffer(\n committedScope(active, sessionGeneration),\n delta,\n (offer) => this.applyClaimedOffer(active, offer, sessionGeneration),\n );\n if (!stillCurrent()) return undefined;\n if (!outcome) return outcome;\n // An apply that finished earlier stands only while nothing replaced it: a\n // later feed pass or purge leaves the caller to read instead. The mutation\n // already committed, so a failed check is only a missed delta.\n const presented = await presentedAppliedCursor(\n active,\n scopedMap(this.presentedCursorsByScope, active),\n ).catch(() => null);\n return stillCurrent() && presented === outcome.readModelCursor\n ? outcome\n : undefined;\n }\n\n private async applyClaimedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<CommittedReadModelOutcome> {\n // Distinct offers apply one after another: each waits out every pass in\n // flight, so none joins another's apply and is consumed unapplied.\n const key = organizationAccessScopeKey(\n active.organizationId,\n active.userId,\n );\n while (this.reconciliationMap(active).has(key))\n await this.settleInFlightReconcile(active);\n return this.applyCommittedOffer(active, offer, sessionGeneration);\n }\n\n /**\n * Present an offer while the projection holds its sent cursor and the scope\n * and session are the ones that waited; a failure only forgoes it.\n */\n private applyCommittedOffer(\n active: ActiveOrganizationDataRuntime,\n offer: CommittedReadModelOffer,\n sessionGeneration: number,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n return this.presentReconciliation(\n active,\n \"delta\",\n async () => {\n const held = await loadHeldOrganizationReadModelCursor(\n committedScope(active, sessionGeneration),\n );\n if (held !== offer.heldCursor || !stillCurrent()) return undefined;\n return applyCommittedOrganizationReadModel({\n currentUserId: active.userId,\n execSql: active.runtime.infra.execSql,\n logError: active.runtime.util.logError,\n organizationId: active.organizationId,\n requestedCursor: offer.heldCursor,\n response: offer.delta,\n stillCurrent,\n });\n },\n stillCurrent,\n ).catch((error: unknown) => {\n active.runtime.util.logError(\n \"Failed to apply a committed organization read-model delta\",\n error,\n );\n return undefined;\n });\n }\n\n sessionGuard(organizationId?: string): () => boolean {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n return active\n ? sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n )\n : () => false;\n }\n\n async reconcileAfterOwnMutation(\n organizationId: string,\n delta: OrganizationReadModelDeltaResponse | undefined,\n startedIn: () => boolean = () => true,\n ): Promise<OrganizationDirectoryAndGroups | null | undefined> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active || !startedIn()) return undefined;\n const current = sessionIsCurrent(\n this.runtimeService,\n active,\n this.runtimeService.sessionGeneration,\n );\n const stillCurrent = () => current() && startedIn();\n const applied = await this.applyCommittedReadModel(organizationId, delta);\n if (applied) return applied;\n // The fallback reads for the session that committed, or not at all.\n await this.settleInFlightReconcile(active);\n return stillCurrent() ? this.reconcile(active.organizationId) : undefined;\n }\n\n async loadAppliedCursor(\n hintPosition?: bigint,\n organizationId?: string,\n ): Promise<string | null> {\n const active = activeOrganizationDataRuntime(\n this.runtimeService,\n organizationId,\n );\n if (!active) return null;\n // The check belongs to the session it started in, before any await.\n const { sessionGeneration } = this.runtimeService;\n const stillCurrent = sessionIsCurrent(\n this.runtimeService,\n active,\n sessionGeneration,\n );\n const presentedCursors = scopedMap(this.presentedCursorsByScope, active);\n // A hint the presentation already covers waits for nothing.\n const presented = await presentedAppliedCursor(active, presentedCursors);\n if (!stillCurrent()) return null;\n if (\n hintPosition !== undefined &&\n presented !== null &&\n (organizationReadModelCursorPosition(presented, active.organizationId) ??\n -1n) >= hintPosition\n )\n return presented;\n // Otherwise this scope's own mutations that could be the hint's commit\n // settle first, and the deltas they carried apply, so a hint naming one of\n // those commits needs no read.\n const scope = committedScope(active, sessionGeneration);\n for (const offer of await awaitCommittedReadModelOffers(\n scope,\n hintPosition,\n )) {\n if (!stillCurrent()) return null;\n await claimCommittedReadModelOffer(scope, offer.delta, (claimed) =>\n this.applyClaimedOffer(active, claimed, sessionGeneration),\n );\n }\n await this.settleInFlightReconcile(active);\n const applied = await presentedAppliedCursor(active, presentedCursors);\n // A replacement session's cursor never answers this session's hint.\n return stillCurrent() ? applied : null;\n }\n\n private async settleInFlightReconcile(\n active: ActiveOrganizationDataRuntime,\n ): Promise<void> {\n await this.reconciliationMap(active)\n .get(organizationAccessScopeKey(active.organizationId, active.userId))\n ?.promise.catch(() => null);\n }\n}\n\nexport function createOrganizationReadModelCoordinator(\n runtimeService: InternalRuntime,\n): OrganizationReadModelCoordinator {\n const existing = coordinatorsByRuntime.get(runtimeService);\n if (existing) {\n return existing;\n }\n\n const coordinator = new OrganizationReadModelCoordinatorImpl(runtimeService);\n coordinatorsByRuntime.set(runtimeService, coordinator);\n return coordinator;\n}\n"]}
@@ -28,7 +28,7 @@ export function activeOrganizationDataRuntime(runtimeService, expectedOrganizati
28
28
  }
29
29
  return { runtime, organizationId, userId };
30
30
  }
31
- export function isOrganizationDataRuntimeCurrent(runtimeService, active, domainScope) {
31
+ export function isOrganizationDataRuntimeCurrent(runtimeService, active, domainScope = active.runtime.state.domainScope) {
32
32
  const current = activeOrganizationDataRuntime(runtimeService, active.organizationId);
33
33
  return (current?.userId === active.userId &&
34
34
  current.runtime.infra.execSql === active.runtime.infra.execSql &&
@@ -1 +1 @@
1
- {"version":3,"file":"organizationWorkflowRuntime.js","sourceRoot":"","sources":["organizationWorkflowRuntime.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,2BAA2B,CACzC,OAAqC;IAErC,OAAO,OAAO,CAAC,IAAI,CAAC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,eAAe;QAChE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc;QAC7B,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,cAA+B,EAC/B,QAAiC,EACjC,oBAA6B;IAE7B,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAC/C,MAAM,oBAAoB,GAAG,2BAA2B,CAAC,OAAO,CAAC,CAAC;IAClE,MAAM,cAAc,GAClB,oBAAoB,KAAK,SAAS;QAChC,CAAC,CAAC,oBAAoB;QACtB,CAAC,CAAC,oBAAoB,CAAC;IAC3B,IAAI,CAAC,oBAAoB,IAAI,CAAC,cAAc,EAAE,CAAC;QAC7C,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,OAAO,QAAQ,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,cAAc,EAAE,CAAC,CAAC;AACpE,CAAC;AAQD,MAAM,UAAU,6BAA6B,CAC3C,cAA+B,EAC/B,sBAA+B;IAE/B,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAC/C,MAAM,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC;IACnD,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;IACnC,IACE,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe;QAC7B,CAAC,cAAc;QACf,CAAC,MAAM;QACP,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO;QAClC,CAAC,sBAAsB,KAAK,SAAS;YACnC,cAAc,KAAK,sBAAsB,CAAC,EAC5C,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,cAA+B,EAC/B,MAAqC,EACrC,WAAwB;IAExB,MAAM,OAAO,GAAG,6BAA6B,CAC3C,cAAc,EACd,MAAM,CAAC,cAAc,CACtB,CAAC;IACF,OAAO,CACL,OAAO,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9D,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,WAAW,CAClD,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\ntype OrganizationWorkflow<T> = (input: {\n readonly apiClient: InternalWorkflowRuntimeInput[\"apiClient\"];\n readonly organizationId: string;\n}) => Promise<T>;\n\nexport function authenticatedOrganizationId(\n runtime: InternalWorkflowRuntimeInput,\n): string | null {\n return runtime.auth.organizationId && runtime.auth.isAuthenticated\n ? runtime.auth.organizationId\n : null;\n}\n\nexport function runForOrganization<T>(\n runtimeService: InternalRuntime,\n workflow: OrganizationWorkflow<T>,\n targetOrganizationId?: string,\n): Promise<T | null> {\n const runtime = runtimeService.workflowInput();\n const activeOrganizationId = authenticatedOrganizationId(runtime);\n const organizationId =\n targetOrganizationId === undefined\n ? activeOrganizationId\n : targetOrganizationId;\n if (!activeOrganizationId || !organizationId) {\n return Promise.resolve(null);\n }\n\n return workflow({ apiClient: runtime.apiClient, organizationId });\n}\n\nexport interface ActiveOrganizationDataRuntime {\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport function activeOrganizationDataRuntime(\n runtimeService: InternalRuntime,\n expectedOrganizationId?: string,\n): ActiveOrganizationDataRuntime | null {\n const runtime = runtimeService.workflowInput();\n const organizationId = runtime.auth.organizationId;\n const userId = runtime.auth.userId;\n if (\n !runtime.auth.isAuthenticated ||\n !organizationId ||\n !userId ||\n runtime.infra.dbStatus !== \"ready\" ||\n (expectedOrganizationId !== undefined &&\n organizationId !== expectedOrganizationId)\n ) {\n return null;\n }\n\n return { runtime, organizationId, userId };\n}\n\nexport function isOrganizationDataRuntimeCurrent(\n runtimeService: InternalRuntime,\n active: ActiveOrganizationDataRuntime,\n domainScope: DomainScope,\n): boolean {\n const current = activeOrganizationDataRuntime(\n runtimeService,\n active.organizationId,\n );\n return (\n current?.userId === active.userId &&\n current.runtime.infra.execSql === active.runtime.infra.execSql &&\n current.runtime.state.domainScope === domainScope\n );\n}\n"]}
1
+ {"version":3,"file":"organizationWorkflowRuntime.js","sourceRoot":"","sources":["organizationWorkflowRuntime.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,2BAA2B,CACzC,OAAqC;IAErC,OAAO,OAAO,CAAC,IAAI,CAAC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,eAAe;QAChE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc;QAC7B,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,MAAM,UAAU,kBAAkB,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F,OAAO,CACL,OAAO,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM;QACjC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9D,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,WAAW,CAClD,CAAC;AACJ,CAAC","sourcesContent":["import type { DomainScope } from \"../../data/shared/domainScope\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\ntype OrganizationWorkflow<T> = (input: {\n readonly apiClient: InternalWorkflowRuntimeInput[\"apiClient\"];\n readonly organizationId: string;\n}) => Promise<T>;\n\nexport function authenticatedOrganizationId(\n runtime: InternalWorkflowRuntimeInput,\n): string | null {\n return runtime.auth.organizationId && runtime.auth.isAuthenticated\n ? runtime.auth.organizationId\n : null;\n}\n\nexport function runForOrganization<T>(\n runtimeService: InternalRuntime,\n workflow: OrganizationWorkflow<T>,\n targetOrganizationId?: string,\n): Promise<T | null> {\n const runtime = runtimeService.workflowInput();\n const activeOrganizationId = authenticatedOrganizationId(runtime);\n const organizationId =\n targetOrganizationId === undefined\n ? activeOrganizationId\n : targetOrganizationId;\n if (!activeOrganizationId || !organizationId) {\n return Promise.resolve(null);\n }\n\n return workflow({ apiClient: runtime.apiClient, organizationId });\n}\n\nexport interface ActiveOrganizationDataRuntime {\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport function activeOrganizationDataRuntime(\n runtimeService: InternalRuntime,\n expectedOrganizationId?: string,\n): ActiveOrganizationDataRuntime | null {\n const runtime = runtimeService.workflowInput();\n const organizationId = runtime.auth.organizationId;\n const userId = runtime.auth.userId;\n if (\n !runtime.auth.isAuthenticated ||\n !organizationId ||\n !userId ||\n runtime.infra.dbStatus !== \"ready\" ||\n (expectedOrganizationId !== undefined &&\n organizationId !== expectedOrganizationId)\n ) {\n return null;\n }\n\n return { runtime, organizationId, userId };\n}\n\nexport function isOrganizationDataRuntimeCurrent(\n runtimeService: InternalRuntime,\n active: ActiveOrganizationDataRuntime,\n domainScope: DomainScope = active.runtime.state.domainScope,\n): boolean {\n const current = activeOrganizationDataRuntime(\n runtimeService,\n active.organizationId,\n );\n return (\n current?.userId === active.userId &&\n current.runtime.infra.execSql === active.runtime.infra.execSql &&\n current.runtime.state.domainScope === domainScope\n );\n}\n"]}
@@ -16,6 +16,10 @@ interface PrincipalMutationApiCustodyInput {
16
16
  readonly api: ApiClient;
17
17
  /** Binds a mutation's committed read-model lease to its session. */
18
18
  readonly readSessionGeneration?: (() => number) | undefined;
19
+ readonly signIn?: {
20
+ readonly epoch: number;
21
+ guard(): () => void;
22
+ };
19
23
  readonly readScope: () => PrincipalMutationRuntimeScope | null;
20
24
  readonly principalMutationTimeoutMs?: number | undefined;
21
25
  }
@@ -37,7 +37,8 @@ export function createPrincipalMutationApiCustody(input) {
37
37
  return {
38
38
  bind() {
39
39
  const scope = input.readScope();
40
- if (cached && sameScope(scope, cached.scope))
40
+ const epoch = input.signIn?.epoch;
41
+ if (cached && epoch === cached.epoch && sameScope(scope, cached.scope))
41
42
  return cached.api;
42
43
  const context = (organizationId) => mutationContext(input, scope, organizationId);
43
44
  const read = async (organizationId) => scope
@@ -64,13 +65,13 @@ export function createPrincipalMutationApiCustody(input) {
64
65
  });
65
66
  },
66
67
  };
67
- const api = bindMutationMethods(input.api, methods);
68
- cached = { scope, api };
68
+ const api = bindMutationMethods(input.api, methods, input.signIn?.guard());
69
+ cached = { epoch, scope, api };
69
70
  return api;
70
71
  },
71
72
  };
72
73
  }
73
- function bindMutationMethods(api, methods) {
74
+ function bindMutationMethods(api, methods, assertCurrent) {
74
75
  const boundMethods = new Map();
75
76
  const bound = new Proxy(api, {
76
77
  get(target, property) {
@@ -82,7 +83,10 @@ function bindMutationMethods(api, methods) {
82
83
  const previous = boundMethods.get(property);
83
84
  if (previous?.source === value)
84
85
  return previous.bound;
85
- const bound = value.bind(target);
86
+ const bound = (...args) => {
87
+ assertCurrent?.();
88
+ return Reflect.apply(value, target, args);
89
+ };
86
90
  boundMethods.set(property, { source: value, bound });
87
91
  return bound;
88
92
  },