@eifi1/ui-kit 0.45.0 → 0.46.1

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 (238) hide show
  1. package/README.md +26 -14
  2. package/dist/admin/admin-area-labels.d.ts +9 -0
  3. package/dist/admin/admin-area-labels.js +5 -1
  4. package/dist/admin/admin-area-labels.js.map +1 -1
  5. package/dist/admin/admin-overview.d.ts +16 -1
  6. package/dist/admin/admin-overview.js +12 -1
  7. package/dist/admin/admin-overview.js.map +1 -1
  8. package/dist/admin/mail-test-card.d.ts +3 -2
  9. package/dist/admin/mail-test-card.js +3 -1
  10. package/dist/admin/mail-test-card.js.map +1 -1
  11. package/dist/admin/user-roster.d.ts +6 -2
  12. package/dist/admin/user-roster.js +7 -3
  13. package/dist/admin/user-roster.js.map +1 -1
  14. package/dist/components/appearance-labels.d.ts +10 -0
  15. package/dist/components/appearance-labels.js +6 -1
  16. package/dist/components/appearance-labels.js.map +1 -1
  17. package/dist/components/data-table-column-settings.js +2 -2
  18. package/dist/components/data-table-column-settings.js.map +1 -1
  19. package/dist/components/data-table-head.js +2 -2
  20. package/dist/components/data-table-head.js.map +1 -1
  21. package/dist/components/data-table-row-actions.d.ts +35 -2
  22. package/dist/components/data-table-row-actions.js +98 -5
  23. package/dist/components/data-table-row-actions.js.map +1 -1
  24. package/dist/components/data-table-shared.js +9 -2
  25. package/dist/components/data-table-shared.js.map +1 -1
  26. package/dist/components/data-table.d.ts +58 -2
  27. package/dist/components/data-table.js +11 -4
  28. package/dist/components/data-table.js.map +1 -1
  29. package/dist/components/date-format-setting.d.ts +29 -0
  30. package/dist/components/date-format-setting.js +36 -0
  31. package/dist/components/date-format-setting.js.map +1 -0
  32. package/dist/components/row-actions.d.ts +12 -5
  33. package/dist/components/row-actions.js +11 -4
  34. package/dist/components/row-actions.js.map +1 -1
  35. package/dist/components/swipeable-row.d.ts +8 -0
  36. package/dist/components/swipeable-row.js.map +1 -1
  37. package/dist/components/tabs.d.ts +3 -2
  38. package/dist/components/tabs.js +1 -1
  39. package/dist/components/tabs.js.map +1 -1
  40. package/dist/components/translation-review-editor.js +1 -0
  41. package/dist/components/translation-review-editor.js.map +1 -1
  42. package/dist/components/translation-review-labels.d.ts +5 -0
  43. package/dist/components/translation-review-labels.js +2 -0
  44. package/dist/components/translation-review-labels.js.map +1 -1
  45. package/dist/components/translation-review.d.ts +18 -8
  46. package/dist/components/translation-review.js +67 -8
  47. package/dist/components/translation-review.js.map +1 -1
  48. package/dist/components/write-lock-labels.js +2 -1
  49. package/dist/components/write-lock-labels.js.map +1 -1
  50. package/dist/components/write-lock.d.ts +33 -3
  51. package/dist/components/write-lock.js +9 -0
  52. package/dist/components/write-lock.js.map +1 -1
  53. package/dist/data-table.d.ts +2 -1
  54. package/dist/data-table.js +2 -0
  55. package/dist/data-table.js.map +1 -1
  56. package/dist/eslint/index.js +1 -1
  57. package/dist/feedback/feedback-row-detail.d.ts +4 -2
  58. package/dist/feedback/feedback-row-detail.js +17 -26
  59. package/dist/feedback/feedback-row-detail.js.map +1 -1
  60. package/dist/feedback/feedback-swipe.d.ts +18 -0
  61. package/dist/feedback/feedback-swipe.js +10 -1
  62. package/dist/feedback/feedback-swipe.js.map +1 -1
  63. package/dist/i18n/german.js +41 -5
  64. package/dist/i18n/german.js.map +1 -1
  65. package/dist/i18n/kit-labels.d.ts +12 -1
  66. package/dist/i18n/kit-labels.js +8 -2
  67. package/dist/i18n/kit-labels.js.map +1 -1
  68. package/dist/i18n/locales/en.js +40 -6
  69. package/dist/i18n/locales/en.js.map +2 -2
  70. package/dist/i18n/locales/es.js +41 -5
  71. package/dist/i18n/locales/es.js.map +1 -1
  72. package/dist/i18n/locales/fr.js +41 -5
  73. package/dist/i18n/locales/fr.js.map +1 -1
  74. package/dist/i18n/locales/hu.js +41 -5
  75. package/dist/i18n/locales/hu.js.map +1 -1
  76. package/dist/i18n/locales/it.js +41 -5
  77. package/dist/i18n/locales/it.js.map +1 -1
  78. package/dist/i18n/locales/zh.js +41 -5
  79. package/dist/i18n/locales/zh.js.map +1 -1
  80. package/dist/i18n/review.js +3 -1
  81. package/dist/i18n/review.js.map +1 -1
  82. package/dist/index.d.ts +17 -4
  83. package/dist/index.js +38 -1
  84. package/dist/index.js.map +1 -1
  85. package/dist/lib/date-format.d.ts +81 -0
  86. package/dist/lib/date-format.js +56 -0
  87. package/dist/lib/date-format.js.map +1 -0
  88. package/dist/lib/format.d.ts +3 -0
  89. package/dist/lib/format.js +5 -4
  90. package/dist/lib/format.js.map +1 -1
  91. package/dist/notifications/device-zone-report.d.ts +34 -0
  92. package/dist/notifications/device-zone-report.js +31 -0
  93. package/dist/notifications/device-zone-report.js.map +1 -0
  94. package/dist/notifications/feedback-notification-types-labels.d.ts +7 -1
  95. package/dist/notifications/feedback-notification-types-labels.js +4 -1
  96. package/dist/notifications/feedback-notification-types-labels.js.map +1 -1
  97. package/dist/notifications/feedback-notification-types.d.ts +24 -5
  98. package/dist/notifications/feedback-notification-types.js +7 -2
  99. package/dist/notifications/feedback-notification-types.js.map +1 -1
  100. package/dist/notifications/notification-bell.d.ts +33 -0
  101. package/dist/notifications/notification-bell.js +74 -0
  102. package/dist/notifications/notification-bell.js.map +1 -0
  103. package/dist/notifications/notification-inbox.d.ts +86 -0
  104. package/dist/notifications/notification-inbox.js +206 -0
  105. package/dist/notifications/notification-inbox.js.map +1 -0
  106. package/dist/notifications/notification-types-setting.d.ts +6 -4
  107. package/dist/notifications/notification-types-setting.js +103 -45
  108. package/dist/notifications/notification-types-setting.js.map +1 -1
  109. package/dist/notifications/notification-types.d.ts +19 -7
  110. package/dist/notifications/notifications-labels.d.ts +44 -8
  111. package/dist/notifications/notifications-labels.js +18 -1
  112. package/dist/notifications/notifications-labels.js.map +1 -1
  113. package/dist/notifications/push-devices-setting.d.ts +20 -3
  114. package/dist/notifications/push-devices-setting.js +93 -33
  115. package/dist/notifications/push-devices-setting.js.map +1 -1
  116. package/dist/notifications/push-worker.d.ts +108 -0
  117. package/dist/notifications/push-worker.js +62 -0
  118. package/dist/notifications/push-worker.js.map +1 -0
  119. package/dist/notifications/quiet-hours-setting.d.ts +29 -17
  120. package/dist/notifications/quiet-hours-setting.js +9 -41
  121. package/dist/notifications/quiet-hours-setting.js.map +1 -1
  122. package/dist/notifications/time-zone-select.d.ts +8 -4
  123. package/dist/notifications/time-zone-select.js +2 -7
  124. package/dist/notifications/time-zone-select.js.map +1 -1
  125. package/dist/notifications/use-push-device.d.ts +4 -17
  126. package/dist/notifications/use-push-device.js +7 -15
  127. package/dist/notifications/use-push-device.js.map +1 -1
  128. package/dist/offline/local-first.d.ts +42 -0
  129. package/dist/offline/local-first.js +53 -0
  130. package/dist/offline/local-first.js.map +1 -0
  131. package/dist/offline/query-persistence.d.ts +26 -1
  132. package/dist/offline/query-persistence.js +27 -23
  133. package/dist/offline/query-persistence.js.map +1 -1
  134. package/dist/offline/service-worker-updates.d.ts +46 -0
  135. package/dist/offline/service-worker-updates.js +39 -0
  136. package/dist/offline/service-worker-updates.js.map +1 -0
  137. package/dist/offline.d.ts +5 -2
  138. package/dist/offline.js +12 -2
  139. package/dist/offline.js.map +1 -1
  140. package/dist/push-worker.d.ts +2 -0
  141. package/dist/push-worker.js +14 -0
  142. package/dist/push-worker.js.map +1 -0
  143. package/dist/shell/account-menu-text-size.d.ts +33 -0
  144. package/dist/shell/account-menu-text-size.js +51 -0
  145. package/dist/shell/account-menu-text-size.js.map +1 -0
  146. package/dist/shell/top-bar-actions.d.ts +6 -2
  147. package/dist/shell/top-bar-actions.js +1 -0
  148. package/dist/shell/top-bar-actions.js.map +1 -1
  149. package/dist/shell.d.ts +2 -0
  150. package/dist/shell.js +2 -0
  151. package/dist/shell.js.map +1 -1
  152. package/dist/sync/db.d.ts +93 -0
  153. package/dist/sync/db.js +33 -0
  154. package/dist/sync/db.js.map +1 -0
  155. package/dist/sync/engine.d.ts +126 -0
  156. package/dist/sync/engine.js +474 -0
  157. package/dist/sync/engine.js.map +1 -0
  158. package/dist/sync/hooks.d.ts +35 -0
  159. package/dist/sync/hooks.js +67 -0
  160. package/dist/sync/hooks.js.map +1 -0
  161. package/dist/sync/testing.d.ts +28 -0
  162. package/dist/sync/testing.js +41 -0
  163. package/dist/sync/testing.js.map +1 -0
  164. package/dist/sync/wire.d.ts +50 -0
  165. package/dist/sync/wire.js +2 -0
  166. package/dist/sync/wire.js.map +1 -0
  167. package/dist/sync.d.ts +7 -0
  168. package/dist/sync.js +25 -0
  169. package/dist/sync.js.map +1 -0
  170. package/dist/tour/tour-labels.js +1 -0
  171. package/dist/tour/tour-labels.js.map +1 -1
  172. package/dist/tour/tour.d.ts +30 -0
  173. package/dist/tour/tour.js +50 -6
  174. package/dist/tour/tour.js.map +1 -1
  175. package/package.json +19 -1
  176. package/src/admin/admin-area-labels.ts +13 -0
  177. package/src/admin/admin-overview.tsx +37 -2
  178. package/src/admin/mail-test-card.tsx +7 -3
  179. package/src/admin/user-roster.tsx +12 -3
  180. package/src/components/appearance-labels.ts +16 -0
  181. package/src/components/data-table-column-settings.tsx +2 -2
  182. package/src/components/data-table-head.tsx +2 -2
  183. package/src/components/data-table-row-actions.tsx +145 -5
  184. package/src/components/data-table-shared.tsx +21 -2
  185. package/src/components/data-table.tsx +68 -6
  186. package/src/components/date-format-setting.tsx +64 -0
  187. package/src/components/row-actions.tsx +33 -9
  188. package/src/components/swipeable-row.tsx +8 -0
  189. package/src/components/tabs.tsx +4 -3
  190. package/src/components/translation-review-editor.tsx +2 -0
  191. package/src/components/translation-review-labels.ts +7 -0
  192. package/src/components/translation-review.tsx +105 -15
  193. package/src/components/write-lock-labels.ts +1 -0
  194. package/src/components/write-lock.tsx +36 -3
  195. package/src/data-table.ts +4 -0
  196. package/src/feedback/feedback-row-detail.tsx +18 -23
  197. package/src/feedback/feedback-swipe.tsx +28 -1
  198. package/src/i18n/german.ts +44 -4
  199. package/src/i18n/kit-labels.tsx +18 -1
  200. package/src/i18n/locales/en.ts +1 -0
  201. package/src/i18n/locales/es.ts +44 -4
  202. package/src/i18n/locales/fr.ts +44 -4
  203. package/src/i18n/locales/hu.ts +44 -4
  204. package/src/i18n/locales/it.ts +44 -4
  205. package/src/i18n/locales/zh.ts +44 -2
  206. package/src/i18n/review.ts +3 -1
  207. package/src/index.ts +50 -1
  208. package/src/lib/date-format.ts +151 -0
  209. package/src/lib/format.ts +10 -4
  210. package/src/notifications/device-zone-report.ts +67 -0
  211. package/src/notifications/feedback-notification-types-labels.ts +10 -1
  212. package/src/notifications/feedback-notification-types.ts +30 -5
  213. package/src/notifications/notification-bell.tsx +116 -0
  214. package/src/notifications/notification-inbox.tsx +314 -0
  215. package/src/notifications/notification-types-setting.tsx +151 -55
  216. package/src/notifications/notification-types.ts +20 -8
  217. package/src/notifications/notifications-labels.ts +72 -12
  218. package/src/notifications/push-devices-setting.tsx +123 -34
  219. package/src/notifications/push-worker.ts +160 -0
  220. package/src/notifications/quiet-hours-setting.tsx +41 -58
  221. package/src/notifications/time-zone-select.tsx +9 -10
  222. package/src/notifications/use-push-device.ts +20 -33
  223. package/src/offline/local-first.ts +100 -0
  224. package/src/offline/query-persistence.ts +57 -24
  225. package/src/offline/service-worker-updates.ts +81 -0
  226. package/src/offline.ts +7 -1
  227. package/src/push-worker.ts +25 -0
  228. package/src/shell/account-menu-text-size.tsx +77 -0
  229. package/src/shell/top-bar-actions.tsx +6 -1
  230. package/src/shell.ts +3 -0
  231. package/src/sync/db.ts +125 -0
  232. package/src/sync/engine.ts +701 -0
  233. package/src/sync/hooks.ts +98 -0
  234. package/src/sync/testing.ts +73 -0
  235. package/src/sync/wire.ts +61 -0
  236. package/src/sync.ts +29 -0
  237. package/src/tour/tour-labels.ts +1 -0
  238. package/src/tour/tour.tsx +100 -7
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/notifications/use-push-device.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useMediaQuery } from \"../hooks/use-media-query\";\nimport { httpStatusOf } from \"../auth/auth-errors\";\n\n/**\n * This browser's Web Push subscription for the signed-in account\n * (docs/notifications-harmonization.md §2.7, §3.5, §4.2) — keksdose's\n * `shared/push/use-push.ts`, lifted. The service worker with its `push` and\n * `notificationclick` handlers stays the app's; this hook owns the browser's side:\n * permission, subscribe with the server's VAPID key, register the subscription, and\n * unsubscribe. The kit makes no request of its own: the app hands it one function per\n * endpoint.\n */\n\n/** The browser's notification permission, or `\"unsupported\"` where it has no push. */\nexport type PushPermission = NotificationPermission | \"unsupported\";\n\n/** Why turning push on or off could not finish — a {@link PushDeviceError}'s `code`. */\nexport type PushDeviceErrorCode = \"no_service_worker\" | \"push_timeout\";\n\n/**\n * The two failures the card has words of its own for: no service worker registered (or\n * one not ready in 10 s) — \"reload and try again\" — and a browser push service that did\n * not answer in 15 s — \"check your connection\". Anything else is the app's request\n * failing, rejected as it came.\n */\nexport class PushDeviceError extends Error {\n readonly code: PushDeviceErrorCode;\n constructor(code: PushDeviceErrorCode) {\n super(code);\n this.name = \"PushDeviceError\";\n this.code = code;\n }\n}\n\n/** What `register` sends: `POST /notifications/devices` (§3.5). */\nexport interface PushSubscriptionInput {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n user_agent: string | null;\n}\n\nexport interface UsePushDeviceOptions {\n /** `GET /notifications/push-key` → its `key`; `\"\"` when push is off on the server. */\n pushKey: () => Promise<string>;\n /** `POST /notifications/devices`. A 409 (another account's endpoint) is recovered\n * once: the hook unsubscribes and registers a fresh endpoint. */\n register: (subscription: PushSubscriptionInput) => Promise<unknown>;\n /** `POST /notifications/devices/unregister {endpoint}` — the endpoint never goes in a\n * URL. */\n unregister: (endpoint: string) => Promise<unknown>;\n /** `GET /notifications/devices`: the account's own list, which says whether THIS\n * account holds this browser's subscription. */\n devices: () => Promise<readonly { endpoint: string }[]>;\n /** `POST /notifications/test` → how many devices the push service accepted it for. */\n test: () => Promise<{ sent: number }>;\n /** Whether `register` refused another account's endpoint. Default: HTTP 409. */\n isEndpointTaken?: (error: unknown) => boolean;\n /** After an enable or a disable: the app refreshes its device queries. */\n onChange?: () => void;\n}\n\n/** What {@link usePushDevice} answers. */\nexport interface PushDevice {\n /** The browser exposes service workers, `PushManager` and `Notification`. */\n supported: boolean;\n /** The server has VAPID keys; `undefined` until `pushKey` answered (or when it failed). */\n configured: boolean | undefined;\n /** Running as an installed app: `display-mode: standalone`, or iOS's\n * `navigator.standalone`. */\n installed: boolean;\n /** iPhone or iPad — where push reaches only the installed app. */\n ios: boolean;\n permission: PushPermission;\n /** THIS account holds this browser's subscription. An unreachable device list falls\n * back to the browser's own answer. */\n subscribed: boolean;\n /** This browser holds a subscription that belongs to another account (two accounts in\n * one browser profile): `subscribed` is false, and turning on mints a fresh one. */\n foreignSubscription: boolean;\n /** This browser's subscription endpoint, or `null` — marks \"This device\" in a list. */\n currentEndpoint: string | null;\n /** An enable or a disable is running. */\n busy: boolean;\n /** Ask for permission (the browser's one prompt), subscribe and register. `false` when\n * the permission was not granted or push is off on the server; rejects with a\n * {@link PushDeviceError} or the app's request's error. */\n enable: () => Promise<boolean>;\n /** Tell the server first, then the browser, so a dropped device stops at once. */\n disable: () => Promise<void>;\n sendTest: () => Promise<{ sent: number }>;\n}\n\n/**\n * The window event every mounted {@link usePushDevice} re-reads its state on. Fired by\n * every enable and disable, and by `PushDevicesSetting` when it removes this device — so\n * an app's own card on the same hook (keksdose's check-up) stays in step. The hook that\n * fires it does not re-read: it knows what it changed. Namespaced for the kit;\n * keksdose's was `\"keksdose:push-subscription-changed\"`.\n */\nexport const PUSH_SUBSCRIPTION_CHANGED = \"eifi1:push-subscription-changed\";\n\n/** Tell every {@link usePushDevice} that this browser's subscription changed. */\nexport function notifyPushSubscriptionChanged(): void {\n if (typeof window !== \"undefined\") window.dispatchEvent(new Event(PUSH_SUBSCRIPTION_CHANGED));\n}\n\n/** Whether this browser has the APIs push needs. iOS exposes them only to an INSTALLED\n * app (Add to Home Screen). */\nexport function pushSupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n \"serviceWorker\" in navigator &&\n \"PushManager\" in window &&\n \"Notification\" in window\n );\n}\n\n/** iPhone or iPad. iPadOS 13+ reports itself as a Mac; the touch points tell it apart. */\nfunction isIos(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent;\n return /iphone|ipad|ipod/i.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);\n}\n\nconst READY_TIMEOUT_MS = 10_000;\nconst PUSH_TIMEOUT_MS = 15_000;\n\n/** `promise`, or a {@link PushDeviceError} after `ms`. The timer is cleared either way. */\nfunction within<T>(promise: Promise<T>, ms: number, code: PushDeviceErrorCode): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new PushDeviceError(code)), ms);\n }),\n ]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The active registration. `navigator.serviceWorker.ready` never settles while the origin\n * has no registration, so a missing one fails at once, and one stuck installing fails\n * after 10 s (keksdose: enable() hung with the button latched before its worker was\n * served).\n */\nasync function activeRegistration(): Promise<ServiceWorkerRegistration> {\n const existing = await navigator.serviceWorker.getRegistration();\n if (!existing) throw new PushDeviceError(\"no_service_worker\");\n return within(navigator.serviceWorker.ready, READY_TIMEOUT_MS, \"no_service_worker\");\n}\n\n/** A VAPID public key (base64url) as the bytes `PushManager.subscribe` wants. */\nfunction keyBytes(key: string): Uint8Array<ArrayBuffer> {\n const base64 = key.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (key.length % 4)) % 4);\n const raw = atob(base64);\n const bytes = new Uint8Array(new ArrayBuffer(raw.length));\n for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);\n return bytes;\n}\n\n/** A subscription's register body, or `null` when the browser handed back an incomplete\n * one. */\nfunction inputOf(subscription: PushSubscription): PushSubscriptionInput | null {\n const json = subscription.toJSON();\n const p256dh = json.keys?.p256dh;\n const auth = json.keys?.auth;\n if (!json.endpoint || !p256dh || !auth) return null;\n return { endpoint: json.endpoint, keys: { p256dh, auth }, user_agent: navigator.userAgent || null };\n}\n\nconst defaultEndpointTaken = (error: unknown) => httpStatusOf(error) === 409;\n\n/**\n * This browser's push for the signed-in account. Hand it one function per endpoint\n * (§3.8); {@link PushDeviceSetting} draws it, and an app's own card may use it too.\n *\n * **\"Subscribed\" means this account**, not \"this browser holds a subscription\": a\n * browser profile's subscription has no account in it, so a second account in the same\n * profile would read the first's as its own (keksdose). The endpoint is checked against\n * the account's own `devices()`; when that list cannot be read (offline), the browser's\n * answer stands — a wrong \"on\" costs what it did before the check, a wrong \"off\" invites\n * re-subscribing a device that is fine.\n *\n * **A 409 from `register`** — the endpoint belongs to another account, and the server\n * will not re-home what it cannot prove this browser holds — unsubscribes and registers\n * a fresh endpoint, once.\n *\n * **Timeouts:** no registration fails at once and a worker not ready in 10 s fails, both\n * `PushDeviceError(\"no_service_worker\")`; the browser's subscribe and unsubscribe are cut\n * at 15 s, `PushDeviceError(\"push_timeout\")` — so `busy` can never latch.\n *\n * Every mounted hook re-reads its state on {@link PUSH_SUBSCRIPTION_CHANGED}.\n */\nexport function usePushDevice(options: UsePushDeviceOptions): PushDevice {\n // The app's functions are usually new on every render; the effects read the latest.\n const latest = useRef(options);\n useEffect(() => {\n latest.current = options;\n });\n\n const supported = pushSupported();\n const ios = isIos();\n const standalone = useMediaQuery(\"(display-mode: standalone)\", false);\n const installed =\n standalone ||\n (typeof navigator !== \"undefined\" && (navigator as Navigator & { standalone?: boolean }).standalone === true);\n\n const [permission, setPermission] = useState<PushPermission>(() =>\n supported ? Notification.permission : \"unsupported\",\n );\n const [configured, setConfigured] = useState<boolean | undefined>(undefined);\n const [subscribed, setSubscribed] = useState(false);\n const [foreignSubscription, setForeignSubscription] = useState(false);\n const [currentEndpoint, setCurrentEndpoint] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const mounted = useRef(true);\n // Set while this hook fires the event itself: it already knows what changed, and a\n // re-read could only be worse — an app whose `devices()` answers from a cache would\n // hand back the list from before the change.\n const announcing = useRef(false);\n const announce = useCallback(() => {\n announcing.current = true;\n try {\n notifyPushSubscriptionChanged();\n } finally {\n announcing.current = false;\n }\n latest.current.onChange?.();\n }, []);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n // Whether the server has keys (\"\" → push is off there). Once per mount.\n useEffect(() => {\n if (!supported) return;\n let cancelled = false;\n latest.current.pushKey().then(\n (key) => {\n if (!cancelled) setConfigured(key !== \"\");\n },\n () => {\n /* unknown: the card shows the ordinary states */\n },\n );\n return () => {\n cancelled = true;\n };\n }, [supported]);\n\n // What this browser holds, and whether it is this account's — at mount, and whenever\n // a subscription changes anywhere in the app.\n useEffect(() => {\n if (!supported) return;\n let cancelled = false;\n const sync = async () => {\n try {\n const registration = await activeRegistration();\n const existing = await registration.pushManager.getSubscription();\n if (cancelled) return;\n // Read again: the person may have changed it in the browser's settings.\n setPermission(Notification.permission);\n if (!existing) {\n setSubscribed(false);\n setForeignSubscription(false);\n setCurrentEndpoint(null);\n return;\n }\n let mine: boolean;\n try {\n const devices = await latest.current.devices();\n mine = devices.some((device) => device.endpoint === existing.endpoint);\n } catch {\n mine = true;\n }\n if (cancelled) return;\n setCurrentEndpoint(existing.endpoint);\n setSubscribed(mine);\n setForeignSubscription(!mine);\n } catch {\n /* no active service worker yet: not subscribed */\n }\n };\n const heard = () => {\n if (!announcing.current) void sync();\n };\n void sync();\n window.addEventListener(PUSH_SUBSCRIPTION_CHANGED, heard);\n return () => {\n cancelled = true;\n window.removeEventListener(PUSH_SUBSCRIPTION_CHANGED, heard);\n };\n }, [supported]);\n\n const enable = useCallback(async (): Promise<boolean> => {\n if (!supported) return false;\n const { pushKey, register, isEndpointTaken = defaultEndpointTaken } = latest.current;\n setBusy(true);\n try {\n const granted = await Notification.requestPermission();\n if (mounted.current) setPermission(granted);\n if (granted !== \"granted\") return false;\n\n const key = await pushKey();\n if (!key) {\n if (mounted.current) setConfigured(false);\n return false;\n }\n if (mounted.current) setConfigured(true);\n\n const registration = await activeRegistration();\n // The one place the browser is asked for a subscription, so the timeout and the\n // `{userVisibleOnly, applicationServerKey}` literal are on both paths.\n const subscribe = (reuse: boolean) =>\n within(\n (async () =>\n (reuse ? await registration.pushManager.getSubscription() : null) ??\n (await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(key) })))(),\n PUSH_TIMEOUT_MS,\n \"push_timeout\",\n );\n\n let subscription = await subscribe(true);\n let input = inputOf(subscription);\n if (!input) return false;\n try {\n await register(input);\n } catch (error) {\n if (!isEndpointTaken(error)) throw error;\n await within(subscription.unsubscribe(), PUSH_TIMEOUT_MS, \"push_timeout\");\n subscription = await subscribe(false);\n input = inputOf(subscription);\n if (!input) return false;\n await register(input);\n }\n if (mounted.current) {\n setSubscribed(true);\n setForeignSubscription(false);\n setCurrentEndpoint(input.endpoint);\n }\n announce();\n return true;\n } finally {\n if (mounted.current) setBusy(false);\n }\n }, [supported, announce]);\n\n const disable = useCallback(async (): Promise<void> => {\n if (!supported) return;\n setBusy(true);\n try {\n const registration = await activeRegistration();\n const subscription = await registration.pushManager.getSubscription();\n if (subscription) {\n // The server first: a dropped device stops receiving even if the browser's\n // unsubscribe below fails.\n await latest.current.unregister(subscription.endpoint);\n await within(subscription.unsubscribe(), PUSH_TIMEOUT_MS, \"push_timeout\");\n }\n if (mounted.current) {\n setSubscribed(false);\n setForeignSubscription(false);\n setCurrentEndpoint(null);\n }\n announce();\n } finally {\n if (mounted.current) setBusy(false);\n }\n }, [supported, announce]);\n\n const sendTest = useCallback(() => latest.current.test(), []);\n\n return {\n supported,\n configured,\n installed,\n ios,\n permission,\n subscribed,\n foreignSubscription,\n currentEndpoint,\n busy,\n enable,\n disable,\n sendTest,\n };\n}\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB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;AACA,eAAS;AACT,aAAO;AAAA,IACT,UAAE;AACA,UAAI,QAAQ,QAAS,SAAQ,KAAK;AAAA,IACpC;AAAA,EACF,GAAG,CAAC,WAAW,QAAQ,CAAC;AAExB,QAAM,UAAU,YAAY,YAA2B;AACrD,QAAI,CAAC,UAAW;AAChB,YAAQ,IAAI;AACZ,QAAI;AACF,YAAM,eAAe,MAAM,mBAAmB;AAC9C,YAAM,eAAe,MAAM,aAAa,YAAY,gBAAgB;AACpE,UAAI,cAAc;AAGhB,cAAM,OAAO,QAAQ,WAAW,aAAa,QAAQ;AACrD,cAAM,OAAO,aAAa,YAAY,GAAG,iBAAiB,cAAc;AAAA,MAC1E;AACA,UAAI,QAAQ,SAAS;AACnB,sBAAc,KAAK;AACnB,+BAAuB,KAAK;AAC5B,2BAAmB,IAAI;AAAA,MACzB;AACA,eAAS;AAAA,IACX,UAAE;AACA,UAAI,QAAQ,QAAS,SAAQ,KAAK;AAAA,IACpC;AAAA,EACF,GAAG,CAAC,WAAW,QAAQ,CAAC;AAExB,QAAM,WAAW,YAAY,MAAM,OAAO,QAAQ,KAAK,GAAG,CAAC,CAAC;AAE5D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/notifications/use-push-device.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useMediaQuery } from \"../hooks/use-media-query\";\nimport { httpStatusOf } from \"../auth/auth-errors\";\nimport { PUSH_SUBSCRIPTION_CHANGED, keyBytes, pushSubscriptionInput as inputOf } from \"./push-worker\";\nimport type { PushSubscriptionInput } from \"./push-worker\";\n\nexport { PUSH_SUBSCRIPTION_CHANGED };\nexport type { PushSubscriptionInput };\n\n/**\n * This browser's Web Push subscription for the signed-in account\n * (docs/notifications-harmonization.md §2.7, §3.5, §4.2) — keksdose's\n * `shared/push/use-push.ts`, lifted. The service worker with its `push` and\n * `notificationclick` handlers stays the app's; this hook owns the browser's side:\n * permission, subscribe with the server's VAPID key, register the subscription, and\n * unsubscribe. The kit makes no request of its own: the app hands it one function per\n * endpoint.\n */\n\n/** The browser's notification permission, or `\"unsupported\"` where it has no push. */\nexport type PushPermission = NotificationPermission | \"unsupported\";\n\n/** Why turning push on or off could not finish — a {@link PushDeviceError}'s `code`. */\nexport type PushDeviceErrorCode = \"no_service_worker\" | \"push_timeout\";\n\n/**\n * The two failures the card has words of its own for: no service worker registered (or\n * one not ready in 10 s) — \"reload and try again\" — and a browser push service that did\n * not answer in 15 s — \"check your connection\". Anything else is the app's request\n * failing, rejected as it came.\n */\nexport class PushDeviceError extends Error {\n readonly code: PushDeviceErrorCode;\n constructor(code: PushDeviceErrorCode) {\n super(code);\n this.name = \"PushDeviceError\";\n this.code = code;\n }\n}\n\nexport interface UsePushDeviceOptions {\n /** `GET /notifications/push-key` → its `key`; `\"\"` when push is off on the server. */\n pushKey: () => Promise<string>;\n /** `POST /notifications/devices`. A 409 (another account's endpoint) is recovered\n * once: the hook unsubscribes and registers a fresh endpoint. */\n register: (subscription: PushSubscriptionInput) => Promise<unknown>;\n /** `POST /notifications/devices/unregister {endpoint}` — the endpoint never goes in a\n * URL. */\n unregister: (endpoint: string) => Promise<unknown>;\n /** `GET /notifications/devices`: the account's own list, which says whether THIS\n * account holds this browser's subscription. */\n devices: () => Promise<readonly { endpoint: string }[]>;\n /** `POST /notifications/test` → how many devices the push service accepted it for. */\n test: () => Promise<{ sent: number }>;\n /** Whether `register` refused another account's endpoint. Default: HTTP 409. */\n isEndpointTaken?: (error: unknown) => boolean;\n /** After an enable or a disable: the app refreshes its device queries. */\n onChange?: () => void;\n}\n\n/** What {@link usePushDevice} answers. */\nexport interface PushDevice {\n /** The browser exposes service workers, `PushManager` and `Notification`. */\n supported: boolean;\n /** The server has VAPID keys; `undefined` until `pushKey` answered (or when it failed). */\n configured: boolean | undefined;\n /** Running as an installed app: `display-mode: standalone`, or iOS's\n * `navigator.standalone`. */\n installed: boolean;\n /** iPhone or iPad — where push reaches only the installed app. */\n ios: boolean;\n permission: PushPermission;\n /** THIS account holds this browser's subscription. An unreachable device list falls\n * back to the browser's own answer. */\n subscribed: boolean;\n /** This browser holds a subscription that belongs to another account (two accounts in\n * one browser profile): `subscribed` is false, and turning on mints a fresh one. */\n foreignSubscription: boolean;\n /** This browser's subscription endpoint, or `null` — marks \"This device\" in a list. */\n currentEndpoint: string | null;\n /** An enable or a disable is running. */\n busy: boolean;\n /** Ask for permission (the browser's one prompt), subscribe and register. `false` when\n * the permission was not granted or push is off on the server; rejects with a\n * {@link PushDeviceError} or the app's request's error. */\n enable: () => Promise<boolean>;\n /** Tell the server first, then the browser, so a dropped device stops at once. */\n disable: () => Promise<void>;\n sendTest: () => Promise<{ sent: number }>;\n}\n\n/*\n * PUSH_SUBSCRIPTION_CHANGED (push-worker.ts): the window event every mounted\n * {@link usePushDevice} re-reads its state on. Fired by every enable and disable, and by\n * `PushDevicesSetting` when it removes this device — so an app's own card on the same\n * hook (keksdose's check-up) stays in step. The hook that fires it does not re-read: it\n * knows what it changed. Since 0.46 also the message a service worker posts after a\n * rotated subscription was re-registered (`handlePushSubscriptionChange`). Namespaced\n * for the kit; keksdose's was `\"keksdose:push-subscription-changed\"`.\n */\n\n/** Tell every {@link usePushDevice} that this browser's subscription changed. */\nexport function notifyPushSubscriptionChanged(): void {\n if (typeof window !== \"undefined\") window.dispatchEvent(new Event(PUSH_SUBSCRIPTION_CHANGED));\n}\n\n/** Whether this browser has the APIs push needs. iOS exposes them only to an INSTALLED\n * app (Add to Home Screen). */\nexport function pushSupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n \"serviceWorker\" in navigator &&\n \"PushManager\" in window &&\n \"Notification\" in window\n );\n}\n\n/** iPhone or iPad. iPadOS 13+ reports itself as a Mac; the touch points tell it apart. */\nfunction isIos(): boolean {\n if (typeof navigator === \"undefined\") return false;\n const ua = navigator.userAgent;\n return /iphone|ipad|ipod/i.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);\n}\n\nconst READY_TIMEOUT_MS = 10_000;\nconst PUSH_TIMEOUT_MS = 15_000;\n\n/** `promise`, or a {@link PushDeviceError} after `ms`. The timer is cleared either way. */\nfunction within<T>(promise: Promise<T>, ms: number, code: PushDeviceErrorCode): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new PushDeviceError(code)), ms);\n }),\n ]).finally(() => clearTimeout(timer));\n}\n\n/**\n * The active registration. `navigator.serviceWorker.ready` never settles while the origin\n * has no registration, so a missing one fails at once, and one stuck installing fails\n * after 10 s (keksdose: enable() hung with the button latched before its worker was\n * served).\n */\nasync function activeRegistration(): Promise<ServiceWorkerRegistration> {\n const existing = await navigator.serviceWorker.getRegistration();\n if (!existing) throw new PushDeviceError(\"no_service_worker\");\n return within(navigator.serviceWorker.ready, READY_TIMEOUT_MS, \"no_service_worker\");\n}\n\nconst defaultEndpointTaken = (error: unknown) => httpStatusOf(error) === 409;\n\n/**\n * This browser's push for the signed-in account. Hand it one function per endpoint\n * (§3.8); {@link PushDeviceSetting} draws it, and an app's own card may use it too.\n *\n * **\"Subscribed\" means this account**, not \"this browser holds a subscription\": a\n * browser profile's subscription has no account in it, so a second account in the same\n * profile would read the first's as its own (keksdose). The endpoint is checked against\n * the account's own `devices()`; when that list cannot be read (offline), the browser's\n * answer stands — a wrong \"on\" costs what it did before the check, a wrong \"off\" invites\n * re-subscribing a device that is fine.\n *\n * **A 409 from `register`** — the endpoint belongs to another account, and the server\n * will not re-home what it cannot prove this browser holds — unsubscribes and registers\n * a fresh endpoint, once.\n *\n * **Timeouts:** no registration fails at once and a worker not ready in 10 s fails, both\n * `PushDeviceError(\"no_service_worker\")`; the browser's subscribe and unsubscribe are cut\n * at 15 s, `PushDeviceError(\"push_timeout\")` — so `busy` can never latch.\n *\n * Every mounted hook re-reads its state on {@link PUSH_SUBSCRIPTION_CHANGED}.\n */\nexport function usePushDevice(options: UsePushDeviceOptions): PushDevice {\n // The app's functions are usually new on every render; the effects read the latest.\n const latest = useRef(options);\n useEffect(() => {\n latest.current = options;\n });\n\n const supported = pushSupported();\n const ios = isIos();\n const standalone = useMediaQuery(\"(display-mode: standalone)\", false);\n const installed =\n standalone ||\n (typeof navigator !== \"undefined\" && (navigator as Navigator & { standalone?: boolean }).standalone === true);\n\n const [permission, setPermission] = useState<PushPermission>(() =>\n supported ? Notification.permission : \"unsupported\",\n );\n const [configured, setConfigured] = useState<boolean | undefined>(undefined);\n const [subscribed, setSubscribed] = useState(false);\n const [foreignSubscription, setForeignSubscription] = useState(false);\n const [currentEndpoint, setCurrentEndpoint] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const mounted = useRef(true);\n // Set while this hook fires the event itself: it already knows what changed, and a\n // re-read could only be worse — an app whose `devices()` answers from a cache would\n // hand back the list from before the change.\n const announcing = useRef(false);\n const announce = useCallback(() => {\n announcing.current = true;\n try {\n notifyPushSubscriptionChanged();\n } finally {\n announcing.current = false;\n }\n latest.current.onChange?.();\n }, []);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n // Whether the server has keys (\"\" → push is off there). Once per mount.\n useEffect(() => {\n if (!supported) return;\n let cancelled = false;\n latest.current.pushKey().then(\n (key) => {\n if (!cancelled) setConfigured(key !== \"\");\n },\n () => {\n /* unknown: the card shows the ordinary states */\n },\n );\n return () => {\n cancelled = true;\n };\n }, [supported]);\n\n // What this browser holds, and whether it is this account's — at mount, and whenever\n // a subscription changes anywhere in the app.\n useEffect(() => {\n if (!supported) return;\n let cancelled = false;\n const sync = async () => {\n try {\n const registration = await activeRegistration();\n const existing = await registration.pushManager.getSubscription();\n if (cancelled) return;\n // Read again: the person may have changed it in the browser's settings.\n setPermission(Notification.permission);\n if (!existing) {\n setSubscribed(false);\n setForeignSubscription(false);\n setCurrentEndpoint(null);\n return;\n }\n let mine: boolean;\n try {\n const devices = await latest.current.devices();\n mine = devices.some((device) => device.endpoint === existing.endpoint);\n } catch {\n mine = true;\n }\n if (cancelled) return;\n setCurrentEndpoint(existing.endpoint);\n setSubscribed(mine);\n setForeignSubscription(!mine);\n } catch {\n /* no active service worker yet: not subscribed */\n }\n };\n const heard = () => {\n if (!announcing.current) void sync();\n };\n // The worker's word after it re-registered a rotated subscription (0.46).\n const fromWorker = (event: MessageEvent) => {\n if ((event.data as { type?: unknown } | null)?.type === PUSH_SUBSCRIPTION_CHANGED) void sync();\n };\n const worker = navigator.serviceWorker as ServiceWorkerContainer | undefined;\n void sync();\n window.addEventListener(PUSH_SUBSCRIPTION_CHANGED, heard);\n worker?.addEventListener?.(\"message\", fromWorker);\n return () => {\n cancelled = true;\n window.removeEventListener(PUSH_SUBSCRIPTION_CHANGED, heard);\n worker?.removeEventListener?.(\"message\", fromWorker);\n };\n }, [supported]);\n\n const enable = useCallback(async (): Promise<boolean> => {\n if (!supported) return false;\n const { pushKey, register, isEndpointTaken = defaultEndpointTaken } = latest.current;\n setBusy(true);\n try {\n const granted = await Notification.requestPermission();\n if (mounted.current) setPermission(granted);\n if (granted !== \"granted\") return false;\n\n const key = await pushKey();\n if (!key) {\n if (mounted.current) setConfigured(false);\n return false;\n }\n if (mounted.current) setConfigured(true);\n\n const registration = await activeRegistration();\n // The one place the browser is asked for a subscription, so the timeout and the\n // `{userVisibleOnly, applicationServerKey}` literal are on both paths.\n const subscribe = (reuse: boolean) =>\n within(\n (async () =>\n (reuse ? await registration.pushManager.getSubscription() : null) ??\n (await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(key) })))(),\n PUSH_TIMEOUT_MS,\n \"push_timeout\",\n );\n\n let subscription = await subscribe(true);\n let input = inputOf(subscription);\n if (!input) return false;\n try {\n await register(input);\n } catch (error) {\n if (!isEndpointTaken(error)) throw error;\n await within(subscription.unsubscribe(), PUSH_TIMEOUT_MS, \"push_timeout\");\n subscription = await subscribe(false);\n input = inputOf(subscription);\n if (!input) return false;\n await register(input);\n }\n if (mounted.current) {\n setSubscribed(true);\n setForeignSubscription(false);\n setCurrentEndpoint(input.endpoint);\n }\n announce();\n return true;\n } finally {\n if (mounted.current) setBusy(false);\n }\n }, [supported, announce]);\n\n const disable = useCallback(async (): Promise<void> => {\n if (!supported) return;\n setBusy(true);\n try {\n const registration = await activeRegistration();\n const subscription = await registration.pushManager.getSubscription();\n if (subscription) {\n // The server first: a dropped device stops receiving even if the browser's\n // unsubscribe below fails.\n await latest.current.unregister(subscription.endpoint);\n await within(subscription.unsubscribe(), PUSH_TIMEOUT_MS, \"push_timeout\");\n }\n if (mounted.current) {\n setSubscribed(false);\n setForeignSubscription(false);\n setCurrentEndpoint(null);\n }\n announce();\n } finally {\n if (mounted.current) setBusy(false);\n }\n }, [supported, announce]);\n\n const sendTest = useCallback(() => latest.current.test(), []);\n\n return {\n supported,\n configured,\n installed,\n ios,\n permission,\n subscribed,\n foreignSubscription,\n currentEndpoint,\n busy,\n enable,\n disable,\n sendTest,\n };\n}\n"],"mappings":";AAAA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,UAAU,yBAAyB,eAAe;AA4B/E,MAAM,wBAAwB,MAAM;AAAA,EAChC;AAAA,EACT,YAAY,MAA2B;AACrC,UAAM,IAAI;AACV,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAgEO,SAAS,gCAAsC;AACpD,MAAI,OAAO,WAAW,YAAa,QAAO,cAAc,IAAI,MAAM,yBAAyB,CAAC;AAC9F;AAIO,SAAS,gBAAyB;AACvC,SACE,OAAO,WAAW,eAClB,OAAO,cAAc,eACrB,mBAAmB,aACnB,iBAAiB,UACjB,kBAAkB;AAEtB;AAGA,S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A,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * An `updated_at` that wins Last-Write-Wins over `previous`: now, or one millisecond past
3
+ * `previous` when that is not behind this clock (keksdose's sync-client.ts:639-643).
4
+ *
5
+ * `/sync` keeps the server's row when it is STRICTLY newer, comparing this device's clock
6
+ * with the server's. A row the server just wrote carries the server's time, so an edit
7
+ * stamped by a clock a second slow would lose and come straight back. The millisecond is
8
+ * enough although the server keeps microseconds: `Date.parse` truncates them.
9
+ */
10
+ export declare function stampAfter(previous: unknown): string;
11
+ /**
12
+ * A name-based UUID, version 5 (RFC 4122 §4.3: SHA-1 of the namespace's 16 bytes and the
13
+ * name's UTF-8), the same as Python's `uuid.uuid5(uuid.UUID(namespace), name)` — for an id
14
+ * the device and the server derive alike (§2: the per-owner vote id
15
+ * `uuid5(namespace, "<item>:<invitation>")`). Lower case, hyphenated. `namespace` is a UUID,
16
+ * hyphenated or not, in either case; anything else is a `TypeError`. Uses `crypto.subtle`
17
+ * (a secure context: https or localhost).
18
+ */
19
+ export declare function uuid5(namespace: string, name: string): Promise<string>;
20
+ /**
21
+ * The connection, not the server, failed: the request had no answer (an axios-like error
22
+ * without `response`, or `fetch`'s `TypeError`), or the session refresh marked a 401 as
23
+ * passing because the server was out of reach ({@link isTransientRefreshFailure}). A real
24
+ * HTTP answer — a 4xx or a 5xx — is never offline: the caller must see it.
25
+ */
26
+ export declare function isOfflineError(err: unknown): boolean;
27
+ /**
28
+ * Read from the server, and from the device's copy only when the connection failed
29
+ * ({@link isOfflineError}); a 4xx or 5xx still throws. `onOnline` gets the server's answer
30
+ * before it is returned (to refresh the copy, say); a throw from it counts as a failure of
31
+ * the online path. The plain form of keksdose's net.ts:58, without its sealed-household
32
+ * and cold-start branches (those stay keksdose's).
33
+ */
34
+ export declare function readLocalFirst<T>(online: () => Promise<T>, offline: () => Promise<T>, onOnline?: (result: T) => void | Promise<void>): Promise<T>;
35
+ /**
36
+ * Write through the server first (`rest`), and queue the change on the device (`queue`)
37
+ * only when the connection failed; any other failure throws, nothing queued. Online writes
38
+ * stay server-stamped (D2). A create mints its id BEFORE calling this and sends it on both
39
+ * paths, so a REST create that timed out after the server applied it is not created twice
40
+ * (D16).
41
+ */
42
+ export declare function writeLocalFirst<T>(rest: () => Promise<T>, queue: () => Promise<T>): Promise<T>;
@@ -0,0 +1,53 @@
1
+ "use client";
2
+ import { isTransientRefreshFailure } from "../lib/session-refresh.js";
3
+ function stampAfter(previous) {
4
+ const now = Date.now();
5
+ const prior = typeof previous === "string" ? Date.parse(previous) : Number.NaN;
6
+ return new Date(Number.isFinite(prior) && prior >= now ? prior + 1 : now).toISOString();
7
+ }
8
+ async function uuid5(namespace, name) {
9
+ const hex = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i.test(namespace) ? namespace.replaceAll("-", "") : null;
10
+ if (!hex) throw new TypeError(`uuid5: the namespace must be a UUID, not ${JSON.stringify(namespace)}`);
11
+ const nameBytes = new TextEncoder().encode(name);
12
+ const input = new Uint8Array(16 + nameBytes.length);
13
+ for (let i = 0; i < 16; i += 1) input[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
14
+ input.set(nameBytes, 16);
15
+ const bytes = new Uint8Array(await crypto.subtle.digest("SHA-1", input)).slice(0, 16);
16
+ bytes[6] = bytes[6] & 15 | 80;
17
+ bytes[8] = bytes[8] & 63 | 128;
18
+ const out = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
19
+ return `${out.slice(0, 8)}-${out.slice(8, 12)}-${out.slice(12, 16)}-${out.slice(16, 20)}-${out.slice(20)}`;
20
+ }
21
+ function isOfflineError(err) {
22
+ if (isTransientRefreshFailure(err)) return true;
23
+ if (typeof err !== "object" || err === null) return false;
24
+ const bag = err;
25
+ if (bag.isAxiosError === true || "response" in bag) return bag.response == null;
26
+ return err instanceof TypeError;
27
+ }
28
+ async function readLocalFirst(online, offline, onOnline) {
29
+ try {
30
+ const result = await online();
31
+ await onOnline?.(result);
32
+ return result;
33
+ } catch (err) {
34
+ if (!isOfflineError(err)) throw err;
35
+ return offline();
36
+ }
37
+ }
38
+ async function writeLocalFirst(rest, queue) {
39
+ try {
40
+ return await rest();
41
+ } catch (err) {
42
+ if (!isOfflineError(err)) throw err;
43
+ return queue();
44
+ }
45
+ }
46
+ export {
47
+ isOfflineError,
48
+ readLocalFirst,
49
+ stampAfter,
50
+ uuid5,
51
+ writeLocalFirst
52
+ };
53
+ //# sourceMappingURL=local-first.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/offline/local-first.ts"],"sourcesContent":["import { isTransientRefreshFailure } from \"../lib/session-refresh\";\n\n/*\n * The leaf utilities of local-first (docs/local-first-harmonization.md §2.3, 0.46): what a\n * page and a sync engine both need, with no store behind them. One module that both\n * `@eifi1/ui-kit/offline` and `@eifi1/ui-kit/sync` export, so `/sync` never loads\n * `/offline`'s TanStack and idb-keyval peers, and `/offline` never loads Dexie. It imports\n * no package at all (packaging-contract.test.ts holds that).\n */\n\n/**\n * An `updated_at` that wins Last-Write-Wins over `previous`: now, or one millisecond past\n * `previous` when that is not behind this clock (keksdose's sync-client.ts:639-643).\n *\n * `/sync` keeps the server's row when it is STRICTLY newer, comparing this device's clock\n * with the server's. A row the server just wrote carries the server's time, so an edit\n * stamped by a clock a second slow would lose and come straight back. The millisecond is\n * enough although the server keeps microseconds: `Date.parse` truncates them.\n */\nexport function stampAfter(previous: unknown): string {\n const now = Date.now();\n const prior = typeof previous === \"string\" ? Date.parse(previous) : Number.NaN;\n return new Date(Number.isFinite(prior) && prior >= now ? prior + 1 : now).toISOString();\n}\n\n/**\n * A name-based UUID, version 5 (RFC 4122 §4.3: SHA-1 of the namespace's 16 bytes and the\n * name's UTF-8), the same as Python's `uuid.uuid5(uuid.UUID(namespace), name)` — for an id\n * the device and the server derive alike (§2: the per-owner vote id\n * `uuid5(namespace, \"<item>:<invitation>\")`). Lower case, hyphenated. `namespace` is a UUID,\n * hyphenated or not, in either case; anything else is a `TypeError`. Uses `crypto.subtle`\n * (a secure context: https or localhost).\n */\nexport async function uuid5(namespace: string, name: string): Promise<string> {\n const hex = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i.test(namespace)\n ? namespace.replaceAll(\"-\", \"\")\n : null;\n if (!hex) throw new TypeError(`uuid5: the namespace must be a UUID, not ${JSON.stringify(namespace)}`);\n const nameBytes = new TextEncoder().encode(name);\n const input = new Uint8Array(16 + nameBytes.length);\n for (let i = 0; i < 16; i += 1) input[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n input.set(nameBytes, 16);\n const bytes = new Uint8Array(await crypto.subtle.digest(\"SHA-1\", input)).slice(0, 16);\n bytes[6] = (bytes[6] & 0x0f) | 0x50; // version 5\n bytes[8] = (bytes[8] & 0x3f) | 0x80; // the RFC 4122 variant\n const out = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${out.slice(0, 8)}-${out.slice(8, 12)}-${out.slice(12, 16)}-${out.slice(16, 20)}-${out.slice(20)}`;\n}\n\n/**\n * The connection, not the server, failed: the request had no answer (an axios-like error\n * without `response`, or `fetch`'s `TypeError`), or the session refresh marked a 401 as\n * passing because the server was out of reach ({@link isTransientRefreshFailure}). A real\n * HTTP answer — a 4xx or a 5xx — is never offline: the caller must see it.\n */\nexport function isOfflineError(err: unknown): boolean {\n if (isTransientRefreshFailure(err)) return true;\n if (typeof err !== \"object\" || err === null) return false;\n const bag = err as { isAxiosError?: unknown; response?: unknown };\n if (bag.isAxiosError === true || \"response\" in bag) return bag.response == null;\n return err instanceof TypeError;\n}\n\n/**\n * Read from the server, and from the device's copy only when the connection failed\n * ({@link isOfflineError}); a 4xx or 5xx still throws. `onOnline` gets the server's answer\n * before it is returned (to refresh the copy, say); a throw from it counts as a failure of\n * the online path. The plain form of keksdose's net.ts:58, without its sealed-household\n * and cold-start branches (those stay keksdose's).\n */\nexport async function readLocalFirst<T>(\n online: () => Promise<T>,\n offline: () => Promise<T>,\n onOnline?: (result: T) => void | Promise<void>,\n): Promise<T> {\n try {\n const result = await online();\n await onOnline?.(result);\n return result;\n } catch (err) {\n if (!isOfflineError(err)) throw err;\n return offline();\n }\n}\n\n/**\n * Write through the server first (`rest`), and queue the change on the device (`queue`)\n * only when the connection failed; any other failure throws, nothing queued. Online writes\n * stay server-stamped (D2). A create mints its id BEFORE calling this and sends it on both\n * paths, so a REST create that timed out after the server applied it is not created twice\n * (D16).\n */\nexport async function writeLocalFirst<T>(rest: () => Promise<T>, queue: () => Promise<T>): Promise<T> {\n try {\n return await rest();\n } catch (err) {\n if (!isOfflineError(err)) throw err;\n return queue();\n }\n}\n"],"mappings":";AAAA,SAAS,iCAAiC;AAmBnC,SAAS,WAAW,UAA2B;AACpD,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,QAAQ,OAAO,aAAa,WAAW,KAAK,MAAM,QAAQ,IAAI,OAAO;AAC3E,SAAO,IAAI,KAAK,OAAO,SAAS,KAAK,KAAK,SAAS,MAAM,QAAQ,IAAI,GAAG,EAAE,YAAY;AACxF;AAUA,eAAsB,MAAM,WAAmB,MAA+B;AAC5E,QAAM,MAAM,sEAAsE,KAAK,SAAS,IAC5F,UAAU,WAAW,KAAK,EAAE,IAC5B;AACJ,MAAI,CAAC,IAAK,OAAM,IAAI,UAAU,4CAA4C,KAAK,UAAU,SAAS,CAAC,EAAE;AACrG,QAAM,YAAY,IAAI,YAAY,EAAE,OAAO,IAAI;AAC/C,QAAM,QAAQ,IAAI,WAAW,KAAK,UAAU,MAAM;AAClD,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK,EAAG,OAAM,CAAC,IAAI,OAAO,SAAS,IAAI,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE;AAC1F,QAAM,IA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61
  throttleTime?: number;
62
+ /**
63
+ * 0.46 (kastlan K1): whether paused mutations are written with the cache. Default `true`
64
+ * (keksdose: an offline write waits in TanStack's queue and is sent after a reload).
65
+ * `false` keeps every mutation off the disk, and drops any an older build wrote on
66
+ * restore — for an app that queues offline writes in its own outbox (kastlan's Dexie
67
+ * outbox), instead of overriding `dehydrateOptions` by hand.
68
+ */
69
+ persistMutations?: boolean;
62
70
  }
63
71
  /**
64
72
  * One persisted cache, for one key. **Mount it per key**: the provider subscribes once and
@@ -91,10 +99,27 @@ export interface QueryPersistence {
91
99
  * account's, another company's). Other apps' keys and fresh ones stay. Never throws. */
92
100
  removeStale: () => Promise<void>;
93
101
  }
