tempest-react-sdk 0.80.0 → 0.82.0

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 (247) hide show
  1. package/README.md +40 -10
  2. package/bin/create-tempest-app.e2e.test.mjs +31 -0
  3. package/bin/create-tempest-app.mjs +11 -1
  4. package/bin/lib/component/generate.test.mjs +13 -1
  5. package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
  6. package/bin/lib/doctor/vitest.mjs +120 -0
  7. package/bin/lib/doctor/vitest.test.mjs +139 -0
  8. package/bin/lib/fs/contain.mjs +7 -0
  9. package/bin/lib/openapi/escape.mjs +68 -4
  10. package/bin/lib/openapi/generate.hostile.test.mjs +150 -1
  11. package/bin/lib/openapi/generate.mjs +78 -13
  12. package/bin/lib/openapi/generate.test.mjs +13 -1
  13. package/bin/lib/openapi/pattern-risk.mjs +134 -0
  14. package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
  15. package/bin/tempest-gen.test.mjs +100 -0
  16. package/bin/tempest.mjs +24 -8
  17. package/dist/access/use-can.cjs +1 -1
  18. package/dist/access/use-can.cjs.map +1 -1
  19. package/dist/access/use-can.js +25 -28
  20. package/dist/access/use-can.js.map +1 -1
  21. package/dist/auth/create-tempest-auth.cjs +1 -1
  22. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  23. package/dist/auth/create-tempest-auth.js +234 -122
  24. package/dist/auth/create-tempest-auth.js.map +1 -1
  25. package/dist/auth/session-identity.cjs +2 -0
  26. package/dist/auth/session-identity.cjs.map +1 -0
  27. package/dist/auth/session-identity.js +12 -0
  28. package/dist/auth/session-identity.js.map +1 -0
  29. package/dist/br/boleto.cjs +1 -1
  30. package/dist/br/boleto.cjs.map +1 -1
  31. package/dist/br/boleto.js +2 -1
  32. package/dist/br/boleto.js.map +1 -1
  33. package/dist/br.d.ts +22 -3
  34. package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
  35. package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
  36. package/dist/components/AuthForm/AuthFieldControl.js +85 -0
  37. package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
  38. package/dist/components/AuthForm/AuthForm.cjs +2 -0
  39. package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
  40. package/dist/components/AuthForm/AuthForm.js +83 -0
  41. package/dist/components/AuthForm/AuthForm.js.map +1 -0
  42. package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
  43. package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
  44. package/dist/components/AuthForm/AuthForm.module.js +14 -0
  45. package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
  46. package/dist/components/AuthForm/AuthLinks.cjs +2 -0
  47. package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
  48. package/dist/components/AuthForm/AuthLinks.js +32 -0
  49. package/dist/components/AuthForm/AuthLinks.js.map +1 -0
  50. package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
  51. package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
  52. package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
  53. package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
  54. package/dist/components/AuthForm/LoginForm.cjs +2 -0
  55. package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
  56. package/dist/components/AuthForm/LoginForm.js +39 -0
  57. package/dist/components/AuthForm/LoginForm.js.map +1 -0
  58. package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
  59. package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
  60. package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
  61. package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
  62. package/dist/components/AuthForm/SignUpForm.cjs +2 -0
  63. package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
  64. package/dist/components/AuthForm/SignUpForm.js +32 -0
  65. package/dist/components/AuthForm/SignUpForm.js.map +1 -0
  66. package/dist/components/AuthForm/auth-defaults.cjs +2 -0
  67. package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
  68. package/dist/components/AuthForm/auth-defaults.js +54 -0
  69. package/dist/components/AuthForm/auth-defaults.js.map +1 -0
  70. package/dist/components/AuthForm/auth-schemas.cjs +2 -0
  71. package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
  72. package/dist/components/AuthForm/auth-schemas.js +26 -0
  73. package/dist/components/AuthForm/auth-schemas.js.map +1 -0
  74. package/dist/components/AuthPage/AuthPage.cjs +2 -0
  75. package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
  76. package/dist/components/AuthPage/AuthPage.js +97 -0
  77. package/dist/components/AuthPage/AuthPage.js.map +1 -0
  78. package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
  79. package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
  80. package/dist/components/AuthPage/AuthPage.module.js +24 -0
  81. package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
  82. package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
  83. package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
  84. package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
  85. package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
  86. package/dist/components/Button/Button.cjs +1 -1
  87. package/dist/components/Button/Button.cjs.map +1 -1
  88. package/dist/components/Button/Button.js +41 -40
  89. package/dist/components/Button/Button.js.map +1 -1
  90. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  91. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  92. package/dist/components/Chat/ChatAttachments.js +38 -38
  93. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  94. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  95. package/dist/components/FilterBar/filter-apply.js +7 -7
  96. package/dist/components/Form/Form.cjs +1 -1
  97. package/dist/components/Form/Form.cjs.map +1 -1
  98. package/dist/components/Form/Form.js +30 -32
  99. package/dist/components/Form/Form.js.map +1 -1
  100. package/dist/components/Layout/Layout.cjs +1 -1
  101. package/dist/components/Layout/Layout.cjs.map +1 -1
  102. package/dist/components/Layout/Layout.js +25 -24
  103. package/dist/components/Layout/Layout.js.map +1 -1
  104. package/dist/components/Layout/gap.cjs +2 -0
  105. package/dist/components/Layout/gap.cjs.map +1 -0
  106. package/dist/components/Layout/gap.js +15 -0
  107. package/dist/components/Layout/gap.js.map +1 -0
  108. package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
  109. package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
  110. package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
  111. package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
  112. package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
  113. package/dist/components/Sidebar/Sidebar.js.map +1 -1
  114. package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
  115. package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
  116. package/dist/components/Sidebar/SidebarEntry.js +30 -29
  117. package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
  118. package/dist/data/create-data-provider.cjs +1 -1
  119. package/dist/data/create-data-provider.cjs.map +1 -1
  120. package/dist/data/create-data-provider.js +1 -2
  121. package/dist/data/create-data-provider.js.map +1 -1
  122. package/dist/forms/index.js +7 -7
  123. package/dist/forms/masked-inputs.cjs +1 -1
  124. package/dist/forms/masked-inputs.cjs.map +1 -1
  125. package/dist/forms/masked-inputs.js +15 -15
  126. package/dist/forms/validate-form.cjs +1 -1
  127. package/dist/forms/validate-form.cjs.map +1 -1
  128. package/dist/forms/validate-form.js +6 -1
  129. package/dist/forms/validate-form.js.map +1 -1
  130. package/dist/forms/zod-resolver.cjs +1 -1
  131. package/dist/forms/zod-resolver.cjs.map +1 -1
  132. package/dist/forms/zod-resolver.js +8 -3
  133. package/dist/forms/zod-resolver.js.map +1 -1
  134. package/dist/http/api-client.cjs +1 -1
  135. package/dist/http/api-client.cjs.map +1 -1
  136. package/dist/http/api-client.js +137 -116
  137. package/dist/http/api-client.js.map +1 -1
  138. package/dist/http/credential-scope.cjs +1 -1
  139. package/dist/http/credential-scope.cjs.map +1 -1
  140. package/dist/http/credential-scope.js +33 -9
  141. package/dist/http/credential-scope.js.map +1 -1
  142. package/dist/http/presigned-post.cjs.map +1 -1
  143. package/dist/http/presigned-post.js.map +1 -1
  144. package/dist/http/resumable-upload.cjs +1 -1
  145. package/dist/http/resumable-upload.cjs.map +1 -1
  146. package/dist/http/resumable-upload.js +140 -134
  147. package/dist/http/resumable-upload.js.map +1 -1
  148. package/dist/http/upload-with-progress.cjs +1 -1
  149. package/dist/http/upload-with-progress.cjs.map +1 -1
  150. package/dist/http/upload-with-progress.js +17 -17
  151. package/dist/http/upload-with-progress.js.map +1 -1
  152. package/dist/http/use-describe-api-error.cjs +1 -1
  153. package/dist/http/use-describe-api-error.cjs.map +1 -1
  154. package/dist/http/use-describe-api-error.js +9 -9
  155. package/dist/oauth/GoogleSignIn.cjs +1 -1
  156. package/dist/oauth/GoogleSignIn.cjs.map +1 -1
  157. package/dist/oauth/GoogleSignIn.js +5 -4
  158. package/dist/oauth/GoogleSignIn.js.map +1 -1
  159. package/dist/offline/create-offline-sync.cjs +1 -1
  160. package/dist/offline/create-offline-sync.cjs.map +1 -1
  161. package/dist/offline/create-offline-sync.js +108 -68
  162. package/dist/offline/create-offline-sync.js.map +1 -1
  163. package/dist/query/offline-persistence.cjs +1 -1
  164. package/dist/query/offline-persistence.cjs.map +1 -1
  165. package/dist/query/offline-persistence.js +54 -44
  166. package/dist/query/offline-persistence.js.map +1 -1
  167. package/dist/sse/create-event-stream.cjs +1 -1
  168. package/dist/sse/create-event-stream.cjs.map +1 -1
  169. package/dist/sse/create-event-stream.js +48 -41
  170. package/dist/sse/create-event-stream.js.map +1 -1
  171. package/dist/sse/ticket-event-stream.cjs +1 -1
  172. package/dist/sse/ticket-event-stream.cjs.map +1 -1
  173. package/dist/sse/ticket-event-stream.js +48 -19
  174. package/dist/sse/ticket-event-stream.js.map +1 -1
  175. package/dist/sse/use-event-stream.cjs +1 -1
  176. package/dist/sse/use-event-stream.cjs.map +1 -1
  177. package/dist/sse/use-event-stream.js +19 -14
  178. package/dist/sse/use-event-stream.js.map +1 -1
  179. package/dist/styles/AuthForm.css +2 -0
  180. package/dist/styles/AuthPage.css +2 -0
  181. package/dist/styles/component/AuthForm.css +9 -0
  182. package/dist/styles/component/AuthPage.css +29 -0
  183. package/dist/styles/forms.css +36 -0
  184. package/dist/styles/manifest.json +63 -0
  185. package/dist/styles.css +1 -1
  186. package/dist/sw/background-sync.cjs +1 -1
  187. package/dist/sw/background-sync.cjs.map +1 -1
  188. package/dist/sw/background-sync.js +132 -112
  189. package/dist/sw/background-sync.js.map +1 -1
  190. package/dist/sw/cache.cjs +1 -1
  191. package/dist/sw/cache.cjs.map +1 -1
  192. package/dist/sw/cache.js +36 -30
  193. package/dist/sw/cache.js.map +1 -1
  194. package/dist/sw/create-push-handler.cjs +1 -1
  195. package/dist/sw/create-push-handler.cjs.map +1 -1
  196. package/dist/sw/create-push-handler.js +20 -10
  197. package/dist/sw/create-push-handler.js.map +1 -1
  198. package/dist/sw.d.ts +93 -28
  199. package/dist/tabular/compact.cjs +1 -1
  200. package/dist/tabular/compact.cjs.map +1 -1
  201. package/dist/tabular/compact.js +35 -16
  202. package/dist/tabular/compact.js.map +1 -1
  203. package/dist/tabular/manifest.cjs +1 -1
  204. package/dist/tabular/manifest.cjs.map +1 -1
  205. package/dist/tabular/manifest.js +33 -15
  206. package/dist/tabular/manifest.js.map +1 -1
  207. package/dist/tabular.d.ts +11 -1
  208. package/dist/tempest-react-sdk.cjs +1 -1
  209. package/dist/tempest-react-sdk.d.ts +1057 -83
  210. package/dist/tempest-react-sdk.js +373 -365
  211. package/dist/theme/initial-theme.cjs +4 -4
  212. package/dist/theme/initial-theme.cjs.map +1 -1
  213. package/dist/theme/initial-theme.js +8 -5
  214. package/dist/theme/initial-theme.js.map +1 -1
  215. package/dist/utils/compressed-storage.cjs +1 -1
  216. package/dist/utils/compressed-storage.cjs.map +1 -1
  217. package/dist/utils/compressed-storage.js +13 -7
  218. package/dist/utils/compressed-storage.js.map +1 -1
  219. package/dist/utils/format.cjs +1 -1
  220. package/dist/utils/format.cjs.map +1 -1
  221. package/dist/utils/format.js +25 -25
  222. package/dist/utils/numbers.cjs +1 -1
  223. package/dist/utils/numbers.cjs.map +1 -1
  224. package/dist/utils/numbers.js +7 -7
  225. package/dist/utils/objects.cjs +1 -1
  226. package/dist/utils/objects.cjs.map +1 -1
  227. package/dist/utils/objects.js +13 -7
  228. package/dist/utils/objects.js.map +1 -1
  229. package/dist/utils/safe-url.cjs +1 -1
  230. package/dist/utils/safe-url.cjs.map +1 -1
  231. package/dist/utils/safe-url.js +4 -1
  232. package/dist/utils/safe-url.js.map +1 -1
  233. package/dist/webrtc/peer-mesh.cjs +1 -1
  234. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  235. package/dist/webrtc/peer-mesh.js +7 -1
  236. package/dist/webrtc/peer-mesh.js.map +1 -1
  237. package/dist/ws/create-web-socket.cjs +1 -1
  238. package/dist/ws/create-web-socket.cjs.map +1 -1
  239. package/dist/ws/create-web-socket.js +77 -61
  240. package/dist/ws/create-web-socket.js.map +1 -1
  241. package/dist/ws/use-web-socket.cjs +1 -1
  242. package/dist/ws/use-web-socket.cjs.map +1 -1
  243. package/dist/ws/use-web-socket.js +4 -3
  244. package/dist/ws/use-web-socket.js.map +1 -1
  245. package/package.json +1 -1
  246. package/template-pwa/src/pwa.tsx +42 -0
  247. package/template-pwa/src/sw.ts +15 -10
