@tearleads/client-sdk 0.1.251 → 0.1.253

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +17 -28
  3. package/Tearleads.js.map +1 -1
  4. package/client/containerContents/index.d.ts +2 -0
  5. package/client/containerContents/index.js +4 -9
  6. package/client/containerContents/index.js.map +1 -1
  7. package/client/containerContents/storeRuntime.d.ts +17 -0
  8. package/client/containerContents/storeRuntime.js +31 -0
  9. package/client/containerContents/storeRuntime.js.map +1 -0
  10. package/client/deviceFirst/index.d.ts +2 -3
  11. package/client/deviceFirst/index.js +44 -22
  12. package/client/deviceFirst/index.js.map +1 -1
  13. package/client/organizations/organizationReadModelPresentation.js +7 -4
  14. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  15. package/client/organizations/organizationReadModels.js +6 -5
  16. package/client/organizations/organizationReadModels.js.map +1 -1
  17. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/runtime/principalMutationApi.d.ts +4 -0
  20. package/client/runtime/principalMutationApi.js +9 -5
  21. package/client/runtime/principalMutationApi.js.map +1 -1
  22. package/client/runtime/runtimeIdentityResolution.js +23 -0
  23. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  24. package/client/runtime/runtimeSubscription.js +68 -0
  25. package/client/runtime/runtimeSubscription.js.map +1 -0
  26. package/client/runtime/workflowRuntime.d.ts +3 -1
  27. package/client/runtime/workflowRuntime.js +31 -81
  28. package/client/runtime/workflowRuntime.js.map +1 -1
  29. package/client/session/authenticationMachine.js +47 -0
  30. package/client/session/authenticationMachine.js.map +1 -0
  31. package/client/session/index.js +75 -93
  32. package/client/session/index.js.map +1 -1
  33. package/client/session/sessionBlobStore.js +39 -0
  34. package/client/session/sessionBlobStore.js.map +1 -0
  35. package/client/session/sessionContext.js +11 -0
  36. package/client/session/sessionContext.js.map +1 -1
  37. package/client/session/sessionIdentityTrust.d.ts +2 -1
  38. package/client/session/sessionIdentityTrust.js +8 -4
  39. package/client/session/sessionIdentityTrust.js.map +1 -1
  40. package/client/session/sessionLifetime.js +87 -0
  41. package/client/session/sessionLifetime.js.map +1 -0
  42. package/client/session/sessionLogin.js +114 -0
  43. package/client/session/sessionLogin.js.map +1 -0
  44. package/client/session/sessionOrganizationCreation.js +3 -2
  45. package/client/session/sessionOrganizationCreation.js.map +1 -1
  46. package/client/session/sessionPurgeRecovery.js +11 -3
  47. package/client/session/sessionPurgeRecovery.js.map +1 -1
  48. package/client/session/sessionTypes.d.ts +6 -2
  49. package/client/session/sessionTypes.js.map +1 -1
  50. package/data/blobs/blobContracts.d.ts +4 -3
  51. package/data/blobs/blobContracts.js.map +1 -1
  52. package/data/blobs/createBlobStore.js +1 -8
  53. package/data/blobs/createBlobStore.js.map +1 -1
  54. package/data/blobs/encryptedBlobStore.js +17 -12
  55. package/data/blobs/encryptedBlobStore.js.map +1 -1
  56. package/data/blobs/memoryBlobStore.js +8 -5
  57. package/data/blobs/memoryBlobStore.js.map +1 -1
  58. package/data/blobs/opfsBlobFile.js +36 -0
  59. package/data/blobs/opfsBlobFile.js.map +1 -0
  60. package/data/blobs/opfsBlobStore.d.ts +1 -1
  61. package/data/blobs/opfsBlobStore.js +91 -21
  62. package/data/blobs/opfsBlobStore.js.map +1 -1
  63. package/data/principals/principalPolicyCoordinator.js +8 -17
  64. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  65. package/data/shared/domainScope.d.ts +2 -0
  66. package/data/shared/domainScope.js +2 -1
  67. package/data/shared/domainScope.js.map +1 -1
  68. package/data/shared/keyedQueue.js +15 -0
  69. package/data/shared/keyedQueue.js.map +1 -0
  70. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  71. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  72. package/data/sqlite/sqlExec.d.ts +6 -0
  73. package/data/sqlite/sqlExec.js +64 -13
  74. package/data/sqlite/sqlExec.js.map +1 -1
  75. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  76. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  77. package/data/sync/syncCoordinator.js +17 -10
  78. package/data/sync/syncCoordinator.js.map +1 -1
  79. package/data/trustedUserIdentity/service.js +2 -1
  80. package/data/trustedUserIdentity/service.js.map +1 -1
  81. package/data/trustedUserIdentity/types.d.ts +1 -1
  82. package/data/trustedUserIdentity/types.js.map +1 -1
  83. package/internal/api-client/ApiClient.d.ts +4 -1
  84. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  85. package/internal/api-client/apiRequestRuntime.js +86 -101
  86. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  87. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  88. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  89. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  90. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  91. package/internal/api-client/client/blobs.d.ts +1 -0
  92. package/internal/api-client/client/blobs.js +12 -3
  93. package/internal/api-client/client/blobs.js.map +1 -1
  94. package/internal/api-client/client/laneListingRequest.js +4 -0
  95. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  96. package/internal/api-client/client/session.d.ts +5 -1
  97. package/internal/api-client/client/session.js +12 -4
  98. package/internal/api-client/client/session.js.map +1 -1
  99. package/internal/api-client/client/writerProjections.js +12 -13
  100. package/internal/api-client/client/writerProjections.js.map +1 -1
  101. package/internal/api-client/operationResponse.d.ts +1 -1
  102. package/internal/api-client/operationResponse.js +10 -23
  103. package/internal/api-client/operationResponse.js.map +1 -1
  104. package/internal/api-client/operationTransport.js +2 -1
  105. package/internal/api-client/operationTransport.js.map +1 -1
  106. package/internal/api-client/principalHistoryRequest.js +25 -20
  107. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  108. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  109. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  110. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  111. package/internal/api-client/principalPolicyPages.js +4 -2
  112. package/internal/api-client/principalPolicyPages.js.map +1 -1
  113. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  114. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  115. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  116. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  117. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  118. package/internal/api-client/routes/blobs/get.js +9 -67
  119. package/internal/api-client/routes/blobs/get.js.map +1 -1
  120. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  121. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  122. package/internal/api-client/sessionRefresh.js +1 -1
  123. package/internal/api-client/sessionRefresh.js.map +1 -1
  124. package/internal/api-client/sessionRenewal.d.ts +31 -0
  125. package/internal/api-client/sessionRenewal.js +91 -6
  126. package/internal/api-client/sessionRenewal.js.map +1 -1
  127. package/internal/api-client/sessionRequestInit.js +22 -0
  128. package/internal/api-client/sessionRequestInit.js.map +1 -0
  129. package/internal/api-client/sessionResponse.js +39 -0
  130. package/internal/api-client/sessionResponse.js.map +1 -0
  131. package/internal/api-client/types.d.ts +1 -0
  132. package/internal/api-client/types.js.map +1 -1
  133. package/internal/api-client/webSocketTickets.d.ts +1 -0
  134. package/internal/api-client/webSocketTickets.js +4 -0
  135. package/internal/api-client/webSocketTickets.js.map +1 -1
  136. package/internal/sqlite-worker/client.d.ts +1 -1
  137. package/internal/sqlite-worker/client.js +6 -1
  138. package/internal/sqlite-worker/client.js.map +1 -1
  139. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  140. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  141. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  142. package/internal/sqlite-worker/types.d.ts +4 -0
  143. package/internal/sqlite-worker/types.js.map +1 -1
  144. package/package.json +1 -1
  145. package/sqlite/worker.js +1 -1
  146. package/stores/container-contents/containerContentsStore.d.ts +3 -9
  147. package/stores/container-contents/containerContentsStore.js +24 -21
  148. package/stores/container-contents/containerContentsStore.js.map +1 -1
  149. package/stores/container-contents/containerState/storeScope.js +6 -0
  150. package/stores/container-contents/containerState/storeScope.js.map +1 -0
  151. package/stores/container-contents/hydration/backgroundHydration.js +2 -1
  152. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  153. package/stores/container-contents/hydration/reconnectRefresh.d.ts +10 -0
  154. package/stores/container-contents/hydration/reconnectRefresh.js +68 -0
  155. package/stores/container-contents/hydration/reconnectRefresh.js.map +1 -0
  156. package/stores/container-contents/hydration/reconnectRefreshMachine.js +49 -0
  157. package/stores/container-contents/hydration/reconnectRefreshMachine.js.map +1 -0
  158. package/stores/container-contents/hydration/remoteHydrationRefresh.js +4 -1
  159. package/stores/container-contents/hydration/remoteHydrationRefresh.js.map +1 -1
  160. package/stores/container-contents/hydration/remoteHydrationRequest.js +79 -10
  161. package/stores/container-contents/hydration/remoteHydrationRequest.js.map +1 -1
  162. package/stores/container-contents/hydration/startupHydration.js +2 -9
  163. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  164. package/stores/container-contents/hydration/treeResetMachine.js +61 -0
  165. package/stores/container-contents/hydration/treeResetMachine.js.map +1 -0
  166. package/stores/container-contents/localRefresh.js +28 -12
  167. package/stores/container-contents/localRefresh.js.map +1 -1
  168. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js +4 -1
  169. package/stores/container-contents/remoteEvents/remoteContainerIngestion.js.map +1 -1
  170. package/stores/container-contents/remoteWrites/writeGeneration.js +5 -2
  171. package/stores/container-contents/remoteWrites/writeGeneration.js.map +1 -1
  172. package/stores/container-contents/state.d.ts +3 -7
  173. package/stores/container-contents/state.js +27 -16
  174. package/stores/container-contents/state.js.map +1 -1
  175. package/stores/container-contents/syncAgent/index.d.ts +7 -2
  176. package/stores/container-contents/syncAgent/index.js +77 -49
  177. package/stores/container-contents/syncAgent/index.js.map +1 -1
  178. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +5 -2
  179. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  180. package/stores/container-contents/syncAgent/syncLaneIteration.js +6 -3
  181. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  182. package/stores/local-projection/localProjectionStore.js +24 -15
  183. package/stores/local-projection/localProjectionStore.js.map +1 -1
  184. package/stores/local-projection/registry.js +2 -2
  185. package/stores/local-projection/registry.js.map +1 -1
  186. package/workflows/container-contents/container-state/create/createChild.js +3 -15
  187. package/workflows/container-contents/container-state/create/createChild.js.map +1 -1
  188. package/workflows/container-contents/containerPersistence.d.ts +4 -8
  189. package/workflows/container-contents/containerPersistence.js +22 -12
  190. package/workflows/container-contents/containerPersistence.js.map +1 -1
  191. package/workflows/container-contents/localState.js +3 -0
  192. package/workflows/container-contents/localState.js.map +1 -1
  193. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.d.ts +12 -0
  194. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js +93 -0
  195. package/workflows/container-contents/remoteHydration/hydrateRemoteContainers.js.map +1 -0
  196. package/workflows/container-contents/remoteHydration/index.d.ts +3 -11
  197. package/workflows/container-contents/remoteHydration/index.js +17 -66
  198. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  199. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js +3 -2
  200. package/workflows/container-contents/remoteHydration/lanes/parentLaneFetch.js.map +1 -1
  201. package/workflows/container-contents/remoteHydration/principalPolicyCache.js +57 -5
  202. package/workflows/container-contents/remoteHydration/principalPolicyCache.js.map +1 -1
  203. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +105 -62
  204. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  205. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +15 -5
  206. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  207. package/workflows/container-contents/remoteHydration/types.d.ts +13 -0
  208. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  209. package/workflows/container-contents/runtime.d.ts +3 -0
  210. package/workflows/container-contents/runtime.js.map +1 -1
  211. package/workflows/container-contents/storedContainerState.js +17 -7
  212. package/workflows/container-contents/storedContainerState.js.map +1 -1
  213. package/workflows/container-contents/syncLane.d.ts +1 -0
  214. package/workflows/container-contents/syncLane.js +9 -1
  215. package/workflows/container-contents/syncLane.js.map +1 -1
  216. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  217. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  218. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  219. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  220. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  221. package/workflows/registration/registerIdentity.js +2 -0
  222. package/workflows/registration/registerIdentity.js.map +1 -1
  223. package/workflows/shared/runtimeInput.d.ts +2 -0
  224. package/workflows/shared/runtimeInput.js.map +1 -1
  225. package/workflows/container-contents/remoteHydration/completeHydration.js +0 -25
  226. package/workflows/container-contents/remoteHydration/completeHydration.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"encryptedBlobStore.js","sourceRoot":"","sources":["encryptedBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAIL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,WAAW,EACX,eAAe,EACf,cAAc,EACd,2BAA2B,EAC3B,yBAAyB,EACzB,2BAA2B,EAC3B,4BAA4B,EAG5B,aAAa,EAEb,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,yBAAyB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c,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;YACnC,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,OAAO,KAAK,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;QAC1C,CAAC;QACD,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;YAC9B,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,OAAO,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC;QACD,eAAe,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE;YAC5C,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,OAAO,KAAK,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;QACnD,CAAC;QACD,UAAU,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE;YACtC,MAAM,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;YAC/B,OAAO,KAAK,CAAC,UAAU,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAC7C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\nimport {\n createDecryptedBlobByteSource,\n createEncryptedBlobByteSource,\n} from \"./encryptedBlobByteSource\";\nimport {\n asBlobBytes,\n assertNamespace,\n createAesGcmIv,\n createKeyDerivationEnvelope,\n ENCRYPTED_BLOB_CHUNK_SIZE,\n ENCRYPTED_BLOB_STORE_FORMAT,\n ENCRYPTED_BLOB_STORE_VERSION,\n type EncryptedBlobEnvelope,\n type EncryptedBlobStoreCipher,\n getChunkCount,\n type KeyDerivationEnvelope,\n normalizeCipher,\n normalizeKdfIterations,\n readBase64Bytes,\n readEncryptedBlobEnvelope,\n serializeEncryptedBlobEnvelope,\n} from \"./encryptedBlobEnvelope\";\nimport { createOpfsBlobStore, isOpfsBlobStoreSupported } from \"./opfsBlobStore\";\n\nexport type { EncryptedBlobStoreCipher };\nexport type EncryptedBlobStoreKey = string | Uint8Array | CryptoKey;\n\nexport interface EncryptedBlobStoreOptions {\n cipher?: EncryptedBlobStoreCipher | undefined;\n kdfIterations?: number | undefined;\n key: EncryptedBlobStoreKey;\n}\n\nexport interface WrapEncryptedBlobStoreOptions\n extends EncryptedBlobStoreOptions {\n namespace: string;\n}\n\nconst AES_256_KEY_BYTES = 32;\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof CryptoKey !== \"undefined\" && value instanceof CryptoKey;\n}\n\nfunction assertCryptoKey(key: CryptoKey): void {\n if (key.type !== \"secret\" || key.algorithm.name !== \"AES-GCM\") {\n throw new Error(\n \"Encrypted blob store CryptoKey must be an AES-GCM secret.\",\n );\n }\n if (!key.usages.includes(\"encrypt\") || !key.usages.includes(\"decrypt\")) {\n throw new Error(\n \"Encrypted blob store CryptoKey must allow encrypt and decrypt.\",\n );\n }\n}\n\nasync function importRawAesKey(key: Uint8Array): Promise<CryptoKey> {\n if (key.byteLength !== AES_256_KEY_BYTES) {\n throw new Error(\"Encrypted blob store AES-256-GCM key must be 32 bytes.\");\n }\n\n return crypto.subtle.importKey(\"raw\", asBlobBytes(key), \"AES-GCM\", false, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\nclass EncryptedBlobStore implements BlobStore {\n private readonly cipher: EncryptedBlobStoreCipher;\n private readonly derivedKeyByEnvelope = new Map<string, Promise<CryptoKey>>();\n private readonly kdfIterations: number;\n private readonly namespace: string;\n private readonly passphraseMaterialPromise: Promise<CryptoKey> | null;\n private readonly rawKeyPromise: Promise<CryptoKey> | null;\n\n constructor(\n private readonly innerStore: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n ) {\n if (!options || !(\"key\" in options)) {\n throw new Error(\"Encrypted blob store key is required.\");\n }\n assertNamespace(options.namespace);\n this.namespace = options.namespace;\n this.cipher = normalizeCipher(options.cipher);\n this.kdfIterations = normalizeKdfIterations(options.kdfIterations);\n\n if (typeof options.key === \"string\") {\n if (options.key.length === 0) {\n throw new Error(\"Encrypted blob store key must be non-empty.\");\n }\n this.rawKeyPromise = null;\n this.passphraseMaterialPromise = crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(options.key),\n \"PBKDF2\",\n false,\n [\"deriveKey\"],\n );\n return;\n }\n\n this.passphraseMaterialPromise = null;\n if (isCryptoKey(options.key)) {\n assertCryptoKey(options.key);\n this.rawKeyPromise = Promise.resolve(options.key);\n return;\n }\n\n if (!(options.key instanceof Uint8Array)) {\n throw new Error(\n \"Encrypted blob store key must be a string, Uint8Array, or CryptoKey.\",\n );\n }\n\n this.rawKeyPromise = importRawAesKey(options.key);\n }\n\n async deleteBytes(storageKey: string): Promise<void> {\n await this.innerStore.deleteBytes(storageKey);\n }\n\n async openByteSource(storageKey: string): Promise<BlobByteSource | null> {\n const encryptedSource = await this.innerStore.openByteSource(storageKey);\n if (!encryptedSource) {\n return null;\n }\n\n const parsed = await readEncryptedBlobEnvelope(encryptedSource);\n const key = await this.getCipherKey(parsed.envelope.keyDerivation);\n return createDecryptedBlobByteSource({\n encryptedSource,\n headerBytes: parsed.headerBytes,\n iv: parsed.iv,\n key,\n namespace: this.namespace,\n parsed,\n storageKey,\n });\n }\n\n async readBytes(storageKey: string): Promise<BlobBytes | null> {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n ): Promise<void> {\n const keyDerivation = this.createKeyDerivationEnvelope();\n const key = await this.getCipherKey(keyDerivation);\n const iv = createAesGcmIv();\n const envelope: EncryptedBlobEnvelope = {\n chunkCount: getChunkCount(source.byteLength),\n chunkSize: ENCRYPTED_BLOB_CHUNK_SIZE,\n cipher: this.cipher,\n format: ENCRYPTED_BLOB_STORE_FORMAT,\n iv: bytesToBase64(iv),\n keyDerivation,\n plaintextByteLength: source.byteLength,\n version: ENCRYPTED_BLOB_STORE_VERSION,\n };\n const { headerBytes, prefixBytes } =\n serializeEncryptedBlobEnvelope(envelope);\n await this.innerStore.writeByteSource(\n storageKey,\n createEncryptedBlobByteSource({\n envelope,\n headerBytes,\n iv,\n key,\n namespace: this.namespace,\n plaintextSource: source,\n prefixBytes,\n storageKey,\n }),\n );\n }\n\n async writeBytes(storageKey: string, bytes: BlobBytes): Promise<void> {\n await this.writeByteSource(storageKey, createBlobByteSource(bytes));\n }\n\n private createKeyDerivationEnvelope(): KeyDerivationEnvelope | null {\n if (!this.passphraseMaterialPromise) {\n return null;\n }\n\n return createKeyDerivationEnvelope({\n cipher: this.cipher,\n iterations: this.kdfIterations,\n namespace: this.namespace,\n });\n }\n\n private async getCipherKey(\n keyDerivation: KeyDerivationEnvelope | null,\n ): Promise<CryptoKey> {\n if (!keyDerivation) {\n if (!this.rawKeyPromise) {\n throw new Error(\n \"Encrypted blob store payload was not written with passphrase key derivation.\",\n );\n }\n\n return this.rawKeyPromise;\n }\n\n if (!this.passphraseMaterialPromise) {\n throw new Error(\n \"Encrypted blob store payload requires a passphrase key.\",\n );\n }\n\n const cacheKey = JSON.stringify(keyDerivation);\n let derivedKeyPromise = this.derivedKeyByEnvelope.get(cacheKey);\n if (!derivedKeyPromise) {\n derivedKeyPromise = this.derivePassphraseKey(keyDerivation);\n derivedKeyPromise.catch(() => {\n if (this.derivedKeyByEnvelope.get(cacheKey) === derivedKeyPromise) {\n this.derivedKeyByEnvelope.delete(cacheKey);\n }\n });\n this.derivedKeyByEnvelope.set(cacheKey, derivedKeyPromise);\n }\n\n return derivedKeyPromise;\n }\n\n private async derivePassphraseKey(\n keyDerivation: KeyDerivationEnvelope,\n ): Promise<CryptoKey> {\n const passphraseMaterial = await this.passphraseMaterialPromise;\n if (!passphraseMaterial) {\n throw new Error(\"Encrypted blob store passphrase material is missing.\");\n }\n\n return crypto.subtle.deriveKey(\n {\n name: \"PBKDF2\",\n hash: \"SHA-256\",\n iterations: keyDerivation.iterations,\n salt: readBase64Bytes(\n { salt: keyDerivation.salt },\n \"salt\",\n \"Encrypted blob store keyDerivation\",\n ),\n },\n passphraseMaterial,\n {\n name: \"AES-GCM\",\n length: 256,\n },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n }\n}\n\nexport function wrapEncryptedBlobStore(\n store: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n): BlobStore {\n return new EncryptedBlobStore(store, options);\n}\n\nexport function createEncryptedBlobStore(\n namespace: string,\n options: EncryptedBlobStoreOptions,\n): BlobStore {\n if (!isOpfsBlobStoreSupported()) {\n throw new Error(\"OPFS blob store is not supported.\");\n }\n\n return wrapEncryptedBlobStore(createOpfsBlobStore(namespace), {\n ...options,\n namespace,\n });\n}\n\nexport function createLazyEncryptedBlobStore(\n namespace: string,\n keyProvider: () => Promise<EncryptedBlobStoreKey>,\n): BlobStore {\n let innerStorePromise: Promise<BlobStore> | null = null;\n\n function getStore(): Promise<BlobStore> {\n if (!innerStorePromise) {\n innerStorePromise = (async () => {\n const key = await keyProvider();\n return createEncryptedBlobStore(namespace, { key });\n })().catch((error: unknown) => {\n // Run cleanup after assignment, even if keyProvider throws synchronously.\n innerStorePromise = null;\n throw error;\n });\n }\n\n return innerStorePromise;\n }\n\n return {\n deleteBytes: async (storageKey) => {\n const store = await getStore();\n return store.deleteBytes(storageKey);\n },\n openByteSource: async (storageKey) => {\n const store = await getStore();\n return store.openByteSource(storageKey);\n },\n readBytes: async (storageKey) => {\n const store = await getStore();\n return store.readBytes(storageKey);\n },\n writeByteSource: async (storageKey, source) => {\n const store = await getStore();\n return store.writeByteSource(storageKey, source);\n },\n writeBytes: async (storageKey, bytes) => {\n const store = await getStore();\n return store.writeBytes(storageKey, bytes);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"encryptedBlobStore.js","sourceRoot":"","sources":["encryptedBlobStore.ts"],"names":[],"mappings":"A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,aAAa,EAAE,EAAE,CAAC;YAClB,OAAO,KAAK,CAAC,UAAU,CAAC,UAAU,EAAE,KAAK,EAAE,aAAa,CAAC,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\nimport {\n createDecryptedBlobByteSource,\n createEncryptedBlobByteSource,\n} from \"./encryptedBlobByteSource\";\nimport {\n asBlobBytes,\n assertNamespace,\n createAesGcmIv,\n createKeyDerivationEnvelope,\n ENCRYPTED_BLOB_CHUNK_SIZE,\n ENCRYPTED_BLOB_STORE_FORMAT,\n ENCRYPTED_BLOB_STORE_VERSION,\n type EncryptedBlobEnvelope,\n type EncryptedBlobStoreCipher,\n getChunkCount,\n type KeyDerivationEnvelope,\n normalizeCipher,\n normalizeKdfIterations,\n readBase64Bytes,\n readEncryptedBlobEnvelope,\n serializeEncryptedBlobEnvelope,\n} from \"./encryptedBlobEnvelope\";\nimport { createOpfsBlobStore, isOpfsBlobStoreSupported } from \"./opfsBlobStore\";\n\nexport type { EncryptedBlobStoreCipher };\nexport type EncryptedBlobStoreKey = string | Uint8Array | CryptoKey;\n\nexport interface EncryptedBlobStoreOptions {\n cipher?: EncryptedBlobStoreCipher | undefined;\n kdfIterations?: number | undefined;\n key: EncryptedBlobStoreKey;\n}\n\nexport interface WrapEncryptedBlobStoreOptions\n extends EncryptedBlobStoreOptions {\n namespace: string;\n}\n\nconst AES_256_KEY_BYTES = 32;\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction isCryptoKey(value: unknown): value is CryptoKey {\n return typeof CryptoKey !== \"undefined\" && value instanceof CryptoKey;\n}\n\nfunction assertCryptoKey(key: CryptoKey): void {\n if (key.type !== \"secret\" || key.algorithm.name !== \"AES-GCM\") {\n throw new Error(\n \"Encrypted blob store CryptoKey must be an AES-GCM secret.\",\n );\n }\n if (!key.usages.includes(\"encrypt\") || !key.usages.includes(\"decrypt\")) {\n throw new Error(\n \"Encrypted blob store CryptoKey must allow encrypt and decrypt.\",\n );\n }\n}\n\nasync function importRawAesKey(key: Uint8Array): Promise<CryptoKey> {\n if (key.byteLength !== AES_256_KEY_BYTES) {\n throw new Error(\"Encrypted blob store AES-256-GCM key must be 32 bytes.\");\n }\n\n return crypto.subtle.importKey(\"raw\", asBlobBytes(key), \"AES-GCM\", false, [\n \"encrypt\",\n \"decrypt\",\n ]);\n}\n\nclass EncryptedBlobStore implements BlobStore {\n private readonly cipher: EncryptedBlobStoreCipher;\n private readonly derivedKeyByEnvelope = new Map<string, Promise<CryptoKey>>();\n private readonly kdfIterations: number;\n private readonly namespace: string;\n private readonly passphraseMaterialPromise: Promise<CryptoKey> | null;\n private readonly rawKeyPromise: Promise<CryptoKey> | null;\n\n constructor(\n private readonly innerStore: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n ) {\n if (!options || !(\"key\" in options)) {\n throw new Error(\"Encrypted blob store key is required.\");\n }\n assertNamespace(options.namespace);\n this.namespace = options.namespace;\n this.cipher = normalizeCipher(options.cipher);\n this.kdfIterations = normalizeKdfIterations(options.kdfIterations);\n\n if (typeof options.key === \"string\") {\n if (options.key.length === 0) {\n throw new Error(\"Encrypted blob store key must be non-empty.\");\n }\n this.rawKeyPromise = null;\n this.passphraseMaterialPromise = crypto.subtle.importKey(\n \"raw\",\n TEXT_ENCODER.encode(options.key),\n \"PBKDF2\",\n false,\n [\"deriveKey\"],\n );\n return;\n }\n\n this.passphraseMaterialPromise = null;\n if (isCryptoKey(options.key)) {\n assertCryptoKey(options.key);\n this.rawKeyPromise = Promise.resolve(options.key);\n return;\n }\n\n if (!(options.key instanceof Uint8Array)) {\n throw new Error(\n \"Encrypted blob store key must be a string, Uint8Array, or CryptoKey.\",\n );\n }\n\n this.rawKeyPromise = importRawAesKey(options.key);\n }\n\n async deleteBytes(\n storageKey: string,\n assertCurrent?: () => void,\n ): Promise<void> {\n assertCurrent?.();\n await this.innerStore.deleteBytes(storageKey, assertCurrent);\n }\n\n async openByteSource(storageKey: string): Promise<BlobByteSource | null> {\n const encryptedSource = await this.innerStore.openByteSource(storageKey);\n if (!encryptedSource) {\n return null;\n }\n\n const parsed = await readEncryptedBlobEnvelope(encryptedSource);\n const key = await this.getCipherKey(parsed.envelope.keyDerivation);\n return createDecryptedBlobByteSource({\n encryptedSource,\n headerBytes: parsed.headerBytes,\n iv: parsed.iv,\n key,\n namespace: this.namespace,\n parsed,\n storageKey,\n });\n }\n\n async readBytes(storageKey: string): Promise<BlobBytes | null> {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ): Promise<void> {\n const keyDerivation = this.createKeyDerivationEnvelope();\n const key = await this.getCipherKey(keyDerivation);\n const iv = createAesGcmIv();\n const envelope: EncryptedBlobEnvelope = {\n chunkCount: getChunkCount(source.byteLength),\n chunkSize: ENCRYPTED_BLOB_CHUNK_SIZE,\n cipher: this.cipher,\n format: ENCRYPTED_BLOB_STORE_FORMAT,\n iv: bytesToBase64(iv),\n keyDerivation,\n plaintextByteLength: source.byteLength,\n version: ENCRYPTED_BLOB_STORE_VERSION,\n };\n const { headerBytes, prefixBytes } =\n serializeEncryptedBlobEnvelope(envelope);\n assertCurrent?.();\n await this.innerStore.writeByteSource(\n storageKey,\n createEncryptedBlobByteSource({\n envelope,\n headerBytes,\n iv,\n key,\n namespace: this.namespace,\n plaintextSource: source,\n prefixBytes,\n storageKey,\n }),\n assertCurrent,\n );\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ): Promise<void> {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n\n private createKeyDerivationEnvelope(): KeyDerivationEnvelope | null {\n if (!this.passphraseMaterialPromise) {\n return null;\n }\n\n return createKeyDerivationEnvelope({\n cipher: this.cipher,\n iterations: this.kdfIterations,\n namespace: this.namespace,\n });\n }\n\n private async getCipherKey(\n keyDerivation: KeyDerivationEnvelope | null,\n ): Promise<CryptoKey> {\n if (!keyDerivation) {\n if (!this.rawKeyPromise) {\n throw new Error(\n \"Encrypted blob store payload was not written with passphrase key derivation.\",\n );\n }\n\n return this.rawKeyPromise;\n }\n\n if (!this.passphraseMaterialPromise) {\n throw new Error(\n \"Encrypted blob store payload requires a passphrase key.\",\n );\n }\n\n const cacheKey = JSON.stringify(keyDerivation);\n let derivedKeyPromise = this.derivedKeyByEnvelope.get(cacheKey);\n if (!derivedKeyPromise) {\n derivedKeyPromise = this.derivePassphraseKey(keyDerivation);\n derivedKeyPromise.catch(() => {\n if (this.derivedKeyByEnvelope.get(cacheKey) === derivedKeyPromise) {\n this.derivedKeyByEnvelope.delete(cacheKey);\n }\n });\n this.derivedKeyByEnvelope.set(cacheKey, derivedKeyPromise);\n }\n\n return derivedKeyPromise;\n }\n\n private async derivePassphraseKey(\n keyDerivation: KeyDerivationEnvelope,\n ): Promise<CryptoKey> {\n const passphraseMaterial = await this.passphraseMaterialPromise;\n if (!passphraseMaterial) {\n throw new Error(\"Encrypted blob store passphrase material is missing.\");\n }\n\n return crypto.subtle.deriveKey(\n {\n name: \"PBKDF2\",\n hash: \"SHA-256\",\n iterations: keyDerivation.iterations,\n salt: readBase64Bytes(\n { salt: keyDerivation.salt },\n \"salt\",\n \"Encrypted blob store keyDerivation\",\n ),\n },\n passphraseMaterial,\n {\n name: \"AES-GCM\",\n length: 256,\n },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n }\n}\n\nexport function wrapEncryptedBlobStore(\n store: BlobStore,\n options: WrapEncryptedBlobStoreOptions,\n): BlobStore {\n return new EncryptedBlobStore(store, options);\n}\n\nexport function createEncryptedBlobStore(\n namespace: string,\n options: EncryptedBlobStoreOptions,\n): BlobStore {\n if (!isOpfsBlobStoreSupported()) {\n throw new Error(\"OPFS blob store is not supported.\");\n }\n\n return wrapEncryptedBlobStore(createOpfsBlobStore(namespace), {\n ...options,\n namespace,\n });\n}\n\nexport function createLazyEncryptedBlobStore(\n namespace: string,\n keyProvider: () => Promise<EncryptedBlobStoreKey>,\n): BlobStore {\n let innerStorePromise: Promise<BlobStore> | null = null;\n\n function getStore(): Promise<BlobStore> {\n if (!innerStorePromise) {\n innerStorePromise = (async () => {\n const key = await keyProvider();\n return createEncryptedBlobStore(namespace, { key });\n })().catch((error: unknown) => {\n // Run cleanup after assignment, even if keyProvider throws synchronously.\n innerStorePromise = null;\n throw error;\n });\n }\n\n return innerStorePromise;\n }\n\n return {\n deleteBytes: async (storageKey, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.deleteBytes(storageKey, assertCurrent);\n },\n openByteSource: async (storageKey) => {\n const store = await getStore();\n return store.openByteSource(storageKey);\n },\n readBytes: async (storageKey) => {\n const store = await getStore();\n return store.readBytes(storageKey);\n },\n writeByteSource: async (storageKey, source, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.writeByteSource(storageKey, source, assertCurrent);\n },\n writeBytes: async (storageKey, bytes, assertCurrent) => {\n const store = await getStore();\n assertCurrent?.();\n return store.writeBytes(storageKey, bytes, assertCurrent);\n },\n };\n}\n"]}