102
+ export interface RemoveStaleQueryCopiesOptions {
103
+ /** Default: IndexedDB (idb-keyval), the store {@link createQueryPersistence} writes to. */
104
+ storage?: QueryPersistenceStorage;
105
+ /** One key to spare whatever its age — the signed-in account's own
106
+ * (`QueryPersistence.removeStale` passes its key). */
107
+ keep?: string;
108
+ }
109
+ /**
110
+ * 0.46 (kastlan K2): deletes this app's persisted query caches (`<app>-query-cache-…`)
111
+ * older than `maxAge`, with no persistence at hand — for the sign-in page, where no
112
+ * account is known. A session that ended with no user known (a refresh token refused at
113
+ * boot) cannot name its key for `clear`; this sweeps its copy once it is stale, without
114
+ * waiting for someone's next sign-in. Other apps' keys, other stores' keys and fresh
115
+ * caches stay; an unreadable one is stale. Never throws.
116
+ * {@link QueryPersistence.removeStale} is this with `keep` = its own key.
117
+ */
118
+ export declare function removeStaleQueryCopies(app: string, maxAge: number, { storage, keep }?: RemoveStaleQueryCopiesOptions): Promise<void>;
94
119
  /**
95
120
  * True when `data` still means the same thing after JSON.stringify and JSON.parse —
96
121
  * keksdose's `isCacheSafe` (query-client.ts:165). Class instances, Map/Set/Date/Blob, a
97
122
  * non-finite number, a function: all refused. An `undefined` property survives.
98
123
  */