@@ -1 +1 @@
1
- {"version":3,"file":"background-sync.js","names":["getSwScope","DEFAULT_QUEUE_NAME","DB_VERSION","STORE","META","EPOCH_KEY","BACKGROUND_SYNC_CREDENTIALS_MESSAGE","CREDENTIALS_TIMEOUT_MS","OWNER_STAMP_GRACE_MS","splitHeaders","kept","stripped","name","value","headers","credentialHeaders","migrateLegacyEntries","cursorRequest","store","cursor","entry","openQueueDb","credentialHeaderSet","request","db","event","resolve","reject","txDone","tx","readEpoch","get","enqueue","id","current","epoch","add","stampOwner","ownerState","owner","readAll","all","req","stillQueued","count","remove","serializeRequest","buffer","deserializeRequest","askClient","channel","answer","client","deadline","hasPrincipal","startDeadline","timer","askAllClients","clients","sw","answers","createReplayRun","warned","key","pending","isDevBuild","chooseAnswer","context","defaultBeforeReplay","credentialed","unchecked","ownerPolicy","run","chosen","provided","replayQueue","config","prepare","beforeReplay","entries","now","maxRetentionMs","state","stored","response","replaysInFlight","drainQueue","running","pass","matches","match","url","stampFromIssuer","issuer","installBackgroundSync","options","DEFAULT_CREDENTIAL_HEADERS","replay","queueName","maxRetentionMinutes","attempt","queued","error","stamp","periodicSyncTag","clearBackgroundSyncQueue","meta","ownerFingerprint","principal","digest","byte","provideBackgroundSyncCredentials","container","onMessage","data","port","getHeaders","getPrincipal"],"sources":["../../src/sw/background-sync.ts"],"sourcesContent":["/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * Credential headers (`Authorization` and the rest of\n * {@link DEFAULT_CREDENTIAL_HEADERS}) are never written to IndexedDB: the queue\n * outlives the session, and a stored bearer stayed readable after logout and was\n * replayed with the old identity (reproduced in Chromium 153, 11/10/2026). On\n * replay the worker asks the open pages for the *current* credentials — see\n * {@link provideBackgroundSyncCredentials} — or a custom `beforeReplay` hook.\n * Credentials carried in the URL or the body are out of reach and are stored\n * as sent.\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { DEFAULT_CREDENTIAL_HEADERS, credentialHeaderSet } from \"./credential-headers\";\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n /** Id of the window client that issued the request, when there is one. */\n clientId?: string;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface PeriodicSyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Minimal shape of a window client the worker can message. */\ninterface WindowClientLike {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n clients?: {\n matchAll(options: { type: \"window\" }): Promise<readonly WindowClientLike[]>;\n get(id: string): Promise<WindowClientLike | undefined>;\n };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n addEventListener(type: \"periodicsync\", listener: (event: PeriodicSyncEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/**\n * How an entry is tied to whoever queued it:\n * - `\"bound\"`: the issuing page reported a principal (or `null` for nobody);\n * the entry only goes out while the same one is signed in.\n * - `\"unbound\"`: the issuing page answered without `getPrincipal`.\n * - `\"unknown\"`: nobody could say — no issuing tab, no answer, an error, or an\n * entry written before owners existed. Fails closed, with or without stripped\n * credentials: a cookie session rides along on the replay, so an entry with no\n * credential header is checked like any other.\n *\n * While the worker is still asking, the stored state is `\"pending\"`, which a\n * replay never sees: it waits, then reads a stamp that never came as `\"unknown\"`.\n */\nexport type BackgroundSyncOwnerState = \"bound\" | \"unbound\" | \"unknown\";\n\n/**\n * How the default `beforeReplay` treats an `\"unknown\"` owner on an entry that\n * carried no credential header:\n * - `\"strict\"` (default): it asks the open pages like any other entry — replayed\n * only when every answer lacks a principal, dropped as soon as one answer has\n * one, pending while nobody answers.\n * - `\"lenient\"`: it is replayed as-is, without asking (the behavior up to 0.77.0).\n *\n * An entry with stripped credentials always asks, under either policy.\n */\nexport type BackgroundSyncOwnerPolicy = \"strict\" | \"lenient\";\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n /** The original `credentials` mode, so cookie-based APIs replay with cookies. */\n credentials?: RequestCredentials;\n /** Lower-cased names of the credential headers removed before persisting. */\n strippedHeaders?: string[];\n /** Absent on entries written before 0.77 — read as `\"unknown\"`. */\n ownerState?: BackgroundSyncOwnerState | \"pending\";\n /** Fingerprint of the principal under `\"bound\"`; `null` for \"nobody signed in\". */\n owner?: string | null;\n}\n\n/** Default IndexedDB database name (and sync tag) of the background-sync queue. */\nconst DEFAULT_QUEUE_NAME = \"tempest-bg-sync\";\n\n/**\n * Schema version of the queue database. Version 2 adds the `meta` store (the\n * clear epoch) and migrates version-1 entries, scrubbing their plaintext\n * credential headers on first open.\n */\nconst DB_VERSION = 2;\nconst STORE = \"requests\";\nconst META = \"meta\";\nconst EPOCH_KEY = \"epoch\";\n\n/**\n * `type` of the message the worker posts to window clients to ask about a queued\n * request. Answered by {@link provideBackgroundSyncCredentials}.\n */\nexport const BACKGROUND_SYNC_CREDENTIALS_MESSAGE = \"tempest:bg-sync-credentials\";\n\n/** How long the worker waits for the window clients to answer, in milliseconds. */\nconst CREDENTIALS_TIMEOUT_MS = 3000;\n\n/**\n * How long a replay waits on an entry whose owner is still being stamped. Past\n * it (the worker died mid-question), the owner is read as `\"unknown\"`.\n */\nconst OWNER_STAMP_GRACE_MS = CREDENTIALS_TIMEOUT_MS * 2;\n\n/** What a queued request looked like when it was stored, passed to `beforeReplay`. */\nexport interface BackgroundSyncReplayContext {\n /** Epoch milliseconds of the original failed attempt. */\n queuedAt: number;\n /** Lower-cased credential header names stripped before the entry was stored. */\n strippedHeaders: readonly string[];\n /** How the entry is tied to its owner. */\n ownerState: BackgroundSyncOwnerState;\n /** Owner fingerprint under `\"bound\"` (`null` for nobody); `undefined` otherwise. */\n owner: string | null | undefined;\n}\n\n/** The request a window client is asked about, as sent by the worker. */\nexport interface BackgroundSyncCredentialsRequest {\n /** Absolute URL of the queued request. */\n url: string;\n /** HTTP method of the queued request. */\n method: string;\n /**\n * `\"enqueue\"` when the worker only wants the owner of a request that just\n * failed; `\"replay\"` when it is about to send it and needs the credentials.\n */\n phase: \"enqueue\" | \"replay\";\n}\n\n/**\n * Resolve the credentials for a queued request: a header record to apply, or\n * `null` when there is no session (the entry is then dropped).\n */\nexport type BackgroundSyncCredentialsProvider = (\n request: BackgroundSyncCredentialsRequest,\n) => Record<string, string> | null | Promise<Record<string, string> | null>;\n\n/** Options for {@link provideBackgroundSyncCredentials}. */\nexport interface ProvideBackgroundSyncCredentialsOptions {\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id;\n * `null`/`undefined` when nobody is. Read when a request is queued and again\n * when it is replayed: an entry is only sent while the same principal is\n * signed in, and dropped otherwise, so a mutation queued by one account is\n * never sent with another account's credentials even when the app forgets\n * `clearSessionData()` on logout. Only a SHA-256 fingerprint reaches the\n * queue, never the value itself. A throw is answered as an explicit error,\n * which leaves the owner unknown (fail closed).\n */\n getPrincipal?: () => string | null | undefined | Promise<string | null | undefined>;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n /**\n * Also drain the queue on the `periodicsync` event carrying this tag,\n * complementing the one-off `sync` replay so long-pending mutations retry\n * even without a fresh navigation. Register the periodic sync from the main\n * thread with {@link registerPeriodicSync}. Default `${queueName}-periodic`.\n */\n periodicSyncTag?: string;\n /**\n * Header names stripped before a request is persisted — and stripped again on\n * replay, so entries written by an older version never go out with the\n * credential they stored. Default {@link DEFAULT_CREDENTIAL_HEADERS}; extend it\n * for a custom credential header (`[...DEFAULT_CREDENTIAL_HEADERS,\n * \"x-tenant-key\"]`). Passing `[]` restores the pre-0.77 behavior of\n * persisting and replaying every header, credentials included.\n */\n credentialHeaders?: readonly string[];\n /**\n * Prepare each queued request right before it is replayed: return the\n * request to send (typically with the current credentials applied) or\n * `null` to drop the entry for good. A thrown error keeps the entry pending.\n * The context carries the entry's owner, so a custom hook can apply the\n * same rule as the default.\n *\n * Default: only an `\"unbound\"` entry with no stripped credentials (and, under\n * `ownerPolicy: \"lenient\"`, an `\"unknown\"` one) is replayed as-is, without\n * asking. Every other entry — credentialed or not —\n * asks every open window client in parallel (see\n * {@link provideBackgroundSyncCredentials}) and picks the answer that fits:\n * - `\"bound\"`: the answer whose owner matches; none among valid answers →\n * dropped, never sent anonymously or as somebody else;\n * - `\"unknown\"`: only when every answer lacks a principal (an app that does\n * not use `getPrincipal`); a single answer with one → dropped, since a\n * stale tab without `getPrincipal` says nothing about who is signed in\n * next to it. This holds for an entry\n * with no credential header too, since the browser attaches the cookies of\n * whoever is signed in at replay time;\n * - `\"unbound\"`: any answer, preferring one without a principal.\n * Then `null` headers drop a credentialed entry, an answer that lacks one of\n * the stripped headers keeps it pending, and only the stripped names are\n * re-applied. No valid answer at all keeps it pending until\n * `maxRetentionMinutes` (and warns once per replay in development builds) —\n * so a page that never calls {@link provideBackgroundSyncCredentials} leaves\n * every entry it queued `\"unknown\"`, and none of them is replayed.\n */\n /**\n * How an `\"unknown\"` owner is handled on an entry with no stripped\n * credentials (see {@link BackgroundSyncOwnerPolicy}). Default `\"strict\"`.\n *\n * `\"lenient\"` restores the replay-as-is of 0.77.0 and earlier for an app without sign-in,\n * where no page ever reports a principal. Do not use it with a cookie\n * session: the browser attaches on replay the cookie of whoever is signed in\n * at that moment, so a mutation queued by A whose owner was never stamped\n * (issuing tab closed, empty `clientId`, stamp lost, legacy entry) goes out\n * with B's session. Entries with stripped credentials ask the pages either\n * way. Ignored when a custom `beforeReplay` is given.\n */\n ownerPolicy?: BackgroundSyncOwnerPolicy;\n beforeReplay?: (\n request: Request,\n context: BackgroundSyncReplayContext,\n ) => Request | null | Promise<Request | null>;\n}\n\n/**\n * Move credential headers out of a header list.\n *\n * @returns The remaining headers and the lower-cased names removed.\n */\nfunction splitHeaders(\n headers: Iterable<[string, string]>,\n credentialHeaders: ReadonlySet<string>,\n): { kept: [string, string][]; stripped: string[] } {\n const kept: [string, string][] = [];\n const stripped: string[] = [];\n for (const [name, value] of headers) {\n if (credentialHeaders.has(name.toLowerCase())) stripped.push(name.toLowerCase());\n else kept.push([name, value]);\n }\n return { kept, stripped };\n}\n\n/**\n * Scrub version-1 entries during the upgrade: their credential headers were\n * stored in plaintext, so they are removed from disk on the first open, recorded\n * as stripped, and the owner is marked unknown.\n */\nfunction migrateLegacyEntries(store: IDBObjectStore, credentialHeaders: ReadonlySet<string>): void {\n const cursorRequest = store.openCursor();\n cursorRequest.onsuccess = () => {\n const cursor = cursorRequest.result;\n if (!cursor) return;\n const entry = cursor.value as QueuedRequest;\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n cursor.update({\n ...entry,\n headers: kept,\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n ownerState: entry.ownerState ?? \"unknown\",\n });\n cursor.continue();\n };\n}\n\nfunction openQueueDb(\n name: string,\n credentialHeaders: ReadonlySet<string> = credentialHeaderSet(),\n): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, DB_VERSION);\n request.onupgradeneeded = (event) => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n } else if (event.oldVersion < 2 && request.transaction) {\n migrateLegacyEntries(request.transaction.objectStore(STORE), credentialHeaders);\n }\n if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\n/** The current clear epoch: bumped by every {@link clearBackgroundSyncQueue}. */\nasync function readEpoch(name: string, credentialHeaders: ReadonlySet<string>): Promise<number> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(META, \"readonly\");\n const get = tx.objectStore(META).get(EPOCH_KEY);\n await txDone(tx);\n db.close();\n return (get.result as number | undefined) ?? 0;\n}\n\n/**\n * Add an entry unless the queue was cleared since `epoch` was read — checked in\n * the same transaction as the write, so a logout that lands while the request\n * is still failing never lets it into the next session's queue.\n *\n * @returns The new entry's key, or `undefined` when the clear won.\n */\nasync function enqueue(\n name: string,\n entry: QueuedRequest,\n epoch: number,\n credentialHeaders: ReadonlySet<string>,\n): Promise<number | undefined> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction([STORE, META], \"readwrite\");\n let id: number | undefined;\n const current = tx.objectStore(META).get(EPOCH_KEY);\n current.onsuccess = () => {\n if (((current.result as number | undefined) ?? 0) !== epoch) return;\n const add = tx.objectStore(STORE).add(entry);\n add.onsuccess = () => {\n id = add.result as number;\n };\n };\n await txDone(tx);\n db.close();\n return id;\n}\n\n/**\n * Record how an entry is owned. A no-op when the entry is already gone\n * (replayed, or the queue was cleared).\n */\nasync function stampOwner(\n name: string,\n id: number,\n ownerState: BackgroundSyncOwnerState,\n owner: string | null | undefined,\n): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n const store = tx.objectStore(STORE);\n const get = store.get(id);\n get.onsuccess = () => {\n const entry = get.result as QueuedRequest | undefined;\n if (!entry) return;\n entry.ownerState = ownerState;\n if (ownerState === \"bound\") entry.owner = owner ?? null;\n store.put(entry);\n };\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(\n name: string,\n credentialHeaders: ReadonlySet<string>,\n): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\n/** Whether an entry is still in the queue — `false` once it was cleared. */\nasync function stillQueued(name: string, id: number): Promise<boolean> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const count = tx.objectStore(STORE).count(id);\n await txDone(tx);\n db.close();\n return count.result > 0;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\n/**\n * Serialize a request for the queue, leaving out every credential header and\n * recording which ones were present.\n */\nasync function serializeRequest(\n request: Request,\n timestamp: number,\n credentialHeaders: ReadonlySet<string>,\n ownerState: QueuedRequest[\"ownerState\"],\n): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n const { kept, stripped } = splitHeaders(request.headers.entries(), credentialHeaders);\n return {\n url: request.url,\n method: request.method,\n headers: kept,\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n credentials: request.credentials,\n strippedHeaders: stripped,\n ownerState,\n };\n}\n\n/**\n * Rebuild a stored request, stripping credential headers once more so an entry\n * that still holds one (a custom `credentialHeaders` the migration did not know)\n * never replays it.\n */\nfunction deserializeRequest(\n entry: QueuedRequest,\n credentialHeaders: ReadonlySet<string>,\n): { request: Request; strippedHeaders: string[] } {\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n return {\n request: new Request(entry.url, {\n method: entry.method,\n headers: kept,\n body: entry.body ?? undefined,\n credentials: entry.credentials,\n }),\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n };\n}\n\n/** A window client's parsed answer. */\ninterface ClientAnswer {\n headers: Record<string, string> | null;\n /** Whether the page has `getPrincipal`. */\n hasPrincipal: boolean;\n owner: string | null;\n}\n\n/**\n * Ask one window client about a queued request over a `MessageChannel`.\n *\n * @returns The parsed answer, or `undefined` when the client stayed silent until\n * `deadline`, answered `{ error: true }`, or answered something unrecognizable.\n */\nasync function askClient(\n client: WindowClientLike,\n request: BackgroundSyncCredentialsRequest,\n deadline: Promise<void>,\n): Promise<ClientAnswer | undefined> {\n const channel = new MessageChannel();\n const answer = await Promise.race([\n new Promise<unknown>((resolve) => {\n channel.port1.onmessage = (event: MessageEvent) => resolve(event.data);\n client.postMessage({ type: BACKGROUND_SYNC_CREDENTIALS_MESSAGE, ...request }, [\n channel.port2,\n ]);\n }),\n deadline.then(() => undefined),\n ]);\n channel.port1.close();\n if (answer === null || typeof answer !== \"object\" || !(\"headers\" in answer)) return undefined;\n const { headers, owner } = answer as { headers: unknown; owner?: unknown };\n const hasPrincipal = \"owner\" in answer;\n if (hasPrincipal && typeof owner !== \"string\" && owner !== null) return undefined;\n return {\n headers:\n headers !== null && typeof headers === \"object\"\n ? (headers as Record<string, string>)\n : null,\n hasPrincipal,\n owner: hasPrincipal ? (owner as string | null) : null,\n };\n}\n\n/** A deadline shared by every client asked in one round. */\nfunction startDeadline(): { promise: Promise<void>; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const promise = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CREDENTIALS_TIMEOUT_MS);\n });\n return { promise, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Ask every open window client in parallel, under one shared deadline.\n *\n * @returns Every valid answer; empty when nobody answered.\n */\nasync function askAllClients(\n sw: BgSwGlobal,\n request: BackgroundSyncCredentialsRequest,\n): Promise<ClientAnswer[]> {\n const clients = (await sw.clients?.matchAll({ type: \"window\" })) ?? [];\n if (clients.length === 0) return [];\n const deadline = startDeadline();\n const answers = await Promise.all(\n clients.map((client) => askClient(client, request, deadline.promise)),\n );\n deadline.cancel();\n return answers.filter((answer): answer is ClientAnswer => answer !== undefined);\n}\n\n/** State of one replay pass: answers cached per URL + method, and the warning flag. */\ninterface ReplayRun {\n ask(request: Request): Promise<ClientAnswer[]>;\n warnNoAnswer(): void;\n}\n\nfunction createReplayRun(sw: BgSwGlobal): ReplayRun {\n const answers = new Map<string, Promise<ClientAnswer[]>>();\n let warned = false;\n return {\n ask(request) {\n const key = `${request.method} ${request.url}`;\n let pending = answers.get(key);\n if (!pending) {\n pending = askAllClients(sw, {\n url: request.url,\n method: request.method,\n phase: \"replay\",\n });\n answers.set(key, pending);\n }\n return pending;\n },\n warnNoAnswer() {\n if (warned || !isDevBuild()) return;\n warned = true;\n console.warn(\n \"[tempest-react-sdk/sw] background-sync: a queued request needs an open page \" +\n \"to confirm who is signed in or to supply the current credentials, and no \" +\n \"open page answered. Call \" +\n \"provideBackgroundSyncCredentials() in the page; the entry stays pending.\",\n );\n },\n };\n}\n\n/**\n * Pick the answer an entry may be replayed with, per its owner state.\n *\n * An `\"unknown\"` owner replays only when every valid answer lacks a principal:\n * one tab reporting a principal (even `null`) is enough to drop it, because a\n * principal-less answer — say a tab still running a bundle from before the app\n * adopted `getPrincipal` — says nothing about whose cookie the replay carries.\n */\nfunction chooseAnswer(\n answers: readonly ClientAnswer[],\n context: BackgroundSyncReplayContext,\n): ClientAnswer | undefined {\n switch (context.ownerState) {\n case \"bound\":\n return answers.find((answer) => answer.hasPrincipal && answer.owner === context.owner);\n case \"unknown\":\n return answers.every((answer) => !answer.hasPrincipal) ? answers[0] : undefined;\n case \"unbound\":\n return answers.find((answer) => !answer.hasPrincipal) ?? answers[0];\n }\n}\n\n/**\n * The default `beforeReplay` (rules on {@link InstallBackgroundSyncOptions}).\n *\n * @throws {Error} When no page answered, or the chosen answer lacks a stripped\n * header — the entry stays pending.\n */\nasync function defaultBeforeReplay(\n run: ReplayRun,\n request: Request,\n context: BackgroundSyncReplayContext,\n ownerPolicy: BackgroundSyncOwnerPolicy,\n): Promise<Request | null> {\n const credentialed = context.strippedHeaders.length > 0;\n const unchecked =\n context.ownerState === \"unbound\" ||\n (ownerPolicy === \"lenient\" && context.ownerState === \"unknown\");\n if (!credentialed && unchecked) return request;\n const answers = await run.ask(request);\n if (answers.length === 0) {\n run.warnNoAnswer();\n throw new Error(\"background-sync: no client answered\");\n }\n const chosen = chooseAnswer(answers, context);\n if (!chosen) return null;\n if (!credentialed) return request;\n if (chosen.headers === null) return null;\n const provided = new Map(\n Object.entries(chosen.headers).map(([name, value]) => [name.toLowerCase(), value]),\n );\n if (context.strippedHeaders.some((name) => !provided.has(name))) {\n throw new Error(\"background-sync: the answer lacks a stripped credential header\");\n }\n const headers = new Headers(request.headers);\n for (const name of context.strippedHeaders) headers.set(name, provided.get(name) as string);\n return new Request(request, { headers });\n}\n\n/** Everything {@link replayQueue} needs besides the clock. */\ninterface ReplayConfig {\n sw: BgSwGlobal;\n name: string;\n maxRetentionMs: number;\n credentialHeaders: ReadonlySet<string>;\n beforeReplay?: InstallBackgroundSyncOptions[\"beforeReplay\"];\n ownerPolicy: BackgroundSyncOwnerPolicy;\n}\n\n/**\n * Replay every queued request once. Entries that succeed, are stale, get a 4xx\n * (a client error that will not fix itself) or that the preparation rejects with\n * `null` are removed; entries that fail again — network error, 5xx, or a\n * preparation that throws — are kept, and so is an entry whose owner is still\n * being stamped (for up to {@link OWNER_STAMP_GRACE_MS}). Each entry is checked\n * against the store right before it is sent, so a queue cleared mid-replay stops\n * the replay. Throws if any entry is still pending, so a `sync` handler keeps\n * the sync registered.\n */\nasync function replayQueue(config: ReplayConfig, now: number): Promise<void> {\n const { sw, name, maxRetentionMs, credentialHeaders, beforeReplay, ownerPolicy } = config;\n const run = createReplayRun(sw);\n const prepare =\n beforeReplay ??\n ((request: Request, context: BackgroundSyncReplayContext) =>\n defaultBeforeReplay(run, request, context, ownerPolicy));\n const entries = await readAll(name, credentialHeaders);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n const state = entry.ownerState ?? \"unknown\";\n if (state === \"pending\" && now - entry.timestamp < OWNER_STAMP_GRACE_MS) {\n pending += 1;\n continue;\n }\n const ownerState: BackgroundSyncOwnerState = state === \"pending\" ? \"unknown\" : state;\n try {\n const { request: stored, strippedHeaders } = deserializeRequest(\n entry,\n credentialHeaders,\n );\n const request = await prepare(stored, {\n queuedAt: entry.timestamp,\n strippedHeaders,\n ownerState,\n owner: ownerState === \"bound\" ? (entry.owner ?? null) : undefined,\n });\n if (!(await stillQueued(name, entry.id))) continue;\n if (request === null) {\n await remove(name, entry.id);\n continue;\n }\n const response = await fetch(request);\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\n/**\n * The replay in flight per queue. `sync`, `periodicsync` and the Safari fallback\n * can fire together; sharing one pass keeps a mutation from being sent twice.\n */\nconst replaysInFlight = new Map<string, Promise<void>>();\n\nfunction drainQueue(config: ReplayConfig): Promise<void> {\n const running = replaysInFlight.get(config.name);\n if (running) return running;\n const pass = replayQueue(config, Date.now()).finally(() => {\n replaysInFlight.delete(config.name);\n });\n replaysInFlight.set(config.name, pass);\n return pass;\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Ask the issuing page who owns a just-queued entry and record it.\n *\n * @returns Resolves once the owner is stamped; never rejects.\n */\nasync function stampFromIssuer(\n name: string,\n id: number,\n issuer: WindowClientLike,\n request: Request,\n): Promise<void> {\n const deadline = startDeadline();\n const answer = await askClient(\n issuer,\n { url: request.url, method: request.method, phase: \"enqueue\" },\n deadline.promise,\n );\n deadline.cancel();\n const state: BackgroundSyncOwnerState = !answer\n ? \"unknown\"\n : answer.hasPrincipal\n ? \"bound\"\n : \"unbound\";\n await stampOwner(name, id, state, answer?.owner);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB (without its credential headers) and a sync is\n * registered; the original fetch still rejects (so your app can show an offline\n * state), and the request is replayed later when the network returns.\n *\n * Right after queueing, the worker asks the page that issued the request who is\n * signed in (`getPrincipal` on {@link provideBackgroundSyncCredentials}) and\n * stamps the entry with that owner, without delaying the rejection. The work is\n * handed to `event.waitUntil` synchronously, so the worker stays alive for it\n * in every engine. Without the Background Sync API (every non-Chromium\n * browser), the queue is drained opportunistically whenever a `GET` goes\n * through the worker.\n *\n * @tempest-limits empty-catch — `registration.sync.register` is unavailable on\n * every non-Chromium browser and fails on a revoked background-sync permission.\n * The entry is already durable in IndexedDB at that point, and the queue is also\n * drained opportunistically on the next successful request, so losing the OS-level\n * wakeup degrades *when* the replay happens, not *whether* it happens.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const {\n match,\n queueName = DEFAULT_QUEUE_NAME,\n maxRetentionMinutes = 1440,\n periodicSyncTag = `${options.queueName ?? DEFAULT_QUEUE_NAME}-periodic`,\n credentialHeaders = DEFAULT_CREDENTIAL_HEADERS,\n beforeReplay,\n ownerPolicy = \"strict\",\n } = options;\n const stripped = credentialHeaderSet(credentialHeaders);\n const replay: ReplayConfig = {\n sw,\n name: queueName,\n maxRetentionMs: maxRetentionMinutes * 60 * 1000,\n credentialHeaders: stripped,\n beforeReplay,\n ownerPolicy,\n };\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n const epoch = readEpoch(queueName, stripped);\n epoch.catch(() => undefined);\n const attempt = fetch(request.clone());\n const queued = attempt.then(\n () => undefined,\n async () => {\n const issuer = event.clientId ? await sw.clients?.get(event.clientId) : undefined;\n const entry = await serializeRequest(\n request,\n Date.now(),\n stripped,\n issuer ? \"pending\" : \"unknown\",\n );\n const id = await enqueue(queueName, entry, await epoch, stripped);\n if (id === undefined) return undefined;\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n /* empty */\n }\n return issuer ? { id, issuer } : undefined;\n },\n );\n event.respondWith(\n attempt.catch(async (error: unknown) => {\n await queued;\n throw error;\n }),\n );\n event.waitUntil(\n queued\n .then((stamp) =>\n stamp ? stampFromIssuer(queueName, stamp.id, stamp.issuer, request) : undefined,\n )\n .catch(() => undefined),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(drainQueue(replay));\n });\n\n sw.addEventListener(\"periodicsync\", (event) => {\n if (event.tag !== periodicSyncTag) return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return;\n if (event.request.method !== \"GET\") return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n}\n\n/**\n * Empty the background-sync queue — every request still waiting to be replayed —\n * and bump its clear epoch. Call it on logout (or use `clearSessionData()`, which\n * also clears the runtime caches) so mutations made under one session are never\n * replayed under the next.\n *\n * Works from the page and from the worker, and reaches work already in flight\n * in the worker: a replay checks each entry right before sending it, and a\n * request still failing when the queue is cleared is not written afterwards.\n *\n * @param queueName - The `queueName` given to {@link installBackgroundSync}.\n * Default `tempest-bg-sync`.\n * @returns `true` once the queue is empty; `false` when IndexedDB is\n * unavailable (SSR, old browsers).\n *\n * @example\n * import { clearBackgroundSyncQueue } from \"tempest-react-sdk/sw\";\n *\n * await clearBackgroundSyncQueue();\n */\nexport async function clearBackgroundSyncQueue(\n queueName: string = DEFAULT_QUEUE_NAME,\n): Promise<boolean> {\n if (typeof indexedDB === \"undefined\") return false;\n const db = await openQueueDb(queueName);\n const tx = db.transaction([STORE, META], \"readwrite\");\n tx.objectStore(STORE).clear();\n const meta = tx.objectStore(META);\n const current = meta.get(EPOCH_KEY);\n current.onsuccess = () => {\n meta.put(((current.result as number | undefined) ?? 0) + 1, EPOCH_KEY);\n };\n await txDone(tx);\n db.close();\n return true;\n}\n\n/**\n * One-way fingerprint of a principal: hex SHA-256, so the queue can compare\n * owners without ever holding the id itself.\n *\n * @returns The fingerprint, or `null` when nobody is signed in.\n */\nasync function ownerFingerprint(principal: string | null | undefined): Promise<string | null> {\n if (principal === null || principal === undefined || principal === \"\") return null;\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`tempest-bg-sync:${principal}`),\n );\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Answer the worker's questions about queued requests (see `beforeReplay` on\n * {@link installBackgroundSync}). Install it once in every page, next to your\n * auth setup; it reads the token at replay time, so the queue never has to store\n * it. Without it, a queued request that carried a credential header is never\n * replayed.\n *\n * `getHeaders` must return **every** credential header the app sends (the worker\n * keeps an entry pending when one it stripped is missing), or `null` when there\n * is no session — the worker then drops the entry instead of replaying it\n * anonymously. A throw from `getHeaders` or `getPrincipal` is answered as an\n * explicit `{ error: true }`. The worker only applies headers whose names the\n * original request carried, so returning `Authorization` for every URL never\n * leaks it to a URL that did not receive it in the first place.\n *\n * Pass `getPrincipal` to bind each entry to whoever queued it: the worker asks\n * the issuing tab right after queueing, asks every tab again before replaying,\n * and drops the entry when no signed-in tab is its owner.\n *\n * @param getHeaders - Resolves the headers for one queued request at replay.\n * @param options - `getPrincipal` binds entries to their owner.\n * @returns A function that removes the listener. A no-op outside the browser.\n *\n * @example\n * import { provideBackgroundSyncCredentials } from \"tempest-react-sdk/sw\";\n *\n * const stop = provideBackgroundSyncCredentials(\n * () => {\n * const token = localStorage.getItem(\"token\");\n * return token ? { Authorization: `Bearer ${token}` } : null;\n * },\n * { getPrincipal: () => localStorage.getItem(\"userId\") },\n * );\n */\nexport function provideBackgroundSyncCredentials(\n getHeaders: BackgroundSyncCredentialsProvider,\n options: ProvideBackgroundSyncCredentialsOptions = {},\n): () => void {\n if (typeof navigator === \"undefined\" || !navigator.serviceWorker) return () => undefined;\n const container = navigator.serviceWorker;\n const { getPrincipal } = options;\n const onMessage = (event: MessageEvent): void => {\n const data = event.data as Partial<BackgroundSyncCredentialsRequest> & { type?: unknown };\n const port = event.ports[0];\n if (data?.type !== BACKGROUND_SYNC_CREDENTIALS_MESSAGE || !port) return;\n const request: BackgroundSyncCredentialsRequest = {\n url: String(data.url),\n method: String(data.method),\n phase: data.phase === \"enqueue\" ? \"enqueue\" : \"replay\",\n };\n void (async () => {\n try {\n const headers = request.phase === \"enqueue\" ? null : await getHeaders(request);\n const answer: { headers: Record<string, string> | null; owner?: string | null } = {\n headers,\n };\n if (getPrincipal) answer.owner = await ownerFingerprint(await getPrincipal());\n port.postMessage(answer);\n } catch {\n port.postMessage({ error: true });\n }\n })();\n };\n container.addEventListener(\"message\", onMessage);\n return () => container.removeEventListener(\"message\", onMessage);\n}\n"],"mappings":";;;AA4DA,SAASA,IAAyB;CAC9B,OAAO;AACX;AAgDA,IAAMC,IAAqB,mBAOrBC,IAAa,GACbC,IAAQ,YACRC,IAAO,QACPC,IAAY,SAMLC,IAAsC,+BAG7CC,IAAyB,KAMzBC,IAAuBD,IAAyB;AAkItD,SAASE,EACL,GACA,GACgD;CAChD,IAAMC,IAA2B,CAAC,GAC5BC,IAAqB,CAAC;CAC5B,KAAK,IAAM,CAACC,GAAMC,MAAUC,GACxB,AAAIC,EAAkB,IAAIH,EAAK,YAAY,CAAC,IAAGD,EAAS,KAAKC,EAAK,YAAY,CAAC,IAC1EF,EAAK,KAAK,CAACE,GAAMC,CAAK,CAAC;CAEhC,OAAO;EAAE;EAAM;CAAS;AAC5B;AAOA,SAASG,EAAqB,GAAuB,GAA8C;CAC/F,IAAMC,IAAg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O,CAAC,GAAG,IAAI,WAAWC,CAAM,CAAC,CAAC,CAAC,KAAK,MAASC,EAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAChG;AAoCA,SAAgBC,EACZ,GACA,IAAmD,CAAC,GAC1C;CACV,IAAI,OAAO,YAAc,OAAe,CAAC,UAAU,eAAe,aAAa,KAAA;CAC/E,IAAMC,IAAY,UAAU,eACtB,EAAE,oBAAiBjB,GACnBkB,KAAa,MAA8B;EAC7C,IAAMC,IAAOzF,EAAM,MACb0F,IAAO1F,EAAM,MAAM;EACzB,IAAIyF,GAAM,SAAA,iCAAgD,CAACC,GAAM;EACjE,IAAM5F,IAA4C;GAC9C,KAAK,OAAO2F,EAAK,GAAG;GACpB,QAAQ,OAAOA,EAAK,MAAM;GAC1B,OAAOA,EAAK,UAAU,YAAY,YAAY;EAClD;EACA,CAAM,YAAY;GACd,IAAI;IAEA,IAAM/D,IAA4E,EAC9E,SAFY5B,EAAQ,UAAU,YAAY,OAAO,MAAM6F,EAAW7F,CAAO,EAG7E;IAEA,AADI8F,MAAc,EAAO,QAAQ,MAAMV,EAAiB,MAAMU,EAAa,CAAC,IAC5EF,EAAK,YAAYhE,CAAM;GAC3B,QAAQ;IACJ,EAAK,YAAY,EAAE,OAAO,GAAK,CAAC;GACpC;EACJ,EAAA,CAAG;CACP;CAEA,OADA6D,EAAU,iBAAiB,WAAWC,CAAS,SAClCD,EAAU,oBAAoB,WAAWC,CAAS;AACnE"}
1
+ {"version":3,"file":"background-sync.js","names":["getSwScope","DEFAULT_QUEUE_NAME","DB_VERSION","STORE","META","EPOCH_KEY","BACKGROUND_SYNC_CREDENTIALS_MESSAGE","CREDENTIALS_TIMEOUT_MS","OWNER_STAMP_GRACE_MS","splitHeaders","kept","stripped","name","value","headers","credentialHeaders","migrateLegacyEntries","cursorRequest","store","cursor","entry","openQueueDb","credentialHeaderSet","request","db","event","resolve","reject","txDone","tx","readEpoch","get","enqueue","id","current","epoch","add","stampOwner","ownerState","owner","readAll","all","req","stillQueued","count","remove","serializeRequest","buffer","deserializeRequest","askClient","channel","answer","client","deadline","hasPrincipal","startDeadline","timer","askAllClients","clients","sw","answers","createReplayRun","outOfScope","warned","key","pending","isDevBuild","origin","url","chooseAnswer","context","defaultBeforeReplay","credentialed","unchecked","ownerPolicy","run","chosen","provided","carriesCredential","replayQueue","config","prepare","beforeReplay","entries","now","maxRetentionMs","state","stored","strippedHeaders","inCredentialScope","response","replaysInFlight","drainQueue","running","pass","matches","match","stampFromIssuer","issuer","installBackgroundSync","options","DEFAULT_CREDENTIAL_HEADERS","workerOrigin","replay","queueName","maxRetentionMinutes","isTrustedCredentialTarget","trustedOrigins","attempt","queued","error","stamp","periodicSyncTag","clearBackgroundSyncQueue","meta","ownerFingerprint","principal","digest","byte","provideBackgroundSyncCredentials","container","getPrincipal","onMessage","data","port","getHeaders"],"sources":["../../src/sw/background-sync.ts"],"sourcesContent":["/**\n * Background-sync helper: queue failed mutating requests (POST/PUT/PATCH/DELETE)\n * while offline and replay them when connectivity returns. A dependency-free\n * take on Workbox's `BackgroundSyncPlugin`, backed by a tiny IndexedDB queue.\n *\n * Import inside your `sw.ts`. Uses the Background Sync API (`registration.sync`)\n * when available, and also replays opportunistically on the next request as a\n * fallback for browsers without it (e.g. Safari).\n *\n * Credential headers (`Authorization` and the rest of\n * {@link DEFAULT_CREDENTIAL_HEADERS}) are never written to IndexedDB: the queue\n * outlives the session, and a stored bearer stayed readable after logout and was\n * replayed with the old identity (reproduced in Chromium 153, 11/10/2026). On\n * replay the worker asks the open pages for the *current* credentials — see\n * {@link provideBackgroundSyncCredentials} — or a custom `beforeReplay` hook.\n * Credentials carried in the URL or the body are out of reach and are stored\n * as sent.\n *\n * @example\n * import { installBackgroundSync } from \"tempest-react-sdk/sw\";\n *\n * installBackgroundSync({ match: (url) => url.pathname.startsWith(\"/api/\") });\n */\nimport { isTrustedCredentialTarget } from \"../http/credential-scope\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport { DEFAULT_CREDENTIAL_HEADERS, credentialHeaderSet } from \"./credential-headers\";\n\ninterface SyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface BgFetchEventLike {\n request: Request;\n /** Id of the window client that issued the request, when there is one. */\n clientId?: string;\n respondWith(response: Response | Promise<Response>): void;\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface PeriodicSyncEventLike {\n tag: string;\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/** Minimal shape of a window client the worker can message. */\ninterface WindowClientLike {\n postMessage(message: unknown, transfer: Transferable[]): void;\n}\n\ninterface BgSwGlobal {\n registration: { sync?: { register(tag: string): Promise<void> } };\n clients?: {\n matchAll(options: { type: \"window\" }): Promise<readonly WindowClientLike[]>;\n get(id: string): Promise<WindowClientLike | undefined>;\n };\n addEventListener(type: \"sync\", listener: (event: SyncEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: BgFetchEventLike) => void): void;\n addEventListener(type: \"periodicsync\", listener: (event: PeriodicSyncEventLike) => void): void;\n}\n\nfunction getSwScope(): BgSwGlobal {\n return globalThis as unknown as BgSwGlobal;\n}\n\n/**\n * How an entry is tied to whoever queued it:\n * - `\"bound\"`: the issuing page reported a principal (or `null` for nobody);\n * the entry only goes out while the same one is signed in.\n * - `\"unbound\"`: the issuing page answered without `getPrincipal`.\n * - `\"unknown\"`: nobody could say — no issuing tab, no answer, an error, or an\n * entry written before owners existed. Fails closed, with or without stripped\n * credentials: a cookie session rides along on the replay, so an entry with no\n * credential header is checked like any other.\n *\n * While the worker is still asking, the stored state is `\"pending\"`, which a\n * replay never sees: it waits, then reads a stamp that never came as `\"unknown\"`.\n */\nexport type BackgroundSyncOwnerState = \"bound\" | \"unbound\" | \"unknown\";\n\n/**\n * How the default `beforeReplay` treats an `\"unknown\"` owner on an entry that\n * carried no credential header:\n * - `\"strict\"` (default): it asks the open pages like any other entry — replayed\n * only when every answer lacks a principal, dropped as soon as one answer has\n * one, pending while nobody answers.\n * - `\"lenient\"`: it is replayed as-is, without asking (the behavior up to 0.77.0).\n *\n * An entry with stripped credentials always asks, under either policy.\n */\nexport type BackgroundSyncOwnerPolicy = \"strict\" | \"lenient\";\n\n/** A serialized request stored in the queue. */\ninterface QueuedRequest {\n id?: number;\n url: string;\n method: string;\n headers: [string, string][];\n body: ArrayBuffer | null;\n timestamp: number;\n /** The original `credentials` mode, so cookie-based APIs replay with cookies. */\n credentials?: RequestCredentials;\n /** Lower-cased names of the credential headers removed before persisting. */\n strippedHeaders?: string[];\n /** Absent on entries written before 0.77 — read as `\"unknown\"`. */\n ownerState?: BackgroundSyncOwnerState | \"pending\";\n /** Fingerprint of the principal under `\"bound\"`; `null` for \"nobody signed in\". */\n owner?: string | null;\n}\n\n/** Default IndexedDB database name (and sync tag) of the background-sync queue. */\nconst DEFAULT_QUEUE_NAME = \"tempest-bg-sync\";\n\n/**\n * Schema version of the queue database. Version 2 adds the `meta` store (the\n * clear epoch) and migrates version-1 entries, scrubbing their plaintext\n * credential headers on first open.\n */\nconst DB_VERSION = 2;\nconst STORE = \"requests\";\nconst META = \"meta\";\nconst EPOCH_KEY = \"epoch\";\n\n/**\n * `type` of the message the worker posts to window clients to ask about a queued\n * request. Answered by {@link provideBackgroundSyncCredentials}.\n */\nexport const BACKGROUND_SYNC_CREDENTIALS_MESSAGE = \"tempest:bg-sync-credentials\";\n\n/** How long the worker waits for the window clients to answer, in milliseconds. */\nconst CREDENTIALS_TIMEOUT_MS = 3000;\n\n/**\n * How long a replay waits on an entry whose owner is still being stamped. Past\n * it (the worker died mid-question), the owner is read as `\"unknown\"`.\n */\nconst OWNER_STAMP_GRACE_MS = CREDENTIALS_TIMEOUT_MS * 2;\n\n/** What a queued request looked like when it was stored, passed to `beforeReplay`. */\nexport interface BackgroundSyncReplayContext {\n /** Epoch milliseconds of the original failed attempt. */\n queuedAt: number;\n /** Lower-cased credential header names stripped before the entry was stored. */\n strippedHeaders: readonly string[];\n /** How the entry is tied to its owner. */\n ownerState: BackgroundSyncOwnerState;\n /** Owner fingerprint under `\"bound\"` (`null` for nobody); `undefined` otherwise. */\n owner: string | null | undefined;\n}\n\n/** The request a window client is asked about, as sent by the worker. */\nexport interface BackgroundSyncCredentialsRequest {\n /** Absolute URL of the queued request. */\n url: string;\n /** HTTP method of the queued request. */\n method: string;\n /**\n * `\"enqueue\"` when the worker only wants the owner of a request that just\n * failed; `\"replay\"` when it is about to send it and needs the credentials.\n */\n phase: \"enqueue\" | \"replay\";\n}\n\n/**\n * Resolve the credentials for a queued request: a header record to apply, or\n * `null` when there is no session (the entry is then dropped).\n */\nexport type BackgroundSyncCredentialsProvider = (\n request: BackgroundSyncCredentialsRequest,\n) => Record<string, string> | null | Promise<Record<string, string> | null>;\n\n/** Options for {@link provideBackgroundSyncCredentials}. */\nexport interface ProvideBackgroundSyncCredentialsOptions {\n /**\n * Who is signed in right now — a stable, non-secret id such as the user id;\n * `null`/`undefined` when nobody is. Read when a request is queued and again\n * when it is replayed: an entry is only sent while the same principal is\n * signed in, and dropped otherwise, so a mutation queued by one account is\n * never sent with another account's credentials even when the app forgets\n * `clearSessionData()` on logout. Only a SHA-256 fingerprint reaches the\n * queue, never the value itself. A throw is answered as an explicit error,\n * which leaves the owner unknown (fail closed).\n */\n getPrincipal?: () => string | null | undefined | Promise<string | null | undefined>;\n}\n\n/** Options for {@link installBackgroundSync}. */\nexport interface InstallBackgroundSyncOptions {\n /**\n * Which requests to queue on failure. A `RegExp` against the URL or a\n * predicate. Only non-`GET` requests are ever considered. Default: all\n * non-`GET` requests.\n */\n match?: RegExp | ((url: URL, request: Request) => boolean);\n /** IndexedDB database name, also used as the sync tag. Default `tempest-bg-sync`. */\n queueName?: string;\n /** Drop queued requests older than this (minutes) on replay. Default `1440` (24h). */\n maxRetentionMinutes?: number;\n /**\n * Also drain the queue on the `periodicsync` event carrying this tag,\n * complementing the one-off `sync` replay so long-pending mutations retry\n * even without a fresh navigation. Register the periodic sync from the main\n * thread with {@link registerPeriodicSync}. Default `${queueName}-periodic`.\n */\n periodicSyncTag?: string;\n /**\n * Header names stripped before a request is persisted — and stripped again on\n * replay, so entries written by an older version never go out with the\n * credential they stored. Default {@link DEFAULT_CREDENTIAL_HEADERS}; extend it\n * for a custom credential header (`[...DEFAULT_CREDENTIAL_HEADERS,\n * \"x-tenant-key\"]`). Passing `[]` restores the pre-0.77 behavior of\n * persisting and replaying every header, credentials included.\n */\n credentialHeaders?: readonly string[];\n /**\n * Origins besides the worker's own that a replayed request may carry a\n * credential header to — typically the API host when it is not the app's\n * origin (`[\"https://api.acme.com\"]`). Default `[]`: only the worker's origin.\n *\n * A credential re-applied at replay comes from the page, so it is the app's\n * credential, whatever the request originally carried under the same header\n * name. Before 0.81.0 the worker checked only the name, and a mutation to a\n * third party that failed offline carrying that party's `Authorization` was\n * replayed to it with the app's bearer (#523). Now, with the rule\n * `isTrustedCredentialTarget` enforces on the live `ApiClient`:\n * - an entry that carried a credential header to an origin outside this\n * scope is dropped before `beforeReplay` runs — re-sending it without the\n * credential would be a request the app never made, and with the app's\n * credential, a leak;\n * - a request returned by `beforeReplay` (custom or default) that carries a\n * header from `credentialHeaders` to an origin outside this scope is\n * dropped instead of sent.\n *\n * Both drops warn once per origin per replay in development builds. Entries\n * with no credential header are not affected: the browser attaches that\n * origin's own cookies, as it did on the original attempt.\n */\n trustedOrigins?: readonly string[];\n /**\n * How an `\"unknown\"` owner is handled on an entry with no stripped\n * credentials (see {@link BackgroundSyncOwnerPolicy}). Default `\"strict\"`.\n *\n * `\"lenient\"` restores the replay-as-is of 0.77.0 and earlier for an app without sign-in,\n * where no page ever reports a principal. Do not use it with a cookie\n * session: the browser attaches on replay the cookie of whoever is signed in\n * at that moment, so a mutation queued by A whose owner was never stamped\n * (issuing tab closed, empty `clientId`, stamp lost, legacy entry) goes out\n * with B's session. Entries with stripped credentials ask the pages either\n * way. Ignored when a custom `beforeReplay` is given.\n */\n ownerPolicy?: BackgroundSyncOwnerPolicy;\n /**\n * Prepare each queued request right before it is replayed: return the\n * request to send (typically with the current credentials applied) or\n * `null` to drop the entry for good. A thrown error keeps the entry pending.\n * The context carries the entry's owner, so a custom hook can apply the\n * same rule as the default.\n *\n * Default: only an `\"unbound\"` entry with no stripped credentials (and, under\n * `ownerPolicy: \"lenient\"`, an `\"unknown\"` one) is replayed as-is, without\n * asking. Every other entry — credentialed or not —\n * asks every open window client in parallel (see\n * {@link provideBackgroundSyncCredentials}) and picks the answer that fits:\n * - `\"bound\"`: the answer whose owner matches; none among valid answers →\n * dropped, never sent anonymously or as somebody else;\n * - `\"unknown\"`: only when every answer lacks a principal (an app that does\n * not use `getPrincipal`); a single answer with one → dropped, since a\n * stale tab without `getPrincipal` says nothing about who is signed in\n * next to it. This holds for an entry\n * with no credential header too, since the browser attaches the cookies of\n * whoever is signed in at replay time;\n * - `\"unbound\"`: any answer, preferring one without a principal.\n * Then `null` headers drop a credentialed entry, an answer that lacks one of\n * the stripped headers keeps it pending, and only the stripped names are\n * re-applied. No valid answer at all keeps it pending until\n * `maxRetentionMinutes` (and warns once per replay in development builds) —\n * so a page that never calls {@link provideBackgroundSyncCredentials} leaves\n * every entry it queued `\"unknown\"`, and none of them is replayed.\n *\n * Whatever the hook returns is still held to `trustedOrigins`: a credential\n * header bound for an origin outside the worker's own and `trustedOrigins` is\n * never sent.\n */\n beforeReplay?: (\n request: Request,\n context: BackgroundSyncReplayContext,\n ) => Request | null | Promise<Request | null>;\n}\n\n/**\n * Move credential headers out of a header list.\n *\n * @returns The remaining headers and the lower-cased names removed.\n */\nfunction splitHeaders(\n headers: Iterable<[string, string]>,\n credentialHeaders: ReadonlySet<string>,\n): { kept: [string, string][]; stripped: string[] } {\n const kept: [string, string][] = [];\n const stripped: string[] = [];\n for (const [name, value] of headers) {\n if (credentialHeaders.has(name.toLowerCase())) stripped.push(name.toLowerCase());\n else kept.push([name, value]);\n }\n return { kept, stripped };\n}\n\n/**\n * Scrub version-1 entries during the upgrade: their credential headers were\n * stored in plaintext, so they are removed from disk on the first open, recorded\n * as stripped, and the owner is marked unknown.\n */\nfunction migrateLegacyEntries(store: IDBObjectStore, credentialHeaders: ReadonlySet<string>): void {\n const cursorRequest = store.openCursor();\n cursorRequest.onsuccess = () => {\n const cursor = cursorRequest.result;\n if (!cursor) return;\n const entry = cursor.value as QueuedRequest;\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n cursor.update({\n ...entry,\n headers: kept,\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n ownerState: entry.ownerState ?? \"unknown\",\n });\n cursor.continue();\n };\n}\n\nfunction openQueueDb(\n name: string,\n credentialHeaders: ReadonlySet<string> = credentialHeaderSet(),\n): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, DB_VERSION);\n request.onupgradeneeded = (event) => {\n const db = request.result;\n if (!db.objectStoreNames.contains(STORE)) {\n db.createObjectStore(STORE, { keyPath: \"id\", autoIncrement: true });\n } else if (event.oldVersion < 2 && request.transaction) {\n migrateLegacyEntries(request.transaction.objectStore(STORE), credentialHeaders);\n }\n if (!db.objectStoreNames.contains(META)) db.createObjectStore(META);\n };\n request.onsuccess = () => {\n const db = request.result;\n db.onversionchange = () => db.close();\n resolve(db);\n };\n request.onerror = () => reject(request.error);\n });\n}\n\nfunction txDone(tx: IDBTransaction): Promise<void> {\n return new Promise((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n tx.onabort = () => reject(tx.error);\n });\n}\n\n/** The current clear epoch: bumped by every {@link clearBackgroundSyncQueue}. */\nasync function readEpoch(name: string, credentialHeaders: ReadonlySet<string>): Promise<number> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(META, \"readonly\");\n const get = tx.objectStore(META).get(EPOCH_KEY);\n await txDone(tx);\n db.close();\n return (get.result as number | undefined) ?? 0;\n}\n\n/**\n * Add an entry unless the queue was cleared since `epoch` was read — checked in\n * the same transaction as the write, so a logout that lands while the request\n * is still failing never lets it into the next session's queue.\n *\n * @returns The new entry's key, or `undefined` when the clear won.\n */\nasync function enqueue(\n name: string,\n entry: QueuedRequest,\n epoch: number,\n credentialHeaders: ReadonlySet<string>,\n): Promise<number | undefined> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction([STORE, META], \"readwrite\");\n let id: number | undefined;\n const current = tx.objectStore(META).get(EPOCH_KEY);\n current.onsuccess = () => {\n if (((current.result as number | undefined) ?? 0) !== epoch) return;\n const add = tx.objectStore(STORE).add(entry);\n add.onsuccess = () => {\n id = add.result as number;\n };\n };\n await txDone(tx);\n db.close();\n return id;\n}\n\n/**\n * Record how an entry is owned. A no-op when the entry is already gone\n * (replayed, or the queue was cleared).\n */\nasync function stampOwner(\n name: string,\n id: number,\n ownerState: BackgroundSyncOwnerState,\n owner: string | null | undefined,\n): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n const store = tx.objectStore(STORE);\n const get = store.get(id);\n get.onsuccess = () => {\n const entry = get.result as QueuedRequest | undefined;\n if (!entry) return;\n entry.ownerState = ownerState;\n if (ownerState === \"bound\") entry.owner = owner ?? null;\n store.put(entry);\n };\n await txDone(tx);\n db.close();\n}\n\nasync function readAll(\n name: string,\n credentialHeaders: ReadonlySet<string>,\n): Promise<QueuedRequest[]> {\n const db = await openQueueDb(name, credentialHeaders);\n const tx = db.transaction(STORE, \"readonly\");\n const all = await new Promise<QueuedRequest[]>((resolve, reject) => {\n const req = tx.objectStore(STORE).getAll();\n req.onsuccess = () => resolve(req.result as QueuedRequest[]);\n req.onerror = () => reject(req.error);\n });\n db.close();\n return all;\n}\n\n/** Whether an entry is still in the queue — `false` once it was cleared. */\nasync function stillQueued(name: string, id: number): Promise<boolean> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readonly\");\n const count = tx.objectStore(STORE).count(id);\n await txDone(tx);\n db.close();\n return count.result > 0;\n}\n\nasync function remove(name: string, id: number): Promise<void> {\n const db = await openQueueDb(name);\n const tx = db.transaction(STORE, \"readwrite\");\n tx.objectStore(STORE).delete(id);\n await txDone(tx);\n db.close();\n}\n\n/**\n * Serialize a request for the queue, leaving out every credential header and\n * recording which ones were present.\n */\nasync function serializeRequest(\n request: Request,\n timestamp: number,\n credentialHeaders: ReadonlySet<string>,\n ownerState: QueuedRequest[\"ownerState\"],\n): Promise<QueuedRequest> {\n const buffer = await request.clone().arrayBuffer();\n const { kept, stripped } = splitHeaders(request.headers.entries(), credentialHeaders);\n return {\n url: request.url,\n method: request.method,\n headers: kept,\n body: buffer.byteLength > 0 ? buffer : null,\n timestamp,\n credentials: request.credentials,\n strippedHeaders: stripped,\n ownerState,\n };\n}\n\n/**\n * Rebuild a stored request, stripping credential headers once more so an entry\n * that still holds one (a custom `credentialHeaders` the migration did not know)\n * never replays it.\n */\nfunction deserializeRequest(\n entry: QueuedRequest,\n credentialHeaders: ReadonlySet<string>,\n): { request: Request; strippedHeaders: string[] } {\n const { kept, stripped } = splitHeaders(entry.headers, credentialHeaders);\n return {\n request: new Request(entry.url, {\n method: entry.method,\n headers: kept,\n body: entry.body ?? undefined,\n credentials: entry.credentials,\n }),\n strippedHeaders: [...new Set([...(entry.strippedHeaders ?? []), ...stripped])],\n };\n}\n\n/** A window client's parsed answer. */\ninterface ClientAnswer {\n headers: Record<string, string> | null;\n /** Whether the page has `getPrincipal`. */\n hasPrincipal: boolean;\n owner: string | null;\n}\n\n/**\n * Ask one window client about a queued request over a `MessageChannel`.\n *\n * @returns The parsed answer, or `undefined` when the client stayed silent until\n * `deadline`, answered `{ error: true }`, or answered something unrecognizable.\n */\nasync function askClient(\n client: WindowClientLike,\n request: BackgroundSyncCredentialsRequest,\n deadline: Promise<void>,\n): Promise<ClientAnswer | undefined> {\n const channel = new MessageChannel();\n const answer = await Promise.race([\n new Promise<unknown>((resolve) => {\n channel.port1.onmessage = (event: MessageEvent) => resolve(event.data);\n client.postMessage({ type: BACKGROUND_SYNC_CREDENTIALS_MESSAGE, ...request }, [\n channel.port2,\n ]);\n }),\n deadline.then(() => undefined),\n ]);\n channel.port1.close();\n if (answer === null || typeof answer !== \"object\" || !(\"headers\" in answer)) return undefined;\n const { headers, owner } = answer as { headers: unknown; owner?: unknown };\n const hasPrincipal = \"owner\" in answer;\n if (hasPrincipal && typeof owner !== \"string\" && owner !== null) return undefined;\n return {\n headers:\n headers !== null && typeof headers === \"object\"\n ? (headers as Record<string, string>)\n : null,\n hasPrincipal,\n owner: hasPrincipal ? (owner as string | null) : null,\n };\n}\n\n/** A deadline shared by every client asked in one round. */\nfunction startDeadline(): { promise: Promise<void>; cancel: () => void } {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const promise = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, CREDENTIALS_TIMEOUT_MS);\n });\n return { promise, cancel: () => clearTimeout(timer) };\n}\n\n/**\n * Ask every open window client in parallel, under one shared deadline.\n *\n * @returns Every valid answer; empty when nobody answered.\n */\nasync function askAllClients(\n sw: BgSwGlobal,\n request: BackgroundSyncCredentialsRequest,\n): Promise<ClientAnswer[]> {\n const clients = (await sw.clients?.matchAll({ type: \"window\" })) ?? [];\n if (clients.length === 0) return [];\n const deadline = startDeadline();\n const answers = await Promise.all(\n clients.map((client) => askClient(client, request, deadline.promise)),\n );\n deadline.cancel();\n return answers.filter((answer): answer is ClientAnswer => answer !== undefined);\n}\n\n/** State of one replay pass: answers cached per URL + method, and the warning flags. */\ninterface ReplayRun {\n ask(request: Request): Promise<ClientAnswer[]>;\n warnNoAnswer(): void;\n warnOutOfScope(url: string): void;\n}\n\nfunction createReplayRun(sw: BgSwGlobal): ReplayRun {\n const answers = new Map<string, Promise<ClientAnswer[]>>();\n const outOfScope = new Set<string>();\n let warned = false;\n return {\n ask(request) {\n const key = `${request.method} ${request.url}`;\n let pending = answers.get(key);\n if (!pending) {\n pending = askAllClients(sw, {\n url: request.url,\n method: request.method,\n phase: \"replay\",\n });\n answers.set(key, pending);\n }\n return pending;\n },\n warnNoAnswer() {\n if (warned || !isDevBuild()) return;\n warned = true;\n console.warn(\n \"[tempest-react-sdk/sw] background-sync: a queued request needs an open page \" +\n \"to confirm who is signed in or to supply the current credentials, and no \" +\n \"open page answered. Call \" +\n \"provideBackgroundSyncCredentials() in the page; the entry stays pending.\",\n );\n },\n warnOutOfScope(url) {\n const origin = new URL(url).origin;\n if (outOfScope.has(origin) || !isDevBuild()) return;\n outOfScope.add(origin);\n console.warn(\n `[tempest-react-sdk/sw] background-sync: dropped a credentialed request to ${origin}; list it in trustedOrigins to replay it.`,\n );\n },\n };\n}\n\n/**\n * Pick the answer an entry may be replayed with, per its owner state.\n *\n * An `\"unknown\"` owner replays only when every valid answer lacks a principal:\n * one tab reporting a principal (even `null`) is enough to drop it, because a\n * principal-less answer — say a tab still running a bundle from before the app\n * adopted `getPrincipal` — says nothing about whose cookie the replay carries.\n */\nfunction chooseAnswer(\n answers: readonly ClientAnswer[],\n context: BackgroundSyncReplayContext,\n): ClientAnswer | undefined {\n switch (context.ownerState) {\n case \"bound\":\n return answers.find((answer) => answer.hasPrincipal && answer.owner === context.owner);\n case \"unknown\":\n return answers.every((answer) => !answer.hasPrincipal) ? answers[0] : undefined;\n case \"unbound\":\n return answers.find((answer) => !answer.hasPrincipal) ?? answers[0];\n }\n}\n\n/**\n * The default `beforeReplay` (rules on {@link InstallBackgroundSyncOptions}).\n *\n * @throws {Error} When no page answered, or the chosen answer lacks a stripped\n * header — the entry stays pending.\n */\nasync function defaultBeforeReplay(\n run: ReplayRun,\n request: Request,\n context: BackgroundSyncReplayContext,\n ownerPolicy: BackgroundSyncOwnerPolicy,\n): Promise<Request | null> {\n const credentialed = context.strippedHeaders.length > 0;\n const unchecked =\n context.ownerState === \"unbound\" ||\n (ownerPolicy === \"lenient\" && context.ownerState === \"unknown\");\n if (!credentialed && unchecked) return request;\n const answers = await run.ask(request);\n if (answers.length === 0) {\n run.warnNoAnswer();\n throw new Error(\"background-sync: no client answered\");\n }\n const chosen = chooseAnswer(answers, context);\n if (!chosen) return null;\n if (!credentialed) return request;\n if (chosen.headers === null) return null;\n const provided = new Map(\n Object.entries(chosen.headers).map(([name, value]) => [name.toLowerCase(), value]),\n );\n if (context.strippedHeaders.some((name) => !provided.has(name))) {\n throw new Error(\"background-sync: the answer lacks a stripped credential header\");\n }\n const headers = new Headers(request.headers);\n for (const name of context.strippedHeaders) headers.set(name, provided.get(name) as string);\n return new Request(request, { headers });\n}\n\n/** Everything {@link replayQueue} needs besides the clock. */\ninterface ReplayConfig {\n sw: BgSwGlobal;\n name: string;\n maxRetentionMs: number;\n credentialHeaders: ReadonlySet<string>;\n beforeReplay?: InstallBackgroundSyncOptions[\"beforeReplay\"];\n ownerPolicy: BackgroundSyncOwnerPolicy;\n /** Whether a request to this URL may carry a credential header. */\n inCredentialScope: (url: string) => boolean;\n}\n\n/** Whether a request carries any of the configured credential headers. */\nfunction carriesCredential(request: Request, credentialHeaders: ReadonlySet<string>): boolean {\n return [...request.headers.keys()].some((name) => credentialHeaders.has(name));\n}\n\n/**\n * Replay every queued request once. Entries that succeed, are stale, get a 4xx\n * (a client error that will not fix itself) or that the preparation rejects with\n * `null` are removed; entries that fail again — network error, 5xx, or a\n * preparation that throws — are kept, and so is an entry whose owner is still\n * being stamped (for up to {@link OWNER_STAMP_GRACE_MS}). Each entry is checked\n * against the store right before it is sent, so a queue cleared mid-replay stops\n * the replay. Throws if any entry is still pending, so a `sync` handler keeps\n * the sync registered.\n *\n * Credential scope (#523) is enforced here rather than in the default hook, so\n * a custom `beforeReplay` is held to it too: an entry that stripped a credential\n * header for an origin outside the scope is dropped before preparation, and a\n * prepared request carrying one to such an origin is dropped instead of sent.\n */\nasync function replayQueue(config: ReplayConfig, now: number): Promise<void> {\n const {\n sw,\n name,\n maxRetentionMs,\n credentialHeaders,\n beforeReplay,\n ownerPolicy,\n inCredentialScope,\n } = config;\n const run = createReplayRun(sw);\n const prepare =\n beforeReplay ??\n ((request: Request, context: BackgroundSyncReplayContext) =>\n defaultBeforeReplay(run, request, context, ownerPolicy));\n const entries = await readAll(name, credentialHeaders);\n let pending = 0;\n\n for (const entry of entries) {\n if (entry.id === undefined) continue;\n if (now - entry.timestamp > maxRetentionMs) {\n await remove(name, entry.id);\n continue;\n }\n const state = entry.ownerState ?? \"unknown\";\n if (state === \"pending\" && now - entry.timestamp < OWNER_STAMP_GRACE_MS) {\n pending += 1;\n continue;\n }\n const ownerState: BackgroundSyncOwnerState = state === \"pending\" ? \"unknown\" : state;\n try {\n const { request: stored, strippedHeaders } = deserializeRequest(\n entry,\n credentialHeaders,\n );\n if (strippedHeaders.length > 0 && !inCredentialScope(stored.url)) {\n run.warnOutOfScope(stored.url);\n await remove(name, entry.id);\n continue;\n }\n const request = await prepare(stored, {\n queuedAt: entry.timestamp,\n strippedHeaders,\n ownerState,\n owner: ownerState === \"bound\" ? (entry.owner ?? null) : undefined,\n });\n if (!(await stillQueued(name, entry.id))) continue;\n if (request === null) {\n await remove(name, entry.id);\n continue;\n }\n if (carriesCredential(request, credentialHeaders) && !inCredentialScope(request.url)) {\n run.warnOutOfScope(request.url);\n await remove(name, entry.id);\n continue;\n }\n const response = await fetch(request);\n if (response.ok || (response.status >= 400 && response.status < 500)) {\n await remove(name, entry.id);\n } else {\n pending += 1;\n }\n } catch {\n pending += 1;\n }\n }\n\n if (pending > 0) throw new Error(`background-sync: ${pending} request(s) still pending`);\n}\n\n/**\n * The replay in flight per queue. `sync`, `periodicsync` and the Safari fallback\n * can fire together; sharing one pass keeps a mutation from being sent twice.\n */\nconst replaysInFlight = new Map<string, Promise<void>>();\n\nfunction drainQueue(config: ReplayConfig): Promise<void> {\n const running = replaysInFlight.get(config.name);\n if (running) return running;\n const pass = replayQueue(config, Date.now()).finally(() => {\n replaysInFlight.delete(config.name);\n });\n replaysInFlight.set(config.name, pass);\n return pass;\n}\n\nfunction matches(\n match: InstallBackgroundSyncOptions[\"match\"],\n url: URL,\n request: Request,\n): boolean {\n if (!match) return true;\n return typeof match === \"function\" ? match(url, request) : match.test(url.href);\n}\n\n/**\n * Ask the issuing page who owns a just-queued entry and record it.\n *\n * @returns Resolves once the owner is stamped; never rejects.\n */\nasync function stampFromIssuer(\n name: string,\n id: number,\n issuer: WindowClientLike,\n request: Request,\n): Promise<void> {\n const deadline = startDeadline();\n const answer = await askClient(\n issuer,\n { url: request.url, method: request.method, phase: \"enqueue\" },\n deadline.promise,\n );\n deadline.cancel();\n const state: BackgroundSyncOwnerState = !answer\n ? \"unknown\"\n : answer.hasPrincipal\n ? \"bound\"\n : \"unbound\";\n await stampOwner(name, id, state, answer?.owner);\n}\n\n/**\n * Install the background-sync queue: on a failed mutating request, the request\n * is serialized to IndexedDB (without its credential headers) and a sync is\n * registered; the original fetch still rejects (so your app can show an offline\n * state), and the request is replayed later when the network returns.\n *\n * Right after queueing, the worker asks the page that issued the request who is\n * signed in (`getPrincipal` on {@link provideBackgroundSyncCredentials}) and\n * stamps the entry with that owner, without delaying the rejection. The work is\n * handed to `event.waitUntil` synchronously, so the worker stays alive for it\n * in every engine. Without the Background Sync API (every non-Chromium\n * browser), the queue is drained opportunistically whenever a `GET` goes\n * through the worker.\n *\n * @tempest-limits empty-catch — `registration.sync.register` is unavailable on\n * every non-Chromium browser and fails on a revoked background-sync permission.\n * The entry is already durable in IndexedDB at that point, and the queue is also\n * drained opportunistically on the next successful request, so losing the OS-level\n * wakeup degrades *when* the replay happens, not *whether* it happens.\n */\nexport function installBackgroundSync(options: InstallBackgroundSyncOptions = {}): void {\n const sw = getSwScope();\n const {\n match,\n queueName = DEFAULT_QUEUE_NAME,\n maxRetentionMinutes = 1440,\n periodicSyncTag = `${options.queueName ?? DEFAULT_QUEUE_NAME}-periodic`,\n credentialHeaders = DEFAULT_CREDENTIAL_HEADERS,\n beforeReplay,\n ownerPolicy = \"strict\",\n trustedOrigins = [],\n } = options;\n const stripped = credentialHeaderSet(credentialHeaders);\n const workerOrigin = globalThis.location?.href ?? \"\";\n const replay: ReplayConfig = {\n sw,\n name: queueName,\n maxRetentionMs: maxRetentionMinutes * 60 * 1000,\n credentialHeaders: stripped,\n beforeReplay,\n ownerPolicy,\n inCredentialScope: (url) => isTrustedCredentialTarget(url, workerOrigin, trustedOrigins),\n };\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method === \"GET\" || request.method === \"HEAD\") return;\n\n const url = new URL(request.url);\n if (!matches(match, url, request)) return;\n\n const epoch = readEpoch(queueName, stripped);\n epoch.catch(() => undefined);\n const attempt = fetch(request.clone());\n const queued = attempt.then(\n () => undefined,\n async () => {\n const issuer = event.clientId ? await sw.clients?.get(event.clientId) : undefined;\n const entry = await serializeRequest(\n request,\n Date.now(),\n stripped,\n issuer ? \"pending\" : \"unknown\",\n );\n const id = await enqueue(queueName, entry, await epoch, stripped);\n if (id === undefined) return undefined;\n try {\n await sw.registration.sync?.register(queueName);\n } catch {\n /* empty */\n }\n return issuer ? { id, issuer } : undefined;\n },\n );\n event.respondWith(\n attempt.catch(async (error: unknown) => {\n await queued;\n throw error;\n }),\n );\n event.waitUntil(\n queued\n .then((stamp) =>\n stamp ? stampFromIssuer(queueName, stamp.id, stamp.issuer, request) : undefined,\n )\n .catch(() => undefined),\n );\n });\n\n sw.addEventListener(\"sync\", (event) => {\n if (event.tag !== queueName) return;\n event.waitUntil(drainQueue(replay));\n });\n\n sw.addEventListener(\"periodicsync\", (event) => {\n if (event.tag !== periodicSyncTag) return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n if (sw.registration.sync) return;\n if (event.request.method !== \"GET\") return;\n event.waitUntil(drainQueue(replay).catch(() => undefined));\n });\n}\n\n/**\n * Empty the background-sync queue — every request still waiting to be replayed —\n * and bump its clear epoch. Call it on logout (or use `clearSessionData()`, which\n * also clears the runtime caches) so mutations made under one session are never\n * replayed under the next.\n *\n * Works from the page and from the worker, and reaches work already in flight\n * in the worker: a replay checks each entry right before sending it, and a\n * request still failing when the queue is cleared is not written afterwards.\n *\n * @param queueName - The `queueName` given to {@link installBackgroundSync}.\n * Default `tempest-bg-sync`.\n * @returns `true` once the queue is empty; `false` when IndexedDB is\n * unavailable (SSR, old browsers).\n *\n * @example\n * import { clearBackgroundSyncQueue } from \"tempest-react-sdk/sw\";\n *\n * await clearBackgroundSyncQueue();\n */\nexport async function clearBackgroundSyncQueue(\n queueName: string = DEFAULT_QUEUE_NAME,\n): Promise<boolean> {\n if (typeof indexedDB === \"undefined\") return false;\n const db = await openQueueDb(queueName);\n const tx = db.transaction([STORE, META], \"readwrite\");\n tx.objectStore(STORE).clear();\n const meta = tx.objectStore(META);\n const current = meta.get(EPOCH_KEY);\n current.onsuccess = () => {\n meta.put(((current.result as number | undefined) ?? 0) + 1, EPOCH_KEY);\n };\n await txDone(tx);\n db.close();\n return true;\n}\n\n/**\n * One-way fingerprint of a principal: hex SHA-256, so the queue can compare\n * owners without ever holding the id itself.\n *\n * @returns The fingerprint, or `null` when nobody is signed in.\n */\nasync function ownerFingerprint(principal: string | null | undefined): Promise<string | null> {\n if (principal === null || principal === undefined || principal === \"\") return null;\n const digest = await crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(`tempest-bg-sync:${principal}`),\n );\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Answer the worker's questions about queued requests (see `beforeReplay` on\n * {@link installBackgroundSync}). Install it once in every page, next to your\n * auth setup; it reads the token at replay time, so the queue never has to store\n * it. Without it, a queued request that carried a credential header is never\n * replayed.\n *\n * `getHeaders` must return **every** credential header the app sends (the worker\n * keeps an entry pending when one it stripped is missing), or `null` when there\n * is no session — the worker then drops the entry instead of replaying it\n * anonymously. A throw from `getHeaders` or `getPrincipal` is answered as an\n * explicit `{ error: true }`.\n *\n * The worker applies only the header names the original request carried, and\n * only to the worker's own origin or the `trustedOrigins` given to\n * {@link installBackgroundSync}: an entry bound for any other origin is dropped\n * without asking this page. Matching the name is not enough on its own — a\n * request to a third party carries *that party's* `Authorization`, and until\n * 0.81.0 its replay received the app's bearer (#523). `getHeaders` still gets\n * the URL, for an app whose trusted origins need different credentials.\n *\n * Pass `getPrincipal` to bind each entry to whoever queued it: the worker asks\n * the issuing tab right after queueing, asks every tab again before replaying,\n * and drops the entry when no signed-in tab is its owner. Without it every\n * entry is `\"unbound\"` and replays with whichever session answers — the next\n * account's bearer included, unless `clearSessionData()` ran on logout — so a\n * development build warns once per call (#531). Treating an unbound\n * credentialed entry as `\"unknown\"` instead would change nothing: an\n * `\"unknown\"` entry replays when no answering tab reports a principal, which is\n * exactly the page that omits `getPrincipal`.\n *\n * @param getHeaders - Resolves the headers for one queued request at replay.\n * @param options - `getPrincipal` binds entries to their owner.\n * @returns A function that removes the listener. A no-op outside the browser.\n *\n * @example\n * import { provideBackgroundSyncCredentials } from \"tempest-react-sdk/sw\";\n *\n * const stop = provideBackgroundSyncCredentials(\n * () => {\n * const token = localStorage.getItem(\"token\");\n * return token ? { Authorization: `Bearer ${token}` } : null;\n * },\n * { getPrincipal: () => localStorage.getItem(\"userId\") },\n * );\n */\nexport function provideBackgroundSyncCredentials(\n getHeaders: BackgroundSyncCredentialsProvider,\n options: ProvideBackgroundSyncCredentialsOptions = {},\n): () => void {\n if (typeof navigator === \"undefined\" || !navigator.serviceWorker) return () => undefined;\n const container = navigator.serviceWorker;\n const { getPrincipal } = options;\n if (!getPrincipal && isDevBuild()) {\n console.warn(\n \"[tempest-react-sdk/sw] provideBackgroundSyncCredentials() without `getPrincipal`: \" +\n \"queued mutations are not bound to the account that made them and replay with \" +\n \"whichever session answers next, unless clearSessionData() runs on logout. \" +\n \"Pass { getPrincipal: () => currentUserId } to bind them.\",\n );\n }\n const onMessage = (event: MessageEvent): void => {\n const data = event.data as Partial<BackgroundSyncCredentialsRequest> & { type?: unknown };\n const port = event.ports[0];\n if (data?.type !== BACKGROUND_SYNC_CREDENTIALS_MESSAGE || !port) return;\n const request: BackgroundSyncCredentialsRequest = {\n url: String(data.url),\n method: String(data.method),\n phase: data.phase === \"enqueue\" ? \"enqueue\" : \"replay\",\n };\n void (async () => {\n try {\n const headers = request.phase === \"enqueue\" ? null : await getHeaders(request);\n const answer: { headers: Record<string, string> | null; owner?: string | null } = {\n headers,\n };\n if (getPrincipal) answer.owner = await ownerFingerprint(await getPrincipal());\n port.postMessage(answer);\n } catch {\n port.postMessage({ error: true });\n }\n })();\n };\n container.addEventListener(\"message\", onMessage);\n return () => container.removeEventListener(\"message\", onMessage);\n}\n"],"mappings":";;;;AA6DA,SAASA,IAAyB;CAC9B,OAAO;AACX;AAgDA,IAAMC,IAAqB,mBAOrBC,IAAa,GACbC,IAAQ,YACRC,IAAO,QACPC,IAAY,SAMLC,IAAsC,+BAG7CC,IAAyB,KAMzBC,IAAuBD,IAAyB;AA8JtD,SAASE,EACL,GACA,GACgD;CAChD,IAAMC,IAA2B,CAAC,GAC5BC,IAAqB,CAAC;CAC5B,KAAK,IAAM,CAACC,GAAMC,MAAUC,GACxB,AAAIC,EAAkB,IAAIH,EAAK,YAAY,CAAC,IAAGD,EAAS,KAAKC,EAAK,YAAY,CAAC,IAC1EF,EAAK,KAAK,CAACE,GAAMC,CAAK,CAAC;CAEhC,OAAO;EAAE;EAAM;CAAS;AAC5B;AAOA,SAASG,EAAqB,GAAuB,GAA8C;CAC/F,IAAMC,IAAgBC,EAAM,WAAW;CACvC,EAAc,kBAAkB;EAC5B,IAAMC,IAASF,EAAc;EAC7B,IAAI,CAACE,GAAQ;EACb,IAAMC,IAAQD,EAAO,OACf,EAAE,SAAM,gBAAaV,EAAaW,EAAM,SAASL,CAAiB;EAOxE,AANAI,EAAO,OAAO;GACV,GAAGC;GACH,SAASV;GACT,iBAAiB,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAIU,EAAM,mBAAmB,CAAC,GAAI,GAAGT,CAAQ,CAAC,CAAC;GAC7E,YAAYS,EAAM,cAAc;EACpC,CAAC,GACDD,EAAO,SAAS;CACpB;AACJ;AAEA,S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AK,YAAYzE,CAAM;GAC3B,QAAQ;IACJ,EAAK,YAAY,EAAE,OAAO,GAAK,CAAC;GACpC;EACJ,EAAA,CAAG;CACP;CAEA,OADAqE,EAAU,iBAAiB,WAAWE,CAAS,SAClCF,EAAU,oBAAoB,WAAWE,CAAS;AACnE"}
package/dist/sw/cache.cjs CHANGED
@@ -1,2 +1,2 @@
1
- const e=require("./credential-headers.cjs");function t(){return globalThis}var n=``,r=new Set,i=`x-tempest-cached-at`;function a(e,t){if(!t)return!1;let n=Number(e.headers.get(i)),r=e.headers.get(`date`),a=n>0?n:r?new Date(r).getTime():NaN;return!Number.isNaN(a)&&(Date.now()-a)/1e3>t}function o(e){return(e.headers.get(`cache-control`)??``).toLowerCase().split(`,`).map(e=>e.trim().split(`=`)[0])}function s(e,t){if(!e.ok)return!1;let n=o(e);return n.includes(`no-store`)?!1:t.cacheAuthenticated===!0||!n.includes(`private`)}function c(t,n){return[...e.credentialHeaderSet(n.credentialHeaders)].filter(e=>t.headers.has(e))}async function l(e,t,n,r){if(!s(n,r))return;let a=new Headers(n.headers);if(a.set(i,String(Date.now())),r.cacheAuthenticated){let e=a.get(`vary`),n=(e??``).toLowerCase().split(`,`).map(e=>e.trim()),i=c(t,r).filter(e=>!n.includes(e));i.length>0&&!n.includes(`*`)&&a.set(`vary`,[e,...i].filter(Boolean).join(`, `))}let o=n.clone();await e.put(t,new Response(o.body,{status:o.status,statusText:o.statusText,headers:a})),await u(r.cacheName,r.maxEntries)}async function u(e,t){if(!t)return;let n=await caches.open(e),r=await n.keys();if(!(r.length<=t))for(let e of r.slice(0,r.length-t))await n.delete(e)}async function d(e,t){let n=await caches.open(t.cacheName),r=await n.match(e);if(r&&!a(r,t.maxAgeSeconds))return r;let i=await fetch(e);return await l(n,e,i,t),i}async function f(e,t,n){let r=await caches.open(t.cacheName),i=(async()=>{let n=await fetch(e);return await l(r,e,n,t),n})(),o=(t.networkTimeoutSeconds??0)*1e3;try{if(o>0){let e=new Promise((e,t)=>setTimeout(()=>{n(i.catch(()=>void 0)),t(Error(`network-timeout`))},o));return await Promise.race([i,e])}return await i}catch{let n=await r.match(e);if(n&&!a(n,t.maxAgeSeconds))return n;throw Error(`network-first: no network and no cache`)}}async function p(e,t,n){let r=await caches.open(t.cacheName),i=await r.match(e),o=fetch(e).then(async n=>(await l(r,e,n,t),n)).catch(()=>void 0),s=i&&!a(i,t.maxAgeSeconds)?i:void 0;if(s)return n(o),s;let c=await o;if(c)return c;throw Error(`stale-while-revalidate: no network and no cache`)}function m(e,t,n){switch(t.strategy){case`cache-first`:return d(e,t);case`network-first`:return f(e,t,n);case`stale-while-revalidate`:return p(e,t,n)}}function h(e,t,n){return typeof e.match==`function`?e.match(t,n):e.match.test(t.href)}async function g(e,t){let n=e.headers.get(`range`);if(!n)return t;let r=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!r||r[1]===``&&r[2]===``)return new Response(null,{status:416,statusText:`Range Not Satisfiable`});let i=await t.clone().arrayBuffer(),a=i.byteLength,o,s;if(r[1]===``){let e=Number(r[2]);o=Math.max(0,a-e),s=a-1}else o=Number(r[1]),s=r[2]===``?a-1:Math.min(Number(r[2]),a-1);if(o>s||o>=a)return new Response(null,{status:416,statusText:`Range Not Satisfiable`,headers:{"Content-Range":`bytes */${a}`}});let c=i.slice(o,s+1),l=new Headers(t.headers);return l.set(`Content-Range`,`bytes ${o}-${s}/${a}`),l.set(`Content-Length`,String(c.byteLength)),l.set(`Accept-Ranges`,`bytes`),new Response(c,{status:206,statusText:`Partial Content`,headers:l})}function _(e){t().addEventListener(`fetch`,t=>{let n=t.request;if(n.method!==`GET`)return;let r=new URL(n.url),i=e.find(e=>h(e,r,n));if(!i||!i.cacheAuthenticated&&c(n,i).length>0)return;let a=e=>t.waitUntil(e);if(i.rangeRequests&&n.headers.has(`range`)){let e=new Request(n.url,{headers:v(n.headers),credentials:n.credentials,mode:n.mode===`navigate`?`same-origin`:n.mode});t.respondWith(m(e,i,a).then(e=>g(n,e)))}else t.respondWith(m(n,i,a))})}function v(e){let t=new Headers(e);return t.delete(`range`),t}function y(e={}){let i=t(),{manifestUrl:a=`/precache-manifest.json`,cacheName:o=`tempest-precache`,navigateFallback:s=`/index.html`,navigateFallbackDenylist:c=[],skipWaiting:l=!0,navigationPreload:u=!0}=e;i.addEventListener(`install`,e=>{e.waitUntil((async()=>{let e=await(await fetch(a,{cache:`no-cache`})).json();n=`${o}-${e.version}`,await(await caches.open(n)).addAll(e.urls);for(let t of e.urls)r.add(new URL(t,i.location.origin).pathname);l&&await i.skipWaiting()})())}),i.addEventListener(`activate`,e=>{e.waitUntil((async()=>{let e=await caches.keys();await Promise.all(e.filter(e=>e.startsWith(`${o}-`)&&e!==n).map(e=>caches.delete(e))),u&&i.registration?.navigationPreload&&await i.registration.navigationPreload.enable(),await i.clients.claim()})())}),i.addEventListener(`fetch`,e=>{let t=e.request;if(t.method!==`GET`)return;let a=new URL(t.url);if(a.origin===i.location.origin){if(t.mode===`navigate`){if(c.some(e=>e.test(a.pathname)))return;e.respondWith((async()=>{try{return await e.preloadResponse||await fetch(t)}catch{let e=await(await caches.open(n)).match(s);if(e)return e;throw Error(`offline and no cached app shell`)}})())}else r.has(a.pathname)&&e.respondWith((async()=>await(await caches.open(n)).match(t)??fetch(t))())}})}exports.createPartialResponse=g,exports.installPrecache=y,exports.installRuntimeCache=_;
1
+ const e=require("./credential-headers.cjs");function t(){return globalThis}var n=``,r=new Set,i=`x-tempest-cached-at`;function a(e,t){if(!t)return!1;let n=Number(e.headers.get(i)),r=e.headers.get(`date`),a=n>0?n:r?new Date(r).getTime():NaN;return!Number.isNaN(a)&&(Date.now()-a)/1e3>t}function o(e){return(e.headers.get(`cache-control`)??``).toLowerCase().split(`,`).map(e=>e.trim().split(`=`)[0])}function s(e){return(e??``).toLowerCase().split(`,`).map(e=>e.trim())}function c(e,t){if(!e.ok||s(e.headers.get(`vary`)).includes(`*`))return!1;let n=o(e);return n.includes(`no-store`)?!1:t.cacheAuthenticated===!0||!n.includes(`private`)}function l(e,t){return e.mode===`cors`&&e.credentials===`include`||u(e,t).length>0}function u(t,n){return[...e.credentialHeaderSet(n.credentialHeaders)].filter(e=>t.headers.has(e))}async function d(e,t,n,r){if(!c(n,r))return;let a=new Headers(n.headers);if(a.set(i,String(Date.now())),r.cacheAuthenticated){let e=a.get(`vary`),n=s(e),i=u(t,r).filter(e=>!n.includes(e));i.length>0&&a.set(`vary`,[e,...i].filter(Boolean).join(`, `))}let o=n.clone();await e.put(t,new Response(o.body,{status:o.status,statusText:o.statusText,headers:a})),await f(r.cacheName,r.maxEntries)}async function f(e,t){if(!t)return;let n=await caches.open(e),r=await n.keys();if(!(r.length<=t))for(let e of r.slice(0,r.length-t))await n.delete(e)}async function p(e,t){let n=await caches.open(t.cacheName),r=await n.match(e);if(r&&!a(r,t.maxAgeSeconds))return r;let i=await fetch(e);return await d(n,e,i,t),i}async function m(e,t,n){let r=await caches.open(t.cacheName),i=(async()=>{let n=await fetch(e);return await d(r,e,n,t),n})(),o=(t.networkTimeoutSeconds??0)*1e3;try{if(o>0){let e=new Promise((e,t)=>setTimeout(()=>{n(i.catch(()=>void 0)),t(Error(`network-timeout`))},o));return await Promise.race([i,e])}return await i}catch{let n=await r.match(e);if(n&&!a(n,t.maxAgeSeconds))return n;throw Error(`network-first: no network and no cache`)}}async function h(e,t,n){let r=await caches.open(t.cacheName),i=await r.match(e),o=fetch(e).then(async n=>(await d(r,e,n,t),n)).catch(()=>void 0),s=i&&!a(i,t.maxAgeSeconds)?i:void 0;if(s)return n(o),s;let c=await o;if(c)return c;throw Error(`stale-while-revalidate: no network and no cache`)}function g(e,t,n){switch(t.strategy){case`cache-first`:return p(e,t);case`network-first`:return m(e,t,n);case`stale-while-revalidate`:return h(e,t,n)}}function _(e,t,n){return typeof e.match==`function`?e.match(t,n):e.match.test(t.href)}async function v(e,t){let n=e.headers.get(`range`);if(!n)return t;let r=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!r||r[1]===``&&r[2]===``)return new Response(null,{status:416,statusText:`Range Not Satisfiable`});let i=await t.clone().arrayBuffer(),a=i.byteLength,o,s;if(r[1]===``){let e=Number(r[2]);o=Math.max(0,a-e),s=a-1}else o=Number(r[1]),s=r[2]===``?a-1:Math.min(Number(r[2]),a-1);if(o>s||o>=a)return new Response(null,{status:416,statusText:`Range Not Satisfiable`,headers:{"Content-Range":`bytes */${a}`}});let c=i.slice(o,s+1),l=new Headers(t.headers);return l.set(`Content-Range`,`bytes ${o}-${s}/${a}`),l.set(`Content-Length`,String(c.byteLength)),l.set(`Accept-Ranges`,`bytes`),new Response(c,{status:206,statusText:`Partial Content`,headers:l})}function y(e){t().addEventListener(`fetch`,t=>{let n=t.request;if(n.method!==`GET`)return;let r=new URL(n.url),i=e.find(e=>_(e,r,n));if(!i||!i.cacheAuthenticated&&l(n,i))return;let a=e=>t.waitUntil(e);if(i.rangeRequests&&n.headers.has(`range`)){let e=new Request(n.url,{headers:b(n.headers),credentials:n.credentials,mode:n.mode===`navigate`?`same-origin`:n.mode});t.respondWith(g(e,i,a).then(e=>v(n,e)))}else t.respondWith(g(n,i,a))})}function b(e){let t=new Headers(e);return t.delete(`range`),t}function x(e={}){let i=t(),{manifestUrl:a=`/precache-manifest.json`,cacheName:o=`tempest-precache`,navigateFallback:s=`/index.html`,navigateFallbackDenylist:c=[],skipWaiting:l=!0,navigationPreload:u=!0}=e;i.addEventListener(`install`,e=>{e.waitUntil((async()=>{let e=await(await fetch(a,{cache:`no-cache`})).json();n=`${o}-${e.version}`,await(await caches.open(n)).addAll(e.urls);for(let t of e.urls)r.add(new URL(t,i.location.origin).pathname);l&&await i.skipWaiting()})())}),i.addEventListener(`activate`,e=>{e.waitUntil((async()=>{let e=await caches.keys();await Promise.all(e.filter(e=>e.startsWith(`${o}-`)&&e!==n).map(e=>caches.delete(e))),u&&i.registration?.navigationPreload&&await i.registration.navigationPreload.enable(),await i.clients.claim()})())}),i.addEventListener(`fetch`,e=>{let t=e.request;if(t.method!==`GET`)return;let a=new URL(t.url);if(a.origin===i.location.origin){if(t.mode===`navigate`){if(c.some(e=>e.test(a.pathname)))return;e.respondWith((async()=>{try{return await e.preloadResponse||await fetch(t)}catch{let e=await(await caches.open(n)).match(s);if(e)return e;throw Error(`offline and no cached app shell`)}})())}else r.has(a.pathname)&&e.respondWith((async()=>await(await caches.open(n)).match(t)??fetch(t))())}})}exports.createPartialResponse=v,exports.installPrecache=x,exports.installRuntimeCache=y;
2
2
  //# sourceMappingURL=cache.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.cjs","names":["credentialHeaderSet","require_credential_headers","getSwScope","precacheName","precachedPaths","CACHED_AT_HEADER","isExpired","maxAgeSeconds","stamp","response","dateHeader","storedAt","cacheControlDirectives","directive","isStorable","directives","route","credentialsOn","request","name","store","headers","vary","varies","missing","copy","cache","trimCache","maxEntries","cacheName","keys","key","cacheFirst","cached","networkFirst","network","timeoutMs","timeout","extend","reject","staleWhileRevalidate","fresh","runRoute","routeMatches","url","createPartialResponse","rangeHeader","match","buffer","total","start","end","suffix","slice","installRuntimeCache","event","routes","candidate","promise","full","stripRange","out","installPrecache","sw","options","manifest","manifestUrl","skipWaiting","navigationPreload","navigateFallbackDenylist","re","shell","navigateFallback"],"sources":["../../src/sw/cache.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — precache, runtime strategies (cache-first, network-\n * first, stale-while-revalidate), expiry and the inspect/clear helpers all address\n * the same Cache Storage namespace, and the naming scheme that keeps them from\n * evicting each other is the file's whole contract.\n */\n/**\n * Service-worker caching helpers — a small, dependency-free subset of what\n * Workbox provides: precaching of the build's app shell (so the app launches\n * offline) plus runtime caching strategies for fonts, APIs and images.\n *\n * Import these inside your own `sw.ts`. They run in the service-worker global\n * scope, not the main thread. Pair `installPrecache` with the\n * `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which\n * emits the `precache-manifest.json` this reads at install time.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installRuntimeCache, installPrecache } from \"tempest-react-sdk/sw\";\n *\n * // Register specific routes FIRST so they win over the precache catch-all.\n * installRuntimeCache([\n * { match: /\\/api\\//, strategy: \"network-first\", cacheName: \"tempest-api\", maxAgeSeconds: 300 },\n * ]);\n * installPrecache();\n */\n\nimport { credentialHeaderSet } from \"./credential-headers\";\n\n/** Minimal shape of the events we touch, to avoid pulling in `lib.webworker`. */\ninterface ExtendableEventLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface FetchEventLike extends ExtendableEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n /** Resolves to the navigation-preload response when it is enabled, else `undefined`. */\n preloadResponse?: Promise<Response | undefined>;\n}\n\n/** Minimal shape of `registration.navigationPreload` (Navigation Preload API). */\ninterface NavigationPreloadManagerLike {\n enable(): Promise<void>;\n disable(): Promise<void>;\n}\n\ninterface CacheSwGlobal {\n addEventListener(type: \"install\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"activate\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchEventLike) => void): void;\n clients: { claim(): Promise<void> };\n skipWaiting(): Promise<void>;\n location: { origin: string };\n registration?: { navigationPreload?: NavigationPreloadManagerLike };\n}\n\nfunction getSwScope(): CacheSwGlobal {\n return globalThis as unknown as CacheSwGlobal;\n}\n\n/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */\nexport type RuntimeStrategy = \"cache-first\" | \"network-first\" | \"stale-while-revalidate\";\n\n/** A single runtime-caching rule, matched against each `GET` request. */\nexport interface RuntimeRoute {\n /** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */\n match: RegExp | ((url: URL, request: Request) => boolean);\n /** How to resolve a match. */\n strategy: RuntimeStrategy;\n /** Cache bucket name for this route. */\n cacheName: string;\n /** Trim the cache to at most this many entries (FIFO) after each write. */\n maxEntries?: number;\n /** Treat a cached response older than this (seconds) as a miss. */\n maxAgeSeconds?: number;\n /** For `network-first`: fall back to cache after this timeout (seconds). */\n networkTimeoutSeconds?: number;\n /**\n * Serve HTTP `Range` requests (206 Partial Content) by slicing the cached\n * full response. Enable for audio/video so seeking works offline. The full\n * resource is cached once (the `Range` header is stripped before caching).\n */\n rangeRequests?: boolean;\n /**\n * Opt in to caching requests that carry a credential header (see\n * `credentialHeaders`), and responses marked `Cache-Control: private`.\n * Default `false`.\n *\n * Cache Storage is keyed by URL and outlives the session: without this\n * gate, a `GET /api/me` stored for one account was served to the next\n * account on the same browser whenever the network failed or exceeded\n * `networkTimeoutSeconds` (reproduced in Chromium 153, 11/10/2026). With\n * the default, credentialed requests bypass the route entirely and reach\n * the network as if no service worker were installed.\n *\n * When enabled, every stored entry gets `Vary` on each credential header the\n * request carried, so the Cache API only matches it for the same credential —\n * another account (or no account) misses instead of reading it. A token\n * rotated while online simply repopulates the entry. Pair it with\n * `clearSessionData()` on logout, which removes the entries themselves.\n * `Cache-Control: no-store` is never cached, opt-in or not.\n *\n * A cookie session is invisible here: the worker cannot see `Cookie`, and\n * gating on `request.credentials` would switch off caching for every\n * same-origin image and font. A cookie-authenticated API stays private only\n * through `Cache-Control: private`/`no-store` on its responses and\n * `clearSessionData()` on logout.\n */\n cacheAuthenticated?: boolean;\n /**\n * Header names that mark a request as credentialed. Default\n * `DEFAULT_CREDENTIAL_HEADERS` (`authorization`, `x-api-key`,\n * `x-auth-token`, …) — the same list the background-sync queue strips.\n */\n credentialHeaders?: readonly string[];\n}\n\n/** Options for {@link installPrecache}. */\nexport interface InstallPrecacheOptions {\n /** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */\n manifestUrl?: string;\n /** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */\n cacheName?: string;\n /** App-shell document served for navigation requests offline. Default `/index.html`. */\n navigateFallback?: string;\n /** Navigation paths that should NOT use the fallback (e.g. `[/^\\/api\\//]`). */\n navigateFallbackDenylist?: RegExp[];\n /** Activate the new worker immediately after precaching. Default `true`. */\n skipWaiting?: boolean;\n /**\n * Enable the Navigation Preload API on `activate`, so the browser fetches\n * the navigation request in parallel with the worker boot and the handler\n * serves `event.preloadResponse` — cutting first-navigation latency after\n * the worker starts. Silently ignored where unsupported. Default `true`.\n */\n navigationPreload?: boolean;\n}\n\ninterface PrecacheManifest {\n version: string;\n urls: string[];\n}\n\nlet precacheName = \"\";\nconst precachedPaths = new Set<string>();\n\n/**\n * Header stamped on every runtime-cache entry with the epoch milliseconds of the\n * write. `Date` alone is not enough: it is not a CORS-safelisted response\n * header, so for a cross-origin API the worker reads `null` and `maxAgeSeconds`\n * would never expire anything.\n */\nconst CACHED_AT_HEADER = \"x-tempest-cached-at\";\n\n/**\n * Whether a cached response has aged past `maxAgeSeconds`. Reads the\n * {@link CACHED_AT_HEADER} stamp written by the runtime cache, and falls back to\n * `Date` for entries written before the stamp existed.\n */\nfunction isExpired(response: Response, maxAgeSeconds?: number): boolean {\n if (!maxAgeSeconds) return false;\n const stamp = Number(response.headers.get(CACHED_AT_HEADER));\n const dateHeader = response.headers.get(\"date\");\n const storedAt = stamp > 0 ? stamp : dateHeader ? new Date(dateHeader).getTime() : NaN;\n if (Number.isNaN(storedAt)) return false;\n return (Date.now() - storedAt) / 1000 > maxAgeSeconds;\n}\n\n/** The `Cache-Control` directives of a response, lower-cased. */\nfunction cacheControlDirectives(response: Response): string[] {\n return (response.headers.get(\"cache-control\") ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((directive) => directive.trim().split(\"=\")[0]);\n}\n\n/**\n * Whether a network response may be written to the route's cache: it must be\n * `ok`, never `no-store`, and `private` only under `cacheAuthenticated`.\n */\nfunction isStorable(response: Response, route: RuntimeRoute): boolean {\n if (!response.ok) return false;\n const directives = cacheControlDirectives(response);\n if (directives.includes(\"no-store\")) return false;\n return route.cacheAuthenticated === true || !directives.includes(\"private\");\n}\n\n/** The credential headers, lower-cased, that a request carries for its route. */\nfunction credentialsOn(request: Request, route: RuntimeRoute): string[] {\n return [...credentialHeaderSet(route.credentialHeaders)].filter((name) =>\n request.headers.has(name),\n );\n}\n\n/**\n * Write a response to the route's cache with the {@link CACHED_AT_HEADER} stamp\n * and, under `cacheAuthenticated`, `Vary` on each credential header the request\n * carried, so the entry only matches the credential that produced it. Skips\n * responses that {@link isStorable} rejects, then trims the cache to\n * `maxEntries`.\n */\nasync function store(\n cache: Cache,\n request: Request,\n response: Response,\n route: RuntimeRoute,\n): Promise<void> {\n if (!isStorable(response, route)) return;\n const headers = new Headers(response.headers);\n headers.set(CACHED_AT_HEADER, String(Date.now()));\n if (route.cacheAuthenticated) {\n const vary = headers.get(\"vary\");\n const varies = (vary ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((name) => name.trim());\n const missing = credentialsOn(request, route).filter((name) => !varies.includes(name));\n if (missing.length > 0 && !varies.includes(\"*\")) {\n headers.set(\"vary\", [vary, ...missing].filter(Boolean).join(\", \"));\n }\n }\n const copy = response.clone();\n await cache.put(\n request,\n new Response(copy.body, { status: copy.status, statusText: copy.statusText, headers }),\n );\n await trimCache(route.cacheName, route.maxEntries);\n}\n\n/** Drop oldest entries until the cache holds at most `maxEntries`. */\nasync function trimCache(cacheName: string, maxEntries?: number): Promise<void> {\n if (!maxEntries) return;\n const cache = await caches.open(cacheName);\n const keys = await cache.keys();\n if (keys.length <= maxEntries) return;\n for (const key of keys.slice(0, keys.length - maxEntries)) {\n await cache.delete(key);\n }\n}\n\nasync function cacheFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n\n const response = await fetch(request);\n await store(cache, request, response, route);\n return response;\n}\n\n/**\n * Network-first. When the timeout wins, the network request keeps running to\n * refresh the cache, and is handed to `extend` (`event.waitUntil`) so the\n * worker is not stopped mid-write.\n */\nasync function networkFirst(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n\n const network = (async (): Promise<Response> => {\n const response = await fetch(request);\n await store(cache, request, response, route);\n return response;\n })();\n\n const timeoutMs = (route.networkTimeoutSeconds ?? 0) * 1000;\n try {\n if (timeoutMs > 0) {\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => {\n extend(network.catch(() => undefined));\n reject(new Error(\"network-timeout\"));\n }, timeoutMs),\n );\n return await Promise.race([network, timeout]);\n }\n return await network;\n } catch {\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n throw new Error(\"network-first: no network and no cache\");\n }\n}\n\n/**\n * Stale-while-revalidate. A fresh cached response is served at once, and the\n * revalidation is handed to `extend` (`event.waitUntil`): without it the\n * browser may stop the worker before the refreshed response is written.\n */\nasync function staleWhileRevalidate(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n\n const network = fetch(request)\n .then(async (response) => {\n await store(cache, request, response, route);\n return response;\n })\n .catch(() => undefined);\n\n const fresh = cached && !isExpired(cached, route.maxAgeSeconds) ? cached : undefined;\n if (fresh) {\n extend(network);\n return fresh;\n }\n const response = await network;\n if (response) return response;\n throw new Error(\"stale-while-revalidate: no network and no cache\");\n}\n\nfunction runRoute(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n switch (route.strategy) {\n case \"cache-first\":\n return cacheFirst(request, route);\n case \"network-first\":\n return networkFirst(request, route, extend);\n case \"stale-while-revalidate\":\n return staleWhileRevalidate(request, route, extend);\n }\n}\n\nfunction routeMatches(route: RuntimeRoute, url: URL, request: Request): boolean {\n return typeof route.match === \"function\"\n ? route.match(url, request)\n : route.match.test(url.href);\n}\n\n/**\n * Build a `206 Partial Content` response from a full one for an HTTP `Range`\n * request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix\n * `bytes=-suffixLength` (the last N bytes). Returns the original response when there is no usable\n * `Range` header, or a `416` when the range is unsatisfiable.\n *\n * @param request The incoming request (its `Range` header drives the slice).\n * @param response The full (200) response to slice.\n */\nexport async function createPartialResponse(\n request: Request,\n response: Response,\n): Promise<Response> {\n const rangeHeader = request.headers.get(\"range\");\n if (!rangeHeader) return response;\n\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(rangeHeader.trim());\n if (!match || (match[1] === \"\" && match[2] === \"\")) {\n return new Response(null, { status: 416, statusText: \"Range Not Satisfiable\" });\n }\n\n const buffer = await response.clone().arrayBuffer();\n const total = buffer.byteLength;\n\n let start: number;\n let end: number;\n if (match[1] === \"\") {\n const suffix = Number(match[2]);\n start = Math.max(0, total - suffix);\n end = total - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? total - 1 : Math.min(Number(match[2]), total - 1);\n }\n\n if (start > end || start >= total) {\n return new Response(null, {\n status: 416,\n statusText: \"Range Not Satisfiable\",\n headers: { \"Content-Range\": `bytes */${total}` },\n });\n }\n\n const slice = buffer.slice(start, end + 1);\n const headers = new Headers(response.headers);\n headers.set(\"Content-Range\", `bytes ${start}-${end}/${total}`);\n headers.set(\"Content-Length\", String(slice.byteLength));\n headers.set(\"Accept-Ranges\", \"bytes\");\n\n return new Response(slice, {\n status: 206,\n statusText: \"Partial Content\",\n headers,\n });\n}\n\n/**\n * Install a `fetch` handler that resolves matching `GET` requests with the\n * given runtime strategies. Non-matching requests are left untouched (no\n * `respondWith`), so a later {@link installPrecache} can handle them.\n *\n * A request carrying a credential header (`Authorization`, `X-Api-Key`, … — the\n * route's `credentialHeaders`) is also left untouched unless its route sets\n * `cacheAuthenticated`, and a response with `Cache-Control: no-store`\n * (or `private`, without that opt-in) is served but never stored. `maxAgeSeconds`\n * applies to every read, including the offline fallback: an expired entry is a\n * miss, never a last resort. Under `rangeRequests`, the full resource is cached\n * once (the `Range` header stripped) and each range is sliced from it.\n *\n * Register this BEFORE `installPrecache` so specific routes win over the\n * precache catch-all.\n *\n * @param routes Ordered rules; the first whose `match` passes handles the request.\n */\nexport function installRuntimeCache(routes: RuntimeRoute[]): void {\n const sw = getSwScope();\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n const route = routes.find((candidate) => routeMatches(candidate, url, request));\n if (!route) return;\n if (!route.cacheAuthenticated && credentialsOn(request, route).length > 0) return;\n const extend = (promise: Promise<unknown>): void => event.waitUntil(promise);\n\n if (route.rangeRequests && request.headers.has(\"range\")) {\n const full = new Request(request.url, {\n headers: stripRange(request.headers),\n credentials: request.credentials,\n mode: request.mode === \"navigate\" ? \"same-origin\" : request.mode,\n });\n event.respondWith(\n runRoute(full, route, extend).then((response) =>\n createPartialResponse(request, response),\n ),\n );\n return;\n }\n\n event.respondWith(runRoute(request, route, extend));\n });\n}\n\n/** Copy headers without the `Range` header (so the cached entry is the full file). */\nfunction stripRange(headers: Headers): Headers {\n const out = new Headers(headers);\n out.delete(\"range\");\n return out;\n}\n\n/**\n * Precache the app shell at `install` and serve it offline:\n * - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),\n * - caches every listed URL under a versioned cache,\n * - on `activate`, deletes stale precache versions and claims open clients,\n * - on `fetch`, serves precached assets cache-first and falls back to the\n * `navigateFallback` document for offline navigations (SPA routing).\n *\n * Same-origin only. Register this LAST, after any {@link installRuntimeCache}.\n */\nexport function installPrecache(options: InstallPrecacheOptions = {}): void {\n const sw = getSwScope();\n const {\n manifestUrl = \"/precache-manifest.json\",\n cacheName = \"tempest-precache\",\n navigateFallback = \"/index.html\",\n navigateFallbackDenylist = [],\n skipWaiting = true,\n navigationPreload = true,\n } = options;\n\n sw.addEventListener(\"install\", (event) => {\n event.waitUntil(\n (async () => {\n const response = await fetch(manifestUrl, { cache: \"no-cache\" });\n const manifest = (await response.json()) as PrecacheManifest;\n precacheName = `${cacheName}-${manifest.version}`;\n\n const cache = await caches.open(precacheName);\n await cache.addAll(manifest.urls);\n for (const url of manifest.urls) {\n precachedPaths.add(new URL(url, sw.location.origin).pathname);\n }\n if (skipWaiting) await sw.skipWaiting();\n })(),\n );\n });\n\n sw.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n (async () => {\n const keys = await caches.keys();\n await Promise.all(\n keys\n .filter((key) => key.startsWith(`${cacheName}-`) && key !== precacheName)\n .map((key) => caches.delete(key)),\n );\n if (navigationPreload && sw.registration?.navigationPreload) {\n await sw.registration.navigationPreload.enable();\n }\n await sw.clients.claim();\n })(),\n );\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n if (url.origin !== sw.location.origin) return;\n\n // SPA navigations: serve the cached app shell when offline.\n if (request.mode === \"navigate\") {\n if (navigateFallbackDenylist.some((re) => re.test(url.pathname))) return;\n event.respondWith(\n (async () => {\n try {\n const preloaded = await event.preloadResponse;\n if (preloaded) return preloaded;\n return await fetch(request);\n } catch {\n const cache = await caches.open(precacheName);\n const shell = await cache.match(navigateFallback);\n if (shell) return shell;\n throw new Error(\"offline and no cached app shell\");\n }\n })(),\n );\n return;\n }\n\n // Precached static assets: cache-first.\n if (precachedPaths.has(url.pathname)) {\n event.respondWith(\n (async () => {\n const cache = await caches.open(precacheName);\n const cached = await cache.match(request);\n return cached ?? fetch(request);\n })(),\n );\n }\n });\n}\n"],"mappings":"A,4CAyDA,SAASE,GAA4B,CACjC,OAAO,UACX,CAqFA,IAAIC,EAAe,GACbC,EAAiB,IAAI,IAQrBC,EAAmB,sBAOzB,SAASC,EAAU,EAAoB,EAAiC,CACpE,GAAI,CAACC,EAAe,MAAO,GAC3B,IAAMC,EAAQ,OAAOC,EAAS,QAAQ,IAAIJ,CAAgB,CAAC,EACrDK,EAAaD,EAAS,QAAQ,IAAI,MAAM,EACxCE,EAAWH,EAAQ,EAAIA,EAAQE,EAAa,IAAI,KAAKA,CAAU,CAAC,CAAC,QAAQ,EAAI,IAEnF,MADA,CAAI,OAAO,MAAMC,CAAQ,IACjB,KAAK,IAAI,EAAIA,GAAY,IAAOJ,CAC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et","require_credential_headers","getSwScope","precacheName","precachedPaths","CACHED_AT_HEADER","isExpired","maxAgeSeconds","stamp","response","dateHeader","storedAt","cacheControlDirectives","directive","varyNames","vary","name","isStorable","directives","route","isCredentialed","request","credentialsOn","store","headers","varies","missing","copy","cache","trimCache","maxEntries","cacheName","keys","key","cacheFirst","cached","networkFirst","network","timeoutMs","timeout","extend","reject","staleWhileRevalidate","fresh","runRoute","routeMatches","url","createPartialResponse","rangeHeader","match","buffer","total","start","end","suffix","slice","installRuntimeCache","event","routes","candidate","promise","full","stripRange","out","installPrecache","sw","options","manifest","manifestUrl","skipWaiting","navigationPreload","navigateFallbackDenylist","re","shell","navigateFallback"],"sources":["../../src/sw/cache.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines — precache, runtime strategies (cache-first, network-\n * first, stale-while-revalidate), expiry and the inspect/clear helpers all address\n * the same Cache Storage namespace, and the naming scheme that keeps them from\n * evicting each other is the file's whole contract.\n */\n/**\n * Service-worker caching helpers — a small, dependency-free subset of what\n * Workbox provides: precaching of the build's app shell (so the app launches\n * offline) plus runtime caching strategies for fonts, APIs and images.\n *\n * Import these inside your own `sw.ts`. They run in the service-worker global\n * scope, not the main thread. Pair `installPrecache` with the\n * `tempestPwaManifest()` Vite plugin (from `tempest-react-sdk/vite`), which\n * emits the `precache-manifest.json` this reads at install time.\n *\n * @example\n * /// <reference lib=\"webworker\" />\n * import { installRuntimeCache, installPrecache } from \"tempest-react-sdk/sw\";\n *\n * // Register specific routes FIRST so they win over the precache catch-all.\n * installRuntimeCache([\n * { match: /\\/api\\//, strategy: \"network-first\", cacheName: \"tempest-api\", maxAgeSeconds: 300 },\n * ]);\n * installPrecache();\n */\n\nimport { credentialHeaderSet } from \"./credential-headers\";\n\n/** Minimal shape of the events we touch, to avoid pulling in `lib.webworker`. */\ninterface ExtendableEventLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\ninterface FetchEventLike extends ExtendableEventLike {\n request: Request;\n respondWith(response: Response | Promise<Response>): void;\n /** Resolves to the navigation-preload response when it is enabled, else `undefined`. */\n preloadResponse?: Promise<Response | undefined>;\n}\n\n/** Minimal shape of `registration.navigationPreload` (Navigation Preload API). */\ninterface NavigationPreloadManagerLike {\n enable(): Promise<void>;\n disable(): Promise<void>;\n}\n\ninterface CacheSwGlobal {\n addEventListener(type: \"install\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"activate\", listener: (event: ExtendableEventLike) => void): void;\n addEventListener(type: \"fetch\", listener: (event: FetchEventLike) => void): void;\n clients: { claim(): Promise<void> };\n skipWaiting(): Promise<void>;\n location: { origin: string };\n registration?: { navigationPreload?: NavigationPreloadManagerLike };\n}\n\nfunction getSwScope(): CacheSwGlobal {\n return globalThis as unknown as CacheSwGlobal;\n}\n\n/** Caching strategy for a runtime route. Mirrors the common Workbox trio. */\nexport type RuntimeStrategy = \"cache-first\" | \"network-first\" | \"stale-while-revalidate\";\n\n/** A single runtime-caching rule, matched against each `GET` request. */\nexport interface RuntimeRoute {\n /** A `RegExp` tested against the full URL, or a predicate over the parsed URL. */\n match: RegExp | ((url: URL, request: Request) => boolean);\n /** How to resolve a match. */\n strategy: RuntimeStrategy;\n /** Cache bucket name for this route. */\n cacheName: string;\n /** Trim the cache to at most this many entries (FIFO) after each write. */\n maxEntries?: number;\n /** Treat a cached response older than this (seconds) as a miss. */\n maxAgeSeconds?: number;\n /** For `network-first`: fall back to cache after this timeout (seconds). */\n networkTimeoutSeconds?: number;\n /**\n * Serve HTTP `Range` requests (206 Partial Content) by slicing the cached\n * full response. Enable for audio/video so seeking works offline. The full\n * resource is cached once (the `Range` header is stripped before caching).\n */\n rangeRequests?: boolean;\n /**\n * Opt in to caching credentialed requests — those that carry a credential\n * header (see `credentialHeaders`) or are a CORS-mode `fetch` sent with\n * `credentials: \"include\"` — and responses marked `Cache-Control: private`.\n * Default `false`.\n *\n * Cache Storage is keyed by URL and outlives the session: without this\n * gate, a `GET /api/me` stored for one account was served to the next\n * account on the same browser whenever the network failed or exceeded\n * `networkTimeoutSeconds` (reproduced in Chromium 153, 11/10/2026). With\n * the default, credentialed requests bypass the route entirely and reach\n * the network as if no service worker were installed.\n *\n * When enabled, every stored entry gets `Vary` on each credential header the\n * request carried, so the Cache API only matches it for the same credential —\n * another account (or no account) misses instead of reading it. A token\n * rotated while online simply repopulates the entry. Pair it with\n * `clearSessionData()` on logout, which removes the entries themselves.\n * `Cache-Control: no-store` is never cached, opt-in or not.\n *\n * A cookie session is only partly visible here: the worker cannot see\n * `Cookie`. What it can see is a `fetch` that asked for cookies explicitly —\n * `mode: \"cors\"` with `credentials: \"include\"`, which is what `ApiClient`\n * sends under `withCredentials` — and since 0.82.0 that request is treated\n * as credentialed too (#531). `<img>`, `<audio>` and `<video>` also send\n * `credentials: \"include\"`, but in `no-cors` mode, so they keep caching. A\n * plain same-origin `fetch` (`credentials: \"same-origin\"`, the default)\n * carries the cookie without saying so; such an API stays private only\n * through `Cache-Control: private`/`no-store` on its responses and\n * `clearSessionData()` on logout. Opting a cookie request in caches it by\n * URL — there is no credential header to vary on — so `clearSessionData()`\n * is then its only isolation.\n */\n cacheAuthenticated?: boolean;\n /**\n * Header names that mark a request as credentialed. Default\n * `DEFAULT_CREDENTIAL_HEADERS` (`authorization`, `x-api-key`,\n * `x-auth-token`, …) — the same list the background-sync queue strips.\n */\n credentialHeaders?: readonly string[];\n}\n\n/** Options for {@link installPrecache}. */\nexport interface InstallPrecacheOptions {\n /** URL of the manifest emitted by `tempestPwaManifest()`. Default `/precache-manifest.json`. */\n manifestUrl?: string;\n /** Cache name prefix; the manifest `version` is appended. Default `tempest-precache`. */\n cacheName?: string;\n /** App-shell document served for navigation requests offline. Default `/index.html`. */\n navigateFallback?: string;\n /** Navigation paths that should NOT use the fallback (e.g. `[/^\\/api\\//]`). */\n navigateFallbackDenylist?: RegExp[];\n /** Activate the new worker immediately after precaching. Default `true`. */\n skipWaiting?: boolean;\n /**\n * Enable the Navigation Preload API on `activate`, so the browser fetches\n * the navigation request in parallel with the worker boot and the handler\n * serves `event.preloadResponse` — cutting first-navigation latency after\n * the worker starts. Silently ignored where unsupported. Default `true`.\n */\n navigationPreload?: boolean;\n}\n\ninterface PrecacheManifest {\n version: string;\n urls: string[];\n}\n\nlet precacheName = \"\";\nconst precachedPaths = new Set<string>();\n\n/**\n * Header stamped on every runtime-cache entry with the epoch milliseconds of the\n * write. `Date` alone is not enough: it is not a CORS-safelisted response\n * header, so for a cross-origin API the worker reads `null` and `maxAgeSeconds`\n * would never expire anything.\n */\nconst CACHED_AT_HEADER = \"x-tempest-cached-at\";\n\n/**\n * Whether a cached response has aged past `maxAgeSeconds`. Reads the\n * {@link CACHED_AT_HEADER} stamp written by the runtime cache, and falls back to\n * `Date` for entries written before the stamp existed.\n */\nfunction isExpired(response: Response, maxAgeSeconds?: number): boolean {\n if (!maxAgeSeconds) return false;\n const stamp = Number(response.headers.get(CACHED_AT_HEADER));\n const dateHeader = response.headers.get(\"date\");\n const storedAt = stamp > 0 ? stamp : dateHeader ? new Date(dateHeader).getTime() : NaN;\n if (Number.isNaN(storedAt)) return false;\n return (Date.now() - storedAt) / 1000 > maxAgeSeconds;\n}\n\n/** The `Cache-Control` directives of a response, lower-cased. */\nfunction cacheControlDirectives(response: Response): string[] {\n return (response.headers.get(\"cache-control\") ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((directive) => directive.trim().split(\"=\")[0]);\n}\n\n/** The comma-separated names of a response's `Vary` header, trimmed and lower-cased. */\nfunction varyNames(vary: string | null): string[] {\n return (vary ?? \"\")\n .toLowerCase()\n .split(\",\")\n .map((name) => name.trim());\n}\n\n/**\n * Whether a network response may be written to the route's cache: it must be\n * `ok`, never `no-store`, never `Vary: *`, and `private` only under\n * `cacheAuthenticated`.\n *\n * `Vary: *` says no later request can be proven to match, and `Cache.put`\n * rejects it with a `TypeError`. Before 0.82.0 that rejection escaped the\n * strategy, so a response the network had delivered became the offline\n * fallback path (network-first), an error (cache-first) or nothing at all\n * (stale-while-revalidate) (#534).\n */\nfunction isStorable(response: Response, route: RuntimeRoute): boolean {\n if (!response.ok) return false;\n if (varyNames(response.headers.get(\"vary\")).includes(\"*\")) return false;\n const directives = cacheControlDirectives(response);\n if (directives.includes(\"no-store\")) return false;\n return route.cacheAuthenticated === true || !directives.includes(\"private\");\n}\n\n/**\n * Whether a request is session-bound for its route: it carries a credential\n * header, or it is a CORS `fetch` that asked for cookies with\n * `credentials: \"include\"` (`ApiClient` under `withCredentials`). A `no-cors`\n * request — `<img>`, `<audio>`, `<video>` — also sends `include` by default and\n * is not counted, or every image would bypass the cache.\n */\nfunction isCredentialed(request: Request, route: RuntimeRoute): boolean {\n if (request.mode === \"cors\" && request.credentials === \"include\") return true;\n return credentialsOn(request, route).length > 0;\n}\n\n/** The credential headers, lower-cased, that a request carries for its route. */\nfunction credentialsOn(request: Request, route: RuntimeRoute): string[] {\n return [...credentialHeaderSet(route.credentialHeaders)].filter((name) =>\n request.headers.has(name),\n );\n}\n\n/**\n * Write a response to the route's cache with the {@link CACHED_AT_HEADER} stamp\n * and, under `cacheAuthenticated`, `Vary` on each credential header the request\n * carried, so the entry only matches the credential that produced it. Skips\n * responses that {@link isStorable} rejects, then trims the cache to\n * `maxEntries`.\n */\nasync function store(\n cache: Cache,\n request: Request,\n response: Response,\n route: RuntimeRoute,\n): Promise<void> {\n if (!isStorable(response, route)) return;\n const headers = new Headers(response.headers);\n headers.set(CACHED_AT_HEADER, String(Date.now()));\n if (route.cacheAuthenticated) {\n const vary = headers.get(\"vary\");\n const varies = varyNames(vary);\n const missing = credentialsOn(request, route).filter((name) => !varies.includes(name));\n if (missing.length > 0) {\n headers.set(\"vary\", [vary, ...missing].filter(Boolean).join(\", \"));\n }\n }\n const copy = response.clone();\n await cache.put(\n request,\n new Response(copy.body, { status: copy.status, statusText: copy.statusText, headers }),\n );\n await trimCache(route.cacheName, route.maxEntries);\n}\n\n/** Drop oldest entries until the cache holds at most `maxEntries`. */\nasync function trimCache(cacheName: string, maxEntries?: number): Promise<void> {\n if (!maxEntries) return;\n const cache = await caches.open(cacheName);\n const keys = await cache.keys();\n if (keys.length <= maxEntries) return;\n for (const key of keys.slice(0, keys.length - maxEntries)) {\n await cache.delete(key);\n }\n}\n\nasync function cacheFirst(request: Request, route: RuntimeRoute): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n\n const response = await fetch(request);\n await store(cache, request, response, route);\n return response;\n}\n\n/**\n * Network-first. When the timeout wins, the network request keeps running to\n * refresh the cache, and is handed to `extend` (`event.waitUntil`) so the\n * worker is not stopped mid-write.\n */\nasync function networkFirst(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n\n const network = (async (): Promise<Response> => {\n const response = await fetch(request);\n await store(cache, request, response, route);\n return response;\n })();\n\n const timeoutMs = (route.networkTimeoutSeconds ?? 0) * 1000;\n try {\n if (timeoutMs > 0) {\n const timeout = new Promise<never>((_, reject) =>\n setTimeout(() => {\n extend(network.catch(() => undefined));\n reject(new Error(\"network-timeout\"));\n }, timeoutMs),\n );\n return await Promise.race([network, timeout]);\n }\n return await network;\n } catch {\n const cached = await cache.match(request);\n if (cached && !isExpired(cached, route.maxAgeSeconds)) return cached;\n throw new Error(\"network-first: no network and no cache\");\n }\n}\n\n/**\n * Stale-while-revalidate. A fresh cached response is served at once, and the\n * revalidation is handed to `extend` (`event.waitUntil`): without it the\n * browser may stop the worker before the refreshed response is written.\n */\nasync function staleWhileRevalidate(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n const cache = await caches.open(route.cacheName);\n const cached = await cache.match(request);\n\n const network = fetch(request)\n .then(async (response) => {\n await store(cache, request, response, route);\n return response;\n })\n .catch(() => undefined);\n\n const fresh = cached && !isExpired(cached, route.maxAgeSeconds) ? cached : undefined;\n if (fresh) {\n extend(network);\n return fresh;\n }\n const response = await network;\n if (response) return response;\n throw new Error(\"stale-while-revalidate: no network and no cache\");\n}\n\nfunction runRoute(\n request: Request,\n route: RuntimeRoute,\n extend: (promise: Promise<unknown>) => void,\n): Promise<Response> {\n switch (route.strategy) {\n case \"cache-first\":\n return cacheFirst(request, route);\n case \"network-first\":\n return networkFirst(request, route, extend);\n case \"stale-while-revalidate\":\n return staleWhileRevalidate(request, route, extend);\n }\n}\n\nfunction routeMatches(route: RuntimeRoute, url: URL, request: Request): boolean {\n return typeof route.match === \"function\"\n ? route.match(url, request)\n : route.match.test(url.href);\n}\n\n/**\n * Build a `206 Partial Content` response from a full one for an HTTP `Range`\n * request. Supports `bytes=start-end`, open-ended `bytes=start-` and suffix\n * `bytes=-suffixLength` (the last N bytes). Returns the original response when there is no usable\n * `Range` header, or a `416` when the range is unsatisfiable.\n *\n * @param request The incoming request (its `Range` header drives the slice).\n * @param response The full (200) response to slice.\n */\nexport async function createPartialResponse(\n request: Request,\n response: Response,\n): Promise<Response> {\n const rangeHeader = request.headers.get(\"range\");\n if (!rangeHeader) return response;\n\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(rangeHeader.trim());\n if (!match || (match[1] === \"\" && match[2] === \"\")) {\n return new Response(null, { status: 416, statusText: \"Range Not Satisfiable\" });\n }\n\n const buffer = await response.clone().arrayBuffer();\n const total = buffer.byteLength;\n\n let start: number;\n let end: number;\n if (match[1] === \"\") {\n const suffix = Number(match[2]);\n start = Math.max(0, total - suffix);\n end = total - 1;\n } else {\n start = Number(match[1]);\n end = match[2] === \"\" ? total - 1 : Math.min(Number(match[2]), total - 1);\n }\n\n if (start > end || start >= total) {\n return new Response(null, {\n status: 416,\n statusText: \"Range Not Satisfiable\",\n headers: { \"Content-Range\": `bytes */${total}` },\n });\n }\n\n const slice = buffer.slice(start, end + 1);\n const headers = new Headers(response.headers);\n headers.set(\"Content-Range\", `bytes ${start}-${end}/${total}`);\n headers.set(\"Content-Length\", String(slice.byteLength));\n headers.set(\"Accept-Ranges\", \"bytes\");\n\n return new Response(slice, {\n status: 206,\n statusText: \"Partial Content\",\n headers,\n });\n}\n\n/**\n * Install a `fetch` handler that resolves matching `GET` requests with the\n * given runtime strategies. Non-matching requests are left untouched (no\n * `respondWith`), so a later {@link installPrecache} can handle them.\n *\n * A request carrying a credential header (`Authorization`, `X-Api-Key`, … — the\n * route's `credentialHeaders`), or a CORS `fetch` sent with\n * `credentials: \"include\"`, is also left untouched unless its route sets\n * `cacheAuthenticated`, and a response with `Cache-Control: no-store`\n * (or `private`, without that opt-in) or `Vary: *` is served but never stored. `maxAgeSeconds`\n * applies to every read, including the offline fallback: an expired entry is a\n * miss, never a last resort. Under `rangeRequests`, the full resource is cached\n * once (the `Range` header stripped) and each range is sliced from it.\n *\n * Register this BEFORE `installPrecache` so specific routes win over the\n * precache catch-all.\n *\n * @param routes Ordered rules; the first whose `match` passes handles the request.\n */\nexport function installRuntimeCache(routes: RuntimeRoute[]): void {\n const sw = getSwScope();\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n const route = routes.find((candidate) => routeMatches(candidate, url, request));\n if (!route) return;\n if (!route.cacheAuthenticated && isCredentialed(request, route)) return;\n const extend = (promise: Promise<unknown>): void => event.waitUntil(promise);\n\n if (route.rangeRequests && request.headers.has(\"range\")) {\n const full = new Request(request.url, {\n headers: stripRange(request.headers),\n credentials: request.credentials,\n mode: request.mode === \"navigate\" ? \"same-origin\" : request.mode,\n });\n event.respondWith(\n runRoute(full, route, extend).then((response) =>\n createPartialResponse(request, response),\n ),\n );\n return;\n }\n\n event.respondWith(runRoute(request, route, extend));\n });\n}\n\n/** Copy headers without the `Range` header (so the cached entry is the full file). */\nfunction stripRange(headers: Headers): Headers {\n const out = new Headers(headers);\n out.delete(\"range\");\n return out;\n}\n\n/**\n * Precache the app shell at `install` and serve it offline:\n * - reads `precache-manifest.json` (emitted by `tempestPwaManifest()`),\n * - caches every listed URL under a versioned cache,\n * - on `activate`, deletes stale precache versions and claims open clients,\n * - on `fetch`, serves precached assets cache-first and falls back to the\n * `navigateFallback` document for offline navigations (SPA routing).\n *\n * Same-origin only. Register this LAST, after any {@link installRuntimeCache}.\n */\nexport function installPrecache(options: InstallPrecacheOptions = {}): void {\n const sw = getSwScope();\n const {\n manifestUrl = \"/precache-manifest.json\",\n cacheName = \"tempest-precache\",\n navigateFallback = \"/index.html\",\n navigateFallbackDenylist = [],\n skipWaiting = true,\n navigationPreload = true,\n } = options;\n\n sw.addEventListener(\"install\", (event) => {\n event.waitUntil(\n (async () => {\n const response = await fetch(manifestUrl, { cache: \"no-cache\" });\n const manifest = (await response.json()) as PrecacheManifest;\n precacheName = `${cacheName}-${manifest.version}`;\n\n const cache = await caches.open(precacheName);\n await cache.addAll(manifest.urls);\n for (const url of manifest.urls) {\n precachedPaths.add(new URL(url, sw.location.origin).pathname);\n }\n if (skipWaiting) await sw.skipWaiting();\n })(),\n );\n });\n\n sw.addEventListener(\"activate\", (event) => {\n event.waitUntil(\n (async () => {\n const keys = await caches.keys();\n await Promise.all(\n keys\n .filter((key) => key.startsWith(`${cacheName}-`) && key !== precacheName)\n .map((key) => caches.delete(key)),\n );\n if (navigationPreload && sw.registration?.navigationPreload) {\n await sw.registration.navigationPreload.enable();\n }\n await sw.clients.claim();\n })(),\n );\n });\n\n sw.addEventListener(\"fetch\", (event) => {\n const request = event.request;\n if (request.method !== \"GET\") return;\n\n const url = new URL(request.url);\n if (url.origin !== sw.location.origin) return;\n\n // SPA navigations: serve the cached app shell when offline.\n if (request.mode === \"navigate\") {\n if (navigateFallbackDenylist.some((re) => re.test(url.pathname))) return;\n event.respondWith(\n (async () => {\n try {\n const preloaded = await event.preloadResponse;\n if (preloaded) return preloaded;\n return await fetch(request);\n } catch {\n const cache = await caches.open(precacheName);\n const shell = await cache.match(navigateFallback);\n if (shell) return shell;\n throw new Error(\"offline and no cached app shell\");\n }\n })(),\n );\n return;\n }\n\n // Precached static assets: cache-first.\n if (precachedPaths.has(url.pathname)) {\n event.respondWith(\n (async () => {\n const cache = await caches.open(precacheName);\n const cached = await cache.match(request);\n return cached ?? fetch(request);\n })(),\n );\n }\n });\n}\n"],"mappings":"A,4CAyDA,SAASE,GAA4B,CACjC,OAAO,UACX,CA6FA,IAAIC,EAAe,GACbC,EAAiB,IAAI,IAQrBC,EAAmB,sBAOzB,SAASC,EAAU,EAAoB,EAAiC,CACpE,GAAI,CAACC,EAAe,MAAO,GAC3B,IAAMC,EAAQ,OAAOC,EAAS,QAAQ,IAAIJ,CAAgB,CAAC,EACrDK,EAAaD,EAAS,QAAQ,IAAI,MAAM,EACxCE,EAAWH,EAAQ,EAAIA,EAAQE,EAAa,IAAI,KAAKA,CAAU,CAAC,CAAC,QAAQ,EAAI,IAEnF,MADA,CAAI,OAAO,MAAMC,CAAQ,IACjB,KAAK,IAAI,EAAIA,GAAY,IAAOJ,CAC5C,CAGA,SAASK,EAAuB,EAA8B,CAC1D,OAAQH,EAAS,QAAQ,IAAI,eAAe,GAAK,GAAA,CAC5C,YAAY,CAAC,CACb,MAAM,GAAG,CAAC,CACV,IAAK,GAAcI,EAAU,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAC1D,CAGA,SAASC,EAAU,EAA+B,CAC9C,OAAQC,GAAQ,GAAA,CACX,YAAY,CAAC,CACb,MAAM,GAAG,CAAC,CACV,IAAK,GAASC,EAAK,KAAK,CAAC,CAClC,CAaA,SAASC,EAAW,EAAoB,EAA8B,CAElE,GADI,CAACR,EAAS,IACVK,EAAUL,EAAS,QAAQ,IAAI,MAAM,CAAC,CAAC,CAAC,SAAS,GAAG,EAAG,MAAO,GAClE,IAAMS,EAAaN,EAAuBH,CAAQ,EAElD,OADIS,EAAW,SAAS,UAAU,EAAU,GACrCC,EAAM,qBAAuB,IAAQ,CAACD,EAAW,SAAS,SAAS,CAC9E,CASA,SAASE,EAAe,EAAkB,EAA8B,CAEpE,OADIC,EAAQ,OAAS,QAAUA,EAA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GAAU,CACpC,IAAM5C,EAAUoC,EAAM,QACtB,GAAIpC,EAAQ,SAAW,MAAO,OAE9B,IAAMyB,EAAM,IAAI,IAAIzB,EAAQ,GAAG,EAC/B,GAAIyB,EAAI,SAAWmB,EAAG,SAAS,OAG/B,IAAI5C,EAAQ,OAAS,WAAY,CAC7B,GAAIkD,EAAyB,KAAM,GAAOC,EAAG,KAAK1B,EAAI,QAAQ,CAAC,EAAG,OAClEW,EAAM,aACD,SAAY,CACT,GAAI,CAGA,OADI,MADoBA,EAAM,iBAEvB,MAAM,MAAMpC,CAAO,CAC9B,MAAQ,CAEJ,IAAMoD,EAAQ,MAAM,MADA,OAAO,KAAKtE,CAAY,EAAA,CAClB,MAAMuE,CAAgB,EAChD,GAAID,EAAO,OAAOA,EAClB,MAAU,MAAM,iCAAiC,CACrD,CACJ,EAAA,CAAG,CACP,CAEJ,MAGIrE,EAAe,IAAI0C,EAAI,QAAQ,GAC/BW,EAAM,aACD,SAGU,MADc,MADD,OAAO,KAAKtD,CAAY,EAAA,CACjB,MAAMkB,CAAO,GACvB,MAAMA,CAAO,EAClC,CAAG,CACP,CAVJ,CAYJ,CAAC,CACL,C"}