@@ -1,7 +1,8 @@
1
1
  import { createBlobByteSource, readBlobByteSource, } from "./blobContracts.js";
2
2
  class MemoryBlobStore {
3
3
  bytesByKey = new Map();
4
- async deleteBytes(storageKey) {
4
+ async deleteBytes(storageKey, assertCurrent) {
5
+ assertCurrent?.();
5
6
  this.bytesByKey.delete(storageKey);
6
7
  }
7
8
  async openByteSource(storageKey) {
@@ -12,11 +13,13 @@ class MemoryBlobStore {
12
13
  const source = await this.openByteSource(storageKey);
13
14
  return source ? readBlobByteSource(source) : null;
14
15
  }
15
- async writeByteSource(storageKey, source) {
16
- this.bytesByKey.set(storageKey, await readBlobByteSource(source));
16
+ async writeByteSource(storageKey, source, assertCurrent) {
17
+ const bytes = await readBlobByteSource(source);
18
+ assertCurrent?.();
19
+ this.bytesByKey.set(storageKey, bytes);
17
20
  }
18
- async writeBytes(storageKey, bytes) {
19
- await this.writeByteSource(storageKey, createBlobByteSource(bytes));
21
+ async writeBytes(storageKey, bytes, assertCurrent) {
22
+ await this.writeByteSource(storageKey, createBlobByteSource(bytes), assertCurrent);
20
23
  }
21
24
  }
22
25
  export function createMemoryBlobStore() {
@@ -1 +1 @@
1
- {"version":3,"file":"memoryBlobStore.js","sourceRoot":"","sources":["memoryBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,eAAe;IACF,UAAU,GAAG,IAAI,GAAG,EAAqB,CAAC;IAE3D,KAAK,CAAC,WAAW,CAAC,UAAkB;QAClC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,UAAkB;QACrC,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC9C,OAAO,KAAK,CAAC,CAAC,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,UAAkB;QAChC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;QACrD,OAAO,MAAM,CAAC,CAAC,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,UAAkB,EAAE,MAAsB;QAC9D,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,EAAE,MAAM,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,UAAkB,EAAE,KAAgB;QACnD,MAAM,IAAI,CAAC,eAAe,CAAC,UAAU,EAAE,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,CAAC;CACF;AAED,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\nclass MemoryBlobStore implements BlobStore {\n private readonly bytesByKey = new Map<string, BlobBytes>();\n\n async deleteBytes(storageKey: string) {\n this.bytesByKey.delete(storageKey);\n }\n\n async openByteSource(storageKey: string) {\n const bytes = this.bytesByKey.get(storageKey);\n return bytes ? createBlobByteSource(bytes) : null;\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(storageKey: string, source: BlobByteSource) {\n this.bytesByKey.set(storageKey, await readBlobByteSource(source));\n }\n\n async writeBytes(storageKey: string, bytes: BlobBytes) {\n await this.writeByteSource(storageKey, createBlobByteSource(bytes));\n }\n}\n\nexport function createMemoryBlobStore(): BlobStore {\n return new MemoryBlobStore();\n}\n"]}
1
+ {"version":3,"file":"memoryBlobStore.js","sourceRoot":"","sources":["memoryBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,eAAe;IACF,UAAU,GAAG,IAAI,GAAG,EAAqB,CAAC;IAE3D,KAAK,CAAC,WAAW,CAAC,UAAkB,EAAE,aAA0B;QAC9D,aAAa,EAAE,EAAE,CAAC;QAClB,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,UAAkB;QACrC,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;QAC9C,OAAO,KAAK,CAAC,CAAC,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,UAAkB;QAChC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;QACrD,OAAO,MAAM,CAAC,CAAC,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpD,CAAC;IAED,KAAK,CAAC,eAAe,CACnB,UAAkB,EAClB,MAAsB,EACtB,aAA0B;QAE1B,MAAM,KAAK,GAAG,MAAM,kBAAkB,CAAC,MAAM,CAAC,CAAC;QAC/C,aAAa,EAAE,EAAE,CAAC;QAClB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,UAAU,CACd,UAAkB,EAClB,KAAgB,EAChB,aAA0B;QAE1B,MAAM,IAAI,CAAC,eAAe,CACxB,UAAU,EACV,oBAAoB,CAAC,KAAK,CAAC,EAC3B,aAAa,CACd,CAAC;IACJ,CAAC;CACF;AAED,MAAM,UAAU,qBAAqB;IACnC,OAAO,IAAI,eAAe,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["import {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\nclass MemoryBlobStore implements BlobStore {\n private readonly bytesByKey = new Map<string, BlobBytes>();\n\n async deleteBytes(storageKey: string, assertCurrent?: () => void) {\n assertCurrent?.();\n this.bytesByKey.delete(storageKey);\n }\n\n async openByteSource(storageKey: string) {\n const bytes = this.bytesByKey.get(storageKey);\n return bytes ? createBlobByteSource(bytes) : null;\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n const bytes = await readBlobByteSource(source);\n assertCurrent?.();\n this.bytesByKey.set(storageKey, bytes);\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ) {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n}\n\nexport function createMemoryBlobStore(): BlobStore {\n return new MemoryBlobStore();\n}\n"]}
@@ -0,0 +1,36 @@
1
+ async function openDestination(directory, name, assertCurrent) {
2
+ try {
3
+ return { handle: await directory.getFileHandle(name), created: false };
4
+ }
5
+ catch (error) {
6
+ if (!(error instanceof DOMException && error.name === "NotFoundError"))
7
+ throw error;
8
+ }
9
+ assertCurrent?.();
10
+ return {
11
+ handle: await directory.getFileHandle(name, { create: true }),
12
+ created: true,
13
+ };
14
+ }
15
+ /** The caller holds the destination's write lock until rollback finishes. */
16
+ export async function commitOpfsFile(directory, name, assertCurrent, stage) {
17
+ assertCurrent?.();
18
+ const { handle, created } = await openDestination(directory, name, assertCurrent);
19
+ let writable;
20
+ try {
21
+ assertCurrent?.();
22
+ writable = await handle.createWritable();
23
+ await stage(writable);
24
+ assertCurrent?.();
25
+ await writable.close();
26
+ }
27
+ catch (error) {
28
+ await writable?.abort(error).catch(() => { });
29
+ // Aborting discards staged bytes, but OPFS created the directory entry
30
+ // eagerly. Undo only this write's creation; an existing file is intact.
31
+ if (created)
32
+ await directory.removeEntry(name);
33
+ throw error;
34
+ }
35
+ }
36
+ //# sourceMappingURL=opfsBlobFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opfsBlobFile.js","sourceRoot":"","sources":["opfsBlobFile.ts"],"names":[],"mappings":"AAAA,KAAK,UAAU,eAAe,CAC5B,SAAoC,EACpC,IAAY,EACZ,aAA0B;IAE1B,IAAI,CAAC;QACH,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IACzE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,CAAC,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,CAAC;YACpE,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,aAAa,EAAE,EAAE,CAAC;IAClB,OAAO;QACL,MAAM,EAAE,MAAM,SAAS,CAAC,aAAa,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QAC7D,OAAO,EAAE,IAAI;KACd,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,SAAoC,EACpC,IAAY,EACZ,aAAuC,EACvC,KAAgE;IAEhE,aAAa,EAAE,EAAE,CAAC;IAClB,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,eAAe,CAC/C,SAAS,EACT,IAAI,EACJ,aAAa,CACd,CAAC;IACF,IAAI,QAAkD,CAAC;IACvD,IAAI,CAAC;QACH,aAAa,EAAE,EAAE,CAAC;QAClB,QAAQ,GAAG,MAAM,MAAM,CAAC,cAAc,EAAE,CAAC;QACzC,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;QACtB,aAAa,EAAE,EAAE,CAAC;QAClB,MAAM,QAAQ,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC7C,uEAAuE;QACvE,wEAAwE;QACxE,IAAI,OAAO;YAAE,MAAM,SAAS,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["async function openDestination(\n directory: FileSystemDirectoryHandle,\n name: string,\n assertCurrent?: () => void,\n) {\n try {\n return { handle: await directory.getFileHandle(name), created: false };\n } catch (error) {\n if (!(error instanceof DOMException && error.name === \"NotFoundError\"))\n throw error;\n }\n assertCurrent?.();\n return {\n handle: await directory.getFileHandle(name, { create: true }),\n created: true,\n };\n}\n\n/** The caller holds the destination's write lock until rollback finishes. */\nexport async function commitOpfsFile(\n directory: FileSystemDirectoryHandle,\n name: string,\n assertCurrent: (() => void) | undefined,\n stage: (writable: FileSystemWritableFileStream) => Promise<void>,\n): Promise<void> {\n assertCurrent?.();\n const { handle, created } = await openDestination(\n directory,\n name,\n assertCurrent,\n );\n let writable: FileSystemWritableFileStream | undefined;\n try {\n assertCurrent?.();\n writable = await handle.createWritable();\n await stage(writable);\n assertCurrent?.();\n await writable.close();\n } catch (error) {\n await writable?.abort(error).catch(() => {});\n // Aborting discards staged bytes, but OPFS created the directory entry\n // eagerly. Undo only this write's creation; an existing file is intact.\n if (created) await directory.removeEntry(name);\n throw error;\n }\n}\n"]}
@@ -7,4 +7,4 @@ export declare function createOpfsBlobStore(namespace: string): BlobStore;
7
7
  * Used to forget local data on logout. No-op when OPFS is unavailable or the
8
8
  * directory was never created; never throws on a missing directory.
9
9
  */
10
- export declare function purgeOpfsBlobStore(namespace: string): Promise<void>;
10
+ export declare function purgeOpfsBlobStore(namespace: string, current?: () => boolean): Promise<void>;
@@ -1,14 +1,65 @@
1
1
  import { blobByteSourceInputLength, createBlobByteSource, readBlobByteSource, } from "./blobContracts.js";
2
+ import { commitOpfsFile } from "./opfsBlobFile.js";
2
3
  const OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;
3
4
  class OpfsBlobStore {
4
5
  namespace;
5
6
  directoryPromise = null;
7
+ active = new Set();
8
+ writers = new Map();
9
+ purgeBarrier;
6
10
  constructor(namespace) {
7
11
  this.namespace = namespace;
8
12
  }
9
- async deleteBytes(storageKey) {
13
+ // File operations run concurrently. A directory removal waits for all
14
+ // of them and any later file operation opens the surviving directory.
15
+ async useFile(key, mode, run) {
16
+ const locked = () => {
17
+ const locks = navigator.locks;
18
+ return typeof locks?.request === "function"
19
+ ? locks.request(JSON.stringify(["tearleads.opfs.blob", this.namespace, key]), { mode }, run)
20
+ : run();
21
+ };
22
+ const writer = this.writers.get(key);
23
+ const operation = writer || this.purgeBarrier
24
+ ? Promise.allSettled([writer, this.purgeBarrier]).then(locked)
25
+ : locked();
26
+ if (mode === "exclusive")
27
+ this.writers.set(key, operation);
28
+ this.active.add(operation);
29
+ try {
30
+ return await operation;
31
+ }
32
+ finally {
33
+ this.active.delete(operation);
34
+ if (this.writers.get(key) === operation)
35
+ this.writers.delete(key);
36
+ }
37
+ }
38
+ async purge(current) {
39
+ const pending = Promise.allSettled([
40
+ ...this.active,
41
+ this.purgeBarrier,
42
+ ]).then(async () => {
43
+ if (current() && (await removeNamespace(this.namespace, current)))
44
+ this.directoryPromise = null;
45
+ });
46
+ const barrier = pending.catch(() => { });
47
+ this.purgeBarrier = barrier;
48
+ try {
49
+ await pending;
50
+ }
51
+ finally {
52
+ if (this.purgeBarrier === barrier)
53
+ this.purgeBarrier = undefined;
54
+ }
55
+ }
56
+ deleteBytes(storageKey, assertCurrent) {
57
+ return this.useFile(storageKey, "exclusive", () => this.removeFile(storageKey, assertCurrent));
58
+ }
59
+ async removeFile(storageKey, assertCurrent) {
10
60
  const directory = await this.getDirectory();
11
61
  try {
62
+ assertCurrent?.();
12
63
  await directory.removeEntry(this.getFileName(storageKey));
13
64
  }
14
65
  catch (error) {
@@ -22,7 +73,10 @@ class OpfsBlobStore {
22
73
  const source = await this.openByteSource(storageKey);
23
74
  return source ? readBlobByteSource(source) : null;
24
75
  }
25
- async openByteSource(storageKey) {
76
+ openByteSource(storageKey) {
77
+ return this.useFile(storageKey, "shared", () => this.openFile(storageKey));
78
+ }
79
+ async openFile(storageKey) {
26
80
  const directory = await this.getDirectory();
27
81
  try {
28
82
  const fileHandle = await directory.getFileHandle(this.getFileName(storageKey));
@@ -36,12 +90,13 @@ class OpfsBlobStore {
36
90
  throw error;
37
91
  }
38
92
  }
39
- async writeByteSource(storageKey, source) {
93
+ writeByteSource(storageKey, source, assertCurrent) {
94
+ return this.useFile(storageKey, "exclusive", () => this.writeFile(storageKey, source, assertCurrent));
95
+ }
96
+ async writeFile(storageKey, source, assertCurrent) {
40
97
  const sourceByteLength = blobByteSourceInputLength(source);
41
98
  const directory = await this.getDirectory();
42
- const fileHandle = await directory.getFileHandle(this.getFileName(storageKey), { create: true });
43
- const writable = await fileHandle.createWritable();
44
- try {
99
+ await commitOpfsFile(directory, this.getFileName(storageKey), assertCurrent, async (writable) => {
45
100
  for (let offset = 0; offset < sourceByteLength;) {
46
101
  const byteLength = Math.min(OPFS_WRITE_CHUNK_SIZE, sourceByteLength - offset);
47
102
  const chunk = await source.read(offset, byteLength);
@@ -51,15 +106,10 @@ class OpfsBlobStore {
51
106
  await writable.write(chunk);
52
107
  offset += byteLength;
53
108
  }
54
- await writable.close();
55
- }
56
- catch (error) {
57
- await writable.abort(error).catch(() => undefined);
58
- throw error;
59
- }
109
+ });
60
110
  }
61
- async writeBytes(storageKey, bytes) {
62
- await this.writeByteSource(storageKey, createBlobByteSource(bytes));
111
+ async writeBytes(storageKey, bytes, assertCurrent) {
112
+ await this.writeByteSource(storageKey, createBlobByteSource(bytes), assertCurrent);
63
113
  }
64
114
  getFileName(storageKey) {
65
115
  return `${encodeURIComponent(storageKey)}.blob`;
@@ -89,8 +139,24 @@ function hasStorageDirectory(storage) {
89
139
  export function isOpfsBlobStoreSupported() {
90
140
  return (typeof navigator === "object" && hasStorageDirectory(navigator.storage));
91
141
  }
142
+ // Plain and encrypted stores address the same OPFS namespace.
143
+ const namespaces = new WeakMap();
144
+ function namespaceStore(namespace) {
145
+ const storage = navigator.storage;
146
+ let stores = namespaces.get(storage);
147
+ if (!stores) {
148
+ stores = new Map();
149
+ namespaces.set(storage, stores);
150
+ }
151
+ let store = stores.get(namespace);
152
+ if (!store) {
153
+ store = new OpfsBlobStore(namespace);
154
+ stores.set(namespace, store);
155
+ }
156
+ return store;
157
+ }
92
158
  export function createOpfsBlobStore(namespace) {
93
- return new OpfsBlobStore(namespace);
159
+ return namespaceStore(namespace);
94
160
  }
95
161
  /**
96
162
  * Permanently remove the OPFS directory backing a namespace's blob store
@@ -98,10 +164,11 @@ export function createOpfsBlobStore(namespace) {
98
164
  * Used to forget local data on logout. No-op when OPFS is unavailable or the
99
165
  * directory was never created; never throws on a missing directory.
100
166
  */
101
- export async function purgeOpfsBlobStore(namespace) {
102
- if (!isOpfsBlobStoreSupported()) {
103
- return;
104
- }
167
+ export async function purgeOpfsBlobStore(namespace, current = () => true) {
168
+ if (isOpfsBlobStoreSupported())
169
+ await namespaceStore(namespace).purge(current);
170
+ }
171
+ async function removeNamespace(namespace, current) {
105
172
  const rootDirectory = await navigator.storage.getDirectory();
106
173
  let appDirectory;
107
174
  try {
@@ -109,16 +176,19 @@ export async function purgeOpfsBlobStore(namespace) {
109
176
  }
110
177
  catch (error) {
111
178
  if (error instanceof DOMException && error.name === "NotFoundError") {
112
- return;
179
+ return true;
113
180
  }
114
181
  throw error;
115
182
  }
116
183
  try {
184
+ if (!current())
185
+ return false;
117
186
  await appDirectory.removeEntry(namespace, { recursive: true });
187
+ return true;
118
188
  }
119
189
  catch (error) {
120
190
  if (error instanceof DOMException && error.name === "NotFoundError") {
121
- return;
191
+ return true;
122
192
  }
123
193
  throw error;
124
194
  }
@@ -1 +1 @@
1
- {"version":3,"file":"opfsBlobStore.js","sourceRoot":"","sources":["opfsBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAMzB,MAAM,qBAAqB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAE9C,MAAM,aAAa;IAGY;IAFrB,gBAAgB,GAA8C,IAAI,CAAC;IAE3E,YAA6B,SAAiB;QAAjB,cAAS,GAAT,SAAS,CAAQ;IAAG,CAAC;IAElD,KAAK,CAAC,WAAW,CAAC,UAAkB;QAClC,MAAM,S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,CAAC;IAC5C,IAAI,CAAC;QACH,YAAY,GAAG,MAAM,aAAa,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;IACrE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACpE,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,MAAM,YAAY,CAAC,WAAW,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACpE,OAAO;QACT,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n blobByteSourceInputLength,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\ninterface StorageDirectoryProvider {\n getDirectory: () => Promise<FileSystemDirectoryHandle>;\n}\n\nconst OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;\n\nclass OpfsBlobStore implements BlobStore {\n private directoryPromise: Promise<FileSystemDirectoryHandle> | null = null;\n\n constructor(private readonly namespace: string) {}\n\n async deleteBytes(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n await directory.removeEntry(this.getFileName(storageKey));\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n\n throw error;\n }\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n async openByteSource(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n );\n const file = await fileHandle.getFile();\n return createBlobByteSource(file);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return null;\n }\n\n throw error;\n }\n }\n\n async writeByteSource(storageKey: string, source: BlobByteSource) {\n const sourceByteLength = blobByteSourceInputLength(source);\n const directory = await this.getDirectory();\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n { create: true },\n );\n const writable = await fileHandle.createWritable();\n\n try {\n for (let offset = 0; offset < sourceByteLength; ) {\n const byteLength = Math.min(\n OPFS_WRITE_CHUNK_SIZE,\n sourceByteLength - offset,\n );\n const chunk = await source.read(offset, byteLength);\n if (chunk.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n await writable.write(chunk);\n offset += byteLength;\n }\n await writable.close();\n } catch (error) {\n await writable.abort(error).catch(() => undefined);\n throw error;\n }\n }\n\n async writeBytes(storageKey: string, bytes: BlobBytes) {\n await this.writeByteSource(storageKey, createBlobByteSource(bytes));\n }\n\n private getFileName(storageKey: string): string {\n return `${encodeURIComponent(storageKey)}.blob`;\n }\n\n private async getDirectory() {\n if (!this.directoryPromise) {\n this.directoryPromise = this.createDirectory().catch((error: unknown) => {\n this.directoryPromise = null;\n throw error;\n });\n }\n\n return this.directoryPromise;\n }\n\n private async createDirectory() {\n const rootDirectory = await navigator.storage.getDirectory();\n const appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\", {\n create: true,\n });\n\n return appDirectory.getDirectoryHandle(this.namespace, { create: true });\n }\n}\n\nfunction hasStorageDirectory(\n storage: StorageManager | undefined,\n): storage is StorageManager & StorageDirectoryProvider {\n return (\n storage !== undefined &&\n \"getDirectory\" in storage &&\n typeof storage.getDirectory === \"function\"\n );\n}\n\nexport function isOpfsBlobStoreSupported(): boolean {\n return (\n typeof navigator === \"object\" && hasStorageDirectory(navigator.storage)\n );\n}\n\nexport function createOpfsBlobStore(namespace: string): BlobStore {\n return new OpfsBlobStore(namespace);\n}\n\n/**\n * Permanently remove the OPFS directory backing a namespace's blob store\n * (`tearleads/<namespace>`), discarding every stored blob for that namespace.\n * Used to forget local data on logout. No-op when OPFS is unavailable or the\n * directory was never created; never throws on a missing directory.\n */\nexport async function purgeOpfsBlobStore(namespace: string): Promise<void> {\n if (!isOpfsBlobStoreSupported()) {\n return;\n }\n\n const rootDirectory = await navigator.storage.getDirectory();\n let appDirectory: FileSystemDirectoryHandle;\n try {\n appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\");\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n throw error;\n }\n\n try {\n await appDirectory.removeEntry(namespace, { recursive: true });\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n throw error;\n }\n}\n"]}
1
+ {"version":3,"file":"opfsBlobStore.js","sourceRoot":"","sources":["opfsBlobStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,yBAAyB,EACzB,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAMhD,MAAM,qBAAqB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAE9C,MAAM,aAAa;IAOY;IANrB,gBAAgB,GAA8C,IAAI,CAAC;IAE1D,MAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IACrC,OAAO,GAAG,IAAI,GAAG,EAA4B,CAAC;IACvD,YAAY,CAA4B;IAEhD,YAA6B,SAAiB;QAAjB,cAAS,GAAT,SAAS,CAAQ;IAAG,CAAC;IAElD,sEAAsE;IACtE,sEAAsE;IAC9D,KAAK,CAAC,OAAO,CACnB,GAAW,EACX,IAAc,EACd,GAAqB;QAErB,MAAM,MAAM,GAAG,GAAG,EAAE;YAClB,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC;YAC9B,OAAO,OAAO,KAAK,EAAE,OAAO,KAAK,UAAU;gBACzC,CAAC,CAAC,KAAK,CAAC,OAAO,CACX,IAAI,CAAC,SAAS,CAAC,CAAC,q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wB,EAAE;QAC5B,MAAM,cAAc,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AACnD,CAAC;AAED,KAAK,UAAU,eAAe,CAC5B,SAAiB,EACjB,OAAsB;IAEtB,MAAM,aAAa,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC;IAC7D,IAAI,YAAuC,CAAC;IAC5C,IAAI,CAAC;QACH,YAAY,GAAG,MAAM,aAAa,CAAC,kBAAkB,CAAC,WAAW,CAAC,CAAC;IACrE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACpE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,IAAI,CAAC,OAAO,EAAE;YAAE,OAAO,KAAK,CAAC;QAC7B,MAAM,YAAY,CAAC,WAAW,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAC/D,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACpE,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n type BlobByteSource,\n type BlobBytes,\n type BlobStore,\n blobByteSourceInputLength,\n createBlobByteSource,\n readBlobByteSource,\n} from \"./blobContracts\";\n\nimport { commitOpfsFile } from \"./opfsBlobFile\";\n\ninterface StorageDirectoryProvider {\n getDirectory: () => Promise<FileSystemDirectoryHandle>;\n}\n\nconst OPFS_WRITE_CHUNK_SIZE = 5 * 1024 * 1024;\n\nclass OpfsBlobStore implements BlobStore {\n private directoryPromise: Promise<FileSystemDirectoryHandle> | null = null;\n\n private readonly active = new Set<Promise<unknown>>();\n private readonly writers = new Map<string, Promise<unknown>>();\n private purgeBarrier: Promise<void> | undefined;\n\n constructor(private readonly namespace: string) {}\n\n // File operations run concurrently. A directory removal waits for all\n // of them and any later file operation opens the surviving directory.\n private async useFile<T>(\n key: string,\n mode: LockMode,\n run: () => Promise<T>,\n ): Promise<T> {\n const locked = () => {\n const locks = navigator.locks;\n return typeof locks?.request === \"function\"\n ? locks.request(\n JSON.stringify([\"tearleads.opfs.blob\", this.namespace, key]),\n { mode },\n run,\n )\n : run();\n };\n const writer = this.writers.get(key);\n const operation =\n writer || this.purgeBarrier\n ? Promise.allSettled([writer, this.purgeBarrier]).then(locked)\n : locked();\n if (mode === \"exclusive\") this.writers.set(key, operation);\n this.active.add(operation);\n try {\n return await operation;\n } finally {\n this.active.delete(operation);\n if (this.writers.get(key) === operation) this.writers.delete(key);\n }\n }\n\n async purge(current: () => boolean): Promise<void> {\n const pending = Promise.allSettled([\n ...this.active,\n this.purgeBarrier,\n ]).then(async () => {\n if (current() && (await removeNamespace(this.namespace, current)))\n this.directoryPromise = null;\n });\n const barrier = pending.catch(() => {});\n this.purgeBarrier = barrier;\n try {\n await pending;\n } finally {\n if (this.purgeBarrier === barrier) this.purgeBarrier = undefined;\n }\n }\n\n deleteBytes(storageKey: string, assertCurrent?: () => void) {\n return this.useFile(storageKey, \"exclusive\", () =>\n this.removeFile(storageKey, assertCurrent),\n );\n }\n\n private async removeFile(storageKey: string, assertCurrent?: () => void) {\n const directory = await this.getDirectory();\n\n try {\n assertCurrent?.();\n await directory.removeEntry(this.getFileName(storageKey));\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return;\n }\n\n throw error;\n }\n }\n\n async readBytes(storageKey: string) {\n const source = await this.openByteSource(storageKey);\n return source ? readBlobByteSource(source) : null;\n }\n\n openByteSource(storageKey: string) {\n return this.useFile(storageKey, \"shared\", () => this.openFile(storageKey));\n }\n\n private async openFile(storageKey: string) {\n const directory = await this.getDirectory();\n\n try {\n const fileHandle = await directory.getFileHandle(\n this.getFileName(storageKey),\n );\n const file = await fileHandle.getFile();\n return createBlobByteSource(file);\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return null;\n }\n\n throw error;\n }\n }\n\n writeByteSource(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n return this.useFile(storageKey, \"exclusive\", () =>\n this.writeFile(storageKey, source, assertCurrent),\n );\n }\n\n private async writeFile(\n storageKey: string,\n source: BlobByteSource,\n assertCurrent?: () => void,\n ) {\n const sourceByteLength = blobByteSourceInputLength(source);\n const directory = await this.getDirectory();\n await commitOpfsFile(\n directory,\n this.getFileName(storageKey),\n assertCurrent,\n async (writable) => {\n for (let offset = 0; offset < sourceByteLength; ) {\n const byteLength = Math.min(\n OPFS_WRITE_CHUNK_SIZE,\n sourceByteLength - offset,\n );\n const chunk = await source.read(offset, byteLength);\n if (chunk.byteLength !== byteLength) {\n throw new Error(\"Blob byte source returned an incomplete read.\");\n }\n await writable.write(chunk);\n offset += byteLength;\n }\n },\n );\n }\n\n async writeBytes(\n storageKey: string,\n bytes: BlobBytes,\n assertCurrent?: () => void,\n ) {\n await this.writeByteSource(\n storageKey,\n createBlobByteSource(bytes),\n assertCurrent,\n );\n }\n\n private getFileName(storageKey: string): string {\n return `${encodeURIComponent(storageKey)}.blob`;\n }\n\n private async getDirectory() {\n if (!this.directoryPromise) {\n this.directoryPromise = this.createDirectory().catch((error: unknown) => {\n this.directoryPromise = null;\n throw error;\n });\n }\n\n return this.directoryPromise;\n }\n\n private async createDirectory() {\n const rootDirectory = await navigator.storage.getDirectory();\n const appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\", {\n create: true,\n });\n\n return appDirectory.getDirectoryHandle(this.namespace, { create: true });\n }\n}\n\nfunction hasStorageDirectory(\n storage: StorageManager | undefined,\n): storage is StorageManager & StorageDirectoryProvider {\n return (\n storage !== undefined &&\n \"getDirectory\" in storage &&\n typeof storage.getDirectory === \"function\"\n );\n}\n\nexport function isOpfsBlobStoreSupported(): boolean {\n return (\n typeof navigator === \"object\" && hasStorageDirectory(navigator.storage)\n );\n}\n\n// Plain and encrypted stores address the same OPFS namespace.\nconst namespaces = new WeakMap<StorageManager, Map<string, OpfsBlobStore>>();\n\nfunction namespaceStore(namespace: string): OpfsBlobStore {\n const storage = navigator.storage;\n let stores = namespaces.get(storage);\n if (!stores) {\n stores = new Map();\n namespaces.set(storage, stores);\n }\n let store = stores.get(namespace);\n if (!store) {\n store = new OpfsBlobStore(namespace);\n stores.set(namespace, store);\n }\n return store;\n}\n\nexport function createOpfsBlobStore(namespace: string): BlobStore {\n return namespaceStore(namespace);\n}\n\n/**\n * Permanently remove the OPFS directory backing a namespace's blob store\n * (`tearleads/<namespace>`), discarding every stored blob for that namespace.\n * Used to forget local data on logout. No-op when OPFS is unavailable or the\n * directory was never created; never throws on a missing directory.\n */\nexport async function purgeOpfsBlobStore(\n namespace: string,\n current: () => boolean = () => true,\n): Promise<void> {\n if (isOpfsBlobStoreSupported())\n await namespaceStore(namespace).purge(current);\n}\n\nasync function removeNamespace(\n namespace: string,\n current: () => boolean,\n): Promise<boolean> {\n const rootDirectory = await navigator.storage.getDirectory();\n let appDirectory: FileSystemDirectoryHandle;\n try {\n appDirectory = await rootDirectory.getDirectoryHandle(\"tearleads\");\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return true;\n }\n throw error;\n }\n\n try {\n if (!current()) return false;\n await appDirectory.removeEntry(namespace, { recursive: true });\n return true;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotFoundError\") {\n return true;\n }\n throw error;\n }\n}\n"]}
@@ -1,22 +1,9 @@
1
+ import { createKeyedQueue } from "../shared/keyedQueue.js";
2
+ import { sqlConnectionIdentity } from "../sqlite/sqlExec.js";
1
3
  import { resolveCanonicalExecSql } from "../sqlite/sqlSchema.js";
2
4
  import { principalMutationJournalScopeId, } from "./principalMutationJournal.js";
3
- /** Runs work for a key after the work already queued for it; idle keys hold nothing. */
4
- function createKeyedQueue() {
5
- const tails = new Map();
6
- return (key, work) => {
7
- const operation = (tails.get(key) ?? Promise.resolve()).then(work);
8
- const settled = operation.then(() => undefined, () => undefined);
9
- tails.set(key, settled);
10
- void settled.then(() => {
11
- if (tails.get(key) === settled)
12
- tails.delete(key);
13
- });
14
- return operation;
15
- };
16
- }
17
- function createPrincipalPolicyCoordinator() {
5
+ function createPrincipalPolicyCoordinator(journalScopes) {
18
6
  const recoveries = createKeyedQueue();
19
- const journalScopes = createKeyedQueue();
20
7
  const epochs = new Map();
21
8
  return {
22
9
  queueRecovery: recoveries,
@@ -27,12 +14,16 @@ function createPrincipalPolicyCoordinator() {
27
14
  runJournalOperation: async (scope, run) => journalScopes(await principalMutationJournalScopeId(scope), run),
28
15
  };
29
16
  }
17
+ const journals = new WeakMap();
30
18
  const coordinators = new WeakMap();
31
19
  export function getOrCreatePrincipalPolicyCoordinator(execSql) {
32
20
  const database = resolveCanonicalExecSql(execSql);
33
21
  let coordinator = coordinators.get(database);
34
22
  if (!coordinator) {
35
- coordinator = createPrincipalPolicyCoordinator();
23
+ const connection = sqlConnectionIdentity(execSql);
24
+ const journal = journals.get(connection) ?? createKeyedQueue();
25
+ journals.set(connection, journal);
26
+ coordinator = createPrincipalPolicyCoordinator(journal);
36
27
  coordinators.set(database, coordinator);
37
28
  }
38
29
  return coordinator;
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCoordinator.js","sourceRoot":"","sources":["principalPolicyCoordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAEL,+BAA+B,GAChC,MAAM,4BAA4B,CAAC;AA+BpC,wFAAwF;AACxF,SAAS,gBAAgB;IACvB,MAAM,KAAK,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC/C,OAAO,CAAI,GAAW,EAAE,IAAsB,EAAc,EAAE;QAC5D,MAAM,SAAS,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D,OAAgB;IAEhB,MAAM,QAAQ,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAClD,IAAI,WAAW,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,gCAAgC,EAAE,CAAC;QACjD,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { type ExecSql, resolveCanonicalExecSql } from \"../sqlite/sqlSchema\";\nimport {\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n} from \"./principalMutationJournal\";\n\n/**\n * The principal-policy work one database coordinates in this process. Every\n * executor for a connection, including a transaction's locked one, resolves to\n * the same coordinator; different databases never share one.\n */\nexport interface PrincipalPolicyCoordinator {\n /**\n * Runs recovery for an organization after the recovery already queued for\n * it. Directory and Admins stages are shared by every reference in an\n * organization, so warmers and registration take turns. Queued work must not\n * queue again for the same organization.\n */\n queueRecovery<T>(organizationId: string, work: () => Promise<T>): Promise<T>;\n /**\n * The organization hints applied in this process. Operation-scoped recovery\n * records it before producing a result and recovers again once it changes.\n * Hints are lossy, so this only shortens reuse; each operation still\n * discovers the current head.\n */\n recoveryEpoch(organizationId: string): number;\n /** Evicts recovered directory and Admins views for this organization. */\n invalidateRecovery(organizationId: string): void;\n /** An owned dispatch finishes before another caller can recover or abandon it. */\n runJournalOperation<T>(\n scope: PrincipalMutationJournalScope,\n run: () => Promise<T>,\n ): Promise<T>;\n}\n\n/** Runs work for a key after the work already queued for it; idle keys hold nothing. */\nfunction createKeyedQueue() {\n const tails = new Map<string, Promise<void>>();\n return <T>(key: string, work: () => Promise<T>): Promise<T> => {\n const operation = (tails.get(key) ?? Promise.resolve()).then(work);\n const settled = operation.then(\n () => undefined,\n () => undefined,\n );\n tails.set(key, settled);\n void settled.then(() => {\n if (tails.get(key) === settled) tails.delete(key);\n });\n return operation;\n };\n}\n\nfunction createPrincipalPolicyCoordinator(): PrincipalPolicyCoordinator {\n const recoveries = createKeyedQueue();\n const journalScopes = createKeyedQueue();\n const epochs = new Map<string, number>();\n return {\n queueRecovery: recoveries,\n recoveryEpoch: (organizationId) => epochs.get(organizationId) ?? 0,\n invalidateRecovery: (organizationId) => {\n epochs.set(organizationId, (epochs.get(organizationId) ?? 0) + 1);\n },\n runJournalOperation: async (scope, run) =>\n journalScopes(await principalMutationJournalScopeId(scope), run),\n };\n}\n\nconst coordinators = new WeakMap<ExecSql, PrincipalPolicyCoordinator>();\n\nexport function getOrCreatePrincipalPolicyCoordinator(\n execSql: ExecSql,\n): PrincipalPolicyCoordinator {\n const database = resolveCanonicalExecSql(execSql);\n let coordinator = coordinators.get(database);\n if (!coordinator) {\n coordinator = createPrincipalPolicyCoordinator();\n coordinators.set(database, coordinator);\n }\n return coordinator;\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCoordinator.js","sourceRoot":"","sources":["principalPolicyCoordinator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAgB,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC5E,OAAO,EAEL,+BAA+B,GAChC,MAAM,4BAA4B,CAAC;AA+BpC,SAAS,gCAAgC,CACvC,aAAkD;IAElD,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;IACtC,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,OAAO;QACL,aAAa,EAAE,UAAU;QACzB,aAAa,EAAE,CAAC,cAAc,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC;QAClE,kBAAkB,EAAE,CAAC,cAAc,EAAE,EAAE;YACrC,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACpE,CAAC;QACD,mBAAmB,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,CACxC,aAAa,CAAC,MAAM,+BAA+B,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA+C,CAAC;AAC5E,MAAM,YAAY,GAAG,IAAI,OAAO,EAAuC,CAAC;AAExE,MAAM,UAAU,qCAAqC,CACnD,OAAgB;IAEhB,MAAM,QAAQ,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAClD,IAAI,WAAW,GAAG,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,UAAU,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;QAClD,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,gBAAgB,EAAE,CAAC;QAC/D,QAAQ,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAClC,WAAW,GAAG,gCAAgC,CAAC,OAAO,CAAC,CAAC;QACxD,YAAY,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import { createKeyedQueue } from \"../shared/keyedQueue\";\nimport { sqlConnectionIdentity } from \"../sqlite/sqlExec\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../sqlite/sqlSchema\";\nimport {\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n} from \"./principalMutationJournal\";\n\n/**\n * Recovery hints belong to one scoped executor and its nested transactions.\n * Journal dispatch and recovery share the physical database's mutation lock\n * across sign-ins.\n */\nexport interface PrincipalPolicyCoordinator {\n /**\n * Runs recovery for an organization after the recovery already queued for\n * it. Directory and Admins stages are shared by every reference in an\n * organization, so warmers and registration take turns. Queued work must not\n * queue again for the same organization.\n */\n queueRecovery<T>(organizationId: string, work: () => Promise<T>): Promise<T>;\n /**\n * The organization hints applied in this process. Operation-scoped recovery\n * records it before producing a result and recovers again once it changes.\n * Hints are lossy, so this only shortens reuse; each operation still\n * discovers the current head.\n */\n recoveryEpoch(organizationId: string): number;\n /** Evicts recovered directory and Admins views for this organization. */\n invalidateRecovery(organizationId: string): void;\n /** An owned dispatch finishes before another caller can recover or abandon it. */\n runJournalOperation<T>(\n scope: PrincipalMutationJournalScope,\n run: () => Promise<T>,\n ): Promise<T>;\n}\n\nfunction createPrincipalPolicyCoordinator(\n journalScopes: ReturnType<typeof createKeyedQueue>,\n): PrincipalPolicyCoordinator {\n const recoveries = createKeyedQueue();\n const epochs = new Map<string, number>();\n return {\n queueRecovery: recoveries,\n recoveryEpoch: (organizationId) => epochs.get(organizationId) ?? 0,\n invalidateRecovery: (organizationId) => {\n epochs.set(organizationId, (epochs.get(organizationId) ?? 0) + 1);\n },\n runJournalOperation: async (scope, run) =>\n journalScopes(await principalMutationJournalScopeId(scope), run),\n };\n}\n\nconst journals = new WeakMap<object, ReturnType<typeof createKeyedQueue>>();\nconst coordinators = new WeakMap<ExecSql, PrincipalPolicyCoordinator>();\n\nexport function getOrCreatePrincipalPolicyCoordinator(\n execSql: ExecSql,\n): PrincipalPolicyCoordinator {\n const database = resolveCanonicalExecSql(execSql);\n let coordinator = coordinators.get(database);\n if (!coordinator) {\n const connection = sqlConnectionIdentity(execSql);\n const journal = journals.get(connection) ?? createKeyedQueue();\n journals.set(connection, journal);\n coordinator = createPrincipalPolicyCoordinator(journal);\n coordinators.set(database, coordinator);\n }\n return coordinator;\n}\n"]}
@@ -1,6 +1,8 @@
1
1
  declare const domainScopeBrand: unique symbol;
2
2
  export interface DomainScope {
3
3
  readonly [domainScopeBrand]: true;
4
+ /** Process-local identity for host components that need a scalar key. */
5
+ readonly id: number;
4
6
  }
5
7
  export declare function createDomainScope(): DomainScope;
6
8
  export {};
@@ -1,5 +1,6 @@
1
+ let nextScopeId = 0;
1
2
  const domainScopeBrand = Symbol("tearleads.domainScope");
2
3
  export function createDomainScope() {
3
- return { [domainScopeBrand]: true };
4
+ return { [domainScopeBrand]: true, id: ++nextScopeId };
4
5
  }
5
6
  //# sourceMappingURL=domainScope.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"domainScope.js","sourceRoot":"","sources":["domainScope.ts"],"names":[],"mappings":"AAAA,MAAM,gBAAgB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAQzD,MAAM,UAAU,iBAAiB;IAC/B,OAAO,EAAE,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAwB,CAAC;AAC5D,CAAC","sourcesContent":["const domainScopeBrand = Symbol(\"tearleads.domainScope\");\n\n// Identity token for in-process caches that must rotate together when the\n// active database or signing identity changes.\nexport interface DomainScope {\n readonly [domainScopeBrand]: true;\n}\n\nexport function createDomainScope(): DomainScope {\n return { [domainScopeBrand]: true } satisfies DomainScope;\n}\n"]}
1
+ {"version":3,"file":"domainScope.js","sourceRoot":"","sources":["domainScope.ts"],"names":[],"mappings":"AAAA,IAAI,WAAW,GAAG,CAAC,CAAC;AACpB,MAAM,gBAAgB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAUzD,MAAM,UAAU,iBAAiB;IAC/B,OAAO,EAAE,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,WAAW,EAAwB,CAAC;AAC/E,CAAC","sourcesContent":["let nextScopeId = 0;\nconst domainScopeBrand = Symbol(\"tearleads.domainScope\");\n\n// Identity token for in-process caches that must rotate together when the\n// active database, signing identity, or sign-in changes.\nexport interface DomainScope {\n readonly [domainScopeBrand]: true;\n /** Process-local identity for host components that need a scalar key. */\n readonly id: number;\n}\n\nexport function createDomainScope(): DomainScope {\n return { [domainScopeBrand]: true, id: ++nextScopeId } satisfies DomainScope;\n}\n"]}
@@ -0,0 +1,15 @@
1
+ /** Runs work for a key after the work already queued for it; idle keys hold nothing. */
2
+ export function createKeyedQueue() {
3
+ const tails = new Map();
4
+ return (key, work) => {
5
+ const operation = (tails.get(key) ?? Promise.resolve()).then(work);
6
+ const settled = operation.then(() => undefined, () => undefined);
7
+ tails.set(key, settled);
8
+ void settled.then(() => {
9
+ if (tails.get(key) === settled)
10
+ tails.delete(key);
11
+ });
12
+ return operation;
13
+ };
14
+ }
15
+ //# sourceMappingURL=keyedQueue.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyedQueue.js","sourceRoot":"","sources":["keyedQueue.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,MAAM,UAAU,gBAAgB;IAC9B,MAAM,KAAK,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC/C,OAAO,CAAI,GAAW,EAAE,IAAsB,EAAc,EAAE;QAC5D,MAAM,SAAS,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACnE,MAAM,OAAO,GAAG,SAAS,CAAC,IAAI,CAC5B,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QACxB,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE;YACrB,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;gBAAE,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/** Runs work for a key after the work already queued for it; idle keys hold nothing. */\nexport function createKeyedQueue() {\n const tails = new Map<string, Promise<void>>();\n return <T>(key: string, work: () => Promise<T>): Promise<T> => {\n const operation = (tails.get(key) ?? Promise.resolve()).then(work);\n const settled = operation.then(\n () => undefined,\n () => undefined,\n );\n tails.set(key, settled);\n void settled.then(() => {\n if (tails.get(key) === settled) tails.delete(key);\n });\n return operation;\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { hasCompletedConnectionOnce, markCompletedConnectionOnce, runSerializedSqlMutation, } from "../sqlExec.js";
1
+ import { hasCompletedConnectionOnce, markCompletedConnectionOnce, rollbackSqlSavepoint, runSerializedSqlMutation, } from "../sqlExec.js";
2
2
  import { assertLocalSchemaMigrations, localSchemaMigrations, } from "./localSchemaMigrations.js";
3
3
  import { classifyLocalSchema, localSchemaStateError, parseLocalSchemaLedger, } from "./localSchemaState.js";
4
4
  /** The ledger table; a local backup carries it like any other table. */
@@ -64,8 +64,7 @@ async function applyPendingSteps(execSql, state, now, verify) {
64
64
  await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`);
65
65
  }
66
66
  catch (error) {
67
- await execSql(`ROLLBACK TO SAVEPOINT ${SAVEPOINT}`).catch(() => undefined);
68
- await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`).catch(() => undefined);
67
+ await rollbackSqlSavepoint(execSql, SAVEPOINT).catch(() => undefined);
69
68
  throw error;
70
69
  }
71
70
  }