tempest-react-sdk 0.48.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/dist/audio/sfx-pool.cjs +1 -1
  2. package/dist/audio/sfx-pool.cjs.map +1 -1
  3. package/dist/audio/sfx-pool.js +16 -7
  4. package/dist/audio/sfx-pool.js.map +1 -1
  5. package/dist/audio/use-sfx-pool.cjs +1 -1
  6. package/dist/audio/use-sfx-pool.cjs.map +1 -1
  7. package/dist/audio/use-sfx-pool.js +3 -8
  8. package/dist/audio/use-sfx-pool.js.map +1 -1
  9. package/dist/auth/passkey.cjs +1 -1
  10. package/dist/auth/passkey.cjs.map +1 -1
  11. package/dist/auth/passkey.js +79 -81
  12. package/dist/auth/passkey.js.map +1 -1
  13. package/dist/charts.cjs +1 -1
  14. package/dist/charts.js +4 -4
  15. package/dist/components/BarList/BarList.cjs +1 -1
  16. package/dist/components/BarList/BarList.cjs.map +1 -1
  17. package/dist/components/BarList/BarList.js +31 -24
  18. package/dist/components/BarList/BarList.js.map +1 -1
  19. package/dist/components/BarList/bar-list-model.cjs +1 -1
  20. package/dist/components/BarList/bar-list-model.cjs.map +1 -1
  21. package/dist/components/BarList/bar-list-model.js +5 -5
  22. package/dist/components/BarList/bar-list-model.js.map +1 -1
  23. package/dist/components/ClickOutside/ClickOutside.cjs +1 -1
  24. package/dist/components/ClickOutside/ClickOutside.cjs.map +1 -1
  25. package/dist/components/ClickOutside/ClickOutside.js +13 -14
  26. package/dist/components/ClickOutside/ClickOutside.js.map +1 -1
  27. package/dist/components/DataTable/DataTable.cjs +1 -1
  28. package/dist/components/DataTable/DataTable.cjs.map +1 -1
  29. package/dist/components/DataTable/DataTable.js +99 -95
  30. package/dist/components/DataTable/DataTable.js.map +1 -1
  31. package/dist/components/DataTable/use-dev-warnings.cjs +1 -1
  32. package/dist/components/DataTable/use-dev-warnings.cjs.map +1 -1
  33. package/dist/components/DataTable/use-dev-warnings.js +5 -3
  34. package/dist/components/DataTable/use-dev-warnings.js.map +1 -1
  35. package/dist/components/FilterBar/filter-apply.cjs +1 -1
  36. package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
  37. package/dist/components/FilterBar/filter-apply.js +35 -38
  38. package/dist/components/FilterBar/filter-apply.js.map +1 -1
  39. package/dist/components/FilterBar/filter-query.cjs +1 -1
  40. package/dist/components/FilterBar/filter-query.cjs.map +1 -1
  41. package/dist/components/FilterBar/filter-query.js +16 -13
  42. package/dist/components/FilterBar/filter-query.js.map +1 -1
  43. package/dist/geo/use-position-tracker.cjs +1 -1
  44. package/dist/geo/use-position-tracker.cjs.map +1 -1
  45. package/dist/geo/use-position-tracker.js +25 -26
  46. package/dist/geo/use-position-tracker.js.map +1 -1
  47. package/dist/hooks/use-async.cjs +1 -1
  48. package/dist/hooks/use-async.cjs.map +1 -1
  49. package/dist/hooks/use-async.js +27 -30
  50. package/dist/hooks/use-async.js.map +1 -1
  51. package/dist/hooks/use-click-outside.cjs +1 -1
  52. package/dist/hooks/use-click-outside.cjs.map +1 -1
  53. package/dist/hooks/use-click-outside.js +8 -9
  54. package/dist/hooks/use-click-outside.js.map +1 -1
  55. package/dist/hooks/use-countdown.cjs +1 -1
  56. package/dist/hooks/use-countdown.cjs.map +1 -1
  57. package/dist/hooks/use-countdown.js +8 -13
  58. package/dist/hooks/use-countdown.js.map +1 -1
  59. package/dist/hooks/use-event-listener.cjs +1 -1
  60. package/dist/hooks/use-event-listener.cjs.map +1 -1
  61. package/dist/hooks/use-event-listener.js +6 -6
  62. package/dist/hooks/use-event-listener.js.map +1 -1
  63. package/dist/hooks/use-interval.cjs +1 -1
  64. package/dist/hooks/use-interval.cjs.map +1 -1
  65. package/dist/hooks/use-interval.js +5 -6
  66. package/dist/hooks/use-interval.js.map +1 -1
  67. package/dist/hooks/use-latest-ref.cjs.map +1 -1
  68. package/dist/hooks/use-latest-ref.js.map +1 -1
  69. package/dist/hooks/use-long-press-handlers.cjs +1 -1
  70. package/dist/hooks/use-long-press-handlers.cjs.map +1 -1
  71. package/dist/hooks/use-long-press-handlers.js +8 -10
  72. package/dist/hooks/use-long-press-handlers.js.map +1 -1
  73. package/dist/hooks/use-long-press.cjs +1 -1
  74. package/dist/hooks/use-long-press.cjs.map +1 -1
  75. package/dist/hooks/use-long-press.js +6 -6
  76. package/dist/hooks/use-long-press.js.map +1 -1
  77. package/dist/hooks/use-online.cjs +1 -1
  78. package/dist/hooks/use-online.cjs.map +1 -1
  79. package/dist/hooks/use-online.js +10 -10
  80. package/dist/hooks/use-online.js.map +1 -1
  81. package/dist/hooks/use-service-worker-update.cjs +1 -1
  82. package/dist/hooks/use-service-worker-update.cjs.map +1 -1
  83. package/dist/hooks/use-service-worker-update.js +24 -25
  84. package/dist/hooks/use-service-worker-update.js.map +1 -1
  85. package/dist/hooks/use-stable-callback.cjs +1 -1
  86. package/dist/hooks/use-stable-callback.cjs.map +1 -1
  87. package/dist/hooks/use-stable-callback.js +4 -3
  88. package/dist/hooks/use-stable-callback.js.map +1 -1
  89. package/dist/hooks/use-timeout.cjs +1 -1
  90. package/dist/hooks/use-timeout.cjs.map +1 -1
  91. package/dist/hooks/use-timeout.js +5 -6
  92. package/dist/hooks/use-timeout.js.map +1 -1
  93. package/dist/hooks/use-typewriter.cjs +1 -1
  94. package/dist/hooks/use-typewriter.cjs.map +1 -1
  95. package/dist/hooks/use-typewriter.js +9 -18
  96. package/dist/hooks/use-typewriter.js.map +1 -1
  97. package/dist/http/api-client.cjs +1 -1
  98. package/dist/http/api-client.cjs.map +1 -1
  99. package/dist/http/api-client.js +11 -16
  100. package/dist/http/api-client.js.map +1 -1
  101. package/dist/http/describe-api-error.cjs +1 -1
  102. package/dist/http/describe-api-error.cjs.map +1 -1
  103. package/dist/http/describe-api-error.js +12 -15
  104. package/dist/http/describe-api-error.js.map +1 -1
  105. package/dist/http/errors.cjs +1 -1
  106. package/dist/http/errors.cjs.map +1 -1
  107. package/dist/http/errors.js +18 -6
  108. package/dist/http/errors.js.map +1 -1
  109. package/dist/http/resumable-upload.cjs +1 -1
  110. package/dist/http/resumable-upload.cjs.map +1 -1
  111. package/dist/http/resumable-upload.js +125 -118
  112. package/dist/http/resumable-upload.js.map +1 -1
  113. package/dist/http/retry.cjs +1 -1
  114. package/dist/http/retry.cjs.map +1 -1
  115. package/dist/http/retry.js +20 -16
  116. package/dist/http/retry.js.map +1 -1
  117. package/dist/http/use-describe-api-error.cjs +1 -1
  118. package/dist/http/use-describe-api-error.cjs.map +1 -1
  119. package/dist/http/use-describe-api-error.js +2 -2
  120. package/dist/http/use-describe-api-error.js.map +1 -1
  121. package/dist/i18n/create-i18n.cjs +1 -1
  122. package/dist/i18n/create-i18n.cjs.map +1 -1
  123. package/dist/i18n/create-i18n.js +6 -6
  124. package/dist/i18n/create-i18n.js.map +1 -1
  125. package/dist/icons/material-symbols.cjs +1 -1
  126. package/dist/icons/material-symbols.cjs.map +1 -1
  127. package/dist/icons/material-symbols.js +136 -5
  128. package/dist/icons/material-symbols.js.map +1 -1
  129. package/dist/icons.d.ts +17 -5
  130. package/dist/offline/create-offline-sync.cjs +1 -1
  131. package/dist/offline/create-offline-sync.cjs.map +1 -1
  132. package/dist/offline/create-offline-sync.js +17 -9
  133. package/dist/offline/create-offline-sync.js.map +1 -1
  134. package/dist/offline/use-offline-sync.cjs +1 -1
  135. package/dist/offline/use-offline-sync.cjs.map +1 -1
  136. package/dist/offline/use-offline-sync.js +7 -8
  137. package/dist/offline/use-offline-sync.js.map +1 -1
  138. package/dist/push/use-push-subscription.cjs +1 -1
  139. package/dist/push/use-push-subscription.cjs.map +1 -1
  140. package/dist/push/use-push-subscription.js +13 -12
  141. package/dist/push/use-push-subscription.js.map +1 -1
  142. package/dist/query/retry-policy.cjs +1 -1
  143. package/dist/query/retry-policy.cjs.map +1 -1
  144. package/dist/query/retry-policy.js +3 -3
  145. package/dist/query/retry-policy.js.map +1 -1
  146. package/dist/sse/use-event-stream.cjs +1 -1
  147. package/dist/sse/use-event-stream.cjs.map +1 -1
  148. package/dist/sse/use-event-stream.js +19 -20
  149. package/dist/sse/use-event-stream.js.map +1 -1
  150. package/dist/tabular/use-tabular-predictor.cjs +1 -1
  151. package/dist/tabular/use-tabular-predictor.cjs.map +1 -1
  152. package/dist/tabular/use-tabular-predictor.js +20 -17
  153. package/dist/tabular/use-tabular-predictor.js.map +1 -1
  154. package/dist/tempest-react-sdk.cjs +1 -1
  155. package/dist/tempest-react-sdk.d.ts +381 -143
  156. package/dist/tempest-react-sdk.js +143 -143
  157. package/dist/theme/ThemeProvider.cjs +1 -1
  158. package/dist/theme/ThemeProvider.cjs.map +1 -1
  159. package/dist/theme/ThemeProvider.js +12 -17
  160. package/dist/theme/ThemeProvider.js.map +1 -1
  161. package/dist/utils/base64.cjs +2 -0
  162. package/dist/utils/base64.cjs.map +1 -0
  163. package/dist/utils/base64.js +16 -0
  164. package/dist/utils/base64.js.map +1 -0
  165. package/dist/utils/compare-values.cjs +1 -1
  166. package/dist/utils/compare-values.cjs.map +1 -1
  167. package/dist/utils/compare-values.js +4 -3
  168. package/dist/utils/compare-values.js.map +1 -1
  169. package/dist/utils/compressed-storage.cjs +1 -1
  170. package/dist/utils/compressed-storage.cjs.map +1 -1
  171. package/dist/utils/compressed-storage.js +16 -46
  172. package/dist/utils/compressed-storage.js.map +1 -1
  173. package/dist/utils/storage.cjs +1 -1
  174. package/dist/utils/storage.cjs.map +1 -1
  175. package/dist/utils/storage.js +37 -17
  176. package/dist/utils/storage.js.map +1 -1
  177. package/dist/vision/use-camera-stream.cjs +1 -1
  178. package/dist/vision/use-camera-stream.cjs.map +1 -1
  179. package/dist/vision/use-camera-stream.js +34 -33
  180. package/dist/vision/use-camera-stream.js.map +1 -1
  181. package/dist/vite/base-url.cjs +2 -0
  182. package/dist/vite/base-url.cjs.map +1 -0
  183. package/dist/vite/base-url.js +8 -0
  184. package/dist/vite/base-url.js.map +1 -0
  185. package/dist/vite/tempest-pwa-dev-sw.cjs +1 -1
  186. package/dist/vite/tempest-pwa-dev-sw.cjs.map +1 -1
  187. package/dist/vite/tempest-pwa-dev-sw.js +54 -29
  188. package/dist/vite/tempest-pwa-dev-sw.js.map +1 -1
  189. package/dist/vite/tempest-pwa-manifest.cjs +2 -2
  190. package/dist/vite/tempest-pwa-manifest.cjs.map +1 -1
  191. package/dist/vite/tempest-pwa-manifest.js +15 -14
  192. package/dist/vite/tempest-pwa-manifest.js.map +1 -1
  193. package/dist/vite.d.ts +2 -2
  194. package/dist/ws/use-web-socket.cjs +1 -1
  195. package/dist/ws/use-web-socket.cjs.map +1 -1
  196. package/dist/ws/use-web-socket.js +40 -42
  197. package/dist/ws/use-web-socket.js.map +1 -1
  198. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.js","names":[],"sources":["../../src/utils/base64.ts"],"sourcesContent":["/**\n * Base64-encode bytes, without splatting the whole array into `fromCharCode`.\n *\n * `String.fromCharCode(...bytes)` overflows the argument limit somewhere around\n * a hundred thousand entries — which a compressed save reaches easily — so the\n * conversion walks the buffer in 32 KiB windows. That is also why this is the\n * version worth sharing: the byte-at-a-time loop the other two call sites used\n * has no argument limit either, but it is markedly slower on the payload sizes\n * `compressedStorage` exists for.\n *\n * @param bytes - The bytes to encode.\n * @param options - Pass `urlSafe` for the base64url alphabet (`-`/`_`, unpadded),\n * which is what WebAuthn and anything travelling in a URL needs.\n * @returns Base64 text.\n */\nexport function bytesToBase64(bytes: Uint8Array, options: { urlSafe?: boolean } = {}): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let index = 0; index < bytes.length; index += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(index, index + chunkSize));\n }\n const encoded = btoa(binary);\n if (!options.urlSafe) return encoded;\n return encoded.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Decode base64 into bytes, accepting either alphabet.\n *\n * Takes no `urlSafe` option on purpose: translating `-`/`_` and restoring the\n * padding are no-ops on standard padded base64, so one permissive decoder is\n * correct for both inputs. Getting this half wrong — usually by feeding\n * unpadded base64url straight to `atob` and losing the last byte — is the\n * classic broken-WebAuthn bug.\n *\n * @param value - Base64 or base64url text, with or without `=` padding.\n * @returns The decoded bytes.\n */\nexport function base64ToBytes(value: string): Uint8Array<ArrayBuffer> {\n const standard = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = standard.padEnd(standard.length + ((4 - (standard.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n"],"mappings":";AAeA,SAAgB,EAAc,GAAmB,IAAiC,CAAC,GAAW;CAC1F,IAAI,IAAS,IACP,IAAY;CAClB,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAM,QAAQ,KAAS,GAC/C,KAAU,OAAO,aAAa,GAAG,EAAM,SAAS,GAAO,IAAQ,CAAS,CAAC;CAE7E,IAAM,IAAU,KAAK,CAAM;CAE3B,OADK,EAAQ,UACN,EAAQ,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE,IAD3C;AAEjC;AAcA,SAAgB,EAAc,GAAwC;CAClE,IAAM,IAAW,EAAM,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,GACrD,IAAS,EAAS,OAAO,EAAS,UAAW,IAAK,EAAS,SAAS,KAAM,GAAI,GAAG,GACjF,IAAS,KAAK,CAAM,GACpB,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAO,QAAQ,KAAS,GAChD,EAAM,KAAS,EAAO,WAAW,CAAK;CAE1C,OAAO;AACX"}
@@ -1,2 +1,2 @@
1
- function e(e,t){return e==null&&t==null?0:e==null?-1:t==null?1:typeof e==`number`&&typeof t==`number`?e-t:e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e==`boolean`&&typeof t==`boolean`?Number(e)-Number(t):String(e).localeCompare(String(t),void 0,{numeric:!0})}exports.compareValues=e;
1
+ var e=new Intl.Collator(void 0,{numeric:!0});function t(t,n){return t==null&&n==null?0:t==null?-1:n==null?1:typeof t==`number`&&typeof n==`number`?t-n:t instanceof Date&&n instanceof Date?t.getTime()-n.getTime():typeof t==`boolean`&&typeof n==`boolean`?Number(t)-Number(n):e.compare(String(t),String(n))}exports.compareValues=t;
2
2
  //# sourceMappingURL=compare-values.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"compare-values.cjs","names":[],"sources":["../../src/utils/compare-values.ts"],"sourcesContent":["/**\n * Compare two arbitrary cell values with stable, type-aware ordering.\n *\n * The comparator every table in the SDK sorts with, so `DataTable` and\n * `VirtualTable` agree on what \"sorted\" means. The type-aware branches exist\n * because the naive `String(a) < String(b)` gets the two most common cases wrong:\n * numbers would sort `10` before `9`, and dates would sort by their formatted\n * text. Strings fall back to `localeCompare` with `numeric: true`, so `\"item 2\"`\n * lands before `\"item 10\"`.\n *\n * `null` and `undefined` sort first, together — a missing value is not smaller\n * than another missing value.\n *\n * @param a - First value.\n * @param b - Second value.\n * @returns Negative when `a < b`, positive when `a > b`, zero when equal.\n */\nexport function compareValues(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n return String(a).localeCompare(String(b), undefined, { numeric: true });\n}\n"],"mappings":"AAiBA,SAAgB,EAAc,EAAY,EAAoB,CAO1D,OANI,GAAK,MAAQ,GAAK,KAAa,EAC/B,GAAK,KAAa,GAClB,GAAK,KAAa,EAClB,OAAO,GAAM,UAAY,OAAO,GAAM,SAAiB,EAAI,EAC3D,aAAa,MAAQ,aAAa,KAAa,EAAE,QAAQ,EAAI,EAAE,QAAQ,EACvE,OAAO,GAAM,WAAa,OAAO,GAAM,UAAkB,OAAO,CAAC,EAAI,OAAO,CAAC,EAC1E,OAAO,CAAC,CAAC,CAAC,cAAc,OAAO,CAAC,EAAG,IAAA,GAAW,CAAE,QAAS,EAAK,CAAC,CAC1E"}
1
+ {"version":3,"file":"compare-values.cjs","names":[],"sources":["../../src/utils/compare-values.ts"],"sourcesContent":["/**\n * One collator for every string comparison a table sort makes.\n *\n * `localeCompare(other, undefined, { numeric: true })` builds a collator per\n * call — passing an options bag opts out of the engine's cached-default fast\n * path — and a sort makes O(n log n) of these. Measured at 200k comparisons:\n * 453 ms through `localeCompare` against 25 ms through a hoisted collator.\n */\nconst TEXT_COLLATOR = new Intl.Collator(undefined, { numeric: true });\n\n/**\n * Compare two arbitrary cell values with stable, type-aware ordering.\n *\n * The comparator every table in the SDK sorts with, so `DataTable` and\n * `VirtualTable` agree on what \"sorted\" means. The type-aware branches exist\n * because the naive `String(a) < String(b)` gets the two most common cases wrong:\n * numbers would sort `10` before `9`, and dates would sort by their formatted\n * text. Strings fall back to `localeCompare` with `numeric: true`, so `\"item 2\"`\n * lands before `\"item 10\"`.\n *\n * `null` and `undefined` sort first, together — a missing value is not smaller\n * than another missing value.\n *\n * @param a - First value.\n * @param b - Second value.\n * @returns Negative when `a < b`, positive when `a > b`, zero when equal.\n */\nexport function compareValues(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n return TEXT_COLLATOR.compare(String(a), String(b));\n}\n"],"mappings":"AAQA,IAAM,EAAgB,IAAI,KAAK,SAAS,IAAA,GAAW,CAAE,QAAS,EAAK,CAAC,EAmBpE,SAAgB,EAAc,EAAY,EAAoB,CAO1D,OANI,GAAK,MAAQ,GAAK,KAAa,EAC/B,GAAK,KAAa,GAClB,GAAK,KAAa,EAClB,OAAO,GAAM,UAAY,OAAO,GAAM,SAAiB,EAAI,EAC3D,aAAa,MAAQ,aAAa,KAAa,EAAE,QAAQ,EAAI,EAAE,QAAQ,EACvE,OAAO,GAAM,WAAa,OAAO,GAAM,UAAkB,OAAO,CAAC,EAAI,OAAO,CAAC,EAC1E,EAAc,QAAQ,OAAO,CAAC,EAAG,OAAO,CAAC,CAAC,CACrD"}
@@ -1,8 +1,9 @@
1
1
  //#region src/utils/compare-values.ts
2
- function e(e, t) {
3
- return e == null && t == null ? 0 : e == null ? -1 : t == null ? 1 : typeof e == "number" && typeof t == "number" ? e - t : e instanceof Date && t instanceof Date ? e.getTime() - t.getTime() : typeof e == "boolean" && typeof t == "boolean" ? Number(e) - Number(t) : String(e).localeCompare(String(t), void 0, { numeric: !0 });
2
+ var e = new Intl.Collator(void 0, { numeric: !0 });
3
+ function t(t, n) {
4
+ return t == null && n == null ? 0 : t == null ? -1 : n == null ? 1 : typeof t == "number" && typeof n == "number" ? t - n : t instanceof Date && n instanceof Date ? t.getTime() - n.getTime() : typeof t == "boolean" && typeof n == "boolean" ? Number(t) - Number(n) : e.compare(String(t), String(n));
4
5
  }
5
6
  //#endregion
6
- export { e as compareValues };
7
+ export { t as compareValues };
7
8
 
8
9
  //# sourceMappingURL=compare-values.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compare-values.js","names":[],"sources":["../../src/utils/compare-values.ts"],"sourcesContent":["/**\n * Compare two arbitrary cell values with stable, type-aware ordering.\n *\n * The comparator every table in the SDK sorts with, so `DataTable` and\n * `VirtualTable` agree on what \"sorted\" means. The type-aware branches exist\n * because the naive `String(a) < String(b)` gets the two most common cases wrong:\n * numbers would sort `10` before `9`, and dates would sort by their formatted\n * text. Strings fall back to `localeCompare` with `numeric: true`, so `\"item 2\"`\n * lands before `\"item 10\"`.\n *\n * `null` and `undefined` sort first, together — a missing value is not smaller\n * than another missing value.\n *\n * @param a - First value.\n * @param b - Second value.\n * @returns Negative when `a < b`, positive when `a > b`, zero when equal.\n */\nexport function compareValues(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n return String(a).localeCompare(String(b), undefined, { numeric: true });\n}\n"],"mappings":";AAiBA,SAAgB,EAAc,GAAY,GAAoB;CAO1D,OANI,KAAK,QAAQ,KAAK,OAAa,IAC/B,KAAK,OAAa,KAClB,KAAK,OAAa,IAClB,OAAO,KAAM,YAAY,OAAO,KAAM,WAAiB,IAAI,IAC3D,aAAa,QAAQ,aAAa,OAAa,EAAE,QAAQ,IAAI,EAAE,QAAQ,IACvE,OAAO,KAAM,aAAa,OAAO,KAAM,YAAkB,OAAO,CAAC,IAAI,OAAO,CAAC,IAC1E,OAAO,CAAC,CAAC,CAAC,cAAc,OAAO,CAAC,GAAG,KAAA,GAAW,EAAE,SAAS,GAAK,CAAC;AAC1E"}
1
+ {"version":3,"file":"compare-values.js","names":[],"sources":["../../src/utils/compare-values.ts"],"sourcesContent":["/**\n * One collator for every string comparison a table sort makes.\n *\n * `localeCompare(other, undefined, { numeric: true })` builds a collator per\n * call — passing an options bag opts out of the engine's cached-default fast\n * path — and a sort makes O(n log n) of these. Measured at 200k comparisons:\n * 453 ms through `localeCompare` against 25 ms through a hoisted collator.\n */\nconst TEXT_COLLATOR = new Intl.Collator(undefined, { numeric: true });\n\n/**\n * Compare two arbitrary cell values with stable, type-aware ordering.\n *\n * The comparator every table in the SDK sorts with, so `DataTable` and\n * `VirtualTable` agree on what \"sorted\" means. The type-aware branches exist\n * because the naive `String(a) < String(b)` gets the two most common cases wrong:\n * numbers would sort `10` before `9`, and dates would sort by their formatted\n * text. Strings fall back to `localeCompare` with `numeric: true`, so `\"item 2\"`\n * lands before `\"item 10\"`.\n *\n * `null` and `undefined` sort first, together — a missing value is not smaller\n * than another missing value.\n *\n * @param a - First value.\n * @param b - Second value.\n * @returns Negative when `a < b`, positive when `a > b`, zero when equal.\n */\nexport function compareValues(a: unknown, b: unknown): number {\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n if (typeof a === \"number\" && typeof b === \"number\") return a - b;\n if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return Number(a) - Number(b);\n return TEXT_COLLATOR.compare(String(a), String(b));\n}\n"],"mappings":";AAQA,IAAM,IAAgB,IAAI,KAAK,SAAS,KAAA,GAAW,EAAE,SAAS,GAAK,CAAC;AAmBpE,SAAgB,EAAc,GAAY,GAAoB;CAO1D,OANI,KAAK,QAAQ,KAAK,OAAa,IAC/B,KAAK,OAAa,KAClB,KAAK,OAAa,IAClB,OAAO,KAAM,YAAY,OAAO,KAAM,WAAiB,IAAI,IAC3D,aAAa,QAAQ,aAAa,OAAa,EAAE,QAAQ,IAAI,EAAE,QAAQ,IACvE,OAAO,KAAM,aAAa,OAAO,KAAM,YAAkB,OAAO,CAAC,IAAI,OAAO,CAAC,IAC1E,EAAc,QAAQ,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;AACrD"}
@@ -1,2 +1,2 @@
1
- let e=require("fflate");var t=`~tgz1:`;function n(e){let t=``,n=32768;for(let r=0;r<e.length;r+=n)t+=String.fromCharCode(...e.subarray(r,r+n));return btoa(t)}function r(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function i(r){let i=JSON.stringify(r);return`${t}${n((0,e.gzipSync)(new TextEncoder().encode(i)))}`}function a(n){if(!n.startsWith(t))return JSON.parse(n);let i=(0,e.gunzipSync)(r(n.slice(6)));return JSON.parse(new TextDecoder().decode(i))}var o={serialize:i,deserialize:a},s={get(e,t){if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:a(n)}catch{return t}},set(e,t){if(typeof window>`u`)return;let n;try{n=i(t)}catch{n=JSON.stringify(t)}try{window.localStorage.setItem(e,n)}catch{}}};exports.compressToString=i,exports.compressedStorage=s,exports.compressedStorageCodec=o,exports.decompressFromString=a;
1
+ const e=require("./storage.cjs"),t=require("./base64.cjs");let n=require("fflate");var r=`~tgz1:`;function i(e){let i=JSON.stringify(e),a=(0,n.gzipSync)(new TextEncoder().encode(i));return`${r}${t.bytesToBase64(a)}`}function a(e){if(!e.startsWith(r))return JSON.parse(e);let i=(0,n.gunzipSync)(t.base64ToBytes(e.slice(6)));return JSON.parse(new TextDecoder().decode(i))}var o={serialize:i,deserialize:a},s=e.createJsonStorage(o);exports.compressToString=i,exports.compressedStorage=s,exports.compressedStorageCodec=o,exports.decompressFromString=a;
2
2
  //# sourceMappingURL=compressed-storage.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"compressed-storage.cjs","names":[],"sources":["../../src/utils/compressed-storage.ts"],"sourcesContent":["import { gunzipSync, gzipSync } from \"fflate\";\n\n/**\n * Gzip-backed `localStorage`, for payloads that would otherwise eat the quota.\n *\n * Kept in its own module rather than folded into {@link storage} so that\n * importing the plain typed wrapper never drags `fflate` into the bundle.\n *\n * @tempest-limits empty-catch — every operation here is best-effort by\n * contract, exactly like {@link storage}. `localStorage` throws on quota\n * exhaustion, in Safari private mode, and when a cross-origin frame has storage\n * blocked; a caller persisting state has no recovery to run and no message to\n * show, so the write is dropped and the value stays in memory for the session.\n */\n\n/**\n * Prefix stamped on every value this module writes.\n *\n * It makes the format self-describing, which is what lets a read fall back to\n * plain JSON: a key that predates compression — or that a degraded write stored\n * uncompressed — is still readable, so turning compression on for an existing\n * key does not orphan the data already there. The character also cannot open a\n * JSON document, so the two cases can never be confused.\n */\nconst MARKER = \"~tgz1:\";\n\n/**\n * Base64-encode bytes without splatting the whole array into `fromCharCode`.\n *\n * `String.fromCharCode(...bytes)` overflows the argument limit somewhere around\n * a hundred thousand entries, which a compressed save reaches easily, so the\n * conversion walks the buffer in 32 KiB windows instead.\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n/** Inverse of {@link bytesToBase64}. */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Serialize a value to a gzipped, base64 string carrying the format marker.\n *\n * Base64 costs a third more characters than the raw compressed bytes, and\n * `localStorage` bills two bytes per character on top of that. Packing the\n * bytes into UTF-16 code units directly would be denser, but lone surrogates\n * survive neither every storage implementation nor a JSON round-trip, and a\n * save that decodes to garbage is far worse than one that is bigger. Even with\n * that overhead a typical JSON document lands well under a third of its\n * uncompressed size.\n *\n * @typeParam T - The value being stored.\n * @param value - Any JSON-serializable value.\n * @returns The encoded string, ready for `localStorage`.\n */\nexport function compressToString<T>(value: T): string {\n const json = JSON.stringify(value);\n const bytes = gzipSync(new TextEncoder().encode(json));\n return `${MARKER}${bytesToBase64(bytes)}`;\n}\n\n/**\n * Decode a string produced by {@link compressToString}.\n *\n * A string without the marker is parsed as plain JSON, so values written before\n * compression was enabled — or by a write that fell back after `gzipSync`\n * failed — still read back.\n *\n * @typeParam T - The expected value shape.\n * @param raw - The stored string.\n * @returns The decoded value.\n * @throws If the payload is neither valid compressed data nor valid JSON.\n */\nexport function decompressFromString<T>(raw: string): T {\n if (!raw.startsWith(MARKER)) return JSON.parse(raw) as T;\n const bytes = gunzipSync(base64ToBytes(raw.slice(MARKER.length)));\n return JSON.parse(new TextDecoder().decode(bytes)) as T;\n}\n\n/**\n * Codec pair for {@link useLocalStorage}, so a compressed key gets the hook's\n * cross-tab sync and SSR guard for free.\n *\n * @example\n * const [save, setSave] = useLocalStorage(\"save\", EMPTY_SAVE, compressedStorageCodec);\n */\nexport const compressedStorageCodec = {\n serialize: compressToString,\n deserialize: decompressFromString,\n};\n\n/**\n * Typed `localStorage` wrapper that gzips what it writes.\n *\n * Mirrors {@link storage} so the two are interchangeable at the call site; the\n * difference is only in how the value is encoded.\n */\nexport const compressedStorage = {\n /**\n * Read and decompress a key.\n *\n * @typeParam T - The expected value shape.\n * @param key - Storage key.\n * @param fallback - Returned when the key is absent, unreadable, or corrupt.\n * @returns The stored value, or `fallback`.\n */\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : decompressFromString<T>(raw);\n } catch {\n return fallback;\n }\n },\n\n /**\n * Compress and write a key.\n *\n * When compression itself fails the value is written as plain JSON rather\n * than dropped: a slightly larger record still loads, an absent one does\n * not. Only a storage-level failure — quota, blocked storage — loses the\n * write.\n *\n * @typeParam T - The value being stored.\n * @param key - Storage key.\n * @param value - Any JSON-serializable value.\n */\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n let encoded: string;\n try {\n encoded = compressToString(value);\n } catch {\n encoded = JSON.stringify(value);\n }\n try {\n window.localStorage.setItem(key, encoded);\n } catch {\n /* empty */\n }\n },\n};\n"],"mappings":"wBAwBA,IAAM,EAAS,SASf,SAAS,EAAc,EAA2B,CAC9C,IAAI,EAAS,GACP,EAAY,MAClB,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,GAAK,EACnC,GAAU,OAAO,aAAa,GAAG,EAAM,SAAS,EAAG,EAAI,CAAS,CAAC,EAErE,OAAO,KAAK,CAAM,CACtB,CAGA,SAAS,EAAc,EAA4B,CAC/C,IAAM,EAAS,KAAK,CAAM,EACpB,EAAQ,IAAI,WAAW,EAAO,MAAM,EAC1C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,GAAK,EACpC,EAAM,GAAK,EAAO,WAAW,CAAC,EAElC,OAAO,CACX,CAiBA,SAAgB,EAAoB,EAAkB,CAClD,IAAM,EAAO,KAAK,UAAU,CAAK,EAEjC,MAAO,GAAG,IAAS,GADb,EAAQ,EAAA,SAAA,CAAS,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CACnB,CAAK,GAC1C,CAcA,SAAgB,EAAwB,EAAgB,CACpD,GAAI,CAAC,EAAI,WAAW,CAAM,EAAG,OAAO,KAAK,MAAM,CAAG,EAClD,IAAM,GAAA,EAAQ,EAAA,WAAA,CAAW,EAAc,EAAI,MAAM,CAAa,CAAC,CAAC,EAChE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CACrD,CASA,IAAa,EAAyB,CAClC,UAAW,EACX,YAAa,CACjB,EAQa,EAAoB,CAS7B,IAAO,EAAa,EAAgB,CAChC,GAAI,OAAO,OAAW,IAAa,OAAO,EAC1C,GAAI,CACA,IAAM,EAAM,OAAO,aAAa,QAAQ,CAAG,EAC3C,OAAO,IAAQ,KAAO,EAAW,EAAwB,CAAG,CAChE,MAAQ,CACJ,OAAO,CACX,CACJ,EAcA,IAAO,EAAa,EAAgB,CAChC,GAAI,OAAO,OAAW,IAAa,OACnC,IAAI,EACJ,GAAI,CACA,EAAU,EAAiB,CAAK,CACpC,MAAQ,CACJ,EAAU,KAAK,UAAU,CAAK,CAClC,CACA,GAAI,CACA,OAAO,aAAa,QAAQ,EAAK,CAAO,CAC5C,MAAQ,CAER,CACJ,CACJ"}
1
+ {"version":3,"file":"compressed-storage.cjs","names":[],"sources":["../../src/utils/compressed-storage.ts"],"sourcesContent":["import { gunzipSync, gzipSync } from \"fflate\";\n\nimport { base64ToBytes, bytesToBase64 } from \"./base64\";\n\nimport { createJsonStorage, type JsonStorage, type StorageCodec } from \"./storage\";\n\n/**\n * Gzip-backed `localStorage`, for payloads that would otherwise eat the quota.\n *\n * Kept in its own module rather than folded into {@link storage} so that\n * importing the plain typed wrapper never drags `fflate` into the bundle.\n *\n * @tempest-limits empty-catch — every operation here is best-effort by\n * contract, exactly like {@link storage}. `localStorage` throws on quota\n * exhaustion, in Safari private mode, and when a cross-origin frame has storage\n * blocked; a caller persisting state has no recovery to run and no message to\n * show, so the write is dropped and the value stays in memory for the session.\n */\n\n/**\n * Prefix stamped on every value this module writes.\n *\n * It makes the format self-describing, which is what lets a read fall back to\n * plain JSON: a key that predates compression — or that a degraded write stored\n * uncompressed — is still readable, so turning compression on for an existing\n * key does not orphan the data already there. The character also cannot open a\n * JSON document, so the two cases can never be confused.\n */\nconst MARKER = \"~tgz1:\";\n\n/**\n * Serialize a value to a gzipped, base64 string carrying the format marker.\n *\n * Base64 costs a third more characters than the raw compressed bytes, and\n * `localStorage` bills two bytes per character on top of that. Packing the\n * bytes into UTF-16 code units directly would be denser, but lone surrogates\n * survive neither every storage implementation nor a JSON round-trip, and a\n * save that decodes to garbage is far worse than one that is bigger. Even with\n * that overhead a typical JSON document lands well under a third of its\n * uncompressed size.\n *\n * @typeParam T - The value being stored.\n * @param value - Any JSON-serializable value.\n * @returns The encoded string, ready for `localStorage`.\n */\nexport function compressToString<T>(value: T): string {\n const json = JSON.stringify(value);\n const bytes = gzipSync(new TextEncoder().encode(json));\n return `${MARKER}${bytesToBase64(bytes)}`;\n}\n\n/**\n * Decode a string produced by {@link compressToString}.\n *\n * A string without the marker is parsed as plain JSON, so values written before\n * compression was enabled — or by a write that fell back after `gzipSync`\n * failed — still read back.\n *\n * @typeParam T - The expected value shape.\n * @param raw - The stored string.\n * @returns The decoded value.\n * @throws If the payload is neither valid compressed data nor valid JSON.\n */\nexport function decompressFromString<T>(raw: string): T {\n if (!raw.startsWith(MARKER)) return JSON.parse(raw) as T;\n const bytes = gunzipSync(base64ToBytes(raw.slice(MARKER.length)));\n return JSON.parse(new TextDecoder().decode(bytes)) as T;\n}\n\n/**\n * Codec pair for {@link useLocalStorage}, so a compressed key gets the hook's\n * cross-tab sync and SSR guard for free.\n *\n * @example\n * const [save, setSave] = useLocalStorage(\"save\", EMPTY_SAVE, compressedStorageCodec);\n */\nexport const compressedStorageCodec: StorageCodec = {\n serialize: compressToString,\n deserialize: decompressFromString,\n};\n\n/**\n * Typed `localStorage` wrapper that gzips what it writes.\n *\n * {@link createJsonStorage} with {@link compressedStorageCodec}, so it is the\n * same implementation as {@link storage} and genuinely interchangeable with it —\n * `get`, `set` and `remove`, differing only in how the value is encoded. It used\n * to be a hand-written copy that had no `remove`, which made that promise false\n * for anybody who took the docstring at its word.\n *\n * When compression itself fails the value is written as plain JSON rather than\n * dropped: a slightly larger record still loads, an absent one does not. Only a\n * storage-level failure — quota, blocked storage — loses the write.\n */\nexport const compressedStorage: JsonStorage = createJsonStorage(compressedStorageCodec);\n"],"mappings":"mFA4BA,IAAM,EAAS,SAiBf,SAAgB,EAAoB,EAAkB,CAClD,IAAM,EAAO,KAAK,UAAU,CAAK,EAC3B,GAAA,EAAQ,EAAA,SAAA,CAAS,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CAAC,EACrD,MAAO,GAAG,IAAS,EAAA,cAAc,CAAK,GAC1C,CAcA,SAAgB,EAAwB,EAAgB,CACpD,GAAI,CAAC,EAAI,WAAW,CAAM,EAAG,OAAO,KAAK,MAAM,CAAG,EAClD,IAAM,GAAA,EAAQ,EAAA,WAAA,CAAW,EAAA,cAAc,EAAI,MAAM,CAAa,CAAC,CAAC,EAChE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CACrD,CASA,IAAa,EAAuC,CAChD,UAAW,EACX,YAAa,CACjB,EAea,EAAiC,EAAA,kBAAkB,CAAsB"}
@@ -1,52 +1,22 @@
1
- import { gunzipSync as e, gzipSync as t } from "fflate";
1
+ import { createJsonStorage as e } from "./storage.js";
2
+ import { base64ToBytes as t, bytesToBase64 as n } from "./base64.js";
3
+ import { gunzipSync as r, gzipSync as i } from "fflate";
2
4
  //#region src/utils/compressed-storage.ts
3
- var n = "~tgz1:";
4
- function r(e) {
5
- let t = "", n = 32768;
6
- for (let r = 0; r < e.length; r += n) t += String.fromCharCode(...e.subarray(r, r + n));
7
- return btoa(t);
5
+ var a = "~tgz1:";
6
+ function o(e) {
7
+ let t = JSON.stringify(e), r = i(new TextEncoder().encode(t));
8
+ return `${a}${n(r)}`;
8
9
  }
9
- function i(e) {
10
- let t = atob(e), n = new Uint8Array(t.length);
11
- for (let e = 0; e < t.length; e += 1) n[e] = t.charCodeAt(e);
12
- return n;
10
+ function s(e) {
11
+ if (!e.startsWith(a)) return JSON.parse(e);
12
+ let n = r(t(e.slice(6)));
13
+ return JSON.parse(new TextDecoder().decode(n));
13
14
  }
14
- function a(e) {
15
- let i = JSON.stringify(e);
16
- return `${n}${r(t(new TextEncoder().encode(i)))}`;
17
- }
18
- function o(t) {
19
- if (!t.startsWith(n)) return JSON.parse(t);
20
- let r = e(i(t.slice(6)));
21
- return JSON.parse(new TextDecoder().decode(r));
22
- }
23
- var s = {
24
- serialize: a,
25
- deserialize: o
26
- }, c = {
27
- get(e, t) {
28
- if (typeof window > "u") return t;
29
- try {
30
- let n = window.localStorage.getItem(e);
31
- return n === null ? t : o(n);
32
- } catch {
33
- return t;
34
- }
35
- },
36
- set(e, t) {
37
- if (typeof window > "u") return;
38
- let n;
39
- try {
40
- n = a(t);
41
- } catch {
42
- n = JSON.stringify(t);
43
- }
44
- try {
45
- window.localStorage.setItem(e, n);
46
- } catch {}
47
- }
48
- };
15
+ var c = {
16
+ serialize: o,
17
+ deserialize: s
18
+ }, l = e(c);
49
19
  //#endregion
50
- export { a as compressToString, c as compressedStorage, s as compressedStorageCodec, o as decompressFromString };
20
+ export { o as compressToString, l as compressedStorage, c as compressedStorageCodec, s as decompressFromString };
51
21
 
52
22
  //# sourceMappingURL=compressed-storage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compressed-storage.js","names":[],"sources":["../../src/utils/compressed-storage.ts"],"sourcesContent":["import { gunzipSync, gzipSync } from \"fflate\";\n\n/**\n * Gzip-backed `localStorage`, for payloads that would otherwise eat the quota.\n *\n * Kept in its own module rather than folded into {@link storage} so that\n * importing the plain typed wrapper never drags `fflate` into the bundle.\n *\n * @tempest-limits empty-catch — every operation here is best-effort by\n * contract, exactly like {@link storage}. `localStorage` throws on quota\n * exhaustion, in Safari private mode, and when a cross-origin frame has storage\n * blocked; a caller persisting state has no recovery to run and no message to\n * show, so the write is dropped and the value stays in memory for the session.\n */\n\n/**\n * Prefix stamped on every value this module writes.\n *\n * It makes the format self-describing, which is what lets a read fall back to\n * plain JSON: a key that predates compression — or that a degraded write stored\n * uncompressed — is still readable, so turning compression on for an existing\n * key does not orphan the data already there. The character also cannot open a\n * JSON document, so the two cases can never be confused.\n */\nconst MARKER = \"~tgz1:\";\n\n/**\n * Base64-encode bytes without splatting the whole array into `fromCharCode`.\n *\n * `String.fromCharCode(...bytes)` overflows the argument limit somewhere around\n * a hundred thousand entries, which a compressed save reaches easily, so the\n * conversion walks the buffer in 32 KiB windows instead.\n */\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n/** Inverse of {@link bytesToBase64}. */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Serialize a value to a gzipped, base64 string carrying the format marker.\n *\n * Base64 costs a third more characters than the raw compressed bytes, and\n * `localStorage` bills two bytes per character on top of that. Packing the\n * bytes into UTF-16 code units directly would be denser, but lone surrogates\n * survive neither every storage implementation nor a JSON round-trip, and a\n * save that decodes to garbage is far worse than one that is bigger. Even with\n * that overhead a typical JSON document lands well under a third of its\n * uncompressed size.\n *\n * @typeParam T - The value being stored.\n * @param value - Any JSON-serializable value.\n * @returns The encoded string, ready for `localStorage`.\n */\nexport function compressToString<T>(value: T): string {\n const json = JSON.stringify(value);\n const bytes = gzipSync(new TextEncoder().encode(json));\n return `${MARKER}${bytesToBase64(bytes)}`;\n}\n\n/**\n * Decode a string produced by {@link compressToString}.\n *\n * A string without the marker is parsed as plain JSON, so values written before\n * compression was enabled — or by a write that fell back after `gzipSync`\n * failed — still read back.\n *\n * @typeParam T - The expected value shape.\n * @param raw - The stored string.\n * @returns The decoded value.\n * @throws If the payload is neither valid compressed data nor valid JSON.\n */\nexport function decompressFromString<T>(raw: string): T {\n if (!raw.startsWith(MARKER)) return JSON.parse(raw) as T;\n const bytes = gunzipSync(base64ToBytes(raw.slice(MARKER.length)));\n return JSON.parse(new TextDecoder().decode(bytes)) as T;\n}\n\n/**\n * Codec pair for {@link useLocalStorage}, so a compressed key gets the hook's\n * cross-tab sync and SSR guard for free.\n *\n * @example\n * const [save, setSave] = useLocalStorage(\"save\", EMPTY_SAVE, compressedStorageCodec);\n */\nexport const compressedStorageCodec = {\n serialize: compressToString,\n deserialize: decompressFromString,\n};\n\n/**\n * Typed `localStorage` wrapper that gzips what it writes.\n *\n * Mirrors {@link storage} so the two are interchangeable at the call site; the\n * difference is only in how the value is encoded.\n */\nexport const compressedStorage = {\n /**\n * Read and decompress a key.\n *\n * @typeParam T - The expected value shape.\n * @param key - Storage key.\n * @param fallback - Returned when the key is absent, unreadable, or corrupt.\n * @returns The stored value, or `fallback`.\n */\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : decompressFromString<T>(raw);\n } catch {\n return fallback;\n }\n },\n\n /**\n * Compress and write a key.\n *\n * When compression itself fails the value is written as plain JSON rather\n * than dropped: a slightly larger record still loads, an absent one does\n * not. Only a storage-level failure — quota, blocked storage — loses the\n * write.\n *\n * @typeParam T - The value being stored.\n * @param key - Storage key.\n * @param value - Any JSON-serializable value.\n */\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n let encoded: string;\n try {\n encoded = compressToString(value);\n } catch {\n encoded = JSON.stringify(value);\n }\n try {\n window.localStorage.setItem(key, encoded);\n } catch {\n /* empty */\n }\n },\n};\n"],"mappings":";;AAwBA,IAAM,IAAS;AASf,SAAS,EAAc,GAA2B;CAC9C,IAAI,IAAS,IACP,IAAY;CAClB,KAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK,GACnC,KAAU,OAAO,aAAa,GAAG,EAAM,SAAS,GAAG,IAAI,CAAS,CAAC;CAErE,OAAO,KAAK,CAAM;AACtB;AAGA,SAAS,EAAc,GAA4B;CAC/C,IAAM,IAAS,KAAK,CAAM,GACpB,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,GACpC,EAAM,KAAK,EAAO,WAAW,CAAC;CAElC,OAAO;AACX;AAiBA,SAAgB,EAAoB,GAAkB;CAClD,IAAM,IAAO,KAAK,UAAU,CAAK;CAEjC,OAAO,GAAG,IAAS,EADL,EAAS,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CACnB,CAAK;AAC1C;AAcA,SAAgB,EAAwB,GAAgB;CACpD,IAAI,CAAC,EAAI,WAAW,CAAM,GAAG,OAAO,KAAK,MAAM,CAAG;CAClD,IAAM,IAAQ,EAAW,EAAc,EAAI,MAAM,CAAa,CAAC,CAAC;CAChE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACrD;AASA,IAAa,IAAyB;CAClC,WAAW;CACX,aAAa;AACjB,GAQa,IAAoB;CAS7B,IAAO,GAAa,GAAgB;EAChC,IAAI,OAAO,SAAW,KAAa,OAAO;EAC1C,IAAI;GACA,IAAM,IAAM,OAAO,aAAa,QAAQ,CAAG;GAC3C,OAAO,MAAQ,OAAO,IAAW,EAAwB,CAAG;EAChE,QAAQ;GACJ,OAAO;EACX;CACJ;CAcA,IAAO,GAAa,GAAgB;EAChC,IAAI,OAAO,SAAW,KAAa;EACnC,IAAI;EACJ,IAAI;GACA,IAAU,EAAiB,CAAK;EACpC,QAAQ;GACJ,IAAU,KAAK,UAAU,CAAK;EAClC;EACA,IAAI;GACA,OAAO,aAAa,QAAQ,GAAK,CAAO;EAC5C,QAAQ,CAER;CACJ;AACJ"}
1
+ {"version":3,"file":"compressed-storage.js","names":[],"sources":["../../src/utils/compressed-storage.ts"],"sourcesContent":["import { gunzipSync, gzipSync } from \"fflate\";\n\nimport { base64ToBytes, bytesToBase64 } from \"./base64\";\n\nimport { createJsonStorage, type JsonStorage, type StorageCodec } from \"./storage\";\n\n/**\n * Gzip-backed `localStorage`, for payloads that would otherwise eat the quota.\n *\n * Kept in its own module rather than folded into {@link storage} so that\n * importing the plain typed wrapper never drags `fflate` into the bundle.\n *\n * @tempest-limits empty-catch — every operation here is best-effort by\n * contract, exactly like {@link storage}. `localStorage` throws on quota\n * exhaustion, in Safari private mode, and when a cross-origin frame has storage\n * blocked; a caller persisting state has no recovery to run and no message to\n * show, so the write is dropped and the value stays in memory for the session.\n */\n\n/**\n * Prefix stamped on every value this module writes.\n *\n * It makes the format self-describing, which is what lets a read fall back to\n * plain JSON: a key that predates compression — or that a degraded write stored\n * uncompressed — is still readable, so turning compression on for an existing\n * key does not orphan the data already there. The character also cannot open a\n * JSON document, so the two cases can never be confused.\n */\nconst MARKER = \"~tgz1:\";\n\n/**\n * Serialize a value to a gzipped, base64 string carrying the format marker.\n *\n * Base64 costs a third more characters than the raw compressed bytes, and\n * `localStorage` bills two bytes per character on top of that. Packing the\n * bytes into UTF-16 code units directly would be denser, but lone surrogates\n * survive neither every storage implementation nor a JSON round-trip, and a\n * save that decodes to garbage is far worse than one that is bigger. Even with\n * that overhead a typical JSON document lands well under a third of its\n * uncompressed size.\n *\n * @typeParam T - The value being stored.\n * @param value - Any JSON-serializable value.\n * @returns The encoded string, ready for `localStorage`.\n */\nexport function compressToString<T>(value: T): string {\n const json = JSON.stringify(value);\n const bytes = gzipSync(new TextEncoder().encode(json));\n return `${MARKER}${bytesToBase64(bytes)}`;\n}\n\n/**\n * Decode a string produced by {@link compressToString}.\n *\n * A string without the marker is parsed as plain JSON, so values written before\n * compression was enabled — or by a write that fell back after `gzipSync`\n * failed — still read back.\n *\n * @typeParam T - The expected value shape.\n * @param raw - The stored string.\n * @returns The decoded value.\n * @throws If the payload is neither valid compressed data nor valid JSON.\n */\nexport function decompressFromString<T>(raw: string): T {\n if (!raw.startsWith(MARKER)) return JSON.parse(raw) as T;\n const bytes = gunzipSync(base64ToBytes(raw.slice(MARKER.length)));\n return JSON.parse(new TextDecoder().decode(bytes)) as T;\n}\n\n/**\n * Codec pair for {@link useLocalStorage}, so a compressed key gets the hook's\n * cross-tab sync and SSR guard for free.\n *\n * @example\n * const [save, setSave] = useLocalStorage(\"save\", EMPTY_SAVE, compressedStorageCodec);\n */\nexport const compressedStorageCodec: StorageCodec = {\n serialize: compressToString,\n deserialize: decompressFromString,\n};\n\n/**\n * Typed `localStorage` wrapper that gzips what it writes.\n *\n * {@link createJsonStorage} with {@link compressedStorageCodec}, so it is the\n * same implementation as {@link storage} and genuinely interchangeable with it —\n * `get`, `set` and `remove`, differing only in how the value is encoded. It used\n * to be a hand-written copy that had no `remove`, which made that promise false\n * for anybody who took the docstring at its word.\n *\n * When compression itself fails the value is written as plain JSON rather than\n * dropped: a slightly larger record still loads, an absent one does not. Only a\n * storage-level failure — quota, blocked storage — loses the write.\n */\nexport const compressedStorage: JsonStorage = createJsonStorage(compressedStorageCodec);\n"],"mappings":";;;;AA4BA,IAAM,IAAS;AAiBf,SAAgB,EAAoB,GAAkB;CAClD,IAAM,IAAO,KAAK,UAAU,CAAK,GAC3B,IAAQ,EAAS,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI,CAAC;CACrD,OAAO,GAAG,IAAS,EAAc,CAAK;AAC1C;AAcA,SAAgB,EAAwB,GAAgB;CACpD,IAAI,CAAC,EAAI,WAAW,CAAM,GAAG,OAAO,KAAK,MAAM,CAAG;CAClD,IAAM,IAAQ,EAAW,EAAc,EAAI,MAAM,CAAa,CAAC,CAAC;CAChE,OAAO,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC;AACrD;AASA,IAAa,IAAuC;CAChD,WAAW;CACX,aAAa;AACjB,GAea,IAAiC,EAAkB,CAAsB"}
@@ -1,2 +1,2 @@
1
- var e={get(e,t){if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return n===null?t:JSON.parse(n)}catch{return t}},set(e,t){if(!(typeof window>`u`))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},remove(e){if(!(typeof window>`u`))try{window.localStorage.removeItem(e)}catch{}}};exports.storage=e;
1
+ var e={serialize:e=>JSON.stringify(e),deserialize:e=>JSON.parse(e)};function t(e,t){try{return e.serialize(t)}catch{try{return JSON.stringify(t)}catch{return null}}}function n(n=e){return{get(e,t){if(typeof window>`u`)return t;try{let r=window.localStorage.getItem(e);return r===null?t:n.deserialize(r)}catch{return t}},set(e,r){if(typeof window>`u`)return;let i=t(n,r);if(i!==null)try{window.localStorage.setItem(e,i)}catch{}},remove(e){if(!(typeof window>`u`))try{window.localStorage.removeItem(e)}catch{}}}}var r=n();exports.createJsonStorage=n,exports.storage=r;
2
2
  //# sourceMappingURL=storage.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.cjs","names":[],"sources":["../../src/utils/storage.ts"],"sourcesContent":["/**\n * Typed wrapper around `localStorage` that JSON-encodes values and\n * silently handles environments where storage is unavailable (SSR, private mode).\n *\n * @tempest-limits empty-catch — every method here is best-effort by contract:\n * `localStorage` throws on quota exhaustion, in Safari private mode, and when a\n * cross-origin frame has storage blocked. A caller persisting a preference has no\n * recovery to run and no user-facing message to show, so the write is dropped and\n * the app keeps the value in memory for the session.\n */\nexport const storage = {\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : (JSON.parse(raw) as T);\n } catch {\n return fallback;\n }\n },\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* empty */\n }\n },\n remove(key: string): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(key);\n } catch {\n /* empty */\n }\n },\n};\n"],"mappings":"AAUA,IAAa,EAAU,CACnB,IAAO,EAAa,EAAgB,CAChC,GAAI,OAAO,OAAW,IAAa,OAAO,EAC1C,GAAI,CACA,IAAM,EAAM,OAAO,aAAa,QAAQ,CAAG,EAC3C,OAAO,IAAQ,KAAO,EAAY,KAAK,MAAM,CAAG,CACpD,MAAQ,CACJ,OAAO,CACX,CACJ,EACA,IAAO,EAAa,EAAgB,CAC5B,YAAO,OAAW,KACtB,GAAI,CACA,OAAO,aAAa,QAAQ,EAAK,KAAK,UAAU,CAAK,CAAC,CAC1D,MAAQ,CAER,CACJ,EACA,OAAO,EAAmB,CAClB,YAAO,OAAW,KACtB,GAAI,CACA,OAAO,aAAa,WAAW,CAAG,CACtC,MAAQ,CAER,CACJ,CACJ"}
1
+ {"version":3,"file":"storage.cjs","names":[],"sources":["../../src/utils/storage.ts"],"sourcesContent":["/** How a {@link createJsonStorage} store turns values into text and back. */\nexport interface StorageCodec {\n /** Encode a value for storage. */\n serialize: <T>(value: T) => string;\n /** Decode a stored string. */\n deserialize: <T>(raw: string) => T;\n}\n\n/** The surface every store built by {@link createJsonStorage} exposes. */\nexport interface JsonStorage {\n /**\n * Read and decode a key.\n *\n * @typeParam T - The expected value shape.\n * @param key - Storage key.\n * @param fallback - Returned when the key is absent, unreadable, or corrupt.\n * @returns The stored value, or `fallback`.\n */\n get<T>(key: string, fallback: T): T;\n /**\n * Encode and write a key.\n *\n * @typeParam T - The value being stored.\n * @param key - Storage key.\n * @param value - Any value the codec can represent.\n */\n set<T>(key: string, value: T): void;\n /**\n * Delete a key.\n *\n * @param key - Storage key.\n */\n remove(key: string): void;\n}\n\nconst jsonCodec: StorageCodec = {\n serialize: (value) => JSON.stringify(value),\n deserialize: (raw) => JSON.parse(raw),\n};\n\n/**\n * Encode with the codec, degrading to plain JSON when the codec itself fails.\n *\n * A codec that throws — a compressor running out of room on a huge value —\n * should cost size, not the record: a slightly larger row still loads, an absent\n * one does not. `null` means not even JSON could represent the value, which is\n * the one case where dropping the write is the only option left.\n *\n * @param codec - The store's codec.\n * @param value - The value to encode.\n * @returns The encoded string, or `null` when the value cannot be represented.\n */\nfunction encode<T>(codec: StorageCodec, value: T): string | null {\n try {\n return codec.serialize(value);\n } catch {\n try {\n return JSON.stringify(value);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Build a typed `localStorage` wrapper around a codec.\n *\n * One implementation behind every store the SDK ships, so they cannot drift in\n * surface. {@link storage} and {@link compressedStorage} are both this function —\n * before it, the compressed one was a hand-written copy of the same guards and\n * had no `remove`, while its own docstring promised the two were interchangeable\n * at the call site. They were not, and the promise failed exactly where somebody\n * followed it.\n *\n * @example\n * const session = createJsonStorage();\n * session.set(\"draft\", { title: \"Sem título\" });\n *\n * @example\n * const packed = createJsonStorage(compressedStorageCodec);\n *\n * @param codec - Encoder pair. Defaults to plain JSON.\n * @returns A store with `get` / `set` / `remove`.\n *\n * @tempest-limits empty-catch — every method is best-effort by contract:\n * `localStorage` throws on quota exhaustion, in Safari private mode, and when a\n * cross-origin frame has storage blocked. A caller persisting a preference has no\n * recovery to run and no user-facing message to show, so the write is dropped and\n * the app keeps the value in memory for the session.\n */\nexport function createJsonStorage(codec: StorageCodec = jsonCodec): JsonStorage {\n return {\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : codec.deserialize<T>(raw);\n } catch {\n return fallback;\n }\n },\n\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n const encoded = encode(codec, value);\n if (encoded === null) return;\n try {\n window.localStorage.setItem(key, encoded);\n } catch {\n /* empty */\n }\n },\n\n remove(key: string): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(key);\n } catch {\n /* empty */\n }\n },\n };\n}\n\n/**\n * Typed wrapper around `localStorage` that JSON-encodes values and silently\n * handles environments where storage is unavailable (SSR, private mode).\n */\nexport const storage: JsonStorage = createJsonStorage();\n"],"mappings":"AAmCA,IAAM,EAA0B,CAC5B,UAAY,GAAU,KAAK,UAAU,CAAK,EAC1C,YAAc,GAAQ,KAAK,MAAM,CAAG,CACxC,EAcA,SAAS,EAAU,EAAqB,EAAyB,CAC7D,GAAI,CACA,OAAO,EAAM,UAAU,CAAK,CAChC,MAAQ,CACJ,GAAI,CACA,OAAO,KAAK,UAAU,CAAK,CAC/B,MAAQ,CACJ,OAAO,IACX,CACJ,CACJ,CA4BA,SAAgB,EAAkB,EAAsB,EAAwB,CAC5E,MAAO,CACH,IAAO,EAAa,EAAgB,CAChC,GAAI,OAAO,OAAW,IAAa,OAAO,EAC1C,GAAI,CACA,IAAM,EAAM,OAAO,aAAa,QAAQ,CAAG,EAC3C,OAAO,IAAQ,KAAO,EAAW,EAAM,YAAe,CAAG,CAC7D,MAAQ,CACJ,OAAO,CACX,CACJ,EAEA,IAAO,EAAa,EAAgB,CAChC,GAAI,OAAO,OAAW,IAAa,OACnC,IAAM,EAAU,EAAO,EAAO,CAAK,EAC/B,OAAY,KAChB,GAAI,CACA,OAAO,aAAa,QAAQ,EAAK,CAAO,CAC5C,MAAQ,CAER,CACJ,EAEA,OAAO,EAAmB,CAClB,YAAO,OAAW,KACtB,GAAI,CACA,OAAO,aAAa,WAAW,CAAG,CACtC,MAAQ,CAER,CACJ,CACJ,CACJ,CAMA,IAAa,EAAuB,EAAkB"}
@@ -1,26 +1,46 @@
1
1
  //#region src/utils/storage.ts
2
2
  var e = {
3
- get(e, t) {
4
- if (typeof window > "u") return t;
3
+ serialize: (e) => JSON.stringify(e),
4
+ deserialize: (e) => JSON.parse(e)
5
+ };
6
+ function t(e, t) {
7
+ try {
8
+ return e.serialize(t);
9
+ } catch {
5
10
  try {
6
- let n = window.localStorage.getItem(e);
7
- return n === null ? t : JSON.parse(n);
11
+ return JSON.stringify(t);
8
12
  } catch {
9
- return t;
13
+ return null;
10
14
  }
11
- },
12
- set(e, t) {
13
- if (!(typeof window > "u")) try {
14
- window.localStorage.setItem(e, JSON.stringify(t));
15
- } catch {}
16
- },
17
- remove(e) {
18
- if (!(typeof window > "u")) try {
19
- window.localStorage.removeItem(e);
20
- } catch {}
21
15
  }
22
- };
16
+ }
17
+ function n(n = e) {
18
+ return {
19
+ get(e, t) {
20
+ if (typeof window > "u") return t;
21
+ try {
22
+ let r = window.localStorage.getItem(e);
23
+ return r === null ? t : n.deserialize(r);
24
+ } catch {
25
+ return t;
26
+ }
27
+ },
28
+ set(e, r) {
29
+ if (typeof window > "u") return;
30
+ let i = t(n, r);
31
+ if (i !== null) try {
32
+ window.localStorage.setItem(e, i);
33
+ } catch {}
34
+ },
35
+ remove(e) {
36
+ if (!(typeof window > "u")) try {
37
+ window.localStorage.removeItem(e);
38
+ } catch {}
39
+ }
40
+ };
41
+ }
42
+ var r = n();
23
43
  //#endregion
24
- export { e as storage };
44
+ export { n as createJsonStorage, r as storage };
25
45
 
26
46
  //# sourceMappingURL=storage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","names":[],"sources":["../../src/utils/storage.ts"],"sourcesContent":["/**\n * Typed wrapper around `localStorage` that JSON-encodes values and\n * silently handles environments where storage is unavailable (SSR, private mode).\n *\n * @tempest-limits empty-catch — every method here is best-effort by contract:\n * `localStorage` throws on quota exhaustion, in Safari private mode, and when a\n * cross-origin frame has storage blocked. A caller persisting a preference has no\n * recovery to run and no user-facing message to show, so the write is dropped and\n * the app keeps the value in memory for the session.\n */\nexport const storage = {\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : (JSON.parse(raw) as T);\n } catch {\n return fallback;\n }\n },\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, JSON.stringify(value));\n } catch {\n /* empty */\n }\n },\n remove(key: string): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(key);\n } catch {\n /* empty */\n }\n },\n};\n"],"mappings":";AAUA,IAAa,IAAU;CACnB,IAAO,GAAa,GAAgB;EAChC,IAAI,OAAO,SAAW,KAAa,OAAO;EAC1C,IAAI;GACA,IAAM,IAAM,OAAO,aAAa,QAAQ,CAAG;GAC3C,OAAO,MAAQ,OAAO,IAAY,KAAK,MAAM,CAAG;EACpD,QAAQ;GACJ,OAAO;EACX;CACJ;CACA,IAAO,GAAa,GAAgB;EAC5B,aAAO,SAAW,MACtB,IAAI;GACA,OAAO,aAAa,QAAQ,GAAK,KAAK,UAAU,CAAK,CAAC;EAC1D,QAAQ,CAER;CACJ;CACA,OAAO,GAAmB;EAClB,aAAO,SAAW,MACtB,IAAI;GACA,OAAO,aAAa,WAAW,CAAG;EACtC,QAAQ,CAER;CACJ;AACJ"}
1
+ {"version":3,"file":"storage.js","names":[],"sources":["../../src/utils/storage.ts"],"sourcesContent":["/** How a {@link createJsonStorage} store turns values into text and back. */\nexport interface StorageCodec {\n /** Encode a value for storage. */\n serialize: <T>(value: T) => string;\n /** Decode a stored string. */\n deserialize: <T>(raw: string) => T;\n}\n\n/** The surface every store built by {@link createJsonStorage} exposes. */\nexport interface JsonStorage {\n /**\n * Read and decode a key.\n *\n * @typeParam T - The expected value shape.\n * @param key - Storage key.\n * @param fallback - Returned when the key is absent, unreadable, or corrupt.\n * @returns The stored value, or `fallback`.\n */\n get<T>(key: string, fallback: T): T;\n /**\n * Encode and write a key.\n *\n * @typeParam T - The value being stored.\n * @param key - Storage key.\n * @param value - Any value the codec can represent.\n */\n set<T>(key: string, value: T): void;\n /**\n * Delete a key.\n *\n * @param key - Storage key.\n */\n remove(key: string): void;\n}\n\nconst jsonCodec: StorageCodec = {\n serialize: (value) => JSON.stringify(value),\n deserialize: (raw) => JSON.parse(raw),\n};\n\n/**\n * Encode with the codec, degrading to plain JSON when the codec itself fails.\n *\n * A codec that throws — a compressor running out of room on a huge value —\n * should cost size, not the record: a slightly larger row still loads, an absent\n * one does not. `null` means not even JSON could represent the value, which is\n * the one case where dropping the write is the only option left.\n *\n * @param codec - The store's codec.\n * @param value - The value to encode.\n * @returns The encoded string, or `null` when the value cannot be represented.\n */\nfunction encode<T>(codec: StorageCodec, value: T): string | null {\n try {\n return codec.serialize(value);\n } catch {\n try {\n return JSON.stringify(value);\n } catch {\n return null;\n }\n }\n}\n\n/**\n * Build a typed `localStorage` wrapper around a codec.\n *\n * One implementation behind every store the SDK ships, so they cannot drift in\n * surface. {@link storage} and {@link compressedStorage} are both this function —\n * before it, the compressed one was a hand-written copy of the same guards and\n * had no `remove`, while its own docstring promised the two were interchangeable\n * at the call site. They were not, and the promise failed exactly where somebody\n * followed it.\n *\n * @example\n * const session = createJsonStorage();\n * session.set(\"draft\", { title: \"Sem título\" });\n *\n * @example\n * const packed = createJsonStorage(compressedStorageCodec);\n *\n * @param codec - Encoder pair. Defaults to plain JSON.\n * @returns A store with `get` / `set` / `remove`.\n *\n * @tempest-limits empty-catch — every method is best-effort by contract:\n * `localStorage` throws on quota exhaustion, in Safari private mode, and when a\n * cross-origin frame has storage blocked. A caller persisting a preference has no\n * recovery to run and no user-facing message to show, so the write is dropped and\n * the app keeps the value in memory for the session.\n */\nexport function createJsonStorage(codec: StorageCodec = jsonCodec): JsonStorage {\n return {\n get<T>(key: string, fallback: T): T {\n if (typeof window === \"undefined\") return fallback;\n try {\n const raw = window.localStorage.getItem(key);\n return raw === null ? fallback : codec.deserialize<T>(raw);\n } catch {\n return fallback;\n }\n },\n\n set<T>(key: string, value: T): void {\n if (typeof window === \"undefined\") return;\n const encoded = encode(codec, value);\n if (encoded === null) return;\n try {\n window.localStorage.setItem(key, encoded);\n } catch {\n /* empty */\n }\n },\n\n remove(key: string): void {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.removeItem(key);\n } catch {\n /* empty */\n }\n },\n };\n}\n\n/**\n * Typed wrapper around `localStorage` that JSON-encodes values and silently\n * handles environments where storage is unavailable (SSR, private mode).\n */\nexport const storage: JsonStorage = createJsonStorage();\n"],"mappings":";AAmCA,IAAM,IAA0B;CAC5B,YAAY,MAAU,KAAK,UAAU,CAAK;CAC1C,cAAc,MAAQ,KAAK,MAAM,CAAG;AACxC;AAcA,SAAS,EAAU,GAAqB,GAAyB;CAC7D,IAAI;EACA,OAAO,EAAM,UAAU,CAAK;CAChC,QAAQ;EACJ,IAAI;GACA,OAAO,KAAK,UAAU,CAAK;EAC/B,QAAQ;GACJ,OAAO;EACX;CACJ;AACJ;AA4BA,SAAgB,EAAkB,IAAsB,GAAwB;CAC5E,OAAO;EACH,IAAO,GAAa,GAAgB;GAChC,IAAI,OAAO,SAAW,KAAa,OAAO;GAC1C,IAAI;IACA,IAAM,IAAM,OAAO,aAAa,QAAQ,CAAG;IAC3C,OAAO,MAAQ,OAAO,IAAW,EAAM,YAAe,CAAG;GAC7D,QAAQ;IACJ,OAAO;GACX;EACJ;EAEA,IAAO,GAAa,GAAgB;GAChC,IAAI,OAAO,SAAW,KAAa;GACnC,IAAM,IAAU,EAAO,GAAO,CAAK;GAC/B,UAAY,MAChB,IAAI;IACA,OAAO,aAAa,QAAQ,GAAK,CAAO;GAC5C,QAAQ,CAER;EACJ;EAEA,OAAO,GAAmB;GAClB,aAAO,SAAW,MACtB,IAAI;IACA,OAAO,aAAa,WAAW,CAAG;GACtC,QAAQ,CAER;EACJ;CACJ;AACJ;AAMA,IAAa,IAAuB,EAAkB"}
@@ -1,2 +1,2 @@
1
- const e=require("../audio/media-access.cjs");let t=require("react");var n={video:{facingMode:{ideal:`environment`},width:{ideal:1920},height:{ideal:1080}},audio:!1};function r({kind:e,message:t}){return{kind:e===`not-found`?`no-camera`:e,message:t}}function i(t){return r(e.classifyMediaError(t,`camera`))}function a(a={}){let[o,s]=(0,t.useState)(`loading`),[c,l]=(0,t.useState)(null),[u,d]=(0,t.useState)(null),[f,p]=(0,t.useState)(0),m=(0,t.useRef)(null),h=(0,t.useRef)(a.constraints??n);(0,t.useEffect)(()=>{h.current=a.constraints??n},[a.constraints]);let g=a.enabled??!0;return(0,t.useEffect)(()=>{let t=!1,n=null,a=null;async function o(){if(!g){s(`idle`),l(null);return}if(s(`loading`),l(null),typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`){t||(l(r(e.missingCaptureApiError(`camera`))),s(`error`));return}try{if(n=await navigator.mediaDevices.getUserMedia(h.current),t){n.getTracks().forEach(e=>e.stop());return}let e=m.current;if(!e){n.getTracks().forEach(e=>e.stop());return}a=e,e.srcObject=n,d(n),await e.play().catch(()=>void 0),t||s(`ready`)}catch(e){t||(l(i(e)),s(`error`))}}return o(),()=>{t=!0,n&&n.getTracks().forEach(e=>e.stop()),a&&(a.srcObject=null),d(null)}},[f,g]),{status:o,error:c,videoRef:m,stream:u,retry:()=>p(e=>e+1)}}exports.useCameraStream=a;
1
+ const e=require("../hooks/use-latest-ref.cjs"),t=require("../audio/media-access.cjs");let n=require("react");var r={video:{facingMode:{ideal:`environment`},width:{ideal:1920},height:{ideal:1080}},audio:!1};function i({kind:e,message:t}){return{kind:e===`not-found`?`no-camera`:e,message:t}}function a(e){return i(t.classifyMediaError(e,`camera`))}function o(o={}){let[s,c]=(0,n.useState)(`loading`),[l,u]=(0,n.useState)(null),[d,f]=(0,n.useState)(null),[p,m]=(0,n.useState)(0),h=(0,n.useRef)(null),g=e.useLatestRef(o.constraints??r),_=o.enabled??!0;return(0,n.useEffect)(()=>{let e=!1,n=null,r=null;async function o(){if(!_){c(`idle`),u(null);return}if(c(`loading`),u(null),typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`){e||(u(i(t.missingCaptureApiError(`camera`))),c(`error`));return}try{if(n=await navigator.mediaDevices.getUserMedia(g.current),e){n.getTracks().forEach(e=>e.stop());return}let t=h.current;if(!t){n.getTracks().forEach(e=>e.stop());return}r=t,t.srcObject=n,f(n),await t.play().catch(()=>void 0),e||c(`ready`)}catch(t){e||(u(a(t)),c(`error`))}}return o(),()=>{e=!0,n&&n.getTracks().forEach(e=>e.stop()),r&&(r.srcObject=null),f(null)}},[p,_,g]),{status:s,error:l,videoRef:h,stream:d,retry:()=>m(e=>e+1)}}exports.useCameraStream=o;
2
2
  //# sourceMappingURL=use-camera-stream.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-camera-stream.cjs","names":[],"sources":["../../src/vision/use-camera-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState, type RefObject } from \"react\";\n\nimport {\n classifyMediaError,\n missingCaptureApiError,\n type MediaAccessError,\n} from \"@/audio/media-access\";\n\n/** Lifecycle status of the camera stream. */\nexport type CameraStreamStatus = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\n/** Classified reason a camera stream could not be acquired. */\nexport type CameraStreamErrorKind =\n \"unsupported\" | \"permission-denied\" | \"no-camera\" | \"in-use\" | \"insecure\" | \"unknown\";\n\n/** A classified camera error with a human-readable, English message. */\nexport interface CameraStreamError {\n kind: CameraStreamErrorKind;\n message: string;\n}\n\n/** Options for {@link useCameraStream}. */\nexport interface UseCameraStreamOptions {\n /**\n * Constraints passed to `getUserMedia`. Defaults to the rear\n * (\"environment\") camera at Full-HD ideal resolution with audio off.\n * Read when the stream (re)starts — change it and call `retry()` to apply.\n */\n constraints?: MediaStreamConstraints;\n /**\n * Hold off acquiring the camera until this is `true`. Default `true`.\n *\n * The point is to be able to *not* prompt. A permission prompt costs the user a\n * decision and, if they refuse, costs the app the feature permanently — so a\n * surface that already knows it cannot do its job (a barcode scanner in a browser\n * with no decoder) must not open the camera to then say so. Flipping this to `false`\n * also releases a stream that is already live.\n */\n enabled?: boolean;\n}\n\n/** Value returned by {@link useCameraStream}. */\nexport interface UseCameraStreamApi {\n /** Current lifecycle status. */\n status: CameraStreamStatus;\n /** The classified error, or `null` while not in the `error` status. */\n error: CameraStreamError | null;\n /** Attach to a `<video ref={…} />`. The stream is wired to it once ready. */\n videoRef: RefObject<HTMLVideoElement | null>;\n /**\n * The live stream, or `null`.\n *\n * Exposed for the things that need the **track** rather than the picture — the LED\n * torch (`useTorch`), the real frame size from `getSettings()`, recording it with\n * `useVideoRecorder`. Do not stop it yourself: the hook owns its lifetime and\n * releases it on unmount and on `retry()`.\n */\n stream: MediaStream | null;\n /** Manually re-attempt after an error (e.g. the user changed permissions). */\n retry: () => void;\n}\n\n/** Rear-camera Full-HD defaults used when no `constraints` are supplied. */\nconst DEFAULT_CONSTRAINTS: MediaStreamConstraints = {\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n audio: false,\n};\n\n/**\n * Re-label a {@link MediaAccessError} as a {@link CameraStreamError}.\n *\n * The classification itself lives in one place for the whole SDK\n * (`classifyMediaError`), so a microphone and a camera failure are never explained\n * two different ways. Only the name of one kind differs: this surface shipped\n * `\"no-camera\"` where the shared taxonomy says `\"not-found\"`, and renaming a\n * published union member would break every consumer switching on it.\n *\n * @param error - The shared classification.\n * @returns The same error under this module's kind names.\n */\nfunction toCameraError({ kind, message }: MediaAccessError): CameraStreamError {\n return { kind: kind === \"not-found\" ? \"no-camera\" : kind, message };\n}\n\n/**\n * Map an unknown `getUserMedia` failure into a {@link CameraStreamError}. Secure-context\n * and environment checks run first (they are the reason `getUserMedia` is missing or\n * rejects), then the `DOMException.name` is mapped to a stable `kind`.\n */\nfunction classifyError(err: unknown): CameraStreamError {\n return toCameraError(classifyMediaError(err, \"camera\"));\n}\n\n/**\n * Acquire a `MediaStream` via `getUserMedia`, attach it to a `<video>` element,\n * and expose status/error so the page can render permission and error states.\n * The stream is automatically released on unmount or retry.\n *\n * Defaults to the rear (\"environment\") camera; desktops fall back to whatever\n * single camera they expose. Pass `options.constraints` to override, or\n * `options.enabled: false` to render the surface without prompting for the camera\n * at all.\n *\n * Implementation notes:\n * - Cleanup detaches the stream from a *snapshotted* video node, so it releases\n * the same element it attached to even if the page remounts the `<video>`.\n * - When `getUserMedia` is missing, an insecure context is the usual cause, so\n * the hook prefers that (actionable) error; otherwise it reports `unsupported`.\n * - `video.play()` rejections are swallowed: autoplay may be blocked, but the\n * user gesture that opened the camera usually counts and playback resumes on\n * the next interaction.\n *\n * @param options - optional configuration (see {@link UseCameraStreamOptions}).\n * @returns The stream status, classified error, a `videoRef` to attach, the live\n * `stream` for whatever needs the track itself, and a `retry()` to re-attempt\n * acquisition.\n */\nexport function useCameraStream(options: UseCameraStreamOptions = {}): UseCameraStreamApi {\n const [status, setStatus] = useState<CameraStreamStatus>(\"loading\");\n const [error, setError] = useState<CameraStreamError | null>(null);\n const [live, setLive] = useState<MediaStream | null>(null);\n const [retryToken, setRetryToken] = useState(0);\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const constraintsRef = useRef<MediaStreamConstraints>(\n options.constraints ?? DEFAULT_CONSTRAINTS,\n );\n useEffect(() => {\n constraintsRef.current = options.constraints ?? DEFAULT_CONSTRAINTS;\n }, [options.constraints]);\n\n const enabled = options.enabled ?? true;\n\n useEffect(() => {\n let cancelled = false;\n let stream: MediaStream | null = null;\n let attachedVideo: HTMLVideoElement | null = null;\n\n async function start(): Promise<void> {\n if (!enabled) {\n setStatus(\"idle\");\n setError(null);\n return;\n }\n setStatus(\"loading\");\n setError(null);\n\n if (\n typeof navigator === \"undefined\" ||\n !navigator.mediaDevices ||\n typeof navigator.mediaDevices.getUserMedia !== \"function\"\n ) {\n if (!cancelled) {\n setError(toCameraError(missingCaptureApiError(\"camera\")));\n setStatus(\"error\");\n }\n return;\n }\n\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraintsRef.current);\n if (cancelled) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n const video = videoRef.current;\n if (!video) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n attachedVideo = video;\n video.srcObject = stream;\n setLive(stream);\n await video.play().catch(() => undefined);\n if (!cancelled) setStatus(\"ready\");\n } catch (err) {\n if (!cancelled) {\n setError(classifyError(err));\n setStatus(\"error\");\n }\n }\n }\n\n void start();\n\n return () => {\n cancelled = true;\n if (stream) {\n stream.getTracks().forEach((track) => track.stop());\n }\n if (attachedVideo) {\n attachedVideo.srcObject = null;\n }\n setLive(null);\n };\n }, [retryToken, enabled]);\n\n return {\n status,\n error,\n videoRef,\n stream: live,\n retry: () => setRetryToken((n) => n + 1),\n };\n}\n"],"mappings":"oEA+DA,IAAM,EAA8C,CAChD,MAAO,CACH,WAAY,CAAE,MAAO,aAAc,EACnC,MAAO,CAAE,MAAO,IAAK,EACrB,OAAQ,CAAE,MAAO,IAAK,CAC1B,EACA,MAAO,EACX,EAcA,SAAS,EAAc,CAAE,OAAM,WAAgD,CAC3E,MAAO,CAAE,KAAM,IAAS,YAAc,YAAc,EAAM,SAAQ,CACtE,CAOA,SAAS,EAAc,EAAiC,CACpD,OAAO,EAAc,EAAA,mBAAmB,EAAK,QAAQ,CAAC,CAC1D,CA0BA,SAAgB,EAAgB,EAAkC,CAAC,EAAuB,CACtF,GAAM,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAA6B,SAAS,EAC5D,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,CAAmC,IAAI,EAC3D,CAAC,EAAM,IAAA,EAAW,EAAA,SAAA,CAA6B,IAAI,EACnD,CAAC,EAAY,IAAA,EAAiB,EAAA,SAAA,CAAS,CAAC,EACxC,GAAA,EAAW,EAAA,OAAA,CAAgC,IAAI,EAC/C,GAAA,EAAiB,EAAA,OAAA,CACnB,EAAQ,aAAe,CAC3B,GACA,EAAA,EAAA,UAAA,KAAgB,CACZ,EAAe,QAAU,EAAQ,aAAe,CACpD,EAAG,CAAC,EAAQ,WAAW,CAAC,EAExB,IAAM,EAAU,EAAQ,SAAW,GAkEnC,OAhEA,EAAA,EAAA,UAAA,KAAgB,CACZ,IAAI,EAAY,GACZ,EAA6B,KAC7B,EAAyC,KAE7C,eAAe,GAAuB,CAClC,GAAI,CAAC,EAAS,CACV,EAAU,MAAM,EAChB,EAAS,IAAI,EACb,MACJ,CAIA,GAHA,EAAU,SAAS,EACnB,EAAS,IAAI,EAGT,OAAO,UAAc,KACrB,CAAC,UAAU,cACX,OAAO,UAAU,aAAa,cAAiB,WACjD,CACO,IACD,EAAS,EAAc,EAAA,uBAAuB,QAAQ,CAAC,CAAC,EACxD,EAAU,OAAO,GAErB,MACJ,CAEA,GAAI,CAEA,GADA,EAAS,MAAM,UAAU,aAAa,aAAa,EAAe,OAAO,EACrE,EAAW,CACX,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAClD,MACJ,CACA,IAAM,EAAQ,EAAS,QACvB,GAAI,CAAC,EAAO,CACR,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAClD,MACJ,CACA,EAAgB,EAChB,EAAM,UAAY,EAClB,EAAQ,CAAM,EACd,MAAM,EAAM,KAAK,CAAC,CAAC,UAAY,IAAA,EAAS,EACnC,GAAW,EAAU,OAAO,CACrC,OAAS,EAAK,CACL,IACD,EAAS,EAAc,CAAG,CAAC,EAC3B,EAAU,OAAO,EAEzB,CACJ,CAIA,OAFA,EAAW,MAEE,CACT,EAAY,GACR,GACA,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAElD,IACA,EAAc,UAAY,MAE9B,EAAQ,IAAI,CAChB,CACJ,EAAG,CAAC,EAAY,CAAO,CAAC,EAEjB,CACH,SACA,QACA,WACA,OAAQ,EACR,UAAa,EAAe,GAAM,EAAI,CAAC,CAC3C,CACJ"}
1
+ {"version":3,"file":"use-camera-stream.cjs","names":[],"sources":["../../src/vision/use-camera-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState, type RefObject } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\n\nimport {\n classifyMediaError,\n missingCaptureApiError,\n type MediaAccessError,\n} from \"@/audio/media-access\";\n\n/** Lifecycle status of the camera stream. */\nexport type CameraStreamStatus = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\n/** Classified reason a camera stream could not be acquired. */\nexport type CameraStreamErrorKind =\n \"unsupported\" | \"permission-denied\" | \"no-camera\" | \"in-use\" | \"insecure\" | \"unknown\";\n\n/** A classified camera error with a human-readable, English message. */\nexport interface CameraStreamError {\n kind: CameraStreamErrorKind;\n message: string;\n}\n\n/** Options for {@link useCameraStream}. */\nexport interface UseCameraStreamOptions {\n /**\n * Constraints passed to `getUserMedia`. Defaults to the rear\n * (\"environment\") camera at Full-HD ideal resolution with audio off.\n * Read when the stream (re)starts — change it and call `retry()` to apply.\n */\n constraints?: MediaStreamConstraints;\n /**\n * Hold off acquiring the camera until this is `true`. Default `true`.\n *\n * The point is to be able to *not* prompt. A permission prompt costs the user a\n * decision and, if they refuse, costs the app the feature permanently — so a\n * surface that already knows it cannot do its job (a barcode scanner in a browser\n * with no decoder) must not open the camera to then say so. Flipping this to `false`\n * also releases a stream that is already live.\n */\n enabled?: boolean;\n}\n\n/** Value returned by {@link useCameraStream}. */\nexport interface UseCameraStreamApi {\n /** Current lifecycle status. */\n status: CameraStreamStatus;\n /** The classified error, or `null` while not in the `error` status. */\n error: CameraStreamError | null;\n /** Attach to a `<video ref={…} />`. The stream is wired to it once ready. */\n videoRef: RefObject<HTMLVideoElement | null>;\n /**\n * The live stream, or `null`.\n *\n * Exposed for the things that need the **track** rather than the picture — the LED\n * torch (`useTorch`), the real frame size from `getSettings()`, recording it with\n * `useVideoRecorder`. Do not stop it yourself: the hook owns its lifetime and\n * releases it on unmount and on `retry()`.\n */\n stream: MediaStream | null;\n /** Manually re-attempt after an error (e.g. the user changed permissions). */\n retry: () => void;\n}\n\n/** Rear-camera Full-HD defaults used when no `constraints` are supplied. */\nconst DEFAULT_CONSTRAINTS: MediaStreamConstraints = {\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n audio: false,\n};\n\n/**\n * Re-label a {@link MediaAccessError} as a {@link CameraStreamError}.\n *\n * The classification itself lives in one place for the whole SDK\n * (`classifyMediaError`), so a microphone and a camera failure are never explained\n * two different ways. Only the name of one kind differs: this surface shipped\n * `\"no-camera\"` where the shared taxonomy says `\"not-found\"`, and renaming a\n * published union member would break every consumer switching on it.\n *\n * @param error - The shared classification.\n * @returns The same error under this module's kind names.\n */\nfunction toCameraError({ kind, message }: MediaAccessError): CameraStreamError {\n return { kind: kind === \"not-found\" ? \"no-camera\" : kind, message };\n}\n\n/**\n * Map an unknown `getUserMedia` failure into a {@link CameraStreamError}. Secure-context\n * and environment checks run first (they are the reason `getUserMedia` is missing or\n * rejects), then the `DOMException.name` is mapped to a stable `kind`.\n */\nfunction classifyError(err: unknown): CameraStreamError {\n return toCameraError(classifyMediaError(err, \"camera\"));\n}\n\n/**\n * Acquire a `MediaStream` via `getUserMedia`, attach it to a `<video>` element,\n * and expose status/error so the page can render permission and error states.\n * The stream is automatically released on unmount or retry.\n *\n * Defaults to the rear (\"environment\") camera; desktops fall back to whatever\n * single camera they expose. Pass `options.constraints` to override, or\n * `options.enabled: false` to render the surface without prompting for the camera\n * at all.\n *\n * Implementation notes:\n * - Cleanup detaches the stream from a *snapshotted* video node, so it releases\n * the same element it attached to even if the page remounts the `<video>`.\n * - When `getUserMedia` is missing, an insecure context is the usual cause, so\n * the hook prefers that (actionable) error; otherwise it reports `unsupported`.\n * - `video.play()` rejections are swallowed: autoplay may be blocked, but the\n * user gesture that opened the camera usually counts and playback resumes on\n * the next interaction.\n *\n * @param options - optional configuration (see {@link UseCameraStreamOptions}).\n * @returns The stream status, classified error, a `videoRef` to attach, the live\n * `stream` for whatever needs the track itself, and a `retry()` to re-attempt\n * acquisition.\n */\nexport function useCameraStream(options: UseCameraStreamOptions = {}): UseCameraStreamApi {\n const [status, setStatus] = useState<CameraStreamStatus>(\"loading\");\n const [error, setError] = useState<CameraStreamError | null>(null);\n const [live, setLive] = useState<MediaStream | null>(null);\n const [retryToken, setRetryToken] = useState(0);\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const constraintsRef = useLatestRef(options.constraints ?? DEFAULT_CONSTRAINTS);\n\n const enabled = options.enabled ?? true;\n\n useEffect(() => {\n let cancelled = false;\n let stream: MediaStream | null = null;\n let attachedVideo: HTMLVideoElement | null = null;\n\n async function start(): Promise<void> {\n if (!enabled) {\n setStatus(\"idle\");\n setError(null);\n return;\n }\n setStatus(\"loading\");\n setError(null);\n\n if (\n typeof navigator === \"undefined\" ||\n !navigator.mediaDevices ||\n typeof navigator.mediaDevices.getUserMedia !== \"function\"\n ) {\n if (!cancelled) {\n setError(toCameraError(missingCaptureApiError(\"camera\")));\n setStatus(\"error\");\n }\n return;\n }\n\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraintsRef.current);\n if (cancelled) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n const video = videoRef.current;\n if (!video) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n attachedVideo = video;\n video.srcObject = stream;\n setLive(stream);\n await video.play().catch(() => undefined);\n if (!cancelled) setStatus(\"ready\");\n } catch (err) {\n if (!cancelled) {\n setError(classifyError(err));\n setStatus(\"error\");\n }\n }\n }\n\n void start();\n\n return () => {\n cancelled = true;\n if (stream) {\n stream.getTracks().forEach((track) => track.stop());\n }\n if (attachedVideo) {\n attachedVideo.srcObject = null;\n }\n setLive(null);\n };\n }, [retryToken, enabled, constraintsRef]);\n\n return {\n status,\n error,\n videoRef,\n stream: live,\n retry: () => setRetryToken((n) => n + 1),\n };\n}\n"],"mappings":"6GAgEA,IAAM,EAA8C,CAChD,MAAO,CACH,WAAY,CAAE,MAAO,aAAc,EACnC,MAAO,CAAE,MAAO,IAAK,EACrB,OAAQ,CAAE,MAAO,IAAK,CAC1B,EACA,MAAO,EACX,EAcA,SAAS,EAAc,CAAE,OAAM,WAAgD,CAC3E,MAAO,CAAE,KAAM,IAAS,YAAc,YAAc,EAAM,SAAQ,CACtE,CAOA,SAAS,EAAc,EAAiC,CACpD,OAAO,EAAc,EAAA,mBAAmB,EAAK,QAAQ,CAAC,CAC1D,CA0BA,SAAgB,EAAgB,EAAkC,CAAC,EAAuB,CACtF,GAAM,CAAC,EAAQ,IAAA,EAAa,EAAA,SAAA,CAA6B,SAAS,EAC5D,CAAC,EAAO,IAAA,EAAY,EAAA,SAAA,CAAmC,IAAI,EAC3D,CAAC,EAAM,IAAA,EAAW,EAAA,SAAA,CAA6B,IAAI,EACnD,CAAC,EAAY,IAAA,EAAiB,EAAA,SAAA,CAAS,CAAC,EACxC,GAAA,EAAW,EAAA,OAAA,CAAgC,IAAI,EAC/C,EAAiB,EAAA,aAAa,EAAQ,aAAe,CAAmB,EAExE,EAAU,EAAQ,SAAW,GAkEnC,OAhEA,EAAA,EAAA,UAAA,KAAgB,CACZ,IAAI,EAAY,GACZ,EAA6B,KAC7B,EAAyC,KAE7C,eAAe,GAAuB,CAClC,GAAI,CAAC,EAAS,CACV,EAAU,MAAM,EAChB,EAAS,IAAI,EACb,MACJ,CAIA,GAHA,EAAU,SAAS,EACnB,EAAS,IAAI,EAGT,OAAO,UAAc,KACrB,CAAC,UAAU,cACX,OAAO,UAAU,aAAa,cAAiB,WACjD,CACO,IACD,EAAS,EAAc,EAAA,uBAAuB,QAAQ,CAAC,CAAC,EACxD,EAAU,OAAO,GAErB,MACJ,CAEA,GAAI,CAEA,GADA,EAAS,MAAM,UAAU,aAAa,aAAa,EAAe,OAAO,EACrE,EAAW,CACX,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAClD,MACJ,CACA,IAAM,EAAQ,EAAS,QACvB,GAAI,CAAC,EAAO,CACR,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAClD,MACJ,CACA,EAAgB,EAChB,EAAM,UAAY,EAClB,EAAQ,CAAM,EACd,MAAM,EAAM,KAAK,CAAC,CAAC,UAAY,IAAA,EAAS,EACnC,GAAW,EAAU,OAAO,CACrC,OAAS,EAAK,CACL,IACD,EAAS,EAAc,CAAG,CAAC,EAC3B,EAAU,OAAO,EAEzB,CACJ,CAIA,OAFA,EAAW,MAEE,CACT,EAAY,GACR,GACA,EAAO,UAAU,CAAC,CAAC,QAAS,GAAU,EAAM,KAAK,CAAC,EAElD,IACA,EAAc,UAAY,MAE9B,EAAQ,IAAI,CAChB,CACJ,EAAG,CAAC,EAAY,EAAS,CAAc,CAAC,EAEjC,CACH,SACA,QACA,WACA,OAAQ,EACR,UAAa,EAAe,GAAM,EAAI,CAAC,CAC3C,CACJ"}
@@ -1,7 +1,8 @@
1
- import { classifyMediaError as e, missingCaptureApiError as t } from "../audio/media-access.js";
2
- import { useEffect as n, useRef as r, useState as i } from "react";
1
+ import { useLatestRef as e } from "../hooks/use-latest-ref.js";
2
+ import { classifyMediaError as t, missingCaptureApiError as n } from "../audio/media-access.js";
3
+ import { useEffect as r, useRef as i, useState as a } from "react";
3
4
  //#region src/vision/use-camera-stream.ts
4
- var a = {
5
+ var o = {
5
6
  video: {
6
7
  facingMode: { ideal: "environment" },
7
8
  width: { ideal: 1920 },
@@ -9,59 +10,59 @@ var a = {
9
10
  },
10
11
  audio: !1
11
12
  };
12
- function o({ kind: e, message: t }) {
13
+ function s({ kind: e, message: t }) {
13
14
  return {
14
15
  kind: e === "not-found" ? "no-camera" : e,
15
16
  message: t
16
17
  };
17
18
  }
18
- function s(t) {
19
- return o(e(t, "camera"));
19
+ function c(e) {
20
+ return s(t(e, "camera"));
20
21
  }
21
- function c(e = {}) {
22
- let [c, l] = i("loading"), [u, d] = i(null), [f, p] = i(null), [m, h] = i(0), g = r(null), _ = r(e.constraints ?? a);
23
- n(() => {
24
- _.current = e.constraints ?? a;
25
- }, [e.constraints]);
26
- let v = e.enabled ?? !0;
27
- return n(() => {
28
- let e = !1, n = null, r = null;
22
+ function l(t = {}) {
23
+ let [l, u] = a("loading"), [d, f] = a(null), [p, m] = a(null), [h, g] = a(0), _ = i(null), v = e(t.constraints ?? o), y = t.enabled ?? !0;
24
+ return r(() => {
25
+ let e = !1, t = null, r = null;
29
26
  async function i() {
30
- if (!v) {
31
- l("idle"), d(null);
27
+ if (!y) {
28
+ u("idle"), f(null);
32
29
  return;
33
30
  }
34
- if (l("loading"), d(null), typeof navigator > "u" || !navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
35
- e || (d(o(t("camera"))), l("error"));
31
+ if (u("loading"), f(null), typeof navigator > "u" || !navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia != "function") {
32
+ e || (f(s(n("camera"))), u("error"));
36
33
  return;
37
34
  }
38
35
  try {
39
- if (n = await navigator.mediaDevices.getUserMedia(_.current), e) {
40
- n.getTracks().forEach((e) => e.stop());
36
+ if (t = await navigator.mediaDevices.getUserMedia(v.current), e) {
37
+ t.getTracks().forEach((e) => e.stop());
41
38
  return;
42
39
  }
43
- let t = g.current;
44
- if (!t) {
45
- n.getTracks().forEach((e) => e.stop());
40
+ let n = _.current;
41
+ if (!n) {
42
+ t.getTracks().forEach((e) => e.stop());
46
43
  return;
47
44
  }
48
- r = t, t.srcObject = n, p(n), await t.play().catch(() => void 0), e || l("ready");
45
+ r = n, n.srcObject = t, m(t), await n.play().catch(() => void 0), e || u("ready");
49
46
  } catch (t) {
50
- e || (d(s(t)), l("error"));
47
+ e || (f(c(t)), u("error"));
51
48
  }
52
49
  }
53
50
  return i(), () => {
54
- e = !0, n && n.getTracks().forEach((e) => e.stop()), r && (r.srcObject = null), p(null);
51
+ e = !0, t && t.getTracks().forEach((e) => e.stop()), r && (r.srcObject = null), m(null);
55
52
  };
56
- }, [m, v]), {
57
- status: c,
58
- error: u,
59
- videoRef: g,
60
- stream: f,
61
- retry: () => h((e) => e + 1)
53
+ }, [
54
+ h,
55
+ y,
56
+ v
57
+ ]), {
58
+ status: l,
59
+ error: d,
60
+ videoRef: _,
61
+ stream: p,
62
+ retry: () => g((e) => e + 1)
62
63
  };
63
64
  }
64
65
  //#endregion
65
- export { c as useCameraStream };
66
+ export { l as useCameraStream };
66
67
 
67
68
  //# sourceMappingURL=use-camera-stream.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-camera-stream.js","names":[],"sources":["../../src/vision/use-camera-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState, type RefObject } from \"react\";\n\nimport {\n classifyMediaError,\n missingCaptureApiError,\n type MediaAccessError,\n} from \"@/audio/media-access\";\n\n/** Lifecycle status of the camera stream. */\nexport type CameraStreamStatus = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\n/** Classified reason a camera stream could not be acquired. */\nexport type CameraStreamErrorKind =\n \"unsupported\" | \"permission-denied\" | \"no-camera\" | \"in-use\" | \"insecure\" | \"unknown\";\n\n/** A classified camera error with a human-readable, English message. */\nexport interface CameraStreamError {\n kind: CameraStreamErrorKind;\n message: string;\n}\n\n/** Options for {@link useCameraStream}. */\nexport interface UseCameraStreamOptions {\n /**\n * Constraints passed to `getUserMedia`. Defaults to the rear\n * (\"environment\") camera at Full-HD ideal resolution with audio off.\n * Read when the stream (re)starts — change it and call `retry()` to apply.\n */\n constraints?: MediaStreamConstraints;\n /**\n * Hold off acquiring the camera until this is `true`. Default `true`.\n *\n * The point is to be able to *not* prompt. A permission prompt costs the user a\n * decision and, if they refuse, costs the app the feature permanently — so a\n * surface that already knows it cannot do its job (a barcode scanner in a browser\n * with no decoder) must not open the camera to then say so. Flipping this to `false`\n * also releases a stream that is already live.\n */\n enabled?: boolean;\n}\n\n/** Value returned by {@link useCameraStream}. */\nexport interface UseCameraStreamApi {\n /** Current lifecycle status. */\n status: CameraStreamStatus;\n /** The classified error, or `null` while not in the `error` status. */\n error: CameraStreamError | null;\n /** Attach to a `<video ref={…} />`. The stream is wired to it once ready. */\n videoRef: RefObject<HTMLVideoElement | null>;\n /**\n * The live stream, or `null`.\n *\n * Exposed for the things that need the **track** rather than the picture — the LED\n * torch (`useTorch`), the real frame size from `getSettings()`, recording it with\n * `useVideoRecorder`. Do not stop it yourself: the hook owns its lifetime and\n * releases it on unmount and on `retry()`.\n */\n stream: MediaStream | null;\n /** Manually re-attempt after an error (e.g. the user changed permissions). */\n retry: () => void;\n}\n\n/** Rear-camera Full-HD defaults used when no `constraints` are supplied. */\nconst DEFAULT_CONSTRAINTS: MediaStreamConstraints = {\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n audio: false,\n};\n\n/**\n * Re-label a {@link MediaAccessError} as a {@link CameraStreamError}.\n *\n * The classification itself lives in one place for the whole SDK\n * (`classifyMediaError`), so a microphone and a camera failure are never explained\n * two different ways. Only the name of one kind differs: this surface shipped\n * `\"no-camera\"` where the shared taxonomy says `\"not-found\"`, and renaming a\n * published union member would break every consumer switching on it.\n *\n * @param error - The shared classification.\n * @returns The same error under this module's kind names.\n */\nfunction toCameraError({ kind, message }: MediaAccessError): CameraStreamError {\n return { kind: kind === \"not-found\" ? \"no-camera\" : kind, message };\n}\n\n/**\n * Map an unknown `getUserMedia` failure into a {@link CameraStreamError}. Secure-context\n * and environment checks run first (they are the reason `getUserMedia` is missing or\n * rejects), then the `DOMException.name` is mapped to a stable `kind`.\n */\nfunction classifyError(err: unknown): CameraStreamError {\n return toCameraError(classifyMediaError(err, \"camera\"));\n}\n\n/**\n * Acquire a `MediaStream` via `getUserMedia`, attach it to a `<video>` element,\n * and expose status/error so the page can render permission and error states.\n * The stream is automatically released on unmount or retry.\n *\n * Defaults to the rear (\"environment\") camera; desktops fall back to whatever\n * single camera they expose. Pass `options.constraints` to override, or\n * `options.enabled: false` to render the surface without prompting for the camera\n * at all.\n *\n * Implementation notes:\n * - Cleanup detaches the stream from a *snapshotted* video node, so it releases\n * the same element it attached to even if the page remounts the `<video>`.\n * - When `getUserMedia` is missing, an insecure context is the usual cause, so\n * the hook prefers that (actionable) error; otherwise it reports `unsupported`.\n * - `video.play()` rejections are swallowed: autoplay may be blocked, but the\n * user gesture that opened the camera usually counts and playback resumes on\n * the next interaction.\n *\n * @param options - optional configuration (see {@link UseCameraStreamOptions}).\n * @returns The stream status, classified error, a `videoRef` to attach, the live\n * `stream` for whatever needs the track itself, and a `retry()` to re-attempt\n * acquisition.\n */\nexport function useCameraStream(options: UseCameraStreamOptions = {}): UseCameraStreamApi {\n const [status, setStatus] = useState<CameraStreamStatus>(\"loading\");\n const [error, setError] = useState<CameraStreamError | null>(null);\n const [live, setLive] = useState<MediaStream | null>(null);\n const [retryToken, setRetryToken] = useState(0);\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const constraintsRef = useRef<MediaStreamConstraints>(\n options.constraints ?? DEFAULT_CONSTRAINTS,\n );\n useEffect(() => {\n constraintsRef.current = options.constraints ?? DEFAULT_CONSTRAINTS;\n }, [options.constraints]);\n\n const enabled = options.enabled ?? true;\n\n useEffect(() => {\n let cancelled = false;\n let stream: MediaStream | null = null;\n let attachedVideo: HTMLVideoElement | null = null;\n\n async function start(): Promise<void> {\n if (!enabled) {\n setStatus(\"idle\");\n setError(null);\n return;\n }\n setStatus(\"loading\");\n setError(null);\n\n if (\n typeof navigator === \"undefined\" ||\n !navigator.mediaDevices ||\n typeof navigator.mediaDevices.getUserMedia !== \"function\"\n ) {\n if (!cancelled) {\n setError(toCameraError(missingCaptureApiError(\"camera\")));\n setStatus(\"error\");\n }\n return;\n }\n\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraintsRef.current);\n if (cancelled) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n const video = videoRef.current;\n if (!video) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n attachedVideo = video;\n video.srcObject = stream;\n setLive(stream);\n await video.play().catch(() => undefined);\n if (!cancelled) setStatus(\"ready\");\n } catch (err) {\n if (!cancelled) {\n setError(classifyError(err));\n setStatus(\"error\");\n }\n }\n }\n\n void start();\n\n return () => {\n cancelled = true;\n if (stream) {\n stream.getTracks().forEach((track) => track.stop());\n }\n if (attachedVideo) {\n attachedVideo.srcObject = null;\n }\n setLive(null);\n };\n }, [retryToken, enabled]);\n\n return {\n status,\n error,\n videoRef,\n stream: live,\n retry: () => setRetryToken((n) => n + 1),\n };\n}\n"],"mappings":";;;AA+DA,IAAM,IAA8C;CAChD,OAAO;EACH,YAAY,EAAE,OAAO,cAAc;EACnC,OAAO,EAAE,OAAO,KAAK;EACrB,QAAQ,EAAE,OAAO,KAAK;CAC1B;CACA,OAAO;AACX;AAcA,SAAS,EAAc,EAAE,SAAM,cAAgD;CAC3E,OAAO;EAAE,MAAM,MAAS,cAAc,cAAc;EAAM;CAAQ;AACtE;AAOA,SAAS,EAAc,GAAiC;CACpD,OAAO,EAAc,EAAmB,GAAK,QAAQ,CAAC;AAC1D;AA0BA,SAAgB,EAAgB,IAAkC,CAAC,GAAuB;CACtF,IAAM,CAAC,GAAQ,KAAa,EAA6B,SAAS,GAC5D,CAAC,GAAO,KAAY,EAAmC,IAAI,GAC3D,CAAC,GAAM,KAAW,EAA6B,IAAI,GACnD,CAAC,GAAY,KAAiB,EAAS,CAAC,GACxC,IAAW,EAAgC,IAAI,GAC/C,IAAiB,EACnB,EAAQ,eAAe,CAC3B;CACA,QAAgB;EACZ,EAAe,UAAU,EAAQ,eAAe;CACpD,GAAG,CAAC,EAAQ,WAAW,CAAC;CAExB,IAAM,IAAU,EAAQ,WAAW;CAkEnC,OAhEA,QAAgB;EACZ,IAAI,IAAY,IACZ,IAA6B,MAC7B,IAAyC;EAE7C,eAAe,IAAuB;GAClC,IAAI,CAAC,GAAS;IAEV,AADA,EAAU,MAAM,GAChB,EAAS,IAAI;IACb;GACJ;GAIA,IAHA,EAAU,SAAS,GACnB,EAAS,IAAI,GAGT,OAAO,YAAc,OACrB,CAAC,UAAU,gBACX,OAAO,UAAU,aAAa,gBAAiB,YACjD;IACE,AAAK,MACD,EAAS,EAAc,EAAuB,QAAQ,CAAC,CAAC,GACxD,EAAU,OAAO;IAErB;GACJ;GAEA,IAAI;IAEA,IADA,IAAS,MAAM,UAAU,aAAa,aAAa,EAAe,OAAO,GACrE,GAAW;KACX,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC;KAClD;IACJ;IACA,IAAM,IAAQ,EAAS;IACvB,IAAI,CAAC,GAAO;KACR,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC;KAClD;IACJ;IAKA,AAJA,IAAgB,GAChB,EAAM,YAAY,GAClB,EAAQ,CAAM,GACd,MAAM,EAAM,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS,GACnC,KAAW,EAAU,OAAO;GACrC,SAAS,GAAK;IACV,AAAK,MACD,EAAS,EAAc,CAAG,CAAC,GAC3B,EAAU,OAAO;GAEzB;EACJ;EAIA,OAFA,EAAW,SAEE;GAQT,AAPA,IAAY,IACR,KACA,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC,GAElD,MACA,EAAc,YAAY,OAE9B,EAAQ,IAAI;EAChB;CACJ,GAAG,CAAC,GAAY,CAAO,CAAC,GAEjB;EACH;EACA;EACA;EACA,QAAQ;EACR,aAAa,GAAe,MAAM,IAAI,CAAC;CAC3C;AACJ"}
1
+ {"version":3,"file":"use-camera-stream.js","names":[],"sources":["../../src/vision/use-camera-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState, type RefObject } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\n\nimport {\n classifyMediaError,\n missingCaptureApiError,\n type MediaAccessError,\n} from \"@/audio/media-access\";\n\n/** Lifecycle status of the camera stream. */\nexport type CameraStreamStatus = \"idle\" | \"loading\" | \"ready\" | \"error\";\n\n/** Classified reason a camera stream could not be acquired. */\nexport type CameraStreamErrorKind =\n \"unsupported\" | \"permission-denied\" | \"no-camera\" | \"in-use\" | \"insecure\" | \"unknown\";\n\n/** A classified camera error with a human-readable, English message. */\nexport interface CameraStreamError {\n kind: CameraStreamErrorKind;\n message: string;\n}\n\n/** Options for {@link useCameraStream}. */\nexport interface UseCameraStreamOptions {\n /**\n * Constraints passed to `getUserMedia`. Defaults to the rear\n * (\"environment\") camera at Full-HD ideal resolution with audio off.\n * Read when the stream (re)starts — change it and call `retry()` to apply.\n */\n constraints?: MediaStreamConstraints;\n /**\n * Hold off acquiring the camera until this is `true`. Default `true`.\n *\n * The point is to be able to *not* prompt. A permission prompt costs the user a\n * decision and, if they refuse, costs the app the feature permanently — so a\n * surface that already knows it cannot do its job (a barcode scanner in a browser\n * with no decoder) must not open the camera to then say so. Flipping this to `false`\n * also releases a stream that is already live.\n */\n enabled?: boolean;\n}\n\n/** Value returned by {@link useCameraStream}. */\nexport interface UseCameraStreamApi {\n /** Current lifecycle status. */\n status: CameraStreamStatus;\n /** The classified error, or `null` while not in the `error` status. */\n error: CameraStreamError | null;\n /** Attach to a `<video ref={…} />`. The stream is wired to it once ready. */\n videoRef: RefObject<HTMLVideoElement | null>;\n /**\n * The live stream, or `null`.\n *\n * Exposed for the things that need the **track** rather than the picture — the LED\n * torch (`useTorch`), the real frame size from `getSettings()`, recording it with\n * `useVideoRecorder`. Do not stop it yourself: the hook owns its lifetime and\n * releases it on unmount and on `retry()`.\n */\n stream: MediaStream | null;\n /** Manually re-attempt after an error (e.g. the user changed permissions). */\n retry: () => void;\n}\n\n/** Rear-camera Full-HD defaults used when no `constraints` are supplied. */\nconst DEFAULT_CONSTRAINTS: MediaStreamConstraints = {\n video: {\n facingMode: { ideal: \"environment\" },\n width: { ideal: 1920 },\n height: { ideal: 1080 },\n },\n audio: false,\n};\n\n/**\n * Re-label a {@link MediaAccessError} as a {@link CameraStreamError}.\n *\n * The classification itself lives in one place for the whole SDK\n * (`classifyMediaError`), so a microphone and a camera failure are never explained\n * two different ways. Only the name of one kind differs: this surface shipped\n * `\"no-camera\"` where the shared taxonomy says `\"not-found\"`, and renaming a\n * published union member would break every consumer switching on it.\n *\n * @param error - The shared classification.\n * @returns The same error under this module's kind names.\n */\nfunction toCameraError({ kind, message }: MediaAccessError): CameraStreamError {\n return { kind: kind === \"not-found\" ? \"no-camera\" : kind, message };\n}\n\n/**\n * Map an unknown `getUserMedia` failure into a {@link CameraStreamError}. Secure-context\n * and environment checks run first (they are the reason `getUserMedia` is missing or\n * rejects), then the `DOMException.name` is mapped to a stable `kind`.\n */\nfunction classifyError(err: unknown): CameraStreamError {\n return toCameraError(classifyMediaError(err, \"camera\"));\n}\n\n/**\n * Acquire a `MediaStream` via `getUserMedia`, attach it to a `<video>` element,\n * and expose status/error so the page can render permission and error states.\n * The stream is automatically released on unmount or retry.\n *\n * Defaults to the rear (\"environment\") camera; desktops fall back to whatever\n * single camera they expose. Pass `options.constraints` to override, or\n * `options.enabled: false` to render the surface without prompting for the camera\n * at all.\n *\n * Implementation notes:\n * - Cleanup detaches the stream from a *snapshotted* video node, so it releases\n * the same element it attached to even if the page remounts the `<video>`.\n * - When `getUserMedia` is missing, an insecure context is the usual cause, so\n * the hook prefers that (actionable) error; otherwise it reports `unsupported`.\n * - `video.play()` rejections are swallowed: autoplay may be blocked, but the\n * user gesture that opened the camera usually counts and playback resumes on\n * the next interaction.\n *\n * @param options - optional configuration (see {@link UseCameraStreamOptions}).\n * @returns The stream status, classified error, a `videoRef` to attach, the live\n * `stream` for whatever needs the track itself, and a `retry()` to re-attempt\n * acquisition.\n */\nexport function useCameraStream(options: UseCameraStreamOptions = {}): UseCameraStreamApi {\n const [status, setStatus] = useState<CameraStreamStatus>(\"loading\");\n const [error, setError] = useState<CameraStreamError | null>(null);\n const [live, setLive] = useState<MediaStream | null>(null);\n const [retryToken, setRetryToken] = useState(0);\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const constraintsRef = useLatestRef(options.constraints ?? DEFAULT_CONSTRAINTS);\n\n const enabled = options.enabled ?? true;\n\n useEffect(() => {\n let cancelled = false;\n let stream: MediaStream | null = null;\n let attachedVideo: HTMLVideoElement | null = null;\n\n async function start(): Promise<void> {\n if (!enabled) {\n setStatus(\"idle\");\n setError(null);\n return;\n }\n setStatus(\"loading\");\n setError(null);\n\n if (\n typeof navigator === \"undefined\" ||\n !navigator.mediaDevices ||\n typeof navigator.mediaDevices.getUserMedia !== \"function\"\n ) {\n if (!cancelled) {\n setError(toCameraError(missingCaptureApiError(\"camera\")));\n setStatus(\"error\");\n }\n return;\n }\n\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraintsRef.current);\n if (cancelled) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n const video = videoRef.current;\n if (!video) {\n stream.getTracks().forEach((track) => track.stop());\n return;\n }\n attachedVideo = video;\n video.srcObject = stream;\n setLive(stream);\n await video.play().catch(() => undefined);\n if (!cancelled) setStatus(\"ready\");\n } catch (err) {\n if (!cancelled) {\n setError(classifyError(err));\n setStatus(\"error\");\n }\n }\n }\n\n void start();\n\n return () => {\n cancelled = true;\n if (stream) {\n stream.getTracks().forEach((track) => track.stop());\n }\n if (attachedVideo) {\n attachedVideo.srcObject = null;\n }\n setLive(null);\n };\n }, [retryToken, enabled, constraintsRef]);\n\n return {\n status,\n error,\n videoRef,\n stream: live,\n retry: () => setRetryToken((n) => n + 1),\n };\n}\n"],"mappings":";;;;AAgEA,IAAM,IAA8C;CAChD,OAAO;EACH,YAAY,EAAE,OAAO,cAAc;EACnC,OAAO,EAAE,OAAO,KAAK;EACrB,QAAQ,EAAE,OAAO,KAAK;CAC1B;CACA,OAAO;AACX;AAcA,SAAS,EAAc,EAAE,SAAM,cAAgD;CAC3E,OAAO;EAAE,MAAM,MAAS,cAAc,cAAc;EAAM;CAAQ;AACtE;AAOA,SAAS,EAAc,GAAiC;CACpD,OAAO,EAAc,EAAmB,GAAK,QAAQ,CAAC;AAC1D;AA0BA,SAAgB,EAAgB,IAAkC,CAAC,GAAuB;CACtF,IAAM,CAAC,GAAQ,KAAa,EAA6B,SAAS,GAC5D,CAAC,GAAO,KAAY,EAAmC,IAAI,GAC3D,CAAC,GAAM,KAAW,EAA6B,IAAI,GACnD,CAAC,GAAY,KAAiB,EAAS,CAAC,GACxC,IAAW,EAAgC,IAAI,GAC/C,IAAiB,EAAa,EAAQ,eAAe,CAAmB,GAExE,IAAU,EAAQ,WAAW;CAkEnC,OAhEA,QAAgB;EACZ,IAAI,IAAY,IACZ,IAA6B,MAC7B,IAAyC;EAE7C,eAAe,IAAuB;GAClC,IAAI,CAAC,GAAS;IAEV,AADA,EAAU,MAAM,GAChB,EAAS,IAAI;IACb;GACJ;GAIA,IAHA,EAAU,SAAS,GACnB,EAAS,IAAI,GAGT,OAAO,YAAc,OACrB,CAAC,UAAU,gBACX,OAAO,UAAU,aAAa,gBAAiB,YACjD;IACE,AAAK,MACD,EAAS,EAAc,EAAuB,QAAQ,CAAC,CAAC,GACxD,EAAU,OAAO;IAErB;GACJ;GAEA,IAAI;IAEA,IADA,IAAS,MAAM,UAAU,aAAa,aAAa,EAAe,OAAO,GACrE,GAAW;KACX,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC;KAClD;IACJ;IACA,IAAM,IAAQ,EAAS;IACvB,IAAI,CAAC,GAAO;KACR,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC;KAClD;IACJ;IAKA,AAJA,IAAgB,GAChB,EAAM,YAAY,GAClB,EAAQ,CAAM,GACd,MAAM,EAAM,KAAK,CAAC,CAAC,YAAY,KAAA,CAAS,GACnC,KAAW,EAAU,OAAO;GACrC,SAAS,GAAK;IACV,AAAK,MACD,EAAS,EAAc,CAAG,CAAC,GAC3B,EAAU,OAAO;GAEzB;EACJ;EAIA,OAFA,EAAW,SAEE;GAQT,AAPA,IAAY,IACR,KACA,EAAO,UAAU,CAAC,CAAC,SAAS,MAAU,EAAM,KAAK,CAAC,GAElD,MACA,EAAc,YAAY,OAE9B,EAAQ,IAAI;EAChB;CACJ,GAAG;EAAC;EAAY;EAAS;CAAc,CAAC,GAEjC;EACH;EACA;EACA;EACA,QAAQ;EACR,aAAa,GAAe,MAAM,IAAI,CAAC;CAC3C;AACJ"}
@@ -0,0 +1,2 @@
1
+ function e(e){return e.endsWith(`/`)?e:`${e}/`}exports.basePrefix=e;
2
+ //# sourceMappingURL=base-url.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-url.cjs","names":[],"sources":["../../src/vite/base-url.ts"],"sourcesContent":["/**\n * The resolved Vite `base` as a prefix that always ends in a slash.\n *\n * One rule, three call sites: the manifest prefixes the URLs it precaches, and\n * the dev middleware matches the paths the browser asks for. They have to agree\n * by definition — when they drift, dev serves `/app/sw.js` while the manifest\n * precached `/sw.js`, and the symptom only appears on a subpath deploy, which is\n * the least exercised configuration there is.\n *\n * @param base - Vite's resolved `base`, with or without a trailing slash.\n * @returns The same base, guaranteed to end in `/`.\n */\nexport function basePrefix(base: string): string {\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n"],"mappings":"AAYA,SAAgB,EAAW,EAAsB,CAC7C,OAAO,EAAK,SAAS,GAAG,EAAI,EAAO,GAAG,EAAK,EAC/C"}
@@ -0,0 +1,8 @@
1
+ //#region src/vite/base-url.ts
2
+ function e(e) {
3
+ return e.endsWith("/") ? e : `${e}/`;
4
+ }
5
+ //#endregion
6
+ export { e as basePrefix };
7
+
8
+ //# sourceMappingURL=base-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base-url.js","names":[],"sources":["../../src/vite/base-url.ts"],"sourcesContent":["/**\n * The resolved Vite `base` as a prefix that always ends in a slash.\n *\n * One rule, three call sites: the manifest prefixes the URLs it precaches, and\n * the dev middleware matches the paths the browser asks for. They have to agree\n * by definition — when they drift, dev serves `/app/sw.js` while the manifest\n * precached `/sw.js`, and the symptom only appears on a subpath deploy, which is\n * the least exercised configuration there is.\n *\n * @param base - Vite's resolved `base`, with or without a trailing slash.\n * @returns The same base, guaranteed to end in `/`.\n */\nexport function basePrefix(base: string): string {\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n"],"mappings":";AAYA,SAAgB,EAAW,GAAsB;CAC7C,OAAO,EAAK,SAAS,GAAG,IAAI,IAAO,GAAG,EAAK;AAC/C"}
@@ -1,2 +1,2 @@
1
- let e=require("node:path");function t(t={}){let{swSrc:n=`src/sw.ts`,swUrl:r=`/sw.js`,manifestUrl:i=`/precache-manifest.json`,enabled:a=!0}=t,o=process.cwd(),s=`/`;function c(e,t){if(e===t)return!0;let n=s.endsWith(`/`)?s:`${s}/`;return n!==`/`&&e===`${n}${t.replace(/^\//,``)}`}return{name:`tempest-pwa-dev-sw`,apply:`serve`,configResolved(e){o=e.root??process.cwd(),s=e.base??`/`},configureServer(t){a&&t.middlewares.use(async(t,a,s)=>{let l=(t.url??``).split(`?`)[0];if(c(l,r)){try{let t=await(await import(`esbuild`)).build({entryPoints:[(0,e.resolve)(o,n)],bundle:!0,format:`iife`,platform:`browser`,target:`es2020`,write:!1,absWorkingDir:o,logLevel:`silent`});a.setHeader(`Content-Type`,`application/javascript`),a.setHeader(`Service-Worker-Allowed`,`/`),a.setHeader(`Cache-Control`,`no-cache`),a.end(t.outputFiles[0].text)}catch(e){a.statusCode=500,a.end(`// SW dev build failed:\n// ${String(e)}`)}return}if(c(l,i)){a.setHeader(`Content-Type`,`application/json`),a.setHeader(`Cache-Control`,`no-cache`),a.end(JSON.stringify({version:`dev`,urls:[]}));return}s()})}}}exports.tempestPwaDevSw=t;
1
+ const e=require("./base-url.cjs");let t=require("node:path");function n(n={}){let{swSrc:r=`src/sw.ts`,swUrl:i=`/sw.js`,manifestUrl:a=`/precache-manifest.json`,enabled:o=!0}=n,s=process.cwd(),c=`/`;function l(t,n){if(t===n)return!0;let r=e.basePrefix(c);return r!==`/`&&t===`${r}${n.replace(/^\//,``)}`}let u=null,d=null;async function f(){return u||(u=await(await import(`esbuild`)).context({entryPoints:[(0,t.resolve)(s,r)],bundle:!0,format:`iife`,platform:`browser`,target:`es2020`,write:!1,absWorkingDir:s,logLevel:`silent`}),u)}function p(){if(d)return d;let e=(async()=>{let e=(await(await f()).rebuild()).outputFiles?.[0]?.text;if(e===void 0)throw Error(`esbuild produced no service-worker output`);return e})();d=e;let t=()=>{d=null};return e.then(t,t),e}async function m(){let e=u;u=null,d=null,await e?.dispose()}return{name:`tempest-pwa-dev-sw`,apply:`serve`,async buildEnd(){await m()},configResolved(e){s=e.root??process.cwd(),c=e.base??`/`},configureServer(e){o&&(e.httpServer?.once(`close`,()=>void m()),e.middlewares.use(async(e,t,n)=>{let r=(e.url??``).split(`?`)[0];if(l(r,i)){try{let e=await p();t.setHeader(`Content-Type`,`application/javascript`),t.setHeader(`Service-Worker-Allowed`,`/`),t.setHeader(`Cache-Control`,`no-cache`),t.end(e)}catch(e){t.statusCode=500,t.end(`// SW dev build failed:\n// ${String(e)}`)}return}if(l(r,a)){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-cache`),t.end(JSON.stringify({version:`dev`,urls:[]}));return}n()}))}}}exports.tempestPwaDevSw=n;
2
2
  //# sourceMappingURL=tempest-pwa-dev-sw.cjs.map