package/dist/sw/cache.js CHANGED
@@ -12,43 +12,49 @@ function a(e, t) {
12
12
  function o(e) {
13
13
  return (e.headers.get("cache-control") ?? "").toLowerCase().split(",").map((e) => e.trim().split("=")[0]);
14
14
  }
15
- function s(e, t) {
16
- if (!e.ok) return !1;
15
+ function s(e) {
16
+ return (e ?? "").toLowerCase().split(",").map((e) => e.trim());
17
+ }
18
+ function c(e, t) {
19
+ if (!e.ok || s(e.headers.get("vary")).includes("*")) return !1;
17
20
  let n = o(e);
18
21
  return n.includes("no-store") ? !1 : t.cacheAuthenticated === !0 || !n.includes("private");
19
22
  }
20
- function c(t, n) {
23
+ function l(e, t) {
24
+ return e.mode === "cors" && e.credentials === "include" || u(e, t).length > 0;
25
+ }
26
+ function u(t, n) {
21
27
  return [...e(n.credentialHeaders)].filter((e) => t.headers.has(e));
22
28
  }
23
- async function l(e, t, n, r) {
24
- if (!s(n, r)) return;
29
+ async function d(e, t, n, r) {
30
+ if (!c(n, r)) return;
25
31
  let a = new Headers(n.headers);
26
32
  if (a.set(i, String(Date.now())), r.cacheAuthenticated) {
27
- let e = a.get("vary"), n = (e ?? "").toLowerCase().split(",").map((e) => e.trim()), i = c(t, r).filter((e) => !n.includes(e));
28
- i.length > 0 && !n.includes("*") && a.set("vary", [e, ...i].filter(Boolean).join(", "));
33
+ let e = a.get("vary"), n = s(e), i = u(t, r).filter((e) => !n.includes(e));
34
+ i.length > 0 && a.set("vary", [e, ...i].filter(Boolean).join(", "));
29
35
  }
30
36
  let o = n.clone();
31
37
  await e.put(t, new Response(o.body, {
32
38
  status: o.status,
33
39
  statusText: o.statusText,
34
40
  headers: a
35
- })), await u(r.cacheName, r.maxEntries);
41
+ })), await f(r.cacheName, r.maxEntries);
36
42
  }
37
- async function u(e, t) {
43
+ async function f(e, t) {
38
44
  if (!t) return;
39
45
  let n = await caches.open(e), r = await n.keys();
40
46
  if (!(r.length <= t)) for (let e of r.slice(0, r.length - t)) await n.delete(e);
41
47
  }
42
- async function d(e, t) {
48
+ async function p(e, t) {
43
49
  let n = await caches.open(t.cacheName), r = await n.match(e);
44
50
  if (r && !a(r, t.maxAgeSeconds)) return r;
45
51
  let i = await fetch(e);
46
- return await l(n, e, i, t), i;
52
+ return await d(n, e, i, t), i;
47
53
  }
48
- async function f(e, t, n) {
54
+ async function m(e, t, n) {
49
55
  let r = await caches.open(t.cacheName), i = (async () => {
50
56
  let n = await fetch(e);
51
- return await l(r, e, n, t), n;
57
+ return await d(r, e, n, t), n;
52
58
  })(), o = (t.networkTimeoutSeconds ?? 0) * 1e3;
53
59
  try {
54
60
  if (o > 0) {
@@ -64,24 +70,24 @@ async function f(e, t, n) {
64
70
  throw Error("network-first: no network and no cache");
65
71
  }
66
72
  }
67
- async function p(e, t, n) {
68
- let r = await caches.open(t.cacheName), i = await r.match(e), o = fetch(e).then(async (n) => (await l(r, e, n, t), n)).catch(() => void 0), s = i && !a(i, t.maxAgeSeconds) ? i : void 0;
73
+ async function h(e, t, n) {
74
+ let r = await caches.open(t.cacheName), i = await r.match(e), o = fetch(e).then(async (n) => (await d(r, e, n, t), n)).catch(() => void 0), s = i && !a(i, t.maxAgeSeconds) ? i : void 0;
69
75
  if (s) return n(o), s;
70
76
  let c = await o;
71
77
  if (c) return c;
72
78
  throw Error("stale-while-revalidate: no network and no cache");
73
79
  }
74
- function m(e, t, n) {
80
+ function g(e, t, n) {
75
81
  switch (t.strategy) {
76
- case "cache-first": return d(e, t);
77
- case "network-first": return f(e, t, n);
78
- case "stale-while-revalidate": return p(e, t, n);
82
+ case "cache-first": return p(e, t);
83
+ case "network-first": return m(e, t, n);
84
+ case "stale-while-revalidate": return h(e, t, n);
79
85
  }
80
86
  }
81
- function h(e, t, n) {
87
+ function _(e, t, n) {
82
88
  return typeof e.match == "function" ? e.match(t, n) : e.match.test(t.href);
83
89
  }
84
- async function g(e, t) {
90
+ async function v(e, t) {
85
91
  let n = e.headers.get("range");
86
92
  if (!n) return t;
87
93
  let r = /^bytes=(\d*)-(\d*)$/.exec(n.trim());
@@ -106,28 +112,28 @@ async function g(e, t) {
106
112
  headers: l
107
113
  });
108
114
  }
109
- function _(e) {
115
+ function y(e) {
110
116
  t().addEventListener("fetch", (t) => {
111
117
  let n = t.request;
112
118
  if (n.method !== "GET") return;
113
- let r = new URL(n.url), i = e.find((e) => h(e, r, n));
114
- if (!i || !i.cacheAuthenticated && c(n, i).length > 0) return;
119
+ let r = new URL(n.url), i = e.find((e) => _(e, r, n));
120
+ if (!i || !i.cacheAuthenticated && l(n, i)) return;
115
121
  let a = (e) => t.waitUntil(e);
116
122
  if (i.rangeRequests && n.headers.has("range")) {
117
123
  let e = new Request(n.url, {
118
- headers: v(n.headers),
124
+ headers: b(n.headers),
119
125
  credentials: n.credentials,
120
126
  mode: n.mode === "navigate" ? "same-origin" : n.mode
121
127
  });
122
- t.respondWith(m(e, i, a).then((e) => g(n, e)));
123
- } else t.respondWith(m(n, i, a));
128
+ t.respondWith(g(e, i, a).then((e) => v(n, e)));
129
+ } else t.respondWith(g(n, i, a));
124
130
  });
125
131
  }
126
- function v(e) {
132
+ function b(e) {
127
133
  let t = new Headers(e);
128
134
  return t.delete("range"), t;
129
135
  }
130
- function y(e = {}) {
136
+ function x(e = {}) {
131
137
  let i = t(), { manifestUrl: a = "/precache-manifest.json", cacheName: o = "tempest-precache", navigateFallback: s = "/index.html", navigateFallbackDenylist: c = [], skipWaiting: l = !0, navigationPreload: u = !0 } = e;
132
138
  i.addEventListener("install", (e) => {
133
139
  e.waitUntil((async () => {
@@ -162,6 +168,6 @@ function y(e = {}) {
162
168
  });
163
169
  }
164
170
  //#endregion
165
- export { g as createPartialResponse, y as installPrecache, _ as installRuntimeCache };
171
+ export { v as createPartialResponse, x as installPrecache, y as installRuntimeCache };
166
172
 
167
173
  //# sourceMappingURL=cache.js.map