99
124
  export declare function isCacheSafe(data: unknown, depth?: number): boolean;
100
- export declare function createQueryPersistence({ app, user, company, shouldPersistKey, denyRoots, scrubFields, onUnsafe, buster, maxAge, storage, throttleTime, }: QueryPersistenceOptions): QueryPersistence;
125
+ export declare function createQueryPersistence({ app, user, company, shouldPersistKey, denyRoots, scrubFields, onUnsafe, buster, maxAge, storage, throttleTime, persistMutations, }: QueryPersistenceOptions): QueryPersistence;
@@ -13,6 +13,26 @@ const idbStorage = {
13
13
  removeItem: (key) => del(key),
14
14
  keys: () => keys()
15
15
  };
16
+ async function removeStaleQueryCopies(app, maxAge, { storage = idbStorage, keep } = {}) {
17
+ const prefix = `${app}-query-cache-`;
18
+ try {
19
+ const now = Date.now();
20
+ for (const k of await storage.keys()) {
21
+ if (typeof k !== "string" || !k.startsWith(prefix) || k === keep) continue;
22
+ let timestamp = 0;
23
+ try {
24
+ const raw = await storage.getItem(k);
25
+ const parsed = raw ? JSON.parse(raw) : null;
26
+ if (parsed && typeof parsed === "object" && typeof parsed.timestamp === "number") {
27
+ timestamp = parsed.timestamp;
28
+ }
29
+ } catch {
30
+ }
31
+ if (now - timestamp > maxAge) await storage.removeItem(k);
32
+ }
33
+ } catch {
34
+ }
35
+ }
16
36
  function isCacheSafe(data, depth = 0) {
17
37
  if (depth > 12) return false;
18
38
  if (data === null) return true;
@@ -51,7 +71,8 @@ function createQueryPersistence({
51
71
  buster,
52
72
  maxAge,
53
73
  storage = idbStorage,
54
- throttleTime = 1e3
74
+ throttleTime = 1e3,
75
+ persistMutations = true
55
76
  }) {
56
77
  const prefix = `${app}-query-cache-`;
57
78
  const key = `${prefix}${user}${company === void 0 || company === null || company === "" ? "" : `-${company}`}`;
@@ -78,7 +99,7 @@ function createQueryPersistence({
78
99
  ([name, v]) => scrubFields.some((f) => typeof f === "string" ? f === name : f.test(name)) || carriesScrubbed(v, depth + 1)
79
100
  );
80
101
  };
81
- const shouldDehydrateMutation = (mutation) => mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);
102
+ const shouldDehydrateMutation = (mutation) => persistMutations && mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);
82
103
  const withScrubbedData = (entry) => {
83
104
  const query = entry;
84
105
  if (!query.state || !("data" in query.state)) return entry;
@@ -100,7 +121,7 @@ function createQueryPersistence({
100
121
  timestamp,
101
122
  buster: stored,
102
123
  clientState: {
103
- mutations: Array.isArray(clientState.mutations) ? clientState.mutations.filter(
124
+ mutations: persistMutations && Array.isArray(clientState.mutations) ? clientState.mutations.filter(
104
125
  (m) => !carriesScrubbed(m?.state?.variables)
105
126
  ) : [],
106
127
  queries: clientState.queries.map(restorable).filter((q) => q !== null)
@@ -144,25 +165,7 @@ function createQueryPersistence({
144
165
  } catch {
145
166
  }
146
167
  };
147
- const removeStale = async () => {
148
- try {
149
- const now = Date.now();
150
- for (const k of await storage.keys()) {
151
- if (typeof k !== "string" || !k.startsWith(prefix) || k === key) continue;
152
- let timestamp = 0;
153
- try {
154
- const raw = await storage.getItem(k);
155
- const parsed = raw ? JSON.parse(raw) : null;
156
- if (parsed && typeof parsed === "object" && typeof parsed.timestamp === "number") {
157
- timestamp = parsed.timestamp;
158
- }
159
- } catch {
160
- }
161
- if (now - timestamp > maxAge) await storage.removeItem(k);
162
- }
163
- } catch {
164
- }
165
- };
168
+ const removeStale = () => removeStaleQueryCopies(app, maxAge, { storage, keep: key });
166
169
  return {
167
170
  key,
168
171
  persistOptions: { persister, maxAge, buster, dehydrateOptions: { shouldDehydrateQuery, shouldDehydrateMutation } },
@@ -174,6 +177,7 @@ function createQueryPersistence({
174
177
  export {
175
178
  DEFAULT_SCRUB_FIELDS,
176
179
  createQueryPersistence,
177
- isCacheSafe
180
+ isCacheSafe,
181
+ removeStaleQueryCopies
178
182
  };
179
183
  //# sourceMappingURL=query-persistence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/offline/query-persistence.ts"],"sourcesContent":["import { createAsyncStoragePersister } from \"@tanstack/query-async-storage-persister\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { PersistedClient, PersistQueryClientOptions } from \"@tanstack/react-query-persist-client\";\nimport { del, get, keys, set } from \"idb-keyval\";\n\n/**\n * The persisted TanStack Query cache, keksdose's policy as a kit helper\n * (docs/local-first-harmonization.md §1.5 D4, D5, D7; §1.6). keksdose's\n * shared/state/query-client.ts is the canon: an IndexedDB persister, a deny-list, the\n * plain-JSON guard on write (`shouldDehydrateQuery`) and its twin on restore that keeps\n * paused mutations. On top: a key per account (and company), a scrub list that removes\n * secret fields from payloads that are otherwise wanted offline, and `removeStale` for\n * another account's leftovers.\n *\n * The only module of the kit that imports TanStack and idb-keyval: both are optional peers\n * of `@eifi1/ui-kit/offline` and never reached from the main barrel (packaging-contract).\n */\n\n/** A field name the scrub removes: an exact name, or a pattern (`/^signature_/`). */\nexport type ScrubField = string | RegExp;\n\n/**\n * Removed from every query's data, at any depth, before it is persisted (D4, D7): bank\n * account numbers and the handover protocol's signatures. A page restored offline shows\n * such a field as missing (\"Needs a connection\").\n */\nexport const DEFAULT_SCRUB_FIELDS: readonly ScrubField[] = Object.freeze([\n \"iban\",\n \"qr_iban\",\n \"default_qr_iban\",\n /^signature_/,\n]);\n\n/** The storage the persister writes to. The default is IndexedDB through idb-keyval. */\nexport interface QueryPersistenceStorage {\n getItem: (key: string) => Promise<string | null | undefined>;\n setItem: (key: string, value: string) => Promise<unknown>;\n removeItem: (key: string) => Promise<unknown>;\n /** Every key in the store — what `removeStale` walks. */\n keys: () => Promise<readonly unknown[]>;\n}\n\nexport interface QueryPersistenceOptions {\n /** The app's name, the key's first part: `kastlan` → `kastlan-query-cache-…`. */\n app: string;\n /** The signed-in account. One cache per account (D5). */\n user: string | number;\n /** The acting company, where the app has several (kastlan): the switch changes the key,\n * so no wipe and no cross-company leak — provided the app switches as\n * {@link QueryPersistence.leave} says (leave, then remount the provider per key). */\n company?: string | number | null;\n /** The app's own rule, beside `denyRoots` — keksdose denies one exact key and every key\n * whose second segment is `\"admin\"`. `false` keeps the query out. */\n shouldPersistKey?: (queryKey: readonly unknown[]) => boolean;\n /** Query roots (`queryKey[0]`) that never reach the disk: admin, billing, reports… */\n denyRoots?: readonly string[];\n /** Replaces {@link DEFAULT_SCRUB_FIELDS}; spread it to add to it. `[]` scrubs nothing.\n * A paused mutation whose variables carry one of these fields is never persisted (a\n * scrubbed mutation would send something else), and one an older build wrote is dropped\n * on restore. */\n scrubFields?: readonly ScrubField[];\n /** Told when a query's data is not plain JSON and is therefore not persisted. Default:\n * `console.error`, as keksdose's `cacheSafeOrWarn`. */\n onUnsafe?: (queryKey: readonly unknown[], data: unknown) => void;\n /** Changes with each deploy (the app version), so a new build discards the old cache. */\n buster: string;\n /** How long a persisted cache is good for, in ms (keksdose: 24 h). The QueryClient's\n * `gcTime` must be at least this, or restore drops every query. */\n maxAge: number;\n /** Default: IndexedDB (idb-keyval). Tests pass an in-memory one. */\n storage?: QueryPersistenceStorage;\n /** Default 1000 ms, as keksdose. */\n throttleTime?: number;\n}\n\n/**\n * One persisted cache, for one key. **Mount it per key**: the provider subscribes once and\n * ignores a changed `persistOptions`, so give it the key as its React key —\n *\n * ```tsx\n * <PersistQueryClientProvider key={persistence.key} client={queryClient} persistOptions={persistence.persistOptions}>\n * ```\n *\n * — and create the persistence once the account (and company) is known (`useMemo` on\n * them); before sign-in, mount the plain `QueryClientProvider`. On a company switch, call\n * {@link QueryPersistence.leave} on the old one BEFORE the new key mounts, instead of a bare\n * `queryClient.clear()`: otherwise the old subscription saves the emptied (or the next\n * company's) cache under the old key.\n */\nexport interface QueryPersistence {\n /** `<app>-query-cache-<user>[-<company>]`. */\n key: string;\n /** Everything `<PersistQueryClientProvider persistOptions>` needs. */\n persistOptions: Omit<PersistQueryClientOptions, \"queryClient\">;\n /** Sign-out: stops writing under this key, empties the in-memory cache and deletes this\n * key's persisted copy. Best-effort; never throws. */\n clear: (queryClient: QueryClient) => Promise<void>;\n /** The company switch (or any change of key without a sign-out): stops writing under this\n * key — a save already scheduled is dropped too — and empties the in-memory cache, so\n * the next key's provider starts clean. The persisted copy stays for the way back. A\n * provider that mounts this persistence again re-arms it with its restore. Never throws. */\n leave: (queryClient: QueryClient) => Promise<void>;\n /** At sign-in: deletes this app's OTHER persisted caches older than `maxAge` (another\n * account's, another company's). Other apps' keys and fresh ones stay. Never throws. */\n removeStale: () => Promise<void>;\n}\n\nconst idbStorage: QueryPersistenceStorage = {\n getItem: (key) => get<string>(key),\n setItem: (key, value) => set(key, value),\n removeItem: (key) => del(key),\n keys: () => keys(),\n};\n\n/**\n * True when `data` still means the same thing after JSON.stringify and JSON.parse —\n * keksdose's `isCacheSafe` (query-client.ts:165). Class instances, Map/Set/Date/Blob, a\n * non-finite number, a function: all refused. An `undefined` property survives.\n */\nexport function isCacheSafe(data: unknown, depth = 0): boolean {\n if (depth > 12) return false;\n if (data === null) return true;\n const t = typeof data;\n if (t === \"string\" || t === \"boolean\") return true;\n if (t === \"number\") return Number.isFinite(data as number);\n if (t !== \"object\") return false;\n if (Array.isArray(data)) return data.every((v) => isCacheSafe(v, depth + 1));\n const proto: unknown = Object.getPrototypeOf(data);\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(data as Record<string, unknown>).every((v) => v === undefined || isCacheSafe(v, depth + 1));\n}\n\n/** A copy of `data` without the scrubbed fields, at any depth. The input is not touched. */\nfunction scrub(data: unknown, fields: readonly ScrubField[]): unknown {\n if (fields.length === 0 || data === null || typeof data !== \"object\") return data;\n if (Array.isArray(data)) return data.map((v) => scrub(v, fields));\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(data as Record<string, unknown>)) {\n if (fields.some((f) => (typeof f === \"string\" ? f === name : f.test(name)))) continue;\n out[name] = scrub(value, fields);\n }\n return out;\n}\n\nconst defaultOnUnsafe = (queryKey: readonly unknown[]) => {\n console.error(\n `[query-cache] refusing to persist ${JSON.stringify(queryKey)}: the value is not plain JSON ` +\n `(a class instance, Map, Set, Date or Blob). Return plain data from the queryFn and build ` +\n `the rich object at the call site.`,\n );\n};\n\nexport function createQueryPersistence({\n app,\n user,\n company,\n shouldPersistKey,\n denyRoots = [],\n scrubFields = DEFAULT_SCRUB_FIELDS,\n onUnsafe = defaultOnUnsafe,\n buster,\n maxAge,\n storage = idbStorage,\n throttleTime = 1000,\n}: QueryPersistenceOptions): QueryPersistence {\n const prefix = `${app}-query-cache-`;\n const key = `${prefix}${user}${company === undefined || company === null || company === \"\" ? \"\" : `-${company}`}`;\n const denied = new Set(denyRoots);\n // Set by `leave` and `clear`: a write under this key after the person left it (a\n // throttled save of the emptied cache) is dropped. A restore re-arms it.\n let retired = false;\n\n const keyAllowed = (queryKey: readonly unknown[]) =>\n !denied.has(String(queryKey[0])) && (shouldPersistKey ? shouldPersistKey(queryKey) : true);\n\n /** The write side: a success, an allowed key, plain JSON (or the warning). */\n const shouldDehydrateQuery = (query: {\n queryKey: readonly unknown[];\n state: { status: string; data?: unknown };\n }): boolean => {\n if (query.state.status !== \"success\" || !keyAllowed(query.queryKey)) return false;\n if (isCacheSafe(query.state.data)) return true;\n onUnsafe(query.queryKey, query.state.data);\n return false;\n };\n\n /** One persisted query entry, scrubbed; `null` when it may not be restored. */\n const restorable = (entry: unknown): unknown => {\n if (!entry || typeof entry !== \"object\") return null;\n const { queryKey, state } = entry as { queryKey?: unknown; state?: { data?: unknown } };\n if (!Array.isArray(queryKey) || !keyAllowed(queryKey)) return null;\n if (!isCacheSafe(state?.data)) return null;\n return withScrubbedData(entry);\n };\n\n /** Whether `value` has a scrubbed field's name anywhere in it. */\n const carriesScrubbed = (value: unknown, depth = 0): boolean => {\n if (scrubFields.length === 0 || depth > 12 || value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return value.some((v) => carriesScrubbed(v, depth + 1));\n return Object.entries(value as Record<string, unknown>).some(\n ([name, v]) =>\n scrubFields.some((f) => (typeof f === \"string\" ? f === name : f.test(name))) || carriesScrubbed(v, depth + 1),\n );\n };\n\n /** The write side for mutations: TanStack's default (paused ones), minus any whose\n * variables carry a scrubbed field (S6). */\n const shouldDehydrateMutation = (mutation: { state: { isPaused: boolean; variables?: unknown } }): boolean =>\n mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);\n\n const withScrubbedData = (entry: unknown): unknown => {\n const query = entry as { state?: { data?: unknown } };\n if (!query.state || !(\"data\" in query.state)) return entry;\n return { ...query, state: { ...query.state, data: scrub(query.state.data, scrubFields) } };\n };\n\n // The scrub on the way OUT: the in-memory cache keeps the field (the page that is open\n // shows it), the disk never sees it. Mutations are a paused write queue and are kept\n // whole — scrubbing one would change what it sends — so one carrying a scrubbed field is\n // not written at all (`shouldDehydrateMutation`).\n const serialize = (client: PersistedClient): string =>\n JSON.stringify({\n ...client,\n clientState: { ...client.clientState, queries: client.clientState.queries.map(withScrubbedData) },\n });\n\n // The twin on the way IN (keksdose's `sanitizePersistedCache`, :264-298): an older build\n // wrote what this one may deny. Never throws; an unreadable blob comes back with\n // `timestamp: 0`, which the restore treats as unusable and removes.\n const deserialize = (raw: string): PersistedClient => {\n const empty: PersistedClient = { timestamp: 0, buster: \"\", clientState: { mutations: [], queries: [] } };\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") return empty;\n const { timestamp, buster: stored, clientState } = parsed as Partial<PersistedClient>;\n if (typeof timestamp !== \"number\" || typeof stored !== \"string\") return empty;\n if (!clientState || typeof clientState !== \"object\" || !Array.isArray(clientState.queries)) return empty;\n return {\n timestamp,\n buster: stored,\n clientState: {\n mutations: Array.isArray(clientState.mutations)\n ? clientState.mutations.filter(\n (m) => !carriesScrubbed((m as { state?: { variables?: unknown } } | null)?.state?.variables),\n )\n : [],\n queries: clientState.queries.map(restorable).filter((q) => q !== null) as PersistedClient[\"clientState\"][\"queries\"],\n },\n };\n } catch {\n return empty;\n }\n };\n\n const persister = createAsyncStoragePersister({\n storage: {\n // Only the provider's restore reads: mounting this persistence again re-arms it.\n getItem: async (k) => {\n retired = false;\n return (await storage.getItem(k)) ?? null;\n },\n setItem: async (k, v) => {\n if (!retired) await storage.setItem(k, v);\n },\n removeItem: async (k) => {\n await storage.removeItem(k);\n },\n },\n key,\n throttleTime,\n serialize,\n deserialize,\n });\n\n const leave = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n } catch {\n /* best-effort */\n }\n };\n\n const clear = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n await persister.removeClient();\n } catch {\n /* best-effort: private mode / IndexedDB unavailable */\n }\n };\n\n const removeStale = async () => {\n try {\n const now = Date.now();\n for (const k of await storage.keys()) {\n if (typeof k !== \"string\" || !k.startsWith(prefix) || k === key) continue;\n let timestamp = 0;\n try {\n const raw = await storage.getItem(k);\n const parsed: unknown = raw ? JSON.parse(raw) : null;\n if (parsed && typeof parsed === \"object\" && typeof (parsed as PersistedClient).timestamp === \"number\") {\n timestamp = (parsed as PersistedClient).timestamp;\n }\n } catch {\n /* unreadable: stale */\n }\n if (now - timestamp > maxAge) await storage.removeItem(k);\n }\n } catch {\n /* best-effort */\n }\n };\n\n return {\n key,\n persistOptions: { persister, maxAge, buster, dehydrateOptions: { shouldDehydrateQuery, shouldDehydrateMutation } },\n clear,\n leave,\n removeStale,\n };\n}\n"],"mappings":";AAAA,SAAS,mCAAmC;AAG5C,SAAS,KAAK,KAAK,MAAM,WAAW;AAuB7B,MAAM,uBAA8C,OAAO,OAAO;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AA4ED,MAAM,aAAsC;AAAA,EAC1C,SAAS,CAAC,QAAQ,IAAY,GAAG;AAAA,EACjC,SAAS,CAAC,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACvC,YAAY,CAAC,QAAQ,IAAI,GAAG;AAAA,EAC5B,MAAM,MAAM,KAAK;AACnB;AAOO,SAAS,YAAY,MAAe,QAAQ,GAAY;AAC7D,MAAI,QAAQ,GAAI,QAAO;AACvB,MAAI,SAAS,KAAM,QAAO;AAC1B,QAAM,IAAI,OAAO;AACjB,MAAI,MAAM,YAAY,MAAM,UAAW,QAAO;AAC9C,MAAI,MAAM,SAAU,QAAO,OAAO,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AAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/offline/query-persistence.ts"],"sourcesContent":["import { createAsyncStoragePersister } from \"@tanstack/query-async-storage-persister\";\nimport type { QueryClient } from \"@tanstack/react-query\";\nimport type { PersistedClient, PersistQueryClientOptions } from \"@tanstack/react-query-persist-client\";\nimport { del, get, keys, set } from \"idb-keyval\";\n\n/**\n * The persisted TanStack Query cache, keksdose's policy as a kit helper\n * (docs/local-first-harmonization.md §1.5 D4, D5, D7; §1.6). keksdose's\n * shared/state/query-client.ts is the canon: an IndexedDB persister, a deny-list, the\n * plain-JSON guard on write (`shouldDehydrateQuery`) and its twin on restore that keeps\n * paused mutations. On top: a key per account (and company), a scrub list that removes\n * secret fields from payloads that are otherwise wanted offline, and `removeStale` for\n * another account's leftovers.\n *\n * The only module of the kit that imports TanStack and idb-keyval: both are optional peers\n * of `@eifi1/ui-kit/offline` and never reached from the main barrel (packaging-contract).\n */\n\n/** A field name the scrub removes: an exact name, or a pattern (`/^signature_/`). */\nexport type ScrubField = string | RegExp;\n\n/**\n * Removed from every query's data, at any depth, before it is persisted (D4, D7): bank\n * account numbers and the handover protocol's signatures. A page restored offline shows\n * such a field as missing (\"Needs a connection\").\n */\nexport const DEFAULT_SCRUB_FIELDS: readonly ScrubField[] = Object.freeze([\n \"iban\",\n \"qr_iban\",\n \"default_qr_iban\",\n /^signature_/,\n]);\n\n/** The storage the persister writes to. The default is IndexedDB through idb-keyval. */\nexport interface QueryPersistenceStorage {\n getItem: (key: string) => Promise<string | null | undefined>;\n setItem: (key: string, value: string) => Promise<unknown>;\n removeItem: (key: string) => Promise<unknown>;\n /** Every key in the store — what `removeStale` walks. */\n keys: () => Promise<readonly unknown[]>;\n}\n\nexport interface QueryPersistenceOptions {\n /** The app's name, the key's first part: `kastlan` → `kastlan-query-cache-…`. */\n app: string;\n /** The signed-in account. One cache per account (D5). */\n user: string | number;\n /** The acting company, where the app has several (kastlan): the switch changes the key,\n * so no wipe and no cross-company leak — provided the app switches as\n * {@link QueryPersistence.leave} says (leave, then remount the provider per key). */\n company?: string | number | null;\n /** The app's own rule, beside `denyRoots` — keksdose denies one exact key and every key\n * whose second segment is `\"admin\"`. `false` keeps the query out. */\n shouldPersistKey?: (queryKey: readonly unknown[]) => boolean;\n /** Query roots (`queryKey[0]`) that never reach the disk: admin, billing, reports… */\n denyRoots?: readonly string[];\n /** Replaces {@link DEFAULT_SCRUB_FIELDS}; spread it to add to it. `[]` scrubs nothing.\n * A paused mutation whose variables carry one of these fields is never persisted (a\n * scrubbed mutation would send something else), and one an older build wrote is dropped\n * on restore. */\n scrubFields?: readonly ScrubField[];\n /** Told when a query's data is not plain JSON and is therefore not persisted. Default:\n * `console.error`, as keksdose's `cacheSafeOrWarn`. */\n onUnsafe?: (queryKey: readonly unknown[], data: unknown) => void;\n /** Changes with each deploy (the app version), so a new build discards the old cache. */\n buster: string;\n /** How long a persisted cache is good for, in ms (keksdose: 24 h). The QueryClient's\n * `gcTime` must be at least this, or restore drops every query. */\n maxAge: number;\n /** Default: IndexedDB (idb-keyval). Tests pass an in-memory one. */\n storage?: QueryPersistenceStorage;\n /** Default 1000 ms, as keksdose. */\n throttleTime?: number;\n /**\n * 0.46 (kastlan K1): whether paused mutations are written with the cache. Default `true`\n * (keksdose: an offline write waits in TanStack's queue and is sent after a reload).\n * `false` keeps every mutation off the disk, and drops any an older build wrote on\n * restore — for an app that queues offline writes in its own outbox (kastlan's Dexie\n * outbox), instead of overriding `dehydrateOptions` by hand.\n */\n persistMutations?: boolean;\n}\n\n/**\n * One persisted cache, for one key. **Mount it per key**: the provider subscribes once and\n * ignores a changed `persistOptions`, so give it the key as its React key —\n *\n * ```tsx\n * <PersistQueryClientProvider key={persistence.key} client={queryClient} persistOptions={persistence.persistOptions}>\n * ```\n *\n * — and create the persistence once the account (and company) is known (`useMemo` on\n * them); before sign-in, mount the plain `QueryClientProvider`. On a company switch, call\n * {@link QueryPersistence.leave} on the old one BEFORE the new key mounts, instead of a bare\n * `queryClient.clear()`: otherwise the old subscription saves the emptied (or the next\n * company's) cache under the old key.\n */\nexport interface QueryPersistence {\n /** `<app>-query-cache-<user>[-<company>]`. */\n key: string;\n /** Everything `<PersistQueryClientProvider persistOptions>` needs. */\n persistOptions: Omit<PersistQueryClientOptions, \"queryClient\">;\n /** Sign-out: stops writing under this key, empties the in-memory cache and deletes this\n * key's persisted copy. Best-effort; never throws. */\n clear: (queryClient: QueryClient) => Promise<void>;\n /** The company switch (or any change of key without a sign-out): stops writing under this\n * key — a save already scheduled is dropped too — and empties the in-memory cache, so\n * the next key's provider starts clean. The persisted copy stays for the way back. A\n * provider that mounts this persistence again re-arms it with its restore. Never throws. */\n leave: (queryClient: QueryClient) => Promise<void>;\n /** At sign-in: deletes this app's OTHER persisted caches older than `maxAge` (another\n * account's, another company's). Other apps' keys and fresh ones stay. Never throws. */\n removeStale: () => Promise<void>;\n}\n\nconst idbStorage: QueryPersistenceStorage = {\n getItem: (key) => get<string>(key),\n setItem: (key, value) => set(key, value),\n removeItem: (key) => del(key),\n keys: () => keys(),\n};\n\nexport interface RemoveStaleQueryCopiesOptions {\n /** Default: IndexedDB (idb-keyval), the store {@link createQueryPersistence} writes to. */\n storage?: QueryPersistenceStorage;\n /** One key to spare whatever its age — the signed-in account's own\n * (`QueryPersistence.removeStale` passes its key). */\n keep?: string;\n}\n\n/**\n * 0.46 (kastlan K2): deletes this app's persisted query caches (`<app>-query-cache-…`)\n * older than `maxAge`, with no persistence at hand — for the sign-in page, where no\n * account is known. A session that ended with no user known (a refresh token refused at\n * boot) cannot name its key for `clear`; this sweeps its copy once it is stale, without\n * waiting for someone's next sign-in. Other apps' keys, other stores' keys and fresh\n * caches stay; an unreadable one is stale. Never throws.\n * {@link QueryPersistence.removeStale} is this with `keep` = its own key.\n */\nexport async function removeStaleQueryCopies(\n app: string,\n maxAge: number,\n { storage = idbStorage, keep }: RemoveStaleQueryCopiesOptions = {},\n): Promise<void> {\n const prefix = `${app}-query-cache-`;\n try {\n const now = Date.now();\n for (const k of await storage.keys()) {\n if (typeof k !== \"string\" || !k.startsWith(prefix) || k === keep) continue;\n let timestamp = 0;\n try {\n const raw = await storage.getItem(k);\n const parsed: unknown = raw ? JSON.parse(raw) : null;\n if (parsed && typeof parsed === \"object\" && typeof (parsed as PersistedClient).timestamp === \"number\") {\n timestamp = (parsed as PersistedClient).timestamp;\n }\n } catch {\n /* unreadable: stale */\n }\n if (now - timestamp > maxAge) await storage.removeItem(k);\n }\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * True when `data` still means the same thing after JSON.stringify and JSON.parse —\n * keksdose's `isCacheSafe` (query-client.ts:165). Class instances, Map/Set/Date/Blob, a\n * non-finite number, a function: all refused. An `undefined` property survives.\n */\nexport function isCacheSafe(data: unknown, depth = 0): boolean {\n if (depth > 12) return false;\n if (data === null) return true;\n const t = typeof data;\n if (t === \"string\" || t === \"boolean\") return true;\n if (t === \"number\") return Number.isFinite(data as number);\n if (t !== \"object\") return false;\n if (Array.isArray(data)) return data.every((v) => isCacheSafe(v, depth + 1));\n const proto: unknown = Object.getPrototypeOf(data);\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(data as Record<string, unknown>).every((v) => v === undefined || isCacheSafe(v, depth + 1));\n}\n\n/** A copy of `data` without the scrubbed fields, at any depth. The input is not touched. */\nfunction scrub(data: unknown, fields: readonly ScrubField[]): unknown {\n if (fields.length === 0 || data === null || typeof data !== \"object\") return data;\n if (Array.isArray(data)) return data.map((v) => scrub(v, fields));\n const out: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(data as Record<string, unknown>)) {\n if (fields.some((f) => (typeof f === \"string\" ? f === name : f.test(name)))) continue;\n out[name] = scrub(value, fields);\n }\n return out;\n}\n\nconst defaultOnUnsafe = (queryKey: readonly unknown[]) => {\n console.error(\n `[query-cache] refusing to persist ${JSON.stringify(queryKey)}: the value is not plain JSON ` +\n `(a class instance, Map, Set, Date or Blob). Return plain data from the queryFn and build ` +\n `the rich object at the call site.`,\n );\n};\n\nexport function createQueryPersistence({\n app,\n user,\n company,\n shouldPersistKey,\n denyRoots = [],\n scrubFields = DEFAULT_SCRUB_FIELDS,\n onUnsafe = defaultOnUnsafe,\n buster,\n maxAge,\n storage = idbStorage,\n throttleTime = 1000,\n persistMutations = true,\n}: QueryPersistenceOptions): QueryPersistence {\n const prefix = `${app}-query-cache-`;\n const key = `${prefix}${user}${company === undefined || company === null || company === \"\" ? \"\" : `-${company}`}`;\n const denied = new Set(denyRoots);\n // Set by `leave` and `clear`: a write under this key after the person left it (a\n // throttled save of the emptied cache) is dropped. A restore re-arms it.\n let retired = false;\n\n const keyAllowed = (queryKey: readonly unknown[]) =>\n !denied.has(String(queryKey[0])) && (shouldPersistKey ? shouldPersistKey(queryKey) : true);\n\n /** The write side: a success, an allowed key, plain JSON (or the warning). */\n const shouldDehydrateQuery = (query: {\n queryKey: readonly unknown[];\n state: { status: string; data?: unknown };\n }): boolean => {\n if (query.state.status !== \"success\" || !keyAllowed(query.queryKey)) return false;\n if (isCacheSafe(query.state.data)) return true;\n onUnsafe(query.queryKey, query.state.data);\n return false;\n };\n\n /** One persisted query entry, scrubbed; `null` when it may not be restored. */\n const restorable = (entry: unknown): unknown => {\n if (!entry || typeof entry !== \"object\") return null;\n const { queryKey, state } = entry as { queryKey?: unknown; state?: { data?: unknown } };\n if (!Array.isArray(queryKey) || !keyAllowed(queryKey)) return null;\n if (!isCacheSafe(state?.data)) return null;\n return withScrubbedData(entry);\n };\n\n /** Whether `value` has a scrubbed field's name anywhere in it. */\n const carriesScrubbed = (value: unknown, depth = 0): boolean => {\n if (scrubFields.length === 0 || depth > 12 || value === null || typeof value !== \"object\") return false;\n if (Array.isArray(value)) return value.some((v) => carriesScrubbed(v, depth + 1));\n return Object.entries(value as Record<string, unknown>).some(\n ([name, v]) =>\n scrubFields.some((f) => (typeof f === \"string\" ? f === name : f.test(name))) || carriesScrubbed(v, depth + 1),\n );\n };\n\n /** The write side for mutations: TanStack's default (paused ones), minus any whose\n * variables carry a scrubbed field (S6); none at all with `persistMutations: false`. */\n const shouldDehydrateMutation = (mutation: { state: { isPaused: boolean; variables?: unknown } }): boolean =>\n persistMutations && mutation.state.isPaused && !carriesScrubbed(mutation.state.variables);\n\n const withScrubbedData = (entry: unknown): unknown => {\n const query = entry as { state?: { data?: unknown } };\n if (!query.state || !(\"data\" in query.state)) return entry;\n return { ...query, state: { ...query.state, data: scrub(query.state.data, scrubFields) } };\n };\n\n // The scrub on the way OUT: the in-memory cache keeps the field (the page that is open\n // shows it), the disk never sees it. Mutations are a paused write queue and are kept\n // whole — scrubbing one would change what it sends — so one carrying a scrubbed field is\n // not written at all (`shouldDehydrateMutation`).\n const serialize = (client: PersistedClient): string =>\n JSON.stringify({\n ...client,\n clientState: { ...client.clientState, queries: client.clientState.queries.map(withScrubbedData) },\n });\n\n // The twin on the way IN (keksdose's `sanitizePersistedCache`, :264-298): an older build\n // wrote what this one may deny. Never throws; an unreadable blob comes back with\n // `timestamp: 0`, which the restore treats as unusable and removes.\n const deserialize = (raw: string): PersistedClient => {\n const empty: PersistedClient = { timestamp: 0, buster: \"\", clientState: { mutations: [], queries: [] } };\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\") return empty;\n const { timestamp, buster: stored, clientState } = parsed as Partial<PersistedClient>;\n if (typeof timestamp !== \"number\" || typeof stored !== \"string\") return empty;\n if (!clientState || typeof clientState !== \"object\" || !Array.isArray(clientState.queries)) return empty;\n return {\n timestamp,\n buster: stored,\n clientState: {\n mutations: persistMutations && Array.isArray(clientState.mutations)\n ? clientState.mutations.filter(\n (m) => !carriesScrubbed((m as { state?: { variables?: unknown } } | null)?.state?.variables),\n )\n : [],\n queries: clientState.queries.map(restorable).filter((q) => q !== null) as PersistedClient[\"clientState\"][\"queries\"],\n },\n };\n } catch {\n return empty;\n }\n };\n\n const persister = createAsyncStoragePersister({\n storage: {\n // Only the provider's restore reads: mounting this persistence again re-arms it.\n getItem: async (k) => {\n retired = false;\n return (await storage.getItem(k)) ?? null;\n },\n setItem: async (k, v) => {\n if (!retired) await storage.setItem(k, v);\n },\n removeItem: async (k) => {\n await storage.removeItem(k);\n },\n },\n key,\n throttleTime,\n serialize,\n deserialize,\n });\n\n const leave = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n } catch {\n /* best-effort */\n }\n };\n\n const clear = async (queryClient: QueryClient) => {\n retired = true;\n try {\n queryClient.clear();\n await persister.removeClient();\n } catch {\n /* best-effort: private mode / IndexedDB unavailable */\n }\n };\n\n const removeStale = () => removeStaleQueryCopies(app, maxAge, { storage, keep: key });\n\n return {\n key,\n persistOptions: { persister, maxAge, buster, dehydrateOptions: { shouldDehydrateQuery, shouldDehydrateMutation } },\n clear,\n leave,\n removeStale,\n };\n}\n"],"mappings":";AAAA,SAAS,mCAAmC;AAG5C,SAAS,KAAK,KAAK,MAAM,WAAW;AAuB7B,MAAM,uBAA8C,OAAO,OAAO;AAAA,EACvE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAoFD,MAAM,aAAsC;AAAA,EAC1C,SAAS,CAAC,QAAQ,IAAY,GAAG;AAAA,EACjC,SAAS,CAAC,KAAK,UAAU,IAAI,KAAK,KAAK;AAAA,EACvC,YAAY,CAAC,QAAQ,IAAI,GAAG;AAAA,EAC5B,MAAM,MAAM,KAAK;AACnB;AAmBA,eAAsB,uBACpB,KACA,QACA,EAAE,UAAU,YAAY,KAAK,IAAmC,CAAC,GAClD;AACf,QAAM,SAAS,GAAG,GAAG;AACrB,MAAI;AACF,UAAM,MAAM,KAAK,IAAI;AACrB,eAAW,KAAK,MAAM,QAAQ,KAAK,GAAG;AACpC,UAAI,OAAO,MAAM,YAAY,CAAC,EAAE,WAAW,MAAM,KAAK,MAAM,KAAM;AAClE,UAAI,YAAY;AAChB,UAAI;AACF,cAAM,MAAM,MAAM,QAAQ,QAAQ,CAAC;AACnC,cAAM,SAAkB,MAAM,KAAK,MAAM,GAAG,I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A,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * vite-plugin-pwa's `registerSW` from `virtual:pwa-register` (`registerType: "prompt"`) —
3
+ * the app passes it in, since a virtual module is the app's build's, not the kit's. It
4
+ * answers the `updateSW(reloadPage)` function.
5
+ */
6
+ export type RegisterServiceWorker = (options: {
7
+ onNeedRefresh?: () => void;
8
+ onOfflineReady?: () => void;
9
+ }) => (reloadPage?: boolean) => Promise<void>;
10
+ /** What {@link createServiceWorkerUpdates} answers: one store per app, a module constant. */
11
+ export interface ServiceWorkerUpdates {
12
+ /** Registers the service worker — once, however often it is called. Call it at start,
13
+ * before the router renders, so the sign-in pages get the offline shell too. */
14
+ start: () => void;
15
+ /** Whether a new version waits. */
16
+ needRefresh: () => boolean;
17
+ /** For `useSyncExternalStore`. */
18
+ subscribe: (listener: () => void) => () => void;
19
+ /** Activates the waiting version and reloads (`updateSW(true)`). Before `start`, nothing. */
20
+ reload: () => void;
21
+ /** The person closed the prompt: the version keeps waiting, the prompt stays down. */
22
+ dismiss: () => void;
23
+ }
24
+ /**
25
+ * 0.46 (kastlan K3, docs/local-first-harmonization.md §1.5 D8): the service worker
26
+ * registered ONCE AT START, and its "a new version waits" state as a small store the
27
+ * prompt reads wherever it lives. vite-plugin-pwa's `useRegisterSW` registers when the
28
+ * component that calls it mounts: an app whose {@link PwaUpdatePrompt} sits in its
29
+ * signed-in shell (it reads the tour state, the route) would register only after sign-in,
30
+ * and the sign-in pages would lose the offline shell on a first visit.
31
+ *
32
+ * ```ts
33
+ * // shared/pwa/sw-updates.ts
34
+ * import { registerSW } from "virtual:pwa-register";
35
+ * export const swUpdates = createServiceWorkerUpdates(registerSW);
36
+ * // main.tsx, before render: swUpdates.start();
37
+ * // the shell: <PwaUpdatePrompt {...useServiceWorkerUpdate(swUpdates)} hold={tourRunning} />
38
+ * ```
39
+ */
40
+ export declare function createServiceWorkerUpdates(register: RegisterServiceWorker): ServiceWorkerUpdates;
41
+ /** {@link PwaUpdatePrompt}'s props from the store: `needRefresh`, `onReload`, `onDismiss`. */
42
+ export declare function useServiceWorkerUpdate(updates: ServiceWorkerUpdates): {
43
+ needRefresh: boolean;
44
+ onReload: () => void;
45
+ onDismiss: () => void;
46
+ };
@@ -0,0 +1,39 @@
1
+ "use client";
2
+ import { useSyncExternalStore } from "react";
3
+ function createServiceWorkerUpdates(register) {
4
+ let waiting = false;
5
+ let update = null;
6
+ const listeners = /* @__PURE__ */ new Set();
7
+ const emit = () => listeners.forEach((listener) => listener());
8
+ const set = (value) => {
9
+ if (waiting === value) return;
10
+ waiting = value;
11
+ emit();
12
+ };
13
+ return {
14
+ start: () => {
15
+ if (update) return;
16
+ update = register({ onNeedRefresh: () => set(true) });
17
+ },
18
+ needRefresh: () => waiting,
19
+ subscribe: (listener) => {
20
+ listeners.add(listener);
21
+ return () => {
22
+ listeners.delete(listener);
23
+ };
24
+ },
25
+ reload: () => {
26
+ void update?.(true);
27
+ },
28
+ dismiss: () => set(false)
29
+ };
30
+ }
31
+ function useServiceWorkerUpdate(updates) {
32
+ const needRefresh = useSyncExternalStore(updates.subscribe, updates.needRefresh, () => false);
33
+ return { needRefresh, onReload: updates.reload, onDismiss: updates.dismiss };
34
+ }
35
+ export {
36
+ createServiceWorkerUpdates,
37
+ useServiceWorkerUpdate
38
+ };
39
+ //# sourceMappingURL=service-worker-updates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/offline/service-worker-updates.ts"],"sourcesContent":["import { useSyncExternalStore } from \"react\";\n\n/**\n * vite-plugin-pwa's `registerSW` from `virtual:pwa-register` (`registerType: \"prompt\"`) —\n * the app passes it in, since a virtual module is the app's build's, not the kit's. It\n * answers the `updateSW(reloadPage)` function.\n */\nexport type RegisterServiceWorker = (options: {\n onNeedRefresh?: () => void;\n onOfflineReady?: () => void;\n}) => (reloadPage?: boolean) => Promise<void>;\n\n/** What {@link createServiceWorkerUpdates} answers: one store per app, a module constant. */\nexport interface ServiceWorkerUpdates {\n /** Registers the service worker — once, however often it is called. Call it at start,\n * before the router renders, so the sign-in pages get the offline shell too. */\n start: () => void;\n /** Whether a new version waits. */\n needRefresh: () => boolean;\n /** For `useSyncExternalStore`. */\n subscribe: (listener: () => void) => () => void;\n /** Activates the waiting version and reloads (`updateSW(true)`). Before `start`, nothing. */\n reload: () => void;\n /** The person closed the prompt: the version keeps waiting, the prompt stays down. */\n dismiss: () => void;\n}\n\n/**\n * 0.46 (kastlan K3, docs/local-first-harmonization.md §1.5 D8): the service worker\n * registered ONCE AT START, and its \"a new version waits\" state as a small store the\n * prompt reads wherever it lives. vite-plugin-pwa's `useRegisterSW` registers when the\n * component that calls it mounts: an app whose {@link PwaUpdatePrompt} sits in its\n * signed-in shell (it reads the tour state, the route) would register only after sign-in,\n * and the sign-in pages would lose the offline shell on a first visit.\n *\n * ```ts\n * // shared/pwa/sw-updates.ts\n * import { registerSW } from \"virtual:pwa-register\";\n * export const swUpdates = createServiceWorkerUpdates(registerSW);\n * // main.tsx, before render: swUpdates.start();\n * // the shell: <PwaUpdatePrompt {...useServiceWorkerUpdate(swUpdates)} hold={tourRunning} />\n * ```\n */\nexport function createServiceWorkerUpdates(register: RegisterServiceWorker): ServiceWorkerUpdates {\n let waiting = false;\n let update: ((reloadPage?: boolean) => Promise<void>) | null = null;\n const listeners = new Set<() => void>();\n const emit = () => listeners.forEach((listener) => listener());\n const set = (value: boolean) => {\n if (waiting === value) return;\n waiting = value;\n emit();\n };\n return {\n start: () => {\n if (update) return;\n update = register({ onNeedRefresh: () => set(true) });\n },\n needRefresh: () => waiting,\n subscribe: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n reload: () => {\n void update?.(true);\n },\n dismiss: () => set(false),\n };\n}\n\n/** {@link PwaUpdatePrompt}'s props from the store: `needRefresh`, `onReload`, `onDismiss`. */\nexport function useServiceWorkerUpdate(updates: ServiceWorkerUpdates): {\n needRefresh: boolean;\n onReload: () => void;\n onDismiss: () => void;\n} {\n const needRefresh = useSyncExternalStore(updates.subscribe, updates.needRefresh, () => false);\n return { needRefresh, onReload: updates.reload, onDismiss: updates.dismiss };\n}\n"],"mappings":";AAAA,SAAS,4BAA4B;AA2C9B,SAAS,2BAA2B,UAAuD;AAChG,MAAI,UAAU;AACd,MAAI,SAA2D;AAC/D,QAAM,YAAY,oBAAI,IAAgB;AACtC,QAAM,OAAO,MAAM,UAAU,QAAQ,CAAC,aAAa,SAAS,CAAC;AAC7D,QAAM,MAAM,CAAC,UAAmB;AAC9B,QAAI,YAAY,MAAO;AACvB,cAAU;AACV,SAAK;AAAA,EACP;AACA,SAAO;AAAA,IACL,OAAO,MAAM;AACX,UAAI,OAAQ;AACZ,eAAS,SAAS,EAAE,eAAe,MAAM,IAAI,IAAI,EAAE,CAAC;AAAA,IACtD;AAAA,IACA,aAAa,MAAM;AAAA,IACnB,WAAW,CAAC,aAAa;AACvB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,QAAQ,MAAM;AACZ,WAAK,SAAS,IAAI;AAAA,IACpB;AAAA,IACA,SAAS,MAAM,IAAI,KAAK;AAAA,EAC1B;AACF;AAGO,SAAS,uBAAuB,SAIrC;AACA,QAAM,cAAc,qBAAqB,QAAQ,WAAW,QAAQ,aAAa,MAAM,KAAK;AAC5F,SAAO,EAAE,aAAa,UAAU,QAAQ,QAAQ,WAAW,QAAQ,QAAQ;AAC7E;","names":[]}
package/dist/offline.d.ts CHANGED
@@ -1,8 +1,11 @@
1
- export { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe } from "./offline/query-persistence.js";
2
- export type { QueryPersistence, QueryPersistenceOptions, QueryPersistenceStorage, ScrubField, } from "./offline/query-persistence.js";
1
+ export { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe, removeStaleQueryCopies } from "./offline/query-persistence.js";
2
+ export type { QueryPersistence, QueryPersistenceOptions, QueryPersistenceStorage, RemoveStaleQueryCopiesOptions, ScrubField, } from "./offline/query-persistence.js";
3
3
  export { SignOutPendingDialog, DEFAULT_SIGN_OUT_PENDING_DIALOG_LABELS } from "./offline/sign-out-pending-dialog.js";
4
4
  export type { SignOutPendingDialogProps, SignOutPendingDialogLabels } from "./offline/sign-out-pending-dialog.js";
5
5
  export { PwaUpdatePrompt, DEFAULT_PWA_UPDATE_PROMPT_LABELS } from "./offline/pwa-update-prompt.js";
6
6
  export type { PwaUpdatePromptProps, PwaUpdatePromptLabels } from "./offline/pwa-update-prompt.js";
7
+ export { createServiceWorkerUpdates, useServiceWorkerUpdate } from "./offline/service-worker-updates.js";
8
+ export type { RegisterServiceWorker, ServiceWorkerUpdates } from "./offline/service-worker-updates.js";
7
9
  export { SharedComputerChoice, DEFAULT_SHARED_COMPUTER_LABELS, isSharedComputer, setSharedComputer, } from "./offline/shared-computer.js";
8
10
  export type { SharedComputerChoiceProps, SharedComputerLabels, SharedComputerStorage } from "./offline/shared-computer.js";
11
+ export { isOfflineError, readLocalFirst, stampAfter, uuid5, writeLocalFirst } from "./offline/local-first.js";
package/dist/offline.js CHANGED
@@ -1,13 +1,15 @@
1
1
  "use client";
2
- import { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe } from "./offline/query-persistence.js";
2
+ import { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe, removeStaleQueryCopies } from "./offline/query-persistence.js";
3
3
  import { SignOutPendingDialog, DEFAULT_SIGN_OUT_PENDING_DIALOG_LABELS } from "./offline/sign-out-pending-dialog.js";
4
4
  import { PwaUpdatePrompt, DEFAULT_PWA_UPDATE_PROMPT_LABELS } from "./offline/pwa-update-prompt.js";
5
+ import { createServiceWorkerUpdates, useServiceWorkerUpdate } from "./offline/service-worker-updates.js";
5
6
  import {
6
7
  SharedComputerChoice,
7
8
  DEFAULT_SHARED_COMPUTER_LABELS,
8
9
  isSharedComputer,
9
10
  setSharedComputer
10
11
  } from "./offline/shared-computer.js";
12
+ import { isOfflineError, readLocalFirst, stampAfter, uuid5, writeLocalFirst } from "./offline/local-first.js";
11
13
  export {
12
14
  DEFAULT_PWA_UPDATE_PROMPT_LABELS,
13
15
  DEFAULT_SCRUB_FIELDS,
@@ -17,8 +19,16 @@ export {
17
19
  SharedComputerChoice,
18
20
  SignOutPendingDialog,
19
21
  createQueryPersistence,
22
+ createServiceWorkerUpdates,
20
23
  isCacheSafe,
24
+ isOfflineError,
21
25
  isSharedComputer,
22
- setSharedComputer
26
+ readLocalFirst,
27
+ removeStaleQueryCopies,
28
+ setSharedComputer,
29
+ stampAfter,
30
+ useServiceWorkerUpdate,
31
+ uuid5,
32
+ writeLocalFirst
23
33
  };
24
34
  //# sourceMappingURL=offline.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/offline.ts"],"sourcesContent":["// `@eifi1/ui-kit/offline` — local-first phase 1 (docs/local-first-harmonization.md §1.6,\n// 0.45): the persisted query cache with its scrub list, the sign-out question while changes\n// wait, the service-worker update prompt, and the shared-computer choice.\n//\n// The only entry point that requires `@tanstack/react-query`,\n// `@tanstack/react-query-persist-client`, `@tanstack/query-async-storage-persister` and\n// `idb-keyval` — optional peers for that reason. NOT re-exported from the main barrel, which\n// would make them everyone's install; the packaging contract test holds that line.\nexport { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe } from \"./offline/query-persistence\";\nexport type {\n QueryPersistence,\n QueryPersistenceOptions,\n QueryPersistenceStorage,\n ScrubField,\n} from \"./offline/query-persistence\";\nexport { SignOutPendingDialog, DEFAULT_SIGN_OUT_PENDING_DIALOG_LABELS } from \"./offline/sign-out-pending-dialog\";\nexport type { SignOutPendingDialogProps, SignOutPendingDialogLabels } from \"./offline/sign-out-pending-dialog\";\nexport { PwaUpdatePrompt, DEFAULT_PWA_UPDATE_PROMPT_LABELS } from \"./offline/pwa-update-prompt\";\nexport type { PwaUpdatePromptProps, PwaUpdatePromptLabels } from \"./offline/pwa-update-prompt\";\nexport {\n SharedComputerChoice,\n DEFAULT_SHARED_COMPUTER_LABELS,\n isSharedComputer,\n setSharedComputer,\n} from \"./offline/shared-computer\";\nexport type { SharedComputerChoiceProps, SharedComputerLabels, SharedComputerStorage } from \"./offline/shared-computer\";\n"],"mappings":";AAQA,SAAS,wBAAwB,sBAAsB,mBAAmB;AAO1E,SAAS,sBAAsB,8CAA8C;AAE7E,SAAS,iBAAiB,wCAAwC;AAElE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":[]}
1
+ {"version":3,"sources":["../src/offline.ts"],"sourcesContent":["// `@eifi1/ui-kit/offline` — local-first phase 1 (docs/local-first-harmonization.md §1.6,\n// 0.45): the persisted query cache with its scrub list, the sign-out question while changes\n// wait, the service-worker update prompt, and the shared-computer choice.\n//\n// The only entry point that requires `@tanstack/react-query`,\n// `@tanstack/react-query-persist-client`, `@tanstack/query-async-storage-persister` and\n// `idb-keyval` — optional peers for that reason. NOT re-exported from the main barrel, which\n// would make them everyone's install; the packaging contract test holds that line.\nexport { createQueryPersistence, DEFAULT_SCRUB_FIELDS, isCacheSafe, removeStaleQueryCopies } from \"./offline/query-persistence\";\nexport type {\n QueryPersistence,\n QueryPersistenceOptions,\n QueryPersistenceStorage,\n RemoveStaleQueryCopiesOptions,\n ScrubField,\n} from \"./offline/query-persistence\";\nexport { SignOutPendingDialog, DEFAULT_SIGN_OUT_PENDING_DIALOG_LABELS } from \"./offline/sign-out-pending-dialog\";\nexport type { SignOutPendingDialogProps, SignOutPendingDialogLabels } from \"./offline/sign-out-pending-dialog\";\nexport { PwaUpdatePrompt, DEFAULT_PWA_UPDATE_PROMPT_LABELS } from \"./offline/pwa-update-prompt\";\nexport type { PwaUpdatePromptProps, PwaUpdatePromptLabels } from \"./offline/pwa-update-prompt\";\n// 0.46 (kastlan K3): the service worker registered once at start, its update state as a store.\nexport { createServiceWorkerUpdates, useServiceWorkerUpdate } from \"./offline/service-worker-updates\";\nexport type { RegisterServiceWorker, ServiceWorkerUpdates } from \"./offline/service-worker-updates\";\nexport {\n SharedComputerChoice,\n DEFAULT_SHARED_COMPUTER_LABELS,\n isSharedComputer,\n setSharedComputer,\n} from \"./offline/shared-computer\";\nexport type { SharedComputerChoiceProps, SharedComputerLabels, SharedComputerStorage } from \"./offline/shared-computer\";\n// 0.46 (§2.3): the leaf utilities, shared with `@eifi1/ui-kit/sync` from one module that imports no peer.\nexport { isOfflineError, readLocalFirst, stampAfter, uuid5, writeLocalFirst } from \"./offline/local-first\";\n"],"mappings":";AAQA,SAAS,wBAAwB,sBAAsB,aAAa,8BAA8B;AAQlG,SAAS,sBAAsB,8CAA8C;AAE7E,SAAS,iBAAiB,wCAAwC;AAGlE,SAAS,4BAA4B,8BAA8B;AAEnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,gBAAgB,gBAAgB,YAAY,OAAO,uBAAuB;","names":[]}
@@ -0,0 +1,2 @@
1
+ export { PUSH_SUBSCRIPTION_CHANGED, handlePushSubscriptionChange, pushSubscriptionInput, resubscribeAfterChange, } from "./notifications/push-worker.js";
2
+ export type { PushReplaceInput, PushResubscribeOutcome, PushSubscriptionChangeEventLike, PushSubscriptionChangeOptions, PushSubscriptionInput, PushWorkerScope, } from "./notifications/push-worker.js";