tempest-react-sdk 0.52.0 → 0.54.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 (507) hide show
  1. package/README.md +58 -7
  2. package/dist/access/Can.cjs +1 -1
  3. package/dist/access/Can.cjs.map +1 -1
  4. package/dist/access/Can.js +3 -3
  5. package/dist/access/Can.js.map +1 -1
  6. package/dist/audio/audio-bus.cjs +2 -0
  7. package/dist/audio/audio-bus.cjs.map +1 -0
  8. package/dist/audio/audio-bus.js +116 -0
  9. package/dist/audio/audio-bus.js.map +1 -0
  10. package/dist/audio/level-meter.cjs +1 -1
  11. package/dist/audio/level-meter.cjs.map +1 -1
  12. package/dist/audio/level-meter.js +15 -15
  13. package/dist/audio/level-meter.js.map +1 -1
  14. package/dist/audio/noise-floor.cjs +2 -0
  15. package/dist/audio/noise-floor.cjs.map +1 -0
  16. package/dist/audio/noise-floor.js +27 -0
  17. package/dist/audio/noise-floor.js.map +1 -0
  18. package/dist/audio/use-audio-bus.cjs +2 -0
  19. package/dist/audio/use-audio-bus.cjs.map +1 -0
  20. package/dist/audio/use-audio-bus.js +11 -0
  21. package/dist/audio/use-audio-bus.js.map +1 -0
  22. package/dist/audio/voice-activity.cjs +2 -0
  23. package/dist/audio/voice-activity.cjs.map +1 -0
  24. package/dist/audio/voice-activity.js +26 -0
  25. package/dist/audio/voice-activity.js.map +1 -0
  26. package/dist/audio/voice-chain-stages.cjs +2 -0
  27. package/dist/audio/voice-chain-stages.cjs.map +1 -0
  28. package/dist/audio/voice-chain-stages.js +82 -0
  29. package/dist/audio/voice-chain-stages.js.map +1 -0
  30. package/dist/audio/voice-chain.cjs +2 -0
  31. package/dist/audio/voice-chain.cjs.map +1 -0
  32. package/dist/audio/voice-chain.js +74 -0
  33. package/dist/audio/voice-chain.js.map +1 -0
  34. package/dist/auth/lazy-with-retry.cjs.map +1 -1
  35. package/dist/auth/lazy-with-retry.js.map +1 -1
  36. package/dist/auth/passkey.cjs.map +1 -1
  37. package/dist/auth/passkey.js.map +1 -1
  38. package/dist/br/BrazilStateCitySelect.cjs +1 -1
  39. package/dist/br/BrazilStateCitySelect.cjs.map +1 -1
  40. package/dist/br/BrazilStateCitySelect.js +36 -28
  41. package/dist/br/BrazilStateCitySelect.js.map +1 -1
  42. package/dist/br/data/br-centroids.cjs +1 -1
  43. package/dist/br/data/br-centroids.cjs.map +1 -1
  44. package/dist/br/data/br-centroids.js +11105 -11045
  45. package/dist/br/data/br-centroids.js.map +1 -1
  46. package/dist/br/data/br-locations.cjs +1 -1
  47. package/dist/br/data/br-locations.cjs.map +1 -1
  48. package/dist/br/data/br-locations.js +5803 -137
  49. package/dist/br/data/br-locations.js.map +1 -1
  50. package/dist/br/data/br-uf-geo.cjs +1 -1
  51. package/dist/br/data/br-uf-geo.cjs.map +1 -1
  52. package/dist/br/data/br-uf-geo.js +5721 -6777
  53. package/dist/br/data/br-uf-geo.js.map +1 -1
  54. package/dist/br/data/mun/AC.cjs +1 -1
  55. package/dist/br/data/mun/AC.cjs.map +1 -1
  56. package/dist/br/data/mun/AC.js +681 -689
  57. package/dist/br/data/mun/AC.js.map +1 -1
  58. package/dist/br/data/mun/AL.cjs +1 -1
  59. package/dist/br/data/mun/AL.cjs.map +1 -1
  60. package/dist/br/data/mun/AL.js +949 -844
  61. package/dist/br/data/mun/AL.js.map +1 -1
  62. package/dist/br/data/mun/AM.cjs +1 -1
  63. package/dist/br/data/mun/AM.cjs.map +1 -1
  64. package/dist/br/data/mun/AM.js +4337 -4218
  65. package/dist/br/data/mun/AM.js.map +1 -1
  66. package/dist/br/data/mun/AP.cjs +1 -1
  67. package/dist/br/data/mun/AP.cjs.map +1 -1
  68. package/dist/br/data/mun/AP.js +786 -780
  69. package/dist/br/data/mun/AP.js.map +1 -1
  70. package/dist/br/data/mun/BA.cjs +1 -1
  71. package/dist/br/data/mun/BA.cjs.map +1 -1
  72. package/dist/br/data/mun/BA.js +6329 -5633
  73. package/dist/br/data/mun/BA.js.map +1 -1
  74. package/dist/br/data/mun/CE.cjs +1 -1
  75. package/dist/br/data/mun/CE.cjs.map +1 -1
  76. package/dist/br/data/mun/CE.js +2544 -2487
  77. package/dist/br/data/mun/CE.js.map +1 -1
  78. package/dist/br/data/mun/DF.cjs +1 -1
  79. package/dist/br/data/mun/DF.cjs.map +1 -1
  80. package/dist/br/data/mun/DF.js +17 -16
  81. package/dist/br/data/mun/DF.js.map +1 -1
  82. package/dist/br/data/mun/ES.cjs +1 -1
  83. package/dist/br/data/mun/ES.cjs.map +1 -1
  84. package/dist/br/data/mun/ES.js +1101 -1070
  85. package/dist/br/data/mun/ES.js.map +1 -1
  86. package/dist/br/data/mun/GO.cjs +1 -1
  87. package/dist/br/data/mun/GO.cjs.map +1 -1
  88. package/dist/br/data/mun/GO.js +4632 -4636
  89. package/dist/br/data/mun/GO.js.map +1 -1
  90. package/dist/br/data/mun/MA.cjs +1 -1
  91. package/dist/br/data/mun/MA.cjs.map +1 -1
  92. package/dist/br/data/mun/MA.js +3603 -3457
  93. package/dist/br/data/mun/MA.js.map +1 -1
  94. package/dist/br/data/mun/MG.cjs +1 -1
  95. package/dist/br/data/mun/MG.cjs.map +1 -1
  96. package/dist/br/data/mun/MG.js +12716 -11739
  97. package/dist/br/data/mun/MG.js.map +1 -1
  98. package/dist/br/data/mun/MS.cjs +1 -1
  99. package/dist/br/data/mun/MS.cjs.map +1 -1
  100. package/dist/br/data/mun/MS.js +2182 -2335
  101. package/dist/br/data/mun/MS.js.map +1 -1
  102. package/dist/br/data/mun/MT.cjs +1 -1
  103. package/dist/br/data/mun/MT.cjs.map +1 -1
  104. package/dist/br/data/mun/MT.js +4808 -4896
  105. package/dist/br/data/mun/MT.js.map +1 -1
  106. package/dist/br/data/mun/PA.cjs +1 -1
  107. package/dist/br/data/mun/PA.cjs.map +1 -1
  108. package/dist/br/data/mun/PA.js +4981 -4901
  109. package/dist/br/data/mun/PA.js.map +1 -1
  110. package/dist/br/data/mun/PB.cjs +1 -1
  111. package/dist/br/data/mun/PB.cjs.map +1 -1
  112. package/dist/br/data/mun/PB.js +2418 -1956
  113. package/dist/br/data/mun/PB.js.map +1 -1
  114. package/dist/br/data/mun/PE.cjs +1 -1
  115. package/dist/br/data/mun/PE.cjs.map +1 -1
  116. package/dist/br/data/mun/PE.js +2164 -1987
  117. package/dist/br/data/mun/PE.js.map +1 -1
  118. package/dist/br/data/mun/PI.cjs +1 -1
  119. package/dist/br/data/mun/PI.cjs.map +1 -1
  120. package/dist/br/data/mun/PI.js +2982 -2844
  121. package/dist/br/data/mun/PI.js.map +1 -1
  122. package/dist/br/data/mun/PR.cjs +1 -1
  123. package/dist/br/data/mun/PR.cjs.map +1 -1
  124. package/dist/br/data/mun/PR.js +5425 -5240
  125. package/dist/br/data/mun/PR.js.map +1 -1
  126. package/dist/br/data/mun/RJ.cjs +1 -1
  127. package/dist/br/data/mun/RJ.cjs.map +1 -1
  128. package/dist/br/data/mun/RJ.js +1395 -1178
  129. package/dist/br/data/mun/RJ.js.map +1 -1
  130. package/dist/br/data/mun/RN.cjs +1 -1
  131. package/dist/br/data/mun/RN.cjs.map +1 -1
  132. package/dist/br/data/mun/RN.js +1608 -1382
  133. package/dist/br/data/mun/RN.js.map +1 -1
  134. package/dist/br/data/mun/RO.cjs +1 -1
  135. package/dist/br/data/mun/RO.cjs.map +1 -1
  136. package/dist/br/data/mun/RO.js +1392 -1470
  137. package/dist/br/data/mun/RO.js.map +1 -1
  138. package/dist/br/data/mun/RR.cjs +1 -1
  139. package/dist/br/data/mun/RR.cjs.map +1 -1
  140. package/dist/br/data/mun/RR.js +795 -778
  141. package/dist/br/data/mun/RR.js.map +1 -1
  142. package/dist/br/data/mun/RS.cjs +1 -1
  143. package/dist/br/data/mun/RS.cjs.map +1 -1
  144. package/dist/br/data/mun/RS.js +7579 -6424
  145. package/dist/br/data/mun/RS.js.map +1 -1
  146. package/dist/br/data/mun/SC.cjs +1 -1
  147. package/dist/br/data/mun/SC.cjs.map +1 -1
  148. package/dist/br/data/mun/SC.js +3979 -3357
  149. package/dist/br/data/mun/SC.js.map +1 -1
  150. package/dist/br/data/mun/SE.cjs +1 -1
  151. package/dist/br/data/mun/SE.cjs.map +1 -1
  152. package/dist/br/data/mun/SE.js +812 -625
  153. package/dist/br/data/mun/SE.js.map +1 -1
  154. package/dist/br/data/mun/SP.cjs +1 -1
  155. package/dist/br/data/mun/SP.cjs.map +1 -1
  156. package/dist/br/data/mun/SP.js +7866 -6803
  157. package/dist/br/data/mun/SP.js.map +1 -1
  158. package/dist/br/data/mun/TO.cjs +1 -1
  159. package/dist/br/data/mun/TO.cjs.map +1 -1
  160. package/dist/br/data/mun/TO.js +2763 -2817
  161. package/dist/br/data/mun/TO.js.map +1 -1
  162. package/dist/br/locations.cjs +1 -1
  163. package/dist/br/locations.cjs.map +1 -1
  164. package/dist/br/locations.js +97 -24
  165. package/dist/br/locations.js.map +1 -1
  166. package/dist/br/scales.cjs +1 -1
  167. package/dist/br/scales.cjs.map +1 -1
  168. package/dist/br/scales.js +8 -4
  169. package/dist/br/scales.js.map +1 -1
  170. package/dist/br/whatsapp.cjs +2 -0
  171. package/dist/br/whatsapp.cjs.map +1 -0
  172. package/dist/br/whatsapp.js +21 -0
  173. package/dist/br/whatsapp.js.map +1 -0
  174. package/dist/br.cjs +1 -1
  175. package/dist/br.cjs.map +1 -1
  176. package/dist/br.d.ts +188 -10
  177. package/dist/br.js +18 -17
  178. package/dist/br.js.map +1 -1
  179. package/dist/components/BottomSheet/BottomSheet.cjs +1 -1
  180. package/dist/components/BottomSheet/BottomSheet.cjs.map +1 -1
  181. package/dist/components/BottomSheet/BottomSheet.js +30 -27
  182. package/dist/components/BottomSheet/BottomSheet.js.map +1 -1
  183. package/dist/components/Command/Command.cjs +1 -1
  184. package/dist/components/Command/Command.cjs.map +1 -1
  185. package/dist/components/Command/Command.js +78 -75
  186. package/dist/components/Command/Command.js.map +1 -1
  187. package/dist/components/Drawer/Drawer.cjs +1 -1
  188. package/dist/components/Drawer/Drawer.cjs.map +1 -1
  189. package/dist/components/Drawer/Drawer.js +42 -39
  190. package/dist/components/Drawer/Drawer.js.map +1 -1
  191. package/dist/components/DropdownMenu/DropdownMenu.cjs +1 -1
  192. package/dist/components/DropdownMenu/DropdownMenu.cjs.map +1 -1
  193. package/dist/components/DropdownMenu/DropdownMenu.js +111 -67
  194. package/dist/components/DropdownMenu/DropdownMenu.js.map +1 -1
  195. package/dist/components/Modal/Modal.cjs +1 -1
  196. package/dist/components/Modal/Modal.cjs.map +1 -1
  197. package/dist/components/Modal/Modal.js +45 -42
  198. package/dist/components/Modal/Modal.js.map +1 -1
  199. package/dist/components/Money/Money.cjs +1 -1
  200. package/dist/components/Money/Money.cjs.map +1 -1
  201. package/dist/components/Money/Money.js +10 -9
  202. package/dist/components/Money/Money.js.map +1 -1
  203. package/dist/components/Pagination/Pagination.cjs +1 -1
  204. package/dist/components/Pagination/Pagination.cjs.map +1 -1
  205. package/dist/components/Pagination/Pagination.js +38 -31
  206. package/dist/components/Pagination/Pagination.js.map +1 -1
  207. package/dist/components/Pagination/Pagination.module.cjs +1 -1
  208. package/dist/components/Pagination/Pagination.module.cjs.map +1 -1
  209. package/dist/components/Pagination/Pagination.module.js +4 -4
  210. package/dist/components/Pagination/Pagination.module.js.map +1 -1
  211. package/dist/components/Portal/Portal.cjs +1 -1
  212. package/dist/components/Portal/Portal.cjs.map +1 -1
  213. package/dist/components/Portal/Portal.js +9 -6
  214. package/dist/components/Portal/Portal.js.map +1 -1
  215. package/dist/components/Portal/portal-host.cjs +2 -0
  216. package/dist/components/Portal/portal-host.cjs.map +1 -0
  217. package/dist/components/Portal/portal-host.js +11 -0
  218. package/dist/components/Portal/portal-host.js.map +1 -0
  219. package/dist/components/RangeSlider/RangeSlider.cjs +1 -1
  220. package/dist/components/RangeSlider/RangeSlider.cjs.map +1 -1
  221. package/dist/components/RangeSlider/RangeSlider.js +23 -23
  222. package/dist/components/RangeSlider/RangeSlider.js.map +1 -1
  223. package/dist/components/Scheduler/Scheduler.cjs +1 -1
  224. package/dist/components/Scheduler/Scheduler.cjs.map +1 -1
  225. package/dist/components/Scheduler/Scheduler.js +83 -82
  226. package/dist/components/Scheduler/Scheduler.js.map +1 -1
  227. package/dist/components/Slider/Slider.cjs +1 -1
  228. package/dist/components/Slider/Slider.cjs.map +1 -1
  229. package/dist/components/Slider/Slider.js +9 -9
  230. package/dist/components/Slider/Slider.js.map +1 -1
  231. package/dist/components/Toast/ToastProvider.cjs +1 -1
  232. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  233. package/dist/components/Toast/ToastProvider.js +55 -53
  234. package/dist/components/Toast/ToastProvider.js.map +1 -1
  235. package/dist/components/VirtualList/VirtualList.cjs +1 -1
  236. package/dist/components/VirtualList/VirtualList.cjs.map +1 -1
  237. package/dist/components/VirtualList/VirtualList.js +41 -31
  238. package/dist/components/VirtualList/VirtualList.js.map +1 -1
  239. package/dist/components/VirtualTable/VirtualTable.cjs +1 -1
  240. package/dist/components/VirtualTable/VirtualTable.cjs.map +1 -1
  241. package/dist/components/VirtualTable/VirtualTable.js +78 -68
  242. package/dist/components/VirtualTable/VirtualTable.js.map +1 -1
  243. package/dist/forms/FormField.cjs +1 -1
  244. package/dist/forms/FormField.cjs.map +1 -1
  245. package/dist/forms/FormField.js +23 -21
  246. package/dist/forms/FormField.js.map +1 -1
  247. package/dist/forms/masked-inputs.cjs +1 -1
  248. package/dist/forms/masked-inputs.cjs.map +1 -1
  249. package/dist/forms/masked-inputs.js +20 -19
  250. package/dist/forms/masked-inputs.js.map +1 -1
  251. package/dist/hooks/use-fullscreen-element.cjs +2 -0
  252. package/dist/hooks/use-fullscreen-element.cjs.map +1 -0
  253. package/dist/hooks/use-fullscreen-element.js +20 -0
  254. package/dist/hooks/use-fullscreen-element.js.map +1 -0
  255. package/dist/hooks/use-fullscreen.cjs +2 -0
  256. package/dist/hooks/use-fullscreen.cjs.map +1 -0
  257. package/dist/hooks/use-fullscreen.js +66 -0
  258. package/dist/hooks/use-fullscreen.js.map +1 -0
  259. package/dist/hooks/use-push-to-talk.cjs +2 -0
  260. package/dist/hooks/use-push-to-talk.cjs.map +1 -0
  261. package/dist/hooks/use-push-to-talk.js +61 -0
  262. package/dist/hooks/use-push-to-talk.js.map +1 -0
  263. package/dist/http/describe-api-error.cjs.map +1 -1
  264. package/dist/http/describe-api-error.js.map +1 -1
  265. package/dist/http/errors.cjs +1 -1
  266. package/dist/http/errors.cjs.map +1 -1
  267. package/dist/http/errors.js +34 -16
  268. package/dist/http/errors.js.map +1 -1
  269. package/dist/http/parse-response.cjs +2 -2
  270. package/dist/http/parse-response.cjs.map +1 -1
  271. package/dist/http/parse-response.js +9 -8
  272. package/dist/http/parse-response.js.map +1 -1
  273. package/dist/i18n/create-i18n.cjs +1 -1
  274. package/dist/i18n/create-i18n.cjs.map +1 -1
  275. package/dist/i18n/create-i18n.js +28 -27
  276. package/dist/i18n/create-i18n.js.map +1 -1
  277. package/dist/query/QueryProvider.cjs +1 -1
  278. package/dist/query/QueryProvider.cjs.map +1 -1
  279. package/dist/query/QueryProvider.js +13 -11
  280. package/dist/query/QueryProvider.js.map +1 -1
  281. package/dist/query/foreign-client-warning.cjs +2 -0
  282. package/dist/query/foreign-client-warning.cjs.map +1 -0
  283. package/dist/query/foreign-client-warning.js +12 -0
  284. package/dist/query/foreign-client-warning.js.map +1 -0
  285. package/dist/router/AppRouter.cjs +1 -1
  286. package/dist/router/AppRouter.cjs.map +1 -1
  287. package/dist/router/AppRouter.js +28 -21
  288. package/dist/router/AppRouter.js.map +1 -1
  289. package/dist/router/RouteGuard.cjs +1 -1
  290. package/dist/router/RouteGuard.cjs.map +1 -1
  291. package/dist/router/RouteGuard.js +4 -4
  292. package/dist/router/RouteGuard.js.map +1 -1
  293. package/dist/sse/create-event-stream.cjs +1 -1
  294. package/dist/sse/create-event-stream.cjs.map +1 -1
  295. package/dist/sse/create-event-stream.js +34 -38
  296. package/dist/sse/create-event-stream.js.map +1 -1
  297. package/dist/styles/AIChat.css +79 -0
  298. package/dist/styles/Accordion.css +12 -0
  299. package/dist/styles/Alert.css +32 -0
  300. package/dist/styles/AppBar.css +17 -0
  301. package/dist/styles/AppShell.css +8 -0
  302. package/dist/styles/AspectRatio.css +3 -0
  303. package/dist/styles/AudioPlayer.css +13 -0
  304. package/dist/styles/AudioRecorder.css +20 -0
  305. package/dist/styles/Avatar.css +13 -0
  306. package/dist/styles/AvatarGroup.css +18 -0
  307. package/dist/styles/Badge.css +25 -0
  308. package/dist/styles/Banner.css +13 -0
  309. package/dist/styles/BarList.css +10 -0
  310. package/dist/styles/BarcodeScanner.css +21 -0
  311. package/dist/styles/BottomNavigation.css +10 -0
  312. package/dist/styles/BottomSheet.css +11 -0
  313. package/dist/styles/BrazilMap.css +20 -0
  314. package/dist/styles/Breadcrumbs.css +8 -0
  315. package/dist/styles/Button.css +42 -0
  316. package/dist/styles/Calendar.css +16 -0
  317. package/dist/styles/Card.css +15 -0
  318. package/dist/styles/Carousel.css +17 -0
  319. package/dist/styles/Center.css +5 -0
  320. package/dist/styles/Chat.css +35 -0
  321. package/dist/styles/Checkbox.css +11 -0
  322. package/dist/styles/ChipInput.css +13 -0
  323. package/dist/styles/CodeBlock.css +25 -0
  324. package/dist/styles/Collapsible.css +6 -0
  325. package/dist/styles/Combobox.css +18 -0
  326. package/dist/styles/Command.css +20 -0
  327. package/dist/styles/ContextMenu.css +11 -0
  328. package/dist/styles/CopyButton.css +4 -0
  329. package/dist/styles/DataList.css +3 -0
  330. package/dist/styles/DataTable.css +19 -0
  331. package/dist/styles/DateRangePicker.css +22 -0
  332. package/dist/styles/DescriptionList.css +4 -0
  333. package/dist/styles/Divider.css +11 -0
  334. package/dist/styles/Drawer.css +22 -0
  335. package/dist/styles/DropdownMenu.css +16 -0
  336. package/dist/styles/Dropzone.css +7 -0
  337. package/dist/styles/EmptyState.css +6 -0
  338. package/dist/styles/ErrorState.css +6 -0
  339. package/dist/styles/ErrorText.css +2 -0
  340. package/dist/styles/FileUpload.css +17 -0
  341. package/dist/styles/FilterBar.css +19 -0
  342. package/dist/styles/FloatingActionButton.css +23 -0
  343. package/dist/styles/Form.css +21 -0
  344. package/dist/styles/HoverCard.css +11 -0
  345. package/dist/styles/IconPicker.css +6 -0
  346. package/dist/styles/Image.css +2 -0
  347. package/dist/styles/ImageCropper.css +16 -0
  348. package/dist/styles/Input.css +24 -0
  349. package/dist/styles/InstallBanner.css +8 -0
  350. package/dist/styles/Kanban.css +15 -0
  351. package/dist/styles/Kbd.css +5 -0
  352. package/dist/styles/Label.css +3 -0
  353. package/dist/styles/Layout.css +22 -0
  354. package/dist/styles/Lightbox.css +21 -0
  355. package/dist/styles/ListTile.css +14 -0
  356. package/dist/styles/MapLegend.css +9 -0
  357. package/dist/styles/Markdown.css +24 -0
  358. package/dist/styles/Masonry.css +4 -0
  359. package/dist/styles/Menubar.css +17 -0
  360. package/dist/styles/Modal.css +21 -0
  361. package/dist/styles/ModalsManager.css +2 -0
  362. package/dist/styles/MultiSelect.css +21 -0
  363. package/dist/styles/MunicipalitySearch.css +6 -0
  364. package/dist/styles/NProgress.css +2 -0
  365. package/dist/styles/Navbar.css +10 -0
  366. package/dist/styles/NavigationMenu.css +12 -0
  367. package/dist/styles/NavigationRail.css +14 -0
  368. package/dist/styles/NotificationCenter.css +21 -0
  369. package/dist/styles/OfflineIndicator.css +7 -0
  370. package/dist/styles/Page.css +13 -0
  371. package/dist/styles/Pagination.css +12 -0
  372. package/dist/styles/PasswordInput.css +21 -0
  373. package/dist/styles/PinInput.css +13 -0
  374. package/dist/styles/PixQRCode.css +9 -0
  375. package/dist/styles/Popover.css +10 -0
  376. package/dist/styles/Progress.css +11 -0
  377. package/dist/styles/QRCode.css +3 -0
  378. package/dist/styles/Radio.css +14 -0
  379. package/dist/styles/RangeSlider.css +15 -0
  380. package/dist/styles/RatingStars.css +11 -0
  381. package/dist/styles/RefreshIndicator.css +5 -0
  382. package/dist/styles/Resizable.css +13 -0
  383. package/dist/styles/RichTextEditor.css +19 -0
  384. package/dist/styles/SafeArea.css +7 -0
  385. package/dist/styles/Scheduler.css +24 -0
  386. package/dist/styles/ScrollArea.css +7 -0
  387. package/dist/styles/SearchBar.css +11 -0
  388. package/dist/styles/SegmentedControl.css +12 -0
  389. package/dist/styles/Select.css +14 -0
  390. package/dist/styles/Sidebar.css +19 -0
  391. package/dist/styles/SignaturePad.css +6 -0
  392. package/dist/styles/Skeleton.css +7 -0
  393. package/dist/styles/Slider.css +15 -0
  394. package/dist/styles/Spacer.css +4 -0
  395. package/dist/styles/Sparkline.css +4 -0
  396. package/dist/styles/Spinner.css +12 -0
  397. package/dist/styles/Stat.css +12 -0
  398. package/dist/styles/Stepper.css +17 -0
  399. package/dist/styles/StepperInput.css +15 -0
  400. package/dist/styles/Switch.css +11 -0
  401. package/dist/styles/SyncStatusBadge.css +13 -0
  402. package/dist/styles/Table.css +16 -0
  403. package/dist/styles/Tabs.css +14 -0
  404. package/dist/styles/Tag.css +14 -0
  405. package/dist/styles/Textarea.css +13 -0
  406. package/dist/styles/TimePicker.css +14 -0
  407. package/dist/styles/Timeline.css +17 -0
  408. package/dist/styles/Toast.css +21 -0
  409. package/dist/styles/Toggle.css +12 -0
  410. package/dist/styles/ToggleGroup.css +9 -0
  411. package/dist/styles/Tooltip.css +10 -0
  412. package/dist/styles/Tour.css +20 -0
  413. package/dist/styles/TrajectoryMap.css +16 -0
  414. package/dist/styles/Transfer.css +21 -0
  415. package/dist/styles/TreeView.css +17 -0
  416. package/dist/styles/TruncateText.css +2 -0
  417. package/dist/styles/UpdatePrompt.css +10 -0
  418. package/dist/styles/VirtualList.css +5 -0
  419. package/dist/styles/VirtualTable.css +17 -0
  420. package/dist/styles/VisuallyHidden.css +2 -0
  421. package/dist/styles/Wizard.css +4 -0
  422. package/dist/styles/actions.css +104 -0
  423. package/dist/styles/advanced.css +66 -0
  424. package/dist/styles/br.css +41 -0
  425. package/dist/styles/chat.css +113 -0
  426. package/dist/styles/core.css +40 -0
  427. package/dist/styles/data.css +222 -0
  428. package/dist/styles/editor.css +19 -0
  429. package/dist/styles/feedback.css +201 -0
  430. package/dist/styles/forms.css +321 -0
  431. package/dist/styles/geo.css +16 -0
  432. package/dist/styles/icons.css +6 -0
  433. package/dist/styles/identity.css +48 -0
  434. package/dist/styles/layout.css +122 -0
  435. package/dist/styles/media.css +52 -0
  436. package/dist/styles/navigation.css +167 -0
  437. package/dist/styles/overlay.css +73 -0
  438. package/dist/styles/utility.css +39 -0
  439. package/dist/styles.css +1 -1
  440. package/dist/sw/register-service-worker.cjs +1 -1
  441. package/dist/sw/register-service-worker.cjs.map +1 -1
  442. package/dist/sw/register-service-worker.js +21 -17
  443. package/dist/sw/register-service-worker.js.map +1 -1
  444. package/dist/sw.d.ts +17 -1
  445. package/dist/tempest-react-sdk.cjs +1 -1
  446. package/dist/tempest-react-sdk.d.ts +1382 -76
  447. package/dist/tempest-react-sdk.js +293 -281
  448. package/dist/utils/dev-mode.cjs.map +1 -1
  449. package/dist/utils/dev-mode.js.map +1 -1
  450. package/dist/utils/duplicate-instance.cjs +2 -0
  451. package/dist/utils/duplicate-instance.cjs.map +1 -0
  452. package/dist/utils/duplicate-instance.js +6 -0
  453. package/dist/utils/duplicate-instance.js.map +1 -0
  454. package/dist/utils/format.cjs +1 -1
  455. package/dist/utils/format.cjs.map +1 -1
  456. package/dist/utils/format.js +22 -14
  457. package/dist/utils/format.js.map +1 -1
  458. package/dist/utils/intl-cache.cjs +2 -0
  459. package/dist/utils/intl-cache.cjs.map +1 -0
  460. package/dist/utils/intl-cache.js +23 -0
  461. package/dist/utils/intl-cache.js.map +1 -0
  462. package/dist/utils/json-frame.cjs +2 -0
  463. package/dist/utils/json-frame.cjs.map +1 -0
  464. package/dist/utils/json-frame.js +30 -0
  465. package/dist/utils/json-frame.js.map +1 -0
  466. package/dist/utils/numbers.cjs +1 -1
  467. package/dist/utils/numbers.cjs.map +1 -1
  468. package/dist/utils/numbers.js +8 -7
  469. package/dist/utils/numbers.js.map +1 -1
  470. package/dist/vision/results.cjs +1 -1
  471. package/dist/vision/results.cjs.map +1 -1
  472. package/dist/vision/results.js +26 -17
  473. package/dist/vision/results.js.map +1 -1
  474. package/dist/vision.d.ts +29 -0
  475. package/dist/vite/tempest-icons.cjs +1 -1
  476. package/dist/vite/tempest-icons.cjs.map +1 -1
  477. package/dist/vite/tempest-icons.js +1 -1
  478. package/dist/vite/tempest-icons.js.map +1 -1
  479. package/dist/webrtc/link-stats.cjs +2 -0
  480. package/dist/webrtc/link-stats.cjs.map +1 -0
  481. package/dist/webrtc/link-stats.js +74 -0
  482. package/dist/webrtc/link-stats.js.map +1 -0
  483. package/dist/webrtc/opus-sdp.cjs +3 -0
  484. package/dist/webrtc/opus-sdp.cjs.map +1 -0
  485. package/dist/webrtc/opus-sdp.js +94 -0
  486. package/dist/webrtc/opus-sdp.js.map +1 -0
  487. package/dist/webrtc/sender-bitrate.cjs +2 -0
  488. package/dist/webrtc/sender-bitrate.cjs.map +1 -0
  489. package/dist/webrtc/sender-bitrate.js +15 -0
  490. package/dist/webrtc/sender-bitrate.js.map +1 -0
  491. package/dist/webrtc/use-link-stats.cjs +2 -0
  492. package/dist/webrtc/use-link-stats.cjs.map +1 -0
  493. package/dist/webrtc/use-link-stats.js +22 -0
  494. package/dist/webrtc/use-link-stats.js.map +1 -0
  495. package/dist/ws/create-web-socket.cjs +1 -1
  496. package/dist/ws/create-web-socket.cjs.map +1 -1
  497. package/dist/ws/create-web-socket.js +130 -58
  498. package/dist/ws/create-web-socket.js.map +1 -1
  499. package/dist/ws/resilience.cjs +2 -0
  500. package/dist/ws/resilience.cjs.map +1 -0
  501. package/dist/ws/resilience.js +21 -0
  502. package/dist/ws/resilience.js.map +1 -0
  503. package/dist/ws/use-web-socket.cjs +1 -1
  504. package/dist/ws/use-web-socket.cjs.map +1 -1
  505. package/dist/ws/use-web-socket.js +47 -39
  506. package/dist/ws/use-web-socket.js.map +1 -1
  507. package/package.json +5 -2
@@ -1 +1 @@
1
- {"version":3,"file":"passkey.cjs","names":[],"sources":["../../src/auth/passkey.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — the WebAuthn client half: the JSON\n * shapes both ceremonies exchange with a backend, base64url ↔ ArrayBuffer, the\n * capability probes and the error classifier. The two ceremonies are near-mirrors\n * that must not drift — register and authenticate encode the same credential fields\n * in the same order — and the file's docstring is also the specification of the four\n * backend routes it expects.\n */\n\nimport { base64ToBytes, bytesToBase64 } from \"@/utils/base64\";\n\n/**\n * Classified reason a passkey ceremony did not produce a credential.\n *\n * The kinds group the raw `DOMException.name` values the way a UI has to branch\n * on them, which is *not* how the spec groups them:\n *\n * - `\"cancelled\"` covers `NotAllowedError`, which the browser raises both when\n * the user dismissed the sheet and when the ceremony timed out. They are\n * indistinguishable **by design** — telling a site \"the user has no credential\n * for you\" would leak account existence — so a UI must treat them as one thing.\n * - `\"already-registered\"` (`InvalidStateError`) is not really a failure: this\n * device already holds a credential for this user. The correct reaction is\n * \"you are already set up on this device\", never a red error.\n * - `\"rp-mismatch\"` (`SecurityError`) is the single most common integration bug:\n * `rp.id` must equal the page's domain or a registrable parent of it.\n */\nexport type PasskeyErrorKind =\n | \"unsupported\"\n | \"insecure\"\n | \"cancelled\"\n | \"already-registered\"\n | \"not-supported\"\n | \"rp-mismatch\"\n | \"invalid-options\"\n | \"aborted\"\n | \"unknown\";\n\n/** Which ceremony was running, so the message can name it. */\nexport type PasskeyCeremony = \"register\" | \"authenticate\";\n\n/**\n * A passkey failure carrying a stable {@link PasskeyErrorKind} plus an English\n * message safe to show a user.\n *\n * A class rather than the plain `{ kind, message }` object the media classifier\n * returns, because these surface by rejecting a promise: an `Error` subclass keeps\n * stack traces, `instanceof` checks and logging intact, and `kind` is what code\n * branches on.\n */\nexport class PasskeyError extends Error {\n /** Stable, branchable classification. */\n readonly kind: PasskeyErrorKind;\n\n /**\n * Build a classified passkey error.\n *\n * @param kind - The classification a UI branches on.\n * @param message - English, user-safe explanation.\n * @param cause - The original thrown value, when there was one.\n */\n constructor(kind: PasskeyErrorKind, message: string, cause?: unknown) {\n super(message);\n this.name = \"PasskeyError\";\n this.kind = kind;\n this.cause = cause;\n }\n}\n\n/**\n * Minimal subset of `navigator.credentials` the passkey client touches.\n *\n * Declared here — the `<X>Like` pattern the SDK's adapters use — for two reasons:\n * jsdom has no `navigator.credentials` at all, so tests must inject a double; and\n * `mediation: \"conditional\"` is newer than some TypeScript DOM libs, which would\n * otherwise reject the call that makes autofill work.\n */\nexport interface CredentialsContainerLike {\n /** Runs the registration ceremony. */\n create(options: {\n publicKey: PublicKeyCredentialCreationOptions;\n signal?: AbortSignal;\n }): Promise<Credential | null>;\n /** Runs the authentication ceremony. */\n get(options: {\n publicKey: PublicKeyCredentialRequestOptions;\n signal?: AbortSignal;\n mediation?: string;\n }): Promise<Credential | null>;\n}\n\n/** How the browser should surface the authentication ceremony. */\nexport type PasskeyMediation = \"optional\" | \"conditional\" | \"required\" | \"silent\";\n\n/**\n * Server-issued registration options, in the base64url JSON shape every WebAuthn\n * backend speaks (`PublicKeyCredentialCreationOptionsJSON` in the spec).\n *\n * `challenge`, `user.id` and every `excludeCredentials[].id` are **base64url**\n * strings here and `ArrayBuffer`s in the DOM API. Converting them is the plumbing\n * this client owns.\n */\nexport interface PasskeyCreationOptionsJSON {\n /** Base64url server challenge. Single-use; the server must remember it. */\n challenge: string;\n /** Relying party. `id` defaults to the client's `rpId`, then to the origin. */\n rp: { name: string; id?: string };\n /** The account. `id` is base64url of an opaque, stable user handle. */\n user: { id: string; name: string; displayName: string };\n /** Allowed COSE algorithms. Defaults to {@link DEFAULT_PUB_KEY_CRED_PARAMS}. */\n pubKeyCredParams?: { type: \"public-key\"; alg: number }[];\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Credentials this user already has, so the authenticator refuses a duplicate. */\n excludeCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Resident-key / user-verification / attachment requirements. */\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n /** Attestation conveyance. Leave unset (`\"none\"`) unless you verify it. */\n attestation?: AttestationConveyancePreference;\n /** Client extension inputs (`credProps`, `largeBlob`, …). */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** Server-issued authentication options, base64url JSON. */\nexport interface PasskeyRequestOptionsJSON {\n /** Base64url server challenge. */\n challenge: string;\n /** Relying party id. Defaults to the client's `rpId`, then to the origin. */\n rpId?: string;\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Restrict to these credentials. **Omit it** for usernameless / autofill flows. */\n allowCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Whether the authenticator must verify the user (biometric / PIN). */\n userVerification?: UserVerificationRequirement;\n /** Client extension inputs. */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** What the client sends to the backend to finish registration. */\nexport interface PasskeyRegistrationJSON {\n /** Base64url credential id. */\n id: string;\n /** Same bytes as `id`; both are sent because servers differ on which they read. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` (this device) or `\"cross-platform\"` (a phone or key). */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data — the server re-checks challenge, origin and type. */\n clientDataJSON: string;\n /** Base64url attestation object, holding the new public key. */\n attestationObject: string;\n /** Transports the authenticator advertises, when the browser exposes them. */\n transports?: string[];\n /** COSE algorithm of the new key, when the browser exposes it. */\n publicKeyAlgorithm?: number;\n /** Base64url SPKI public key, when the browser exposes it. */\n publicKey?: string;\n /** Base64url authenticator data, when the browser exposes it. */\n authenticatorData?: string;\n };\n /** Extension outputs — `credProps.rk` tells you whether it is discoverable. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** What the client sends to the backend to finish authentication. */\nexport interface PasskeyAuthenticationJSON {\n /** Base64url credential id — the server looks up the stored public key by it. */\n id: string;\n /** Same bytes as `id`. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` or `\"cross-platform\"`. */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data. */\n clientDataJSON: string;\n /** Base64url authenticator data, carrying the signature counter. */\n authenticatorData: string;\n /** Base64url signature over `authenticatorData || sha256(clientDataJSON)`. */\n signature: string;\n /** Base64url user handle — present on discoverable credentials, else null. */\n userHandle: string | null;\n };\n /** Extension outputs. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** Per-call knobs for {@link PasskeyClient.register}. */\nexport interface PasskeyRegisterInit {\n /** Cancel the ceremony (closes the browser sheet). */\n signal?: AbortSignal;\n}\n\n/** Per-call knobs for {@link PasskeyClient.authenticate}. */\nexport interface PasskeyAuthenticateInit extends PasskeyRegisterInit {\n /**\n * `\"conditional\"` is the autofill flow: no modal, the browser offers passkeys\n * inside a field marked `autocomplete=\"webauthn\"`. Requires a `signal`, and\n * only one conditional request may be live per page.\n */\n mediation?: PasskeyMediation;\n}\n\n/** Framework-free WebAuthn client. Build one with {@link createPasskeyClient}. */\nexport interface PasskeyClient {\n /** Run the registration ceremony and return the JSON your backend verifies. */\n register(\n options: PasskeyCreationOptionsJSON,\n init?: PasskeyRegisterInit,\n ): Promise<PasskeyRegistrationJSON>;\n /** Run the authentication ceremony and return the JSON your backend verifies. */\n authenticate(\n options: PasskeyRequestOptionsJSON,\n init?: PasskeyAuthenticateInit,\n ): Promise<PasskeyAuthenticationJSON>;\n /**\n * Whether this client can run a ceremony at all — the WebAuthn API exists, or a\n * `credentials` container was injected.\n */\n isSupported(): boolean;\n /** Whether this device has a built-in authenticator (Face ID, Hello, …). */\n isPlatformAuthenticatorAvailable(): Promise<boolean>;\n /** Whether autofill-driven (`\"conditional\"`) requests are available. */\n isConditionalMediationAvailable(): Promise<boolean>;\n}\n\n/** Options for {@link createPasskeyClient}. */\nexport interface CreatePasskeyClientOptions {\n /**\n * Default relying-party id, applied when the server options omit one. Must be\n * the page's domain or a registrable parent of it (`app.acme.com` may use\n * `acme.com`, never the other way round).\n */\n rpId?: string;\n /** Default ceremony timeout in ms. Default `60_000`. */\n timeoutMs?: number;\n /** `navigator.credentials` replacement, for tests. */\n credentials?: CredentialsContainerLike;\n}\n\n/**\n * COSE algorithms offered when the server sends no `pubKeyCredParams`, in\n * preference order.\n *\n * `-8` is Ed25519, which modern authenticators prefer and which produces the\n * smallest signatures. `-7` is ES256, the one algorithm every WebAuthn\n * authenticator supports. `-257` is RS256, needed for TPM-backed Windows Hello.\n * Offering all three is what avoids a `NotSupportedError` on some device you do\n * not own; a server that cannot verify one of them should send its own list.\n */\nexport const DEFAULT_PUB_KEY_CRED_PARAMS: { type: \"public-key\"; alg: number }[] = [\n { type: \"public-key\", alg: -8 },\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n];\n\n/** Static members of `PublicKeyCredential` that are not in every DOM lib yet. */\ninterface PublicKeyCredentialStatics {\n isUserVerifyingPlatformAuthenticatorAvailable?: () => Promise<boolean>;\n isConditionalMediationAvailable?: () => Promise<boolean>;\n}\n\n/** The browser-supplied extras on an attestation response, all optional. */\ninterface AttestationExtras {\n getTransports?: () => string[];\n getPublicKey?: () => ArrayBuffer | null;\n getPublicKeyAlgorithm?: () => number;\n getAuthenticatorData?: () => ArrayBuffer;\n}\n\nfunction publicKeyCredentialStatics(): PublicKeyCredentialStatics | undefined {\n return (globalThis as { PublicKeyCredential?: PublicKeyCredentialStatics }).PublicKeyCredential;\n}\n\n/**\n * Decode a base64url string into bytes.\n *\n * WebAuthn transports every binary field as base64url (`-`/`_`, no padding)\n * because that is what survives JSON, while the DOM API insists on\n * `ArrayBuffer`. Getting this pair wrong — usually by feeding plain base64 to\n * `atob` and losing the last byte — is the classic broken-WebAuthn bug, which is\n * why the SDK owns it instead of leaving it to each app.\n *\n * This is the WebAuthn-facing name for {@link base64ToBytes}; the codec itself is\n * shared, so the padding rule has one implementation rather than three.\n *\n * @param value - Base64url text, with or without `=` padding.\n * @returns The decoded bytes.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n return base64ToBytes(value);\n}\n\n/**\n * Encode bytes as an unpadded base64url string.\n *\n * Normalises `ArrayBuffer` to a view — which is what the WebAuthn response\n * fields hand over — and delegates the encoding to {@link bytesToBase64}.\n *\n * @param value - Bytes to encode, as a view or a raw buffer.\n * @returns Base64url text, safe to put in JSON and in a URL.\n */\nexport function bytesToBase64Url(value: ArrayBuffer | Uint8Array): string {\n const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);\n return bytesToBase64(bytes, { urlSafe: true });\n}\n\n/**\n * Whether this browser exposes WebAuthn at all.\n *\n * Note that \"supported\" is not \"usable\": WebAuthn also requires a secure context,\n * and a device may have no authenticator. Use\n * {@link isPlatformAuthenticatorAvailable} before offering a passkey button.\n */\nexport function isPasskeySupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.credentials !== undefined &&\n typeof navigator.credentials.create === \"function\" &&\n publicKeyCredentialStatics() !== undefined\n );\n}\n\n/**\n * Whether the device has a **built-in** authenticator — Face ID, Touch ID,\n * Windows Hello, an Android screen lock.\n *\n * This is the check that decides whether \"Entrar com passkey\" may be shown at\n * all. `isPasskeySupported()` is true on a desktop with no biometrics and no\n * security key, and offering a passkey there sends the user into a sheet that can\n * only be cancelled. A `false` here does not forbid passkeys — a phone can still\n * be used over hybrid/QR — it means the flow needs a second step, so present it\n * as \"usar meu celular\", not as one tap.\n *\n * @returns `false` when the API is missing, so a caller never has to null-check.\n */\nexport async function isPlatformAuthenticatorAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isUserVerifyingPlatformAuthenticatorAvailable) return false;\n try {\n return await statics.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Whether autofill-driven passkeys (`mediation: \"conditional\"`) are available.\n *\n * @returns `false` when the API is missing or throws.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isConditionalMediationAvailable) return false;\n try {\n return await statics.isConditionalMediationAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Map a thrown WebAuthn failure onto a {@link PasskeyError}.\n *\n * The secure-context check runs first for the same reason it does in the media\n * classifier: over plain HTTP the whole API is absent or refuses, and reporting\n * \"not supported\" sends a developer hunting for a polyfill for something an\n * `https://` URL fixes.\n *\n * @param error - Whatever `navigator.credentials` rejected with.\n * @param ceremony - Which ceremony was running, for the message.\n * @returns The classified error, ready to throw or to show.\n */\nexport function classifyPasskeyError(error: unknown, ceremony: PasskeyCeremony): PasskeyError {\n if (error instanceof PasskeyError) return error;\n\n if (typeof window !== \"undefined\" && !window.isSecureContext) {\n return new PasskeyError(\"insecure\", \"Passkeys require a secure (HTTPS) connection.\", error);\n }\n\n if (error instanceof DOMException) {\n switch (error.name) {\n case \"NotAllowedError\":\n return new PasskeyError(\n \"cancelled\",\n \"The passkey prompt was dismissed or timed out. The browser does not say which — it must not reveal whether a credential exists.\",\n error,\n );\n case \"InvalidStateError\":\n return new PasskeyError(\n \"already-registered\",\n \"This device already has a passkey for this account. Sign in with it instead of creating another.\",\n error,\n );\n case \"NotSupportedError\":\n return new PasskeyError(\n \"not-supported\",\n \"No authenticator here supports the requested algorithms. Check the server's pubKeyCredParams.\",\n error,\n );\n case \"SecurityError\":\n return new PasskeyError(\n \"rp-mismatch\",\n \"The relying-party id does not match this origin. rp.id must be the page's domain or a registrable parent of it.\",\n error,\n );\n case \"AbortError\":\n return new PasskeyError(\"aborted\", \"The passkey request was aborted.\", error);\n }\n }\n\n if (error instanceof TypeError) {\n return new PasskeyError(\n \"invalid-options\",\n `The ${ceremony} options the server sent are malformed. Check that challenge, user.id and credential ids are base64url.`,\n error,\n );\n }\n\n return new PasskeyError(\n \"unknown\",\n error instanceof Error\n ? error.message\n : `Unexpected error during the passkey ${ceremony} ceremony.`,\n error,\n );\n}\n\nfunction toDescriptors(\n list: { id: string; type: \"public-key\"; transports?: string[] }[] | undefined,\n): PublicKeyCredentialDescriptor[] | undefined {\n if (!list) return undefined;\n return list.map((item) => ({\n id: base64UrlToBytes(item.id) as unknown as BufferSource,\n type: item.type,\n transports: item.transports as AuthenticatorTransport[] | undefined,\n }));\n}\n\n/**\n * Build a WebAuthn client: the base64url ↔ `ArrayBuffer` plumbing, the two\n * ceremonies, and one classified error type.\n *\n * ## What your backend must do\n *\n * This is the **client half only**, and a WebAuthn client that documents only its\n * own half is unusable. Four routes are yours to implement:\n *\n * 1. `POST /webauthn/register/begin` → a {@link PasskeyCreationOptionsJSON}. Mint a\n * random `challenge` (≥16 bytes), store it against the session, and list the\n * user's existing credentials in `excludeCredentials`.\n * 2. `POST /webauthn/register/finish` ← a {@link PasskeyRegistrationJSON}. Verify\n * the challenge, `origin` and `type` inside `clientDataJSON`, parse the\n * attestation object, then store the credential id, public key and signature\n * counter.\n * 3. `POST /webauthn/signin/begin` → a {@link PasskeyRequestOptionsJSON}. New\n * challenge. Omit `allowCredentials` for a usernameless or autofill flow.\n * 4. `POST /webauthn/signin/finish` ← a {@link PasskeyAuthenticationJSON}. Look the\n * credential up by `id`, verify the signature over\n * `authenticatorData || sha256(clientDataJSON)`, and reject a signature counter\n * that did not grow (a clone). Only then issue your session token.\n *\n * @param options - Defaults applied when the server options omit them.\n * @returns A client usable from anywhere — React, a plain form, a worker.\n *\n * @example\n * const passkeys = createPasskeyClient({ rpId: \"acme.com\" });\n *\n * const options = await api.post(\"/webauthn/register/begin\");\n * const credential = await passkeys.register(options);\n * await api.post(\"/webauthn/register/finish\", { body: credential });\n */\nexport function createPasskeyClient(options: CreatePasskeyClientOptions = {}): PasskeyClient {\n const { rpId, timeoutMs = 60_000, credentials } = options;\n\n function container(): CredentialsContainerLike {\n if (credentials) return credentials;\n if (!isPasskeySupported()) {\n throw new PasskeyError(\n \"unsupported\",\n typeof window !== \"undefined\" && !window.isSecureContext\n ? \"Passkeys require a secure (HTTPS) connection.\"\n : \"This browser does not support passkeys (WebAuthn).\",\n );\n }\n return navigator.credentials as unknown as CredentialsContainerLike;\n }\n\n async function register(\n json: PasskeyCreationOptionsJSON,\n init: PasskeyRegisterInit = {},\n ): Promise<PasskeyRegistrationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialCreationOptions = {\n challenge: base64UrlToBytes(json.challenge) as unknown as BufferSource,\n rp: { name: json.rp.name, id: json.rp.id ?? rpId },\n user: {\n id: base64UrlToBytes(json.user.id) as unknown as BufferSource,\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams ?? DEFAULT_PUB_KEY_CRED_PARAMS,\n timeout: json.timeout ?? timeoutMs,\n excludeCredentials: toDescriptors(json.excludeCredentials),\n authenticatorSelection: json.authenticatorSelection,\n attestation: json.attestation,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.create({ publicKey, signal: init.signal });\n } catch (error) {\n throw classifyPasskeyError(error, \"register\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAttestationResponse & AttestationExtras;\n const publicKeyBytes = response.getPublicKey?.();\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n transports: response.getTransports?.(),\n publicKeyAlgorithm: response.getPublicKeyAlgorithm?.(),\n publicKey: publicKeyBytes ? bytesToBase64Url(publicKeyBytes) : undefined,\n authenticatorData: response.getAuthenticatorData\n ? bytesToBase64Url(response.getAuthenticatorData())\n : undefined,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n async function authenticate(\n json: PasskeyRequestOptionsJSON,\n init: PasskeyAuthenticateInit = {},\n ): Promise<PasskeyAuthenticationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialRequestOptions = {\n challenge: base64UrlToBytes(json.challenge) as unknown as BufferSource,\n rpId: json.rpId ?? rpId,\n timeout: json.timeout ?? timeoutMs,\n allowCredentials: toDescriptors(json.allowCredentials),\n userVerification: json.userVerification,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.get({\n publicKey,\n signal: init.signal,\n mediation: init.mediation,\n });\n } catch (error) {\n throw classifyPasskeyError(error, \"authenticate\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAssertionResponse;\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n return {\n register,\n authenticate,\n isSupported: () => credentials !== undefined || isPasskeySupported(),\n isPlatformAuthenticatorAvailable,\n isConditionalMediationAvailable,\n };\n}\n"],"mappings":"uCAkDA,IAAa,EAAb,cAAkC,KAAM,CAEpC,KASA,YAAY,EAAwB,EAAiB,EAAiB,CAClE,MAAM,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,KAAO,EACZ,KAAK,MAAQ,CACjB,CACJ,EAyLa,EAAqE,CAC9E,CAAE,KAAM,aAAc,IAAK,EAAG,EAC9B,CAAE,KAAM,aAAc,IAAK,EAAG,EAC9B,CAAE,KAAM,aAAc,IAAK,IAAK,CACpC,EAgBA,SAAS,GAAqE,CAC1E,OAAQ,WAAoE,mBAChF,CAiBA,SAAgB,EAAiB,EAAwC,CACrE,OAAO,EAAA,cAAc,CAAK,CAC9B,CAWA,SAAgB,EAAiB,EAAyC,CACtE,IAAM,EAAQ,aAAiB,WAAa,EAAQ,IAAI,WAAW,CAAK,EACxE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BAAoB,EAAS,wBAAwB,EACrD,UAAW,EAAiB,EAAiB,CAAc,EAAI,IAAA,GAC/D,kBAAmB,EAAS,qBACtB,EAAiB,EAAS,qBAAqB,CAAC,EAChD,IAAA,EACV,EACA,uBAAwB,EAAM,0BAA0B,CAC5D,CACJ,CAEA,eAAe,EACX,EACA,EAAgC,CAAC,EACC,CAClC,IAAM,EAAM,EAAU,EAChB,EAA+C,CACjD,UAAW,EAAiB,EAAK,SAAS,EAC1C,KAAM,EAAK,MAAQ,EACnB,QAAS,EAAK,SAAW,EACzB,iBAAkB,EAAc,EAAK,gBAAgB,EACrD,iBAAkB,EAAK,iBACvB,WAAY,EAAK,UACrB,EAEI,EACJ,GAAI,CACA,EAAa,MAAM,EAAI,IAAI,CACvB,YACA,OAAQ,EAAK,OACb,UAAW,EAAK,SACpB,CAAC,CACL,OAAS,EAAO,CACZ,MAAM,EAAqB,EAAO,cAAc,CACpD,CACA,GAAI,CAAC,EACD,MAAM,IAAI,EAAa,UAAW,2CAA2C,EAGjF,IAAM,EAAQ,EACR,EAAW,EAAM,SAEvB,MAAO,CACH,GAAI,EAAM,GACV,MAAO,EAAiB,EAAM,KAAK,EACnC,KAAM,aACN,wBAAyB,EAAM,yBAA2B,KAC1D,SAAU,CACN,eAAgB,EAAiB,EAAS,cAAc,EACxD,kBAAmB,EAAiB,EAAS,iBAAiB,EAC9D,UAAW,EAAiB,EAAS,SAAS,EAC9C,WAAY,EAAS,WAAa,EAAiB,EAAS,UAAU,EAAI,IAC9E,EACA,uBAAwB,EAAM,0BAA0B,CAC5D,CACJ,CAEA,MAAO,CACH,WACA,eACA,gBAAmB,IAAgB,IAAA,IAAa,EAAmB,EACnE,mCACA,iCACJ,CACJ"}
1
+ {"version":3,"file":"passkey.cjs","names":[],"sources":["../../src/auth/passkey.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — the WebAuthn client half: the JSON\n * shapes both ceremonies exchange with a backend, base64url ↔ ArrayBuffer, the\n * capability probes and the error classifier. The two ceremonies are near-mirrors\n * that must not drift — register and authenticate encode the same credential fields\n * in the same order — and the file's docstring is also the specification of the four\n * backend routes it expects.\n */\n\nimport { base64ToBytes, bytesToBase64 } from \"@/utils/base64\";\n\n/**\n * Classified reason a passkey ceremony did not produce a credential.\n *\n * The kinds group the raw `DOMException.name` values the way a UI has to branch\n * on them, which is *not* how the spec groups them:\n *\n * - `\"cancelled\"` covers `NotAllowedError`, which the browser raises both when\n * the user dismissed the sheet and when the ceremony timed out. They are\n * indistinguishable **by design** — telling a site \"the user has no credential\n * for you\" would leak account existence — so a UI must treat them as one thing.\n * - `\"already-registered\"` (`InvalidStateError`) is not really a failure: this\n * device already holds a credential for this user. The correct reaction is\n * \"you are already set up on this device\", never a red error.\n * - `\"rp-mismatch\"` (`SecurityError`) is the single most common integration bug:\n * `rp.id` must equal the page's domain or a registrable parent of it.\n */\nexport type PasskeyErrorKind =\n | \"unsupported\"\n | \"insecure\"\n | \"cancelled\"\n | \"already-registered\"\n | \"not-supported\"\n | \"rp-mismatch\"\n | \"invalid-options\"\n | \"aborted\"\n | \"unknown\";\n\n/** Which ceremony was running, so the message can name it. */\nexport type PasskeyCeremony = \"register\" | \"authenticate\";\n\n/**\n * A passkey failure carrying a stable {@link PasskeyErrorKind} plus an English\n * message safe to show a user.\n *\n * A class rather than the plain `{ kind, message }` object the media classifier\n * returns, because these surface by rejecting a promise: an `Error` subclass keeps\n * stack traces, `instanceof` checks and logging intact, and `kind` is what code\n * branches on.\n */\nexport class PasskeyError extends Error {\n /** Stable, branchable classification. */\n readonly kind: PasskeyErrorKind;\n\n /**\n * Build a classified passkey error.\n *\n * @param kind - The classification a UI branches on.\n * @param message - English, user-safe explanation.\n * @param cause - The original thrown value, when there was one.\n */\n constructor(kind: PasskeyErrorKind, message: string, cause?: unknown) {\n super(message);\n this.name = \"PasskeyError\";\n this.kind = kind;\n this.cause = cause;\n }\n}\n\n/**\n * Minimal subset of `navigator.credentials` the passkey client touches.\n *\n * Declared here — the `<X>Like` pattern the SDK's adapters use — for two reasons:\n * jsdom has no `navigator.credentials` at all, so tests must inject a double; and\n * `mediation: \"conditional\"` is newer than some TypeScript DOM libs, which would\n * otherwise reject the call that makes autofill work.\n */\nexport interface CredentialsContainerLike {\n /** Runs the registration ceremony. */\n create(options: {\n publicKey: PublicKeyCredentialCreationOptions;\n signal?: AbortSignal;\n }): Promise<Credential | null>;\n /** Runs the authentication ceremony. */\n get(options: {\n publicKey: PublicKeyCredentialRequestOptions;\n signal?: AbortSignal;\n mediation?: string;\n }): Promise<Credential | null>;\n}\n\n/** How the browser should surface the authentication ceremony. */\nexport type PasskeyMediation = \"optional\" | \"conditional\" | \"required\" | \"silent\";\n\n/**\n * Server-issued registration options, in the base64url JSON shape every WebAuthn\n * backend speaks (`PublicKeyCredentialCreationOptionsJSON` in the spec).\n *\n * `challenge`, `user.id` and every `excludeCredentials[].id` are **base64url**\n * strings here and `ArrayBuffer`s in the DOM API. Converting them is the plumbing\n * this client owns.\n */\nexport interface PasskeyCreationOptionsJSON {\n /** Base64url server challenge. Single-use; the server must remember it. */\n challenge: string;\n /** Relying party. `id` defaults to the client's `rpId`, then to the origin. */\n rp: { name: string; id?: string };\n /** The account. `id` is base64url of an opaque, stable user handle. */\n user: { id: string; name: string; displayName: string };\n /** Allowed COSE algorithms. Defaults to {@link DEFAULT_PUB_KEY_CRED_PARAMS}. */\n pubKeyCredParams?: { type: \"public-key\"; alg: number }[];\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Credentials this user already has, so the authenticator refuses a duplicate. */\n excludeCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Resident-key / user-verification / attachment requirements. */\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n /** Attestation conveyance. Leave unset (`\"none\"`) unless you verify it. */\n attestation?: AttestationConveyancePreference;\n /** Client extension inputs (`credProps`, `largeBlob`, …). */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** Server-issued authentication options, base64url JSON. */\nexport interface PasskeyRequestOptionsJSON {\n /** Base64url server challenge. */\n challenge: string;\n /** Relying party id. Defaults to the client's `rpId`, then to the origin. */\n rpId?: string;\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Restrict to these credentials. **Omit it** for usernameless / autofill flows. */\n allowCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Whether the authenticator must verify the user (biometric / PIN). */\n userVerification?: UserVerificationRequirement;\n /** Client extension inputs. */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** What the client sends to the backend to finish registration. */\nexport interface PasskeyRegistrationJSON {\n /** Base64url credential id. */\n id: string;\n /** Same bytes as `id`; both are sent because servers differ on which they read. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` (this device) or `\"cross-platform\"` (a phone or key). */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data — the server re-checks challenge, origin and type. */\n clientDataJSON: string;\n /** Base64url attestation object, holding the new public key. */\n attestationObject: string;\n /** Transports the authenticator advertises, when the browser exposes them. */\n transports?: string[];\n /** COSE algorithm of the new key, when the browser exposes it. */\n publicKeyAlgorithm?: number;\n /** Base64url SPKI public key, when the browser exposes it. */\n publicKey?: string;\n /** Base64url authenticator data, when the browser exposes it. */\n authenticatorData?: string;\n };\n /** Extension outputs — `credProps.rk` tells you whether it is discoverable. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** What the client sends to the backend to finish authentication. */\nexport interface PasskeyAuthenticationJSON {\n /** Base64url credential id — the server looks up the stored public key by it. */\n id: string;\n /** Same bytes as `id`. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` or `\"cross-platform\"`. */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data. */\n clientDataJSON: string;\n /** Base64url authenticator data, carrying the signature counter. */\n authenticatorData: string;\n /** Base64url signature over `authenticatorData || sha256(clientDataJSON)`. */\n signature: string;\n /** Base64url user handle — present on discoverable credentials, else null. */\n userHandle: string | null;\n };\n /** Extension outputs. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** Per-call knobs for {@link PasskeyClient.register}. */\nexport interface PasskeyRegisterInit {\n /** Cancel the ceremony (closes the browser sheet). */\n signal?: AbortSignal;\n}\n\n/** Per-call knobs for {@link PasskeyClient.authenticate}. */\nexport interface PasskeyAuthenticateInit extends PasskeyRegisterInit {\n /**\n * `\"conditional\"` is the autofill flow: no modal, the browser offers passkeys\n * inside a field marked `autocomplete=\"webauthn\"`. Requires a `signal`, and\n * only one conditional request may be live per page.\n */\n mediation?: PasskeyMediation;\n}\n\n/** Framework-free WebAuthn client. Build one with {@link createPasskeyClient}. */\nexport interface PasskeyClient {\n /** Run the registration ceremony and return the JSON your backend verifies. */\n register(\n options: PasskeyCreationOptionsJSON,\n init?: PasskeyRegisterInit,\n ): Promise<PasskeyRegistrationJSON>;\n /** Run the authentication ceremony and return the JSON your backend verifies. */\n authenticate(\n options: PasskeyRequestOptionsJSON,\n init?: PasskeyAuthenticateInit,\n ): Promise<PasskeyAuthenticationJSON>;\n /**\n * Whether this client can run a ceremony at all — the WebAuthn API exists, or a\n * `credentials` container was injected.\n */\n isSupported(): boolean;\n /** Whether this device has a built-in authenticator (Face ID, Hello, …). */\n isPlatformAuthenticatorAvailable(): Promise<boolean>;\n /** Whether autofill-driven (`\"conditional\"`) requests are available. */\n isConditionalMediationAvailable(): Promise<boolean>;\n}\n\n/** Options for {@link createPasskeyClient}. */\nexport interface CreatePasskeyClientOptions {\n /**\n * Default relying-party id, applied when the server options omit one. Must be\n * the page's domain or a registrable parent of it (`app.acme.com` may use\n * `acme.com`, never the other way round).\n */\n rpId?: string;\n /** Default ceremony timeout in ms. Default `60_000`. */\n timeoutMs?: number;\n /** `navigator.credentials` replacement, for tests. */\n credentials?: CredentialsContainerLike;\n}\n\n/**\n * COSE algorithms offered when the server sends no `pubKeyCredParams`, in\n * preference order.\n *\n * `-8` is Ed25519, which modern authenticators prefer and which produces the\n * smallest signatures. `-7` is ES256, the one algorithm every WebAuthn\n * authenticator supports. `-257` is RS256, needed for TPM-backed Windows Hello.\n * Offering all three is what avoids a `NotSupportedError` on some device you do\n * not own; a server that cannot verify one of them should send its own list.\n */\nexport const DEFAULT_PUB_KEY_CRED_PARAMS: { type: \"public-key\"; alg: number }[] = [\n { type: \"public-key\", alg: -8 },\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n];\n\n/** Static members of `PublicKeyCredential` that are not in every DOM lib yet. */\ninterface PublicKeyCredentialStatics {\n isUserVerifyingPlatformAuthenticatorAvailable?: () => Promise<boolean>;\n isConditionalMediationAvailable?: () => Promise<boolean>;\n}\n\n/** The browser-supplied extras on an attestation response, all optional. */\ninterface AttestationExtras {\n getTransports?: () => string[];\n getPublicKey?: () => ArrayBuffer | null;\n getPublicKeyAlgorithm?: () => number;\n getAuthenticatorData?: () => ArrayBuffer;\n}\n\nfunction publicKeyCredentialStatics(): PublicKeyCredentialStatics | undefined {\n return (globalThis as { PublicKeyCredential?: PublicKeyCredentialStatics }).PublicKeyCredential;\n}\n\n/**\n * Decode a base64url string into bytes.\n *\n * WebAuthn transports every binary field as base64url (`-`/`_`, no padding)\n * because that is what survives JSON, while the DOM API insists on\n * `ArrayBuffer`. Getting this pair wrong — usually by feeding plain base64 to\n * `atob` and losing the last byte — is the classic broken-WebAuthn bug, which is\n * why the SDK owns it instead of leaving it to each app.\n *\n * This is the WebAuthn-facing name for {@link base64ToBytes}; the codec itself is\n * shared, so the padding rule has one implementation rather than three.\n *\n * @param value - Base64url text, with or without `=` padding.\n * @returns The decoded bytes.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n return base64ToBytes(value);\n}\n\n/**\n * Encode bytes as an unpadded base64url string.\n *\n * Normalises `ArrayBuffer` to a view — which is what the WebAuthn response\n * fields hand over — and delegates the encoding to {@link bytesToBase64}.\n *\n * @param value - Bytes to encode, as a view or a raw buffer.\n * @returns Base64url text, safe to put in JSON and in a URL.\n */\nexport function bytesToBase64Url(value: ArrayBuffer | Uint8Array): string {\n const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);\n return bytesToBase64(bytes, { urlSafe: true });\n}\n\n/**\n * Whether this browser exposes WebAuthn at all.\n *\n * Note that \"supported\" is not \"usable\": WebAuthn also requires a secure context,\n * and a device may have no authenticator. Use\n * {@link isPlatformAuthenticatorAvailable} before offering a passkey button.\n */\nexport function isPasskeySupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.credentials !== undefined &&\n typeof navigator.credentials.create === \"function\" &&\n publicKeyCredentialStatics() !== undefined\n );\n}\n\n/**\n * Whether the device has a **built-in** authenticator — Face ID, Touch ID,\n * Windows Hello, an Android screen lock.\n *\n * This is the check that decides whether \"Entrar com passkey\" may be shown at\n * all. `isPasskeySupported()` is true on a desktop with no biometrics and no\n * security key, and offering a passkey there sends the user into a sheet that can\n * only be cancelled. A `false` here does not forbid passkeys — a phone can still\n * be used over hybrid/QR — it means the flow needs a second step, so present it\n * as \"usar meu celular\", not as one tap.\n *\n * @returns `false` when the API is missing, so a caller never has to null-check.\n */\nexport async function isPlatformAuthenticatorAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isUserVerifyingPlatformAuthenticatorAvailable) return false;\n try {\n return await statics.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Whether autofill-driven passkeys (`mediation: \"conditional\"`) are available.\n *\n * @returns `false` when the API is missing or throws.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isConditionalMediationAvailable) return false;\n try {\n return await statics.isConditionalMediationAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Map a thrown WebAuthn failure onto a {@link PasskeyError}.\n *\n * The secure-context check runs first for the same reason it does in the media\n * classifier: over plain HTTP the whole API is absent or refuses, and reporting\n * \"not supported\" sends a developer hunting for a polyfill for something an\n * `https://` URL fixes.\n *\n * @param error - Whatever `navigator.credentials` rejected with.\n * @param ceremony - Which ceremony was running, for the message.\n * @returns The classified error, ready to throw or to show.\n */\nexport function classifyPasskeyError(error: unknown, ceremony: PasskeyCeremony): PasskeyError {\n if (error instanceof PasskeyError) return error;\n\n if (typeof window !== \"undefined\" && !window.isSecureContext) {\n return new PasskeyError(\"insecure\", \"Passkeys require a secure (HTTPS) connection.\", error);\n }\n\n if (error instanceof DOMException) {\n switch (error.name) {\n case \"NotAllowedError\":\n return new PasskeyError(\n \"cancelled\",\n \"The passkey prompt was dismissed or timed out. The browser does not say which — it must not reveal whether a credential exists.\",\n error,\n );\n case \"InvalidStateError\":\n return new PasskeyError(\n \"already-registered\",\n \"This device already has a passkey for this account. Sign in with it instead of creating another.\",\n error,\n );\n case \"NotSupportedError\":\n return new PasskeyError(\n \"not-supported\",\n \"No authenticator here supports the requested algorithms. Check the server's pubKeyCredParams.\",\n error,\n );\n case \"SecurityError\":\n return new PasskeyError(\n \"rp-mismatch\",\n \"The relying-party id does not match this origin. rp.id must be the page's domain or a registrable parent of it.\",\n error,\n );\n case \"AbortError\":\n return new PasskeyError(\"aborted\", \"The passkey request was aborted.\", error);\n }\n }\n\n if (error instanceof TypeError) {\n return new PasskeyError(\n \"invalid-options\",\n `The ${ceremony} options the server sent are malformed. Check that challenge, user.id and credential ids are base64url.`,\n error,\n );\n }\n\n return new PasskeyError(\n \"unknown\",\n error instanceof Error\n ? error.message\n : `Unexpected error during the passkey ${ceremony} ceremony.`,\n error,\n );\n}\n\nfunction toDescriptors(\n list: { id: string; type: \"public-key\"; transports?: string[] }[] | undefined,\n): PublicKeyCredentialDescriptor[] | undefined {\n if (!list) return undefined;\n return list.map((item) => ({\n id: base64UrlToBytes(item.id),\n type: item.type,\n transports: item.transports as AuthenticatorTransport[] | undefined,\n }));\n}\n\n/**\n * Build a WebAuthn client: the base64url ↔ `ArrayBuffer` plumbing, the two\n * ceremonies, and one classified error type.\n *\n * ## What your backend must do\n *\n * This is the **client half only**, and a WebAuthn client that documents only its\n * own half is unusable. Four routes are yours to implement:\n *\n * 1. `POST /webauthn/register/begin` → a {@link PasskeyCreationOptionsJSON}. Mint a\n * random `challenge` (≥16 bytes), store it against the session, and list the\n * user's existing credentials in `excludeCredentials`.\n * 2. `POST /webauthn/register/finish` ← a {@link PasskeyRegistrationJSON}. Verify\n * the challenge, `origin` and `type` inside `clientDataJSON`, parse the\n * attestation object, then store the credential id, public key and signature\n * counter.\n * 3. `POST /webauthn/signin/begin` → a {@link PasskeyRequestOptionsJSON}. New\n * challenge. Omit `allowCredentials` for a usernameless or autofill flow.\n * 4. `POST /webauthn/signin/finish` ← a {@link PasskeyAuthenticationJSON}. Look the\n * credential up by `id`, verify the signature over\n * `authenticatorData || sha256(clientDataJSON)`, and reject a signature counter\n * that did not grow (a clone). Only then issue your session token.\n *\n * @param options - Defaults applied when the server options omit them.\n * @returns A client usable from anywhere — React, a plain form, a worker.\n *\n * @example\n * const passkeys = createPasskeyClient({ rpId: \"acme.com\" });\n *\n * const options = await api.post(\"/webauthn/register/begin\");\n * const credential = await passkeys.register(options);\n * await api.post(\"/webauthn/register/finish\", { body: credential });\n */\nexport function createPasskeyClient(options: CreatePasskeyClientOptions = {}): PasskeyClient {\n const { rpId, timeoutMs = 60_000, credentials } = options;\n\n function container(): CredentialsContainerLike {\n if (credentials) return credentials;\n if (!isPasskeySupported()) {\n throw new PasskeyError(\n \"unsupported\",\n typeof window !== \"undefined\" && !window.isSecureContext\n ? \"Passkeys require a secure (HTTPS) connection.\"\n : \"This browser does not support passkeys (WebAuthn).\",\n );\n }\n return navigator.credentials as unknown as CredentialsContainerLike;\n }\n\n async function register(\n json: PasskeyCreationOptionsJSON,\n init: PasskeyRegisterInit = {},\n ): Promise<PasskeyRegistrationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialCreationOptions = {\n challenge: base64UrlToBytes(json.challenge),\n rp: { name: json.rp.name, id: json.rp.id ?? rpId },\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams ?? DEFAULT_PUB_KEY_CRED_PARAMS,\n timeout: json.timeout ?? timeoutMs,\n excludeCredentials: toDescriptors(json.excludeCredentials),\n authenticatorSelection: json.authenticatorSelection,\n attestation: json.attestation,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.create({ publicKey, signal: init.signal });\n } catch (error) {\n throw classifyPasskeyError(error, \"register\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAttestationResponse & AttestationExtras;\n const publicKeyBytes = response.getPublicKey?.();\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n transports: response.getTransports?.(),\n publicKeyAlgorithm: response.getPublicKeyAlgorithm?.(),\n publicKey: publicKeyBytes ? bytesToBase64Url(publicKeyBytes) : undefined,\n authenticatorData: response.getAuthenticatorData\n ? bytesToBase64Url(response.getAuthenticatorData())\n : undefined,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n async function authenticate(\n json: PasskeyRequestOptionsJSON,\n init: PasskeyAuthenticateInit = {},\n ): Promise<PasskeyAuthenticationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialRequestOptions = {\n challenge: base64UrlToBytes(json.challenge),\n rpId: json.rpId ?? rpId,\n timeout: json.timeout ?? timeoutMs,\n allowCredentials: toDescriptors(json.allowCredentials),\n userVerification: json.userVerification,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.get({\n publicKey,\n signal: init.signal,\n mediation: init.mediation,\n });\n } catch (error) {\n throw classifyPasskeyError(error, \"authenticate\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAssertionResponse;\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n return {\n register,\n authenticate,\n isSupported: () => credentials !== undefined || isPasskeySupported(),\n isPlatformAuthenticatorAvailable,\n isConditionalMediationAvailable,\n };\n}\n"],"mappings":"uCAkDA,IAAa,EAAb,cAAkC,KAAM,CAEpC,KASA,YAAY,EAAwB,EAAiB,EAAiB,CAClE,MAAM,CAAO,EACb,KAAK,KAAO,eACZ,KAAK,KAAO,EACZ,KAAK,MAAQ,CACjB,CACJ,EAyLa,EAAqE,CAC9E,CAAE,KAAM,aAAc,IAAK,EAAG,EAC9B,CAAE,KAAM,aAAc,IAAK,EAAG,EAC9B,CAAE,KAAM,aAAc,IAAK,IAAK,CACpC,EAgBA,SAAS,GAAqE,CAC1E,OAAQ,WAAoE,mBAChF,CAiBA,SAAgB,EAAiB,EAAwC,CACrE,OAAO,EAAA,cAAc,CAAK,CAC9B,CAWA,SAAgB,EAAiB,EAAyC,CACtE,IAAM,EAAQ,aAAiB,WAAa,EAAQ,IAAI,WAAW,CAAK,EACxE,OAAO,EAAA,cAAc,EAAO,CAAE,QAAS,EAAK,CAAC,CACjD,CASA,SAAgB,GAA8B,CAC1C,OACI,OAAO,OAAW,KAClB,OAAO,UAAc,KACrB,UAAU,cAAgB,IAAA,IAC1B,OAAO,UAAU,YAAY,QAAW,YACxC,EAA2B,IAAM,IAAA,EAEzC,CAeA,eA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,EACC,CAClC,IAAM,EAAM,EAAU,EAChB,EAA+C,CACjD,UAAW,EAAiB,EAAK,SAAS,EAC1C,KAAM,EAAK,MAAQ,EACnB,QAAS,EAAK,SAAW,EACzB,iBAAkB,EAAc,EAAK,gBAAgB,EACrD,iBAAkB,EAAK,iBACvB,WAAY,EAAK,UACrB,EAEI,EACJ,GAAI,CACA,EAAa,MAAM,EAAI,IAAI,CACvB,YACA,OAAQ,EAAK,OACb,UAAW,EAAK,SACpB,CAAC,CACL,OAAS,EAAO,CACZ,MAAM,EAAqB,EAAO,cAAc,CACpD,CACA,GAAI,CAAC,EACD,MAAM,IAAI,EAAa,UAAW,2CAA2C,EAGjF,IAAM,EAAQ,EACR,EAAW,EAAM,SAEvB,MAAO,CACH,GAAI,EAAM,GACV,MAAO,EAAiB,EAAM,KAAK,EACnC,KAAM,aACN,wBAAyB,EAAM,yBAA2B,KAC1D,SAAU,CACN,eAAgB,EAAiB,EAAS,cAAc,EACxD,kBAAmB,EAAiB,EAAS,iBAAiB,EAC9D,UAAW,EAAiB,EAAS,SAAS,EAC9C,WAAY,EAAS,WAAa,EAAiB,EAAS,UAAU,EAAI,IAC9E,EACA,uBAAwB,EAAM,0BAA0B,CAC5D,CACJ,CAEA,MAAO,CACH,WACA,eACA,gBAAmB,IAAgB,IAAA,IAAa,EAAmB,EACnE,mCACA,iCACJ,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"passkey.js","names":[],"sources":["../../src/auth/passkey.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — the WebAuthn client half: the JSON\n * shapes both ceremonies exchange with a backend, base64url ↔ ArrayBuffer, the\n * capability probes and the error classifier. The two ceremonies are near-mirrors\n * that must not drift — register and authenticate encode the same credential fields\n * in the same order — and the file's docstring is also the specification of the four\n * backend routes it expects.\n */\n\nimport { base64ToBytes, bytesToBase64 } from \"@/utils/base64\";\n\n/**\n * Classified reason a passkey ceremony did not produce a credential.\n *\n * The kinds group the raw `DOMException.name` values the way a UI has to branch\n * on them, which is *not* how the spec groups them:\n *\n * - `\"cancelled\"` covers `NotAllowedError`, which the browser raises both when\n * the user dismissed the sheet and when the ceremony timed out. They are\n * indistinguishable **by design** — telling a site \"the user has no credential\n * for you\" would leak account existence — so a UI must treat them as one thing.\n * - `\"already-registered\"` (`InvalidStateError`) is not really a failure: this\n * device already holds a credential for this user. The correct reaction is\n * \"you are already set up on this device\", never a red error.\n * - `\"rp-mismatch\"` (`SecurityError`) is the single most common integration bug:\n * `rp.id` must equal the page's domain or a registrable parent of it.\n */\nexport type PasskeyErrorKind =\n | \"unsupported\"\n | \"insecure\"\n | \"cancelled\"\n | \"already-registered\"\n | \"not-supported\"\n | \"rp-mismatch\"\n | \"invalid-options\"\n | \"aborted\"\n | \"unknown\";\n\n/** Which ceremony was running, so the message can name it. */\nexport type PasskeyCeremony = \"register\" | \"authenticate\";\n\n/**\n * A passkey failure carrying a stable {@link PasskeyErrorKind} plus an English\n * message safe to show a user.\n *\n * A class rather than the plain `{ kind, message }` object the media classifier\n * returns, because these surface by rejecting a promise: an `Error` subclass keeps\n * stack traces, `instanceof` checks and logging intact, and `kind` is what code\n * branches on.\n */\nexport class PasskeyError extends Error {\n /** Stable, branchable classification. */\n readonly kind: PasskeyErrorKind;\n\n /**\n * Build a classified passkey error.\n *\n * @param kind - The classification a UI branches on.\n * @param message - English, user-safe explanation.\n * @param cause - The original thrown value, when there was one.\n */\n constructor(kind: PasskeyErrorKind, message: string, cause?: unknown) {\n super(message);\n this.name = \"PasskeyError\";\n this.kind = kind;\n this.cause = cause;\n }\n}\n\n/**\n * Minimal subset of `navigator.credentials` the passkey client touches.\n *\n * Declared here — the `<X>Like` pattern the SDK's adapters use — for two reasons:\n * jsdom has no `navigator.credentials` at all, so tests must inject a double; and\n * `mediation: \"conditional\"` is newer than some TypeScript DOM libs, which would\n * otherwise reject the call that makes autofill work.\n */\nexport interface CredentialsContainerLike {\n /** Runs the registration ceremony. */\n create(options: {\n publicKey: PublicKeyCredentialCreationOptions;\n signal?: AbortSignal;\n }): Promise<Credential | null>;\n /** Runs the authentication ceremony. */\n get(options: {\n publicKey: PublicKeyCredentialRequestOptions;\n signal?: AbortSignal;\n mediation?: string;\n }): Promise<Credential | null>;\n}\n\n/** How the browser should surface the authentication ceremony. */\nexport type PasskeyMediation = \"optional\" | \"conditional\" | \"required\" | \"silent\";\n\n/**\n * Server-issued registration options, in the base64url JSON shape every WebAuthn\n * backend speaks (`PublicKeyCredentialCreationOptionsJSON` in the spec).\n *\n * `challenge`, `user.id` and every `excludeCredentials[].id` are **base64url**\n * strings here and `ArrayBuffer`s in the DOM API. Converting them is the plumbing\n * this client owns.\n */\nexport interface PasskeyCreationOptionsJSON {\n /** Base64url server challenge. Single-use; the server must remember it. */\n challenge: string;\n /** Relying party. `id` defaults to the client's `rpId`, then to the origin. */\n rp: { name: string; id?: string };\n /** The account. `id` is base64url of an opaque, stable user handle. */\n user: { id: string; name: string; displayName: string };\n /** Allowed COSE algorithms. Defaults to {@link DEFAULT_PUB_KEY_CRED_PARAMS}. */\n pubKeyCredParams?: { type: \"public-key\"; alg: number }[];\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Credentials this user already has, so the authenticator refuses a duplicate. */\n excludeCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Resident-key / user-verification / attachment requirements. */\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n /** Attestation conveyance. Leave unset (`\"none\"`) unless you verify it. */\n attestation?: AttestationConveyancePreference;\n /** Client extension inputs (`credProps`, `largeBlob`, …). */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** Server-issued authentication options, base64url JSON. */\nexport interface PasskeyRequestOptionsJSON {\n /** Base64url server challenge. */\n challenge: string;\n /** Relying party id. Defaults to the client's `rpId`, then to the origin. */\n rpId?: string;\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Restrict to these credentials. **Omit it** for usernameless / autofill flows. */\n allowCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Whether the authenticator must verify the user (biometric / PIN). */\n userVerification?: UserVerificationRequirement;\n /** Client extension inputs. */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** What the client sends to the backend to finish registration. */\nexport interface PasskeyRegistrationJSON {\n /** Base64url credential id. */\n id: string;\n /** Same bytes as `id`; both are sent because servers differ on which they read. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` (this device) or `\"cross-platform\"` (a phone or key). */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data — the server re-checks challenge, origin and type. */\n clientDataJSON: string;\n /** Base64url attestation object, holding the new public key. */\n attestationObject: string;\n /** Transports the authenticator advertises, when the browser exposes them. */\n transports?: string[];\n /** COSE algorithm of the new key, when the browser exposes it. */\n publicKeyAlgorithm?: number;\n /** Base64url SPKI public key, when the browser exposes it. */\n publicKey?: string;\n /** Base64url authenticator data, when the browser exposes it. */\n authenticatorData?: string;\n };\n /** Extension outputs — `credProps.rk` tells you whether it is discoverable. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** What the client sends to the backend to finish authentication. */\nexport interface PasskeyAuthenticationJSON {\n /** Base64url credential id — the server looks up the stored public key by it. */\n id: string;\n /** Same bytes as `id`. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` or `\"cross-platform\"`. */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data. */\n clientDataJSON: string;\n /** Base64url authenticator data, carrying the signature counter. */\n authenticatorData: string;\n /** Base64url signature over `authenticatorData || sha256(clientDataJSON)`. */\n signature: string;\n /** Base64url user handle — present on discoverable credentials, else null. */\n userHandle: string | null;\n };\n /** Extension outputs. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** Per-call knobs for {@link PasskeyClient.register}. */\nexport interface PasskeyRegisterInit {\n /** Cancel the ceremony (closes the browser sheet). */\n signal?: AbortSignal;\n}\n\n/** Per-call knobs for {@link PasskeyClient.authenticate}. */\nexport interface PasskeyAuthenticateInit extends PasskeyRegisterInit {\n /**\n * `\"conditional\"` is the autofill flow: no modal, the browser offers passkeys\n * inside a field marked `autocomplete=\"webauthn\"`. Requires a `signal`, and\n * only one conditional request may be live per page.\n */\n mediation?: PasskeyMediation;\n}\n\n/** Framework-free WebAuthn client. Build one with {@link createPasskeyClient}. */\nexport interface PasskeyClient {\n /** Run the registration ceremony and return the JSON your backend verifies. */\n register(\n options: PasskeyCreationOptionsJSON,\n init?: PasskeyRegisterInit,\n ): Promise<PasskeyRegistrationJSON>;\n /** Run the authentication ceremony and return the JSON your backend verifies. */\n authenticate(\n options: PasskeyRequestOptionsJSON,\n init?: PasskeyAuthenticateInit,\n ): Promise<PasskeyAuthenticationJSON>;\n /**\n * Whether this client can run a ceremony at all — the WebAuthn API exists, or a\n * `credentials` container was injected.\n */\n isSupported(): boolean;\n /** Whether this device has a built-in authenticator (Face ID, Hello, …). */\n isPlatformAuthenticatorAvailable(): Promise<boolean>;\n /** Whether autofill-driven (`\"conditional\"`) requests are available. */\n isConditionalMediationAvailable(): Promise<boolean>;\n}\n\n/** Options for {@link createPasskeyClient}. */\nexport interface CreatePasskeyClientOptions {\n /**\n * Default relying-party id, applied when the server options omit one. Must be\n * the page's domain or a registrable parent of it (`app.acme.com` may use\n * `acme.com`, never the other way round).\n */\n rpId?: string;\n /** Default ceremony timeout in ms. Default `60_000`. */\n timeoutMs?: number;\n /** `navigator.credentials` replacement, for tests. */\n credentials?: CredentialsContainerLike;\n}\n\n/**\n * COSE algorithms offered when the server sends no `pubKeyCredParams`, in\n * preference order.\n *\n * `-8` is Ed25519, which modern authenticators prefer and which produces the\n * smallest signatures. `-7` is ES256, the one algorithm every WebAuthn\n * authenticator supports. `-257` is RS256, needed for TPM-backed Windows Hello.\n * Offering all three is what avoids a `NotSupportedError` on some device you do\n * not own; a server that cannot verify one of them should send its own list.\n */\nexport const DEFAULT_PUB_KEY_CRED_PARAMS: { type: \"public-key\"; alg: number }[] = [\n { type: \"public-key\", alg: -8 },\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n];\n\n/** Static members of `PublicKeyCredential` that are not in every DOM lib yet. */\ninterface PublicKeyCredentialStatics {\n isUserVerifyingPlatformAuthenticatorAvailable?: () => Promise<boolean>;\n isConditionalMediationAvailable?: () => Promise<boolean>;\n}\n\n/** The browser-supplied extras on an attestation response, all optional. */\ninterface AttestationExtras {\n getTransports?: () => string[];\n getPublicKey?: () => ArrayBuffer | null;\n getPublicKeyAlgorithm?: () => number;\n getAuthenticatorData?: () => ArrayBuffer;\n}\n\nfunction publicKeyCredentialStatics(): PublicKeyCredentialStatics | undefined {\n return (globalThis as { PublicKeyCredential?: PublicKeyCredentialStatics }).PublicKeyCredential;\n}\n\n/**\n * Decode a base64url string into bytes.\n *\n * WebAuthn transports every binary field as base64url (`-`/`_`, no padding)\n * because that is what survives JSON, while the DOM API insists on\n * `ArrayBuffer`. Getting this pair wrong — usually by feeding plain base64 to\n * `atob` and losing the last byte — is the classic broken-WebAuthn bug, which is\n * why the SDK owns it instead of leaving it to each app.\n *\n * This is the WebAuthn-facing name for {@link base64ToBytes}; the codec itself is\n * shared, so the padding rule has one implementation rather than three.\n *\n * @param value - Base64url text, with or without `=` padding.\n * @returns The decoded bytes.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n return base64ToBytes(value);\n}\n\n/**\n * Encode bytes as an unpadded base64url string.\n *\n * Normalises `ArrayBuffer` to a view — which is what the WebAuthn response\n * fields hand over — and delegates the encoding to {@link bytesToBase64}.\n *\n * @param value - Bytes to encode, as a view or a raw buffer.\n * @returns Base64url text, safe to put in JSON and in a URL.\n */\nexport function bytesToBase64Url(value: ArrayBuffer | Uint8Array): string {\n const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);\n return bytesToBase64(bytes, { urlSafe: true });\n}\n\n/**\n * Whether this browser exposes WebAuthn at all.\n *\n * Note that \"supported\" is not \"usable\": WebAuthn also requires a secure context,\n * and a device may have no authenticator. Use\n * {@link isPlatformAuthenticatorAvailable} before offering a passkey button.\n */\nexport function isPasskeySupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.credentials !== undefined &&\n typeof navigator.credentials.create === \"function\" &&\n publicKeyCredentialStatics() !== undefined\n );\n}\n\n/**\n * Whether the device has a **built-in** authenticator — Face ID, Touch ID,\n * Windows Hello, an Android screen lock.\n *\n * This is the check that decides whether \"Entrar com passkey\" may be shown at\n * all. `isPasskeySupported()` is true on a desktop with no biometrics and no\n * security key, and offering a passkey there sends the user into a sheet that can\n * only be cancelled. A `false` here does not forbid passkeys — a phone can still\n * be used over hybrid/QR — it means the flow needs a second step, so present it\n * as \"usar meu celular\", not as one tap.\n *\n * @returns `false` when the API is missing, so a caller never has to null-check.\n */\nexport async function isPlatformAuthenticatorAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isUserVerifyingPlatformAuthenticatorAvailable) return false;\n try {\n return await statics.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Whether autofill-driven passkeys (`mediation: \"conditional\"`) are available.\n *\n * @returns `false` when the API is missing or throws.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isConditionalMediationAvailable) return false;\n try {\n return await statics.isConditionalMediationAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Map a thrown WebAuthn failure onto a {@link PasskeyError}.\n *\n * The secure-context check runs first for the same reason it does in the media\n * classifier: over plain HTTP the whole API is absent or refuses, and reporting\n * \"not supported\" sends a developer hunting for a polyfill for something an\n * `https://` URL fixes.\n *\n * @param error - Whatever `navigator.credentials` rejected with.\n * @param ceremony - Which ceremony was running, for the message.\n * @returns The classified error, ready to throw or to show.\n */\nexport function classifyPasskeyError(error: unknown, ceremony: PasskeyCeremony): PasskeyError {\n if (error instanceof PasskeyError) return error;\n\n if (typeof window !== \"undefined\" && !window.isSecureContext) {\n return new PasskeyError(\"insecure\", \"Passkeys require a secure (HTTPS) connection.\", error);\n }\n\n if (error instanceof DOMException) {\n switch (error.name) {\n case \"NotAllowedError\":\n return new PasskeyError(\n \"cancelled\",\n \"The passkey prompt was dismissed or timed out. The browser does not say which — it must not reveal whether a credential exists.\",\n error,\n );\n case \"InvalidStateError\":\n return new PasskeyError(\n \"already-registered\",\n \"This device already has a passkey for this account. Sign in with it instead of creating another.\",\n error,\n );\n case \"NotSupportedError\":\n return new PasskeyError(\n \"not-supported\",\n \"No authenticator here supports the requested algorithms. Check the server's pubKeyCredParams.\",\n error,\n );\n case \"SecurityError\":\n return new PasskeyError(\n \"rp-mismatch\",\n \"The relying-party id does not match this origin. rp.id must be the page's domain or a registrable parent of it.\",\n error,\n );\n case \"AbortError\":\n return new PasskeyError(\"aborted\", \"The passkey request was aborted.\", error);\n }\n }\n\n if (error instanceof TypeError) {\n return new PasskeyError(\n \"invalid-options\",\n `The ${ceremony} options the server sent are malformed. Check that challenge, user.id and credential ids are base64url.`,\n error,\n );\n }\n\n return new PasskeyError(\n \"unknown\",\n error instanceof Error\n ? error.message\n : `Unexpected error during the passkey ${ceremony} ceremony.`,\n error,\n );\n}\n\nfunction toDescriptors(\n list: { id: string; type: \"public-key\"; transports?: string[] }[] | undefined,\n): PublicKeyCredentialDescriptor[] | undefined {\n if (!list) return undefined;\n return list.map((item) => ({\n id: base64UrlToBytes(item.id) as unknown as BufferSource,\n type: item.type,\n transports: item.transports as AuthenticatorTransport[] | undefined,\n }));\n}\n\n/**\n * Build a WebAuthn client: the base64url ↔ `ArrayBuffer` plumbing, the two\n * ceremonies, and one classified error type.\n *\n * ## What your backend must do\n *\n * This is the **client half only**, and a WebAuthn client that documents only its\n * own half is unusable. Four routes are yours to implement:\n *\n * 1. `POST /webauthn/register/begin` → a {@link PasskeyCreationOptionsJSON}. Mint a\n * random `challenge` (≥16 bytes), store it against the session, and list the\n * user's existing credentials in `excludeCredentials`.\n * 2. `POST /webauthn/register/finish` ← a {@link PasskeyRegistrationJSON}. Verify\n * the challenge, `origin` and `type` inside `clientDataJSON`, parse the\n * attestation object, then store the credential id, public key and signature\n * counter.\n * 3. `POST /webauthn/signin/begin` → a {@link PasskeyRequestOptionsJSON}. New\n * challenge. Omit `allowCredentials` for a usernameless or autofill flow.\n * 4. `POST /webauthn/signin/finish` ← a {@link PasskeyAuthenticationJSON}. Look the\n * credential up by `id`, verify the signature over\n * `authenticatorData || sha256(clientDataJSON)`, and reject a signature counter\n * that did not grow (a clone). Only then issue your session token.\n *\n * @param options - Defaults applied when the server options omit them.\n * @returns A client usable from anywhere — React, a plain form, a worker.\n *\n * @example\n * const passkeys = createPasskeyClient({ rpId: \"acme.com\" });\n *\n * const options = await api.post(\"/webauthn/register/begin\");\n * const credential = await passkeys.register(options);\n * await api.post(\"/webauthn/register/finish\", { body: credential });\n */\nexport function createPasskeyClient(options: CreatePasskeyClientOptions = {}): PasskeyClient {\n const { rpId, timeoutMs = 60_000, credentials } = options;\n\n function container(): CredentialsContainerLike {\n if (credentials) return credentials;\n if (!isPasskeySupported()) {\n throw new PasskeyError(\n \"unsupported\",\n typeof window !== \"undefined\" && !window.isSecureContext\n ? \"Passkeys require a secure (HTTPS) connection.\"\n : \"This browser does not support passkeys (WebAuthn).\",\n );\n }\n return navigator.credentials as unknown as CredentialsContainerLike;\n }\n\n async function register(\n json: PasskeyCreationOptionsJSON,\n init: PasskeyRegisterInit = {},\n ): Promise<PasskeyRegistrationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialCreationOptions = {\n challenge: base64UrlToBytes(json.challenge) as unknown as BufferSource,\n rp: { name: json.rp.name, id: json.rp.id ?? rpId },\n user: {\n id: base64UrlToBytes(json.user.id) as unknown as BufferSource,\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams ?? DEFAULT_PUB_KEY_CRED_PARAMS,\n timeout: json.timeout ?? timeoutMs,\n excludeCredentials: toDescriptors(json.excludeCredentials),\n authenticatorSelection: json.authenticatorSelection,\n attestation: json.attestation,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.create({ publicKey, signal: init.signal });\n } catch (error) {\n throw classifyPasskeyError(error, \"register\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAttestationResponse & AttestationExtras;\n const publicKeyBytes = response.getPublicKey?.();\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n transports: response.getTransports?.(),\n publicKeyAlgorithm: response.getPublicKeyAlgorithm?.(),\n publicKey: publicKeyBytes ? bytesToBase64Url(publicKeyBytes) : undefined,\n authenticatorData: response.getAuthenticatorData\n ? bytesToBase64Url(response.getAuthenticatorData())\n : undefined,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n async function authenticate(\n json: PasskeyRequestOptionsJSON,\n init: PasskeyAuthenticateInit = {},\n ): Promise<PasskeyAuthenticationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialRequestOptions = {\n challenge: base64UrlToBytes(json.challenge) as unknown as BufferSource,\n rpId: json.rpId ?? rpId,\n timeout: json.timeout ?? timeoutMs,\n allowCredentials: toDescriptors(json.allowCredentials),\n userVerification: json.userVerification,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.get({\n publicKey,\n signal: init.signal,\n mediation: init.mediation,\n });\n } catch (error) {\n throw classifyPasskeyError(error, \"authenticate\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAssertionResponse;\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n return {\n register,\n authenticate,\n isSupported: () => credentials !== undefined || isPasskeySupported(),\n isPlatformAuthenticatorAvailable,\n isConditionalMediationAvailable,\n };\n}\n"],"mappings":";;AAkDA,IAAa,IAAb,cAAkC,MAAM;CAEpC;CASA,YAAY,GAAwB,GAAiB,GAAiB;EAIlE,AAHA,MAAM,CAAO,GACb,KAAK,OAAO,gBACZ,KAAK,OAAO,GACZ,KAAK,QAAQ;CACjB;AACJ,GAyLa,IAAqE;CAC9E;EAAE,MAAM;EAAc,KAAK;CAAG;CAC9B;EAAE,MAAM;EAAc,KAAK;CAAG;CAC9B;EAAE,MAAM;EAAc,KAAK;CAAK;AACpC;AAgBA,SAAS,IAAqE;CAC1E,OAAQ,WAAoE;AAChF;AAiBA,SAAgB,EAAiB,GAAwC;CACrE,OAAO,EAAc,CAAK;AAC9B;AAWA,SAAgB,EAAiB,GAAyC;CACtE,IAAM,IAAQ,aAAiB,aAAa,IAAQ,IAAI,WAAW,CAAK;CACxE,OAAO,EAAc,GAAO,EAAE,SAAS,GAAK,CAAC;AACjD;AASA,SAAgB,IAA8B;CAC1C,OACI,OAAO,SAAW,OAClB,OAAO,YAAc,OACrB,UAAU,gBAAgB,KAAA,KAC1B,OAAO,UAAU,YAAY,UAAW,cACxC,EAA2B,MAAM,KAAA;AAEzC;AAeA,eAAsB,IAAqD;CACvE,IAAM,IAAU,EAA2B;CAC3C,IAAI,CAAC,GAAS,+CAA+C,OAAO;CACpE,IAAI;EACA,OAAO,MAAM,EAAQ,8CAA8C;CACvE,QAAQ;EACJ,OAAO;CACX;AAC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BAAgB;GACrD,kBAAkB,EAAK;GACvB,YAAY,EAAK;EACrB,GAEI;EACJ,IAAI;GACA,IAAa,MAAM,EAAI,IAAI;IACvB;IACA,QAAQ,EAAK;IACb,WAAW,EAAK;GACpB,CAAC;EACL,SAAS,GAAO;GACZ,MAAM,EAAqB,GAAO,cAAc;EACpD;EACA,IAAI,CAAC,GACD,MAAM,IAAI,EAAa,WAAW,2CAA2C;EAGjF,IAAM,IAAQ,GACR,IAAW,EAAM;EAEvB,OAAO;GACH,IAAI,EAAM;GACV,OAAO,EAAiB,EAAM,KAAK;GACnC,MAAM;GACN,yBAAyB,EAAM,2BAA2B;GAC1D,UAAU;IACN,gBAAgB,EAAiB,EAAS,cAAc;IACxD,mBAAmB,EAAiB,EAAS,iBAAiB;IAC9D,WAAW,EAAiB,EAAS,SAAS;IAC9C,YAAY,EAAS,aAAa,EAAiB,EAAS,UAAU,IAAI;GAC9E;GACA,wBAAwB,EAAM,0BAA0B;EAC5D;CACJ;CAEA,OAAO;EACH;EACA;EACA,mBAAmB,MAAgB,KAAA,KAAa,EAAmB;EACnE;EACA;CACJ;AACJ"}
1
+ {"version":3,"file":"passkey.js","names":[],"sources":["../../src/auth/passkey.ts"],"sourcesContent":["/**\n * @tempest-limits file-lines, function-lines — the WebAuthn client half: the JSON\n * shapes both ceremonies exchange with a backend, base64url ↔ ArrayBuffer, the\n * capability probes and the error classifier. The two ceremonies are near-mirrors\n * that must not drift — register and authenticate encode the same credential fields\n * in the same order — and the file's docstring is also the specification of the four\n * backend routes it expects.\n */\n\nimport { base64ToBytes, bytesToBase64 } from \"@/utils/base64\";\n\n/**\n * Classified reason a passkey ceremony did not produce a credential.\n *\n * The kinds group the raw `DOMException.name` values the way a UI has to branch\n * on them, which is *not* how the spec groups them:\n *\n * - `\"cancelled\"` covers `NotAllowedError`, which the browser raises both when\n * the user dismissed the sheet and when the ceremony timed out. They are\n * indistinguishable **by design** — telling a site \"the user has no credential\n * for you\" would leak account existence — so a UI must treat them as one thing.\n * - `\"already-registered\"` (`InvalidStateError`) is not really a failure: this\n * device already holds a credential for this user. The correct reaction is\n * \"you are already set up on this device\", never a red error.\n * - `\"rp-mismatch\"` (`SecurityError`) is the single most common integration bug:\n * `rp.id` must equal the page's domain or a registrable parent of it.\n */\nexport type PasskeyErrorKind =\n | \"unsupported\"\n | \"insecure\"\n | \"cancelled\"\n | \"already-registered\"\n | \"not-supported\"\n | \"rp-mismatch\"\n | \"invalid-options\"\n | \"aborted\"\n | \"unknown\";\n\n/** Which ceremony was running, so the message can name it. */\nexport type PasskeyCeremony = \"register\" | \"authenticate\";\n\n/**\n * A passkey failure carrying a stable {@link PasskeyErrorKind} plus an English\n * message safe to show a user.\n *\n * A class rather than the plain `{ kind, message }` object the media classifier\n * returns, because these surface by rejecting a promise: an `Error` subclass keeps\n * stack traces, `instanceof` checks and logging intact, and `kind` is what code\n * branches on.\n */\nexport class PasskeyError extends Error {\n /** Stable, branchable classification. */\n readonly kind: PasskeyErrorKind;\n\n /**\n * Build a classified passkey error.\n *\n * @param kind - The classification a UI branches on.\n * @param message - English, user-safe explanation.\n * @param cause - The original thrown value, when there was one.\n */\n constructor(kind: PasskeyErrorKind, message: string, cause?: unknown) {\n super(message);\n this.name = \"PasskeyError\";\n this.kind = kind;\n this.cause = cause;\n }\n}\n\n/**\n * Minimal subset of `navigator.credentials` the passkey client touches.\n *\n * Declared here — the `<X>Like` pattern the SDK's adapters use — for two reasons:\n * jsdom has no `navigator.credentials` at all, so tests must inject a double; and\n * `mediation: \"conditional\"` is newer than some TypeScript DOM libs, which would\n * otherwise reject the call that makes autofill work.\n */\nexport interface CredentialsContainerLike {\n /** Runs the registration ceremony. */\n create(options: {\n publicKey: PublicKeyCredentialCreationOptions;\n signal?: AbortSignal;\n }): Promise<Credential | null>;\n /** Runs the authentication ceremony. */\n get(options: {\n publicKey: PublicKeyCredentialRequestOptions;\n signal?: AbortSignal;\n mediation?: string;\n }): Promise<Credential | null>;\n}\n\n/** How the browser should surface the authentication ceremony. */\nexport type PasskeyMediation = \"optional\" | \"conditional\" | \"required\" | \"silent\";\n\n/**\n * Server-issued registration options, in the base64url JSON shape every WebAuthn\n * backend speaks (`PublicKeyCredentialCreationOptionsJSON` in the spec).\n *\n * `challenge`, `user.id` and every `excludeCredentials[].id` are **base64url**\n * strings here and `ArrayBuffer`s in the DOM API. Converting them is the plumbing\n * this client owns.\n */\nexport interface PasskeyCreationOptionsJSON {\n /** Base64url server challenge. Single-use; the server must remember it. */\n challenge: string;\n /** Relying party. `id` defaults to the client's `rpId`, then to the origin. */\n rp: { name: string; id?: string };\n /** The account. `id` is base64url of an opaque, stable user handle. */\n user: { id: string; name: string; displayName: string };\n /** Allowed COSE algorithms. Defaults to {@link DEFAULT_PUB_KEY_CRED_PARAMS}. */\n pubKeyCredParams?: { type: \"public-key\"; alg: number }[];\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Credentials this user already has, so the authenticator refuses a duplicate. */\n excludeCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Resident-key / user-verification / attachment requirements. */\n authenticatorSelection?: AuthenticatorSelectionCriteria;\n /** Attestation conveyance. Leave unset (`\"none\"`) unless you verify it. */\n attestation?: AttestationConveyancePreference;\n /** Client extension inputs (`credProps`, `largeBlob`, …). */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** Server-issued authentication options, base64url JSON. */\nexport interface PasskeyRequestOptionsJSON {\n /** Base64url server challenge. */\n challenge: string;\n /** Relying party id. Defaults to the client's `rpId`, then to the origin. */\n rpId?: string;\n /** Ceremony timeout in ms. Defaults to the client's `timeoutMs`. */\n timeout?: number;\n /** Restrict to these credentials. **Omit it** for usernameless / autofill flows. */\n allowCredentials?: { id: string; type: \"public-key\"; transports?: string[] }[];\n /** Whether the authenticator must verify the user (biometric / PIN). */\n userVerification?: UserVerificationRequirement;\n /** Client extension inputs. */\n extensions?: AuthenticationExtensionsClientInputs;\n}\n\n/** What the client sends to the backend to finish registration. */\nexport interface PasskeyRegistrationJSON {\n /** Base64url credential id. */\n id: string;\n /** Same bytes as `id`; both are sent because servers differ on which they read. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` (this device) or `\"cross-platform\"` (a phone or key). */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data — the server re-checks challenge, origin and type. */\n clientDataJSON: string;\n /** Base64url attestation object, holding the new public key. */\n attestationObject: string;\n /** Transports the authenticator advertises, when the browser exposes them. */\n transports?: string[];\n /** COSE algorithm of the new key, when the browser exposes it. */\n publicKeyAlgorithm?: number;\n /** Base64url SPKI public key, when the browser exposes it. */\n publicKey?: string;\n /** Base64url authenticator data, when the browser exposes it. */\n authenticatorData?: string;\n };\n /** Extension outputs — `credProps.rk` tells you whether it is discoverable. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** What the client sends to the backend to finish authentication. */\nexport interface PasskeyAuthenticationJSON {\n /** Base64url credential id — the server looks up the stored public key by it. */\n id: string;\n /** Same bytes as `id`. */\n rawId: string;\n type: \"public-key\";\n /** `\"platform\"` or `\"cross-platform\"`. */\n authenticatorAttachment: string | null;\n response: {\n /** Base64url client data. */\n clientDataJSON: string;\n /** Base64url authenticator data, carrying the signature counter. */\n authenticatorData: string;\n /** Base64url signature over `authenticatorData || sha256(clientDataJSON)`. */\n signature: string;\n /** Base64url user handle — present on discoverable credentials, else null. */\n userHandle: string | null;\n };\n /** Extension outputs. */\n clientExtensionResults: AuthenticationExtensionsClientOutputs;\n}\n\n/** Per-call knobs for {@link PasskeyClient.register}. */\nexport interface PasskeyRegisterInit {\n /** Cancel the ceremony (closes the browser sheet). */\n signal?: AbortSignal;\n}\n\n/** Per-call knobs for {@link PasskeyClient.authenticate}. */\nexport interface PasskeyAuthenticateInit extends PasskeyRegisterInit {\n /**\n * `\"conditional\"` is the autofill flow: no modal, the browser offers passkeys\n * inside a field marked `autocomplete=\"webauthn\"`. Requires a `signal`, and\n * only one conditional request may be live per page.\n */\n mediation?: PasskeyMediation;\n}\n\n/** Framework-free WebAuthn client. Build one with {@link createPasskeyClient}. */\nexport interface PasskeyClient {\n /** Run the registration ceremony and return the JSON your backend verifies. */\n register(\n options: PasskeyCreationOptionsJSON,\n init?: PasskeyRegisterInit,\n ): Promise<PasskeyRegistrationJSON>;\n /** Run the authentication ceremony and return the JSON your backend verifies. */\n authenticate(\n options: PasskeyRequestOptionsJSON,\n init?: PasskeyAuthenticateInit,\n ): Promise<PasskeyAuthenticationJSON>;\n /**\n * Whether this client can run a ceremony at all — the WebAuthn API exists, or a\n * `credentials` container was injected.\n */\n isSupported(): boolean;\n /** Whether this device has a built-in authenticator (Face ID, Hello, …). */\n isPlatformAuthenticatorAvailable(): Promise<boolean>;\n /** Whether autofill-driven (`\"conditional\"`) requests are available. */\n isConditionalMediationAvailable(): Promise<boolean>;\n}\n\n/** Options for {@link createPasskeyClient}. */\nexport interface CreatePasskeyClientOptions {\n /**\n * Default relying-party id, applied when the server options omit one. Must be\n * the page's domain or a registrable parent of it (`app.acme.com` may use\n * `acme.com`, never the other way round).\n */\n rpId?: string;\n /** Default ceremony timeout in ms. Default `60_000`. */\n timeoutMs?: number;\n /** `navigator.credentials` replacement, for tests. */\n credentials?: CredentialsContainerLike;\n}\n\n/**\n * COSE algorithms offered when the server sends no `pubKeyCredParams`, in\n * preference order.\n *\n * `-8` is Ed25519, which modern authenticators prefer and which produces the\n * smallest signatures. `-7` is ES256, the one algorithm every WebAuthn\n * authenticator supports. `-257` is RS256, needed for TPM-backed Windows Hello.\n * Offering all three is what avoids a `NotSupportedError` on some device you do\n * not own; a server that cannot verify one of them should send its own list.\n */\nexport const DEFAULT_PUB_KEY_CRED_PARAMS: { type: \"public-key\"; alg: number }[] = [\n { type: \"public-key\", alg: -8 },\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n];\n\n/** Static members of `PublicKeyCredential` that are not in every DOM lib yet. */\ninterface PublicKeyCredentialStatics {\n isUserVerifyingPlatformAuthenticatorAvailable?: () => Promise<boolean>;\n isConditionalMediationAvailable?: () => Promise<boolean>;\n}\n\n/** The browser-supplied extras on an attestation response, all optional. */\ninterface AttestationExtras {\n getTransports?: () => string[];\n getPublicKey?: () => ArrayBuffer | null;\n getPublicKeyAlgorithm?: () => number;\n getAuthenticatorData?: () => ArrayBuffer;\n}\n\nfunction publicKeyCredentialStatics(): PublicKeyCredentialStatics | undefined {\n return (globalThis as { PublicKeyCredential?: PublicKeyCredentialStatics }).PublicKeyCredential;\n}\n\n/**\n * Decode a base64url string into bytes.\n *\n * WebAuthn transports every binary field as base64url (`-`/`_`, no padding)\n * because that is what survives JSON, while the DOM API insists on\n * `ArrayBuffer`. Getting this pair wrong — usually by feeding plain base64 to\n * `atob` and losing the last byte — is the classic broken-WebAuthn bug, which is\n * why the SDK owns it instead of leaving it to each app.\n *\n * This is the WebAuthn-facing name for {@link base64ToBytes}; the codec itself is\n * shared, so the padding rule has one implementation rather than three.\n *\n * @param value - Base64url text, with or without `=` padding.\n * @returns The decoded bytes.\n */\nexport function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {\n return base64ToBytes(value);\n}\n\n/**\n * Encode bytes as an unpadded base64url string.\n *\n * Normalises `ArrayBuffer` to a view — which is what the WebAuthn response\n * fields hand over — and delegates the encoding to {@link bytesToBase64}.\n *\n * @param value - Bytes to encode, as a view or a raw buffer.\n * @returns Base64url text, safe to put in JSON and in a URL.\n */\nexport function bytesToBase64Url(value: ArrayBuffer | Uint8Array): string {\n const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);\n return bytesToBase64(bytes, { urlSafe: true });\n}\n\n/**\n * Whether this browser exposes WebAuthn at all.\n *\n * Note that \"supported\" is not \"usable\": WebAuthn also requires a secure context,\n * and a device may have no authenticator. Use\n * {@link isPlatformAuthenticatorAvailable} before offering a passkey button.\n */\nexport function isPasskeySupported(): boolean {\n return (\n typeof window !== \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.credentials !== undefined &&\n typeof navigator.credentials.create === \"function\" &&\n publicKeyCredentialStatics() !== undefined\n );\n}\n\n/**\n * Whether the device has a **built-in** authenticator — Face ID, Touch ID,\n * Windows Hello, an Android screen lock.\n *\n * This is the check that decides whether \"Entrar com passkey\" may be shown at\n * all. `isPasskeySupported()` is true on a desktop with no biometrics and no\n * security key, and offering a passkey there sends the user into a sheet that can\n * only be cancelled. A `false` here does not forbid passkeys — a phone can still\n * be used over hybrid/QR — it means the flow needs a second step, so present it\n * as \"usar meu celular\", not as one tap.\n *\n * @returns `false` when the API is missing, so a caller never has to null-check.\n */\nexport async function isPlatformAuthenticatorAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isUserVerifyingPlatformAuthenticatorAvailable) return false;\n try {\n return await statics.isUserVerifyingPlatformAuthenticatorAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Whether autofill-driven passkeys (`mediation: \"conditional\"`) are available.\n *\n * @returns `false` when the API is missing or throws.\n */\nexport async function isConditionalMediationAvailable(): Promise<boolean> {\n const statics = publicKeyCredentialStatics();\n if (!statics?.isConditionalMediationAvailable) return false;\n try {\n return await statics.isConditionalMediationAvailable();\n } catch {\n return false;\n }\n}\n\n/**\n * Map a thrown WebAuthn failure onto a {@link PasskeyError}.\n *\n * The secure-context check runs first for the same reason it does in the media\n * classifier: over plain HTTP the whole API is absent or refuses, and reporting\n * \"not supported\" sends a developer hunting for a polyfill for something an\n * `https://` URL fixes.\n *\n * @param error - Whatever `navigator.credentials` rejected with.\n * @param ceremony - Which ceremony was running, for the message.\n * @returns The classified error, ready to throw or to show.\n */\nexport function classifyPasskeyError(error: unknown, ceremony: PasskeyCeremony): PasskeyError {\n if (error instanceof PasskeyError) return error;\n\n if (typeof window !== \"undefined\" && !window.isSecureContext) {\n return new PasskeyError(\"insecure\", \"Passkeys require a secure (HTTPS) connection.\", error);\n }\n\n if (error instanceof DOMException) {\n switch (error.name) {\n case \"NotAllowedError\":\n return new PasskeyError(\n \"cancelled\",\n \"The passkey prompt was dismissed or timed out. The browser does not say which — it must not reveal whether a credential exists.\",\n error,\n );\n case \"InvalidStateError\":\n return new PasskeyError(\n \"already-registered\",\n \"This device already has a passkey for this account. Sign in with it instead of creating another.\",\n error,\n );\n case \"NotSupportedError\":\n return new PasskeyError(\n \"not-supported\",\n \"No authenticator here supports the requested algorithms. Check the server's pubKeyCredParams.\",\n error,\n );\n case \"SecurityError\":\n return new PasskeyError(\n \"rp-mismatch\",\n \"The relying-party id does not match this origin. rp.id must be the page's domain or a registrable parent of it.\",\n error,\n );\n case \"AbortError\":\n return new PasskeyError(\"aborted\", \"The passkey request was aborted.\", error);\n }\n }\n\n if (error instanceof TypeError) {\n return new PasskeyError(\n \"invalid-options\",\n `The ${ceremony} options the server sent are malformed. Check that challenge, user.id and credential ids are base64url.`,\n error,\n );\n }\n\n return new PasskeyError(\n \"unknown\",\n error instanceof Error\n ? error.message\n : `Unexpected error during the passkey ${ceremony} ceremony.`,\n error,\n );\n}\n\nfunction toDescriptors(\n list: { id: string; type: \"public-key\"; transports?: string[] }[] | undefined,\n): PublicKeyCredentialDescriptor[] | undefined {\n if (!list) return undefined;\n return list.map((item) => ({\n id: base64UrlToBytes(item.id),\n type: item.type,\n transports: item.transports as AuthenticatorTransport[] | undefined,\n }));\n}\n\n/**\n * Build a WebAuthn client: the base64url ↔ `ArrayBuffer` plumbing, the two\n * ceremonies, and one classified error type.\n *\n * ## What your backend must do\n *\n * This is the **client half only**, and a WebAuthn client that documents only its\n * own half is unusable. Four routes are yours to implement:\n *\n * 1. `POST /webauthn/register/begin` → a {@link PasskeyCreationOptionsJSON}. Mint a\n * random `challenge` (≥16 bytes), store it against the session, and list the\n * user's existing credentials in `excludeCredentials`.\n * 2. `POST /webauthn/register/finish` ← a {@link PasskeyRegistrationJSON}. Verify\n * the challenge, `origin` and `type` inside `clientDataJSON`, parse the\n * attestation object, then store the credential id, public key and signature\n * counter.\n * 3. `POST /webauthn/signin/begin` → a {@link PasskeyRequestOptionsJSON}. New\n * challenge. Omit `allowCredentials` for a usernameless or autofill flow.\n * 4. `POST /webauthn/signin/finish` ← a {@link PasskeyAuthenticationJSON}. Look the\n * credential up by `id`, verify the signature over\n * `authenticatorData || sha256(clientDataJSON)`, and reject a signature counter\n * that did not grow (a clone). Only then issue your session token.\n *\n * @param options - Defaults applied when the server options omit them.\n * @returns A client usable from anywhere — React, a plain form, a worker.\n *\n * @example\n * const passkeys = createPasskeyClient({ rpId: \"acme.com\" });\n *\n * const options = await api.post(\"/webauthn/register/begin\");\n * const credential = await passkeys.register(options);\n * await api.post(\"/webauthn/register/finish\", { body: credential });\n */\nexport function createPasskeyClient(options: CreatePasskeyClientOptions = {}): PasskeyClient {\n const { rpId, timeoutMs = 60_000, credentials } = options;\n\n function container(): CredentialsContainerLike {\n if (credentials) return credentials;\n if (!isPasskeySupported()) {\n throw new PasskeyError(\n \"unsupported\",\n typeof window !== \"undefined\" && !window.isSecureContext\n ? \"Passkeys require a secure (HTTPS) connection.\"\n : \"This browser does not support passkeys (WebAuthn).\",\n );\n }\n return navigator.credentials as unknown as CredentialsContainerLike;\n }\n\n async function register(\n json: PasskeyCreationOptionsJSON,\n init: PasskeyRegisterInit = {},\n ): Promise<PasskeyRegistrationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialCreationOptions = {\n challenge: base64UrlToBytes(json.challenge),\n rp: { name: json.rp.name, id: json.rp.id ?? rpId },\n user: {\n id: base64UrlToBytes(json.user.id),\n name: json.user.name,\n displayName: json.user.displayName,\n },\n pubKeyCredParams: json.pubKeyCredParams ?? DEFAULT_PUB_KEY_CRED_PARAMS,\n timeout: json.timeout ?? timeoutMs,\n excludeCredentials: toDescriptors(json.excludeCredentials),\n authenticatorSelection: json.authenticatorSelection,\n attestation: json.attestation,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.create({ publicKey, signal: init.signal });\n } catch (error) {\n throw classifyPasskeyError(error, \"register\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAttestationResponse & AttestationExtras;\n const publicKeyBytes = response.getPublicKey?.();\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n attestationObject: bytesToBase64Url(response.attestationObject),\n transports: response.getTransports?.(),\n publicKeyAlgorithm: response.getPublicKeyAlgorithm?.(),\n publicKey: publicKeyBytes ? bytesToBase64Url(publicKeyBytes) : undefined,\n authenticatorData: response.getAuthenticatorData\n ? bytesToBase64Url(response.getAuthenticatorData())\n : undefined,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n async function authenticate(\n json: PasskeyRequestOptionsJSON,\n init: PasskeyAuthenticateInit = {},\n ): Promise<PasskeyAuthenticationJSON> {\n const api = container();\n const publicKey: PublicKeyCredentialRequestOptions = {\n challenge: base64UrlToBytes(json.challenge),\n rpId: json.rpId ?? rpId,\n timeout: json.timeout ?? timeoutMs,\n allowCredentials: toDescriptors(json.allowCredentials),\n userVerification: json.userVerification,\n extensions: json.extensions,\n };\n\n let credential: Credential | null;\n try {\n credential = await api.get({\n publicKey,\n signal: init.signal,\n mediation: init.mediation,\n });\n } catch (error) {\n throw classifyPasskeyError(error, \"authenticate\");\n }\n if (!credential) {\n throw new PasskeyError(\"unknown\", \"The authenticator returned no credential.\");\n }\n\n const typed = credential as PublicKeyCredential;\n const response = typed.response as AuthenticatorAssertionResponse;\n\n return {\n id: typed.id,\n rawId: bytesToBase64Url(typed.rawId),\n type: \"public-key\",\n authenticatorAttachment: typed.authenticatorAttachment ?? null,\n response: {\n clientDataJSON: bytesToBase64Url(response.clientDataJSON),\n authenticatorData: bytesToBase64Url(response.authenticatorData),\n signature: bytesToBase64Url(response.signature),\n userHandle: response.userHandle ? bytesToBase64Url(response.userHandle) : null,\n },\n clientExtensionResults: typed.getClientExtensionResults(),\n };\n }\n\n return {\n register,\n authenticate,\n isSupported: () => credentials !== undefined || isPasskeySupported(),\n isPlatformAuthenticatorAvailable,\n isConditionalMediationAvailable,\n };\n}\n"],"mappings":";;AAkDA,IAAa,IAAb,cAAkC,MAAM;CAEpC;CASA,YAAY,GAAwB,GAAiB,GAAiB;EAIlE,AAHA,MAAM,CAAO,GACb,KAAK,OAAO,gBACZ,KAAK,OAAO,GACZ,KAAK,QAAQ;CACjB;AACJ,GAyLa,IAAqE;CAC9E;EAAE,MAAM;EAAc,KAAK;CAAG;CAC9B;EAAE,MAAM;EAAc,KAAK;CAAG;CAC9B;EAAE,MAAM;EAAc,KAAK;CAAK;AACpC;AAgBA,SAAS,IAAqE;CAC1E,OAAQ,WAAoE;AAChF;AAiBA,SAAgB,EAAiB,GAAwC;CACrE,OAAO,EAAc,CAAK;AAC9B;AAWA,SAAgB,EAAiB,GAAyC;CACtE,IAAM,IAAQ,aAAiB,aAAa,IAAQ,IAAI,WAAW,CAAK;CACxE,OAAO,EAAc,GAAO,EAAE,SAAS,GAAK,CAAC;AACjD;AASA,SAAgB,IAA8B;CAC1C,OACI,OAAO,SAAW,OAClB,OAAO,YAAc,OACrB,UAAU,gBAAgB,KAAA,KAC1B,OAAO,UAAU,YAAY,UAAW,cACxC,EAA2B,MAAM,KAAA;AAEzC;AAeA,eAAsB,IAAqD;CACvE,IAAM,IAAU,EAA2B;CAC3C,IAAI,CAAC,GAAS,+CAA+C,OAAO;CACpE,IAAI;EACA,OAAO,MAAM,EAAQ,8CAA8C;CACvE,QAAQ;EACJ,OAAO;CACX;AACJ;AAOA,eAAsB,IAAoD;CACtE,IAAM,IAAU,EAA2B;CAC3C,IAAI,CAAC,GAAS,iCAAiC,OAAO;CACtD,IAAI;EACA,OAAO,MAAM,EAAQ,gCAAgC;CACzD,QAAQ;EACJ,OAAO;CACX;AACJ;AAcA,SAAgB,EAAqB,GAAgB,GAAyC;CAC1F,IAAI,aAA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,GACD,MAAM,IAAI,EAAa,WAAW,2CAA2C;EAGjF,IAAM,IAAQ,GACR,IAAW,EAAM;EAEvB,OAAO;GACH,IAAI,EAAM;GACV,OAAO,EAAiB,EAAM,KAAK;GACnC,MAAM;GACN,yBAAyB,EAAM,2BAA2B;GAC1D,UAAU;IACN,gBAAgB,EAAiB,EAAS,cAAc;IACxD,mBAAmB,EAAiB,EAAS,iBAAiB;IAC9D,WAAW,EAAiB,EAAS,SAAS;IAC9C,YAAY,EAAS,aAAa,EAAiB,EAAS,UAAU,IAAI;GAC9E;GACA,wBAAwB,EAAM,0BAA0B;EAC5D;CACJ;CAEA,OAAO;EACH;EACA;EACA,mBAAmB,MAAgB,KAAA,KAAa,EAAmB;EACnE;EACA;CACJ;AACJ"}
@@ -1,2 +1,2 @@
1
- const e=require("../components/Select/Select.cjs"),t=require("./locations.cjs");let n=require("react"),r=require("react/jsx-runtime");function i({defaultUf:i,defaultCity:a,onChange:o,stateLabel:s=`Estado`,cityLabel:c=`Cidade`,statePlaceholder:l=`Selecione o estado`,cityPlaceholder:u=`Selecione a cidade`,disabled:d=!1,layout:f=`row`}){let[p,m]=(0,n.useState)(i??null),[h,g]=(0,n.useState)(a??null),_=(0,n.useMemo)(()=>t.listStates().map(e=>({value:e.uf,label:e.name})),[]),v=(0,n.useMemo)(()=>p?t.cityChoices(p):[],[p]);function y(e){let n=t.normalizeUf(e);m(n),g(null),o?.({uf:n,city:null})}function b(e){let t=e||null;g(t),o?.({uf:p,city:t})}return(0,r.jsxs)(`div`,{style:{display:`flex`,flexDirection:f===`row`?`row`:`column`,gap:`var(--tempest-space-3, 12px)`,flexWrap:`wrap`},children:[(0,r.jsx)(e.Select,{label:s,placeholder:l,options:_,value:p??``,disabled:d,onChange:e=>y(e.target.value),style:{minWidth:0}}),(0,r.jsx)(e.Select,{label:c,placeholder:u,options:v,value:h??``,disabled:d||!p,onChange:e=>b(e.target.value),style:{minWidth:0}})]})}exports.BrazilStateCitySelect=i;
1
+ const e=require("../components/Select/Select.cjs"),t=require("./locations.cjs");let n=require("react"),r=require("react/jsx-runtime");function i(e){return[...t.municipalitiesByUf(e).map(e=>e.name),...t.administrativeRegionsByUf(e).map(e=>e.name)].sort((e,t)=>e.localeCompare(t,`pt-BR`)).map(e=>({value:e,label:e}))}function a({defaultUf:a,defaultCity:o,onChange:s,stateLabel:c=`Estado`,cityLabel:l=`Cidade`,statePlaceholder:u=`Selecione o estado`,cityPlaceholder:d=`Selecione a cidade`,disabled:f=!1,layout:p=`row`}){let[m,h]=(0,n.useState)(a??null),[g,_]=(0,n.useState)(o??null),v=(0,n.useMemo)(()=>t.listStates().map(e=>({value:e.uf,label:e.name})),[]),y=(0,n.useMemo)(()=>m?i(m):[],[m]);function b(e){let n=t.normalizeUf(e);h(n),_(null),s?.({uf:n,city:null,municipalityId:null})}function x(e){let n=e||null;_(n),s?.({uf:m,city:n,municipalityId:m&&n?t.resolveMunicipality(m,n)?.id??null:null})}return(0,r.jsxs)(`div`,{style:{display:`flex`,flexDirection:p===`row`?`row`:`column`,gap:`var(--tempest-space-3, 12px)`,flexWrap:`wrap`},children:[(0,r.jsx)(e.Select,{label:c,placeholder:u,options:v,value:m??``,disabled:f,onChange:e=>b(e.target.value),style:{minWidth:0}}),(0,r.jsx)(e.Select,{label:l,placeholder:d,options:y,value:g??``,disabled:f||!m,onChange:e=>x(e.target.value),style:{minWidth:0}})]})}exports.BrazilStateCitySelect=a;
2
2
  //# sourceMappingURL=BrazilStateCitySelect.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"BrazilStateCitySelect.cjs","names":[],"sources":["../../src/br/BrazilStateCitySelect.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — two dependent selects in one control, so every knob\n * comes in pairs: stateLabel and cityLabel, statePlaceholder and cityPlaceholder,\n * defaultUf and defaultCity. The pairing is the feature — the city list is derived\n * from the chosen UF, which is exactly what a caller wiring two separate selects has\n * to reimplement.\n */\nimport { useMemo, useState, type ReactElement } from \"react\";\nimport { Select } from \"@/components/Select\";\nimport { cityChoices, listStates, normalizeUf, type UF } from \"./locations\";\n\n/** Current selection emitted by {@link BrazilStateCitySelect}. */\nexport interface BrazilStateCitySelection {\n /** Selected federative unit, or `null` when none. */\n uf: UF | null;\n /** Selected city, or `null` when none. */\n city: string | null;\n}\n\nexport interface BrazilStateCitySelectProps {\n /** Pre-selected UF (uncontrolled initial value). */\n defaultUf?: UF;\n /** Pre-selected city (uncontrolled initial value). */\n defaultCity?: string;\n /** Fired whenever the state or city changes. */\n onChange?: (selection: BrazilStateCitySelection) => void;\n /** Label for the state select. Default: `\"Estado\"`. */\n stateLabel?: string;\n /** Label for the city select. Default: `\"Cidade\"`. */\n cityLabel?: string;\n /** Placeholder for the state select. Default: `\"Selecione o estado\"`. */\n statePlaceholder?: string;\n /** Placeholder for the city select. Default: `\"Selecione a cidade\"`. */\n cityPlaceholder?: string;\n /** Disable both selects. */\n disabled?: boolean;\n /** Layout of the two selects. Default: `\"row\"`. */\n layout?: \"row\" | \"column\";\n}\n\n/**\n * Cascading Estado → Cidade selector backed by the bundled BR locations data —\n * pick a state and the city list narrows to that UF's municipalities. No\n * network, no external API. Complements {@link BrazilMap} (wire the map's\n * `onSelect` to drive the same UF).\n *\n * @example\n * <BrazilStateCitySelect onChange={({ uf, city }) => console.log(uf, city)} />\n */\nexport function BrazilStateCitySelect({\n defaultUf,\n defaultCity,\n onChange,\n stateLabel = \"Estado\",\n cityLabel = \"Cidade\",\n statePlaceholder = \"Selecione o estado\",\n cityPlaceholder = \"Selecione a cidade\",\n disabled = false,\n layout = \"row\",\n}: BrazilStateCitySelectProps): ReactElement {\n const [uf, setUf] = useState<UF | null>(defaultUf ?? null);\n const [city, setCity] = useState<string | null>(defaultCity ?? null);\n\n const stateOptions = useMemo(\n () => listStates().map((s) => ({ value: s.uf, label: s.name })),\n [],\n );\n const cityOptions = useMemo(() => (uf ? cityChoices(uf) : []), [uf]);\n\n function handleUf(next: string): void {\n const nextUf = normalizeUf(next);\n setUf(nextUf);\n setCity(null);\n onChange?.({ uf: nextUf, city: null });\n }\n\n function handleCity(next: string): void {\n const nextCity = next || null;\n setCity(nextCity);\n onChange?.({ uf, city: nextCity });\n }\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: layout === \"row\" ? \"row\" : \"column\",\n gap: \"var(--tempest-space-3, 12px)\",\n flexWrap: \"wrap\",\n }}\n >\n <Select\n label={stateLabel}\n placeholder={statePlaceholder}\n options={stateOptions}\n value={uf ?? \"\"}\n disabled={disabled}\n onChange={(e) => handleUf(e.target.value)}\n style={{ minWidth: 0 }}\n />\n <Select\n label={cityLabel}\n placeholder={cityPlaceholder}\n options={cityOptions}\n value={city ?? \"\"}\n disabled={disabled || !uf}\n onChange={(e) => handleCity(e.target.value)}\n style={{ minWidth: 0 }}\n />\n </div>\n );\n}\n"],"mappings":"sIAiDA,SAAgB,EAAsB,CAClC,YACA,cACA,WACA,aAAa,SACb,YAAY,SACZ,mBAAmB,qBACnB,kBAAkB,qBAClB,WAAW,GACX,SAAS,OACgC,CACzC,GAAM,CAAC,EAAI,IAAA,EAAS,EAAA,SAAA,CAAoB,GAAa,IAAI,EACnD,CAAC,EAAM,IAAA,EAAW,EAAA,SAAA,CAAwB,GAAe,IAAI,EAE7D,GAAA,EAAe,EAAA,QAAA,KACX,EAAA,WAAW,CAAC,CAAC,IAAK,IAAO,CAAE,MAAO,EAAE,GAAI,MAAO,EAAE,IAAK,EAAE,EAC9D,CAAC,CACL,EACM,GAAA,EAAc,EAAA,QAAA,KAAe,EAAK,EAAA,YAAY,CAAE,EAAI,CAAC,EAAI,CAAC,CAAE,CAAC,EAEnE,SAAS,EAAS,EAAoB,CAClC,IAAM,EAAS,EAAA,YAAY,CAAI,EAC/B,EAAM,CAAM,EACZ,EAAQ,IAAI,EACZ,IAAW,CAAE,GAAI,EAAQ,KAAM,IAAK,CAAC,CACzC,CAEA,SAAS,EAAW,EAAoB,CACpC,IAAM,EAAW,GAAQ,KACzB,EAAQ,CAAQ,EAChB,IAAW,CAAE,KAAI,KAAM,CAAS,CAAC,CACrC,CAEA,OACI,EAAA,EAAA,KAAA,CAAC,MAAD,CACI,MAAO,CACH,QAAS,OACT,cAAe,IAAW,MAAQ,MAAQ,SAC1C,IAAK,+BACL,SAAU,MACd,EANJ,SAAA,EAQI,EAAA,EAAA,IAAA,CAAC,EAAA,OAAD,CACI,MAAO,EACP,YAAa,EACb,QAAS,EACT,MAAO,GAAM,GACH,WACV,SAAW,GAAM,EAAS,EAAE,OAAO,KAAK,EACxC,MAAO,CAAE,SAAU,CAAE,CACxB,CAAA,GACD,EAAA,EAAA,IAAA,CAAC,EAAA,OAAD,CACI,MAAO,EACP,YAAa,EACb,QAAS,EACT,MAAO,GAAQ,GACf,SAAU,GAAY,CAAC,EACvB,SAAW,GAAM,EAAW,EAAE,OAAO,KAAK,EAC1C,MAAO,CAAE,SAAU,CAAE,CACxB,CAAA,CACA,GAEb"}
1
+ {"version":3,"file":"BrazilStateCitySelect.cjs","names":[],"sources":["../../src/br/BrazilStateCitySelect.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — two dependent selects in one control, so every knob\n * comes in pairs: stateLabel and cityLabel, statePlaceholder and cityPlaceholder,\n * defaultUf and defaultCity. The pairing is the feature — the city list is derived\n * from the chosen UF, which is exactly what a caller wiring two separate selects has\n * to reimplement.\n */\nimport { useMemo, useState, type ReactElement } from \"react\";\nimport { Select } from \"@/components/Select\";\nimport {\n administrativeRegionsByUf,\n listStates,\n municipalitiesByUf,\n normalizeUf,\n resolveMunicipality,\n type Choice,\n type UF,\n} from \"./locations\";\n\n/** Current selection emitted by {@link BrazilStateCitySelect}. */\nexport interface BrazilStateCitySelection {\n /** Selected federative unit, or `null` when none. */\n uf: UF | null;\n /** Selected city, or `null` when none. */\n city: string | null;\n /**\n * IBGE code of the selected municipality, or `null` when none is selected.\n *\n * This is the value to store. It survives the renames `city` does not, and\n * it is what `geocodeMunicipality` and every other dataset here join on. A\n * DF administrative region carries Brasília's code, because that is the\n * municipality it is part of.\n */\n municipalityId: string | null;\n}\n\nexport interface BrazilStateCitySelectProps {\n /** Pre-selected UF (uncontrolled initial value). */\n defaultUf?: UF;\n /** Pre-selected city (uncontrolled initial value). */\n defaultCity?: string;\n /** Fired whenever the state or city changes. */\n onChange?: (selection: BrazilStateCitySelection) => void;\n /** Label for the state select. Default: `\"Estado\"`. */\n stateLabel?: string;\n /** Label for the city select. Default: `\"Cidade\"`. */\n cityLabel?: string;\n /** Placeholder for the state select. Default: `\"Selecione o estado\"`. */\n statePlaceholder?: string;\n /** Placeholder for the city select. Default: `\"Selecione a cidade\"`. */\n cityPlaceholder?: string;\n /** Disable both selects. */\n disabled?: boolean;\n /** Layout of the two selects. Default: `\"row\"`. */\n layout?: \"row\" | \"column\";\n}\n\n/**\n * Cascading Estado → Cidade selector backed by the bundled BR locations data —\n * pick a state and the city list narrows to that UF's municipalities. No\n * network, no external API. Complements {@link BrazilMap} (wire the map's\n * `onSelect` to drive the same UF).\n *\n * @example\n * <BrazilStateCitySelect onChange={({ uf, city }) => console.log(uf, city)} />\n */\n/**\n * The pickable places of a federative unit: its municipalities, plus the DF's\n * administrative regions.\n *\n * The DF has one municipality and nobody there writes \"Brasília\" in an address\n * field — they write Ceilândia, Taguatinga, Gama. Offering only the municipality\n * would be faithful to IBGE and useless in a form, so the 35 regions are listed\n * beside it and every one of them resolves to Brasília's code.\n *\n * @param uf - The selected federative unit.\n * @returns `{ value, label }` options, alphabetically, value === label.\n */\nfunction placeChoices(uf: UF): Choice[] {\n const names = [\n ...municipalitiesByUf(uf).map((m) => m.name),\n ...administrativeRegionsByUf(uf).map((r) => r.name),\n ].sort((a, b) => a.localeCompare(b, \"pt-BR\"));\n return names.map((name) => ({ value: name, label: name }));\n}\n\nexport function BrazilStateCitySelect({\n defaultUf,\n defaultCity,\n onChange,\n stateLabel = \"Estado\",\n cityLabel = \"Cidade\",\n statePlaceholder = \"Selecione o estado\",\n cityPlaceholder = \"Selecione a cidade\",\n disabled = false,\n layout = \"row\",\n}: BrazilStateCitySelectProps): ReactElement {\n const [uf, setUf] = useState<UF | null>(defaultUf ?? null);\n const [city, setCity] = useState<string | null>(defaultCity ?? null);\n\n const stateOptions = useMemo(\n () => listStates().map((s) => ({ value: s.uf, label: s.name })),\n [],\n );\n const cityOptions = useMemo(() => (uf ? placeChoices(uf) : []), [uf]);\n\n function handleUf(next: string): void {\n const nextUf = normalizeUf(next);\n setUf(nextUf);\n setCity(null);\n onChange?.({ uf: nextUf, city: null, municipalityId: null });\n }\n\n function handleCity(next: string): void {\n const nextCity = next || null;\n setCity(nextCity);\n onChange?.({\n uf,\n city: nextCity,\n municipalityId: uf && nextCity ? (resolveMunicipality(uf, nextCity)?.id ?? null) : null,\n });\n }\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: layout === \"row\" ? \"row\" : \"column\",\n gap: \"var(--tempest-space-3, 12px)\",\n flexWrap: \"wrap\",\n }}\n >\n <Select\n label={stateLabel}\n placeholder={statePlaceholder}\n options={stateOptions}\n value={uf ?? \"\"}\n disabled={disabled}\n onChange={(e) => handleUf(e.target.value)}\n style={{ minWidth: 0 }}\n />\n <Select\n label={cityLabel}\n placeholder={cityPlaceholder}\n options={cityOptions}\n value={city ?? \"\"}\n disabled={disabled || !uf}\n onChange={(e) => handleCity(e.target.value)}\n style={{ minWidth: 0 }}\n />\n </div>\n );\n}\n"],"mappings":"sIA8EA,SAAS,EAAa,EAAkB,CAKpC,MAJc,CACV,GAAG,EAAA,mBAAmB,CAAE,CAAC,CAAC,IAAK,GAAM,EAAE,IAAI,EAC3C,GAAG,EAAA,0BAA0B,CAAE,CAAC,CAAC,IAAK,GAAM,EAAE,IAAI,CACtD,CAAC,CAAC,MAAM,EAAG,IAAM,EAAE,cAAc,EAAG,OAAO,CACpC,CAAA,CAAM,IAAK,IAAU,CAAE,MAAO,EAAM,MAAO,CAAK,EAAE,CAC7D,CAEA,SAAgB,EAAsB,CAClC,YACA,cACA,WACA,aAAa,SACb,YA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AAW,EAAE,OAAO,KAAK,EAC1C,MAAO,CAAE,SAAU,CAAE,CACxB,CAAA,CACA,GAEb"}
@@ -1,54 +1,62 @@
1
1
  import { Select as e } from "../components/Select/Select.js";
2
- import { cityChoices as t, listStates as n, normalizeUf as r } from "./locations.js";
3
- import { useMemo as i, useState as a } from "react";
4
- import { jsx as o, jsxs as s } from "react/jsx-runtime";
2
+ import { administrativeRegionsByUf as t, listStates as n, municipalitiesByUf as r, normalizeUf as i, resolveMunicipality as a } from "./locations.js";
3
+ import { useMemo as o, useState as s } from "react";
4
+ import { jsx as c, jsxs as l } from "react/jsx-runtime";
5
5
  //#region src/br/BrazilStateCitySelect.tsx
6
- function c({ defaultUf: c, defaultCity: l, onChange: u, stateLabel: d = "Estado", cityLabel: f = "Cidade", statePlaceholder: p = "Selecione o estado", cityPlaceholder: m = "Selecione a cidade", disabled: h = !1, layout: g = "row" }) {
7
- let [_, v] = a(c ?? null), [y, b] = a(l ?? null), x = i(() => n().map((e) => ({
6
+ function u(e) {
7
+ return [...r(e).map((e) => e.name), ...t(e).map((e) => e.name)].sort((e, t) => e.localeCompare(t, "pt-BR")).map((e) => ({
8
+ value: e,
9
+ label: e
10
+ }));
11
+ }
12
+ function d({ defaultUf: t, defaultCity: r, onChange: d, stateLabel: f = "Estado", cityLabel: p = "Cidade", statePlaceholder: m = "Selecione o estado", cityPlaceholder: h = "Selecione a cidade", disabled: g = !1, layout: _ = "row" }) {
13
+ let [v, y] = s(t ?? null), [b, x] = s(r ?? null), S = o(() => n().map((e) => ({
8
14
  value: e.uf,
9
15
  label: e.name
10
- })), []), S = i(() => _ ? t(_) : [], [_]);
11
- function C(e) {
12
- let t = r(e);
13
- v(t), b(null), u?.({
16
+ })), []), C = o(() => v ? u(v) : [], [v]);
17
+ function w(e) {
18
+ let t = i(e);
19
+ y(t), x(null), d?.({
14
20
  uf: t,
15
- city: null
21
+ city: null,
22
+ municipalityId: null
16
23
  });
17
24
  }
18
- function w(e) {
25
+ function T(e) {
19
26
  let t = e || null;
20
- b(t), u?.({
21
- uf: _,
22
- city: t
27
+ x(t), d?.({
28
+ uf: v,
29
+ city: t,
30
+ municipalityId: v && t ? a(v, t)?.id ?? null : null
23
31
  });
24
32
  }
25
- return /* @__PURE__ */ s("div", {
33
+ return /* @__PURE__ */ l("div", {
26
34
  style: {
27
35
  display: "flex",
28
- flexDirection: g === "row" ? "row" : "column",
36
+ flexDirection: _ === "row" ? "row" : "column",
29
37
  gap: "var(--tempest-space-3, 12px)",
30
38
  flexWrap: "wrap"
31
39
  },
32
- children: [/* @__PURE__ */ o(e, {
33
- label: d,
34
- placeholder: p,
35
- options: x,
36
- value: _ ?? "",
37
- disabled: h,
38
- onChange: (e) => C(e.target.value),
39
- style: { minWidth: 0 }
40
- }), /* @__PURE__ */ o(e, {
40
+ children: [/* @__PURE__ */ c(e, {
41
41
  label: f,
42
42
  placeholder: m,
43
43
  options: S,
44
- value: y ?? "",
45
- disabled: h || !_,
44
+ value: v ?? "",
45
+ disabled: g,
46
46
  onChange: (e) => w(e.target.value),
47
47
  style: { minWidth: 0 }
48
+ }), /* @__PURE__ */ c(e, {
49
+ label: p,
50
+ placeholder: h,
51
+ options: C,
52
+ value: b ?? "",
53
+ disabled: g || !v,
54
+ onChange: (e) => T(e.target.value),
55
+ style: { minWidth: 0 }
48
56
  })]
49
57
  });
50
58
  }
51
59
  //#endregion
52
- export { c as BrazilStateCitySelect };
60
+ export { d as BrazilStateCitySelect };
53
61
 
54
62
  //# sourceMappingURL=BrazilStateCitySelect.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"BrazilStateCitySelect.js","names":[],"sources":["../../src/br/BrazilStateCitySelect.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — two dependent selects in one control, so every knob\n * comes in pairs: stateLabel and cityLabel, statePlaceholder and cityPlaceholder,\n * defaultUf and defaultCity. The pairing is the feature — the city list is derived\n * from the chosen UF, which is exactly what a caller wiring two separate selects has\n * to reimplement.\n */\nimport { useMemo, useState, type ReactElement } from \"react\";\nimport { Select } from \"@/components/Select\";\nimport { cityChoices, listStates, normalizeUf, type UF } from \"./locations\";\n\n/** Current selection emitted by {@link BrazilStateCitySelect}. */\nexport interface BrazilStateCitySelection {\n /** Selected federative unit, or `null` when none. */\n uf: UF | null;\n /** Selected city, or `null` when none. */\n city: string | null;\n}\n\nexport interface BrazilStateCitySelectProps {\n /** Pre-selected UF (uncontrolled initial value). */\n defaultUf?: UF;\n /** Pre-selected city (uncontrolled initial value). */\n defaultCity?: string;\n /** Fired whenever the state or city changes. */\n onChange?: (selection: BrazilStateCitySelection) => void;\n /** Label for the state select. Default: `\"Estado\"`. */\n stateLabel?: string;\n /** Label for the city select. Default: `\"Cidade\"`. */\n cityLabel?: string;\n /** Placeholder for the state select. Default: `\"Selecione o estado\"`. */\n statePlaceholder?: string;\n /** Placeholder for the city select. Default: `\"Selecione a cidade\"`. */\n cityPlaceholder?: string;\n /** Disable both selects. */\n disabled?: boolean;\n /** Layout of the two selects. Default: `\"row\"`. */\n layout?: \"row\" | \"column\";\n}\n\n/**\n * Cascading Estado → Cidade selector backed by the bundled BR locations data —\n * pick a state and the city list narrows to that UF's municipalities. No\n * network, no external API. Complements {@link BrazilMap} (wire the map's\n * `onSelect` to drive the same UF).\n *\n * @example\n * <BrazilStateCitySelect onChange={({ uf, city }) => console.log(uf, city)} />\n */\nexport function BrazilStateCitySelect({\n defaultUf,\n defaultCity,\n onChange,\n stateLabel = \"Estado\",\n cityLabel = \"Cidade\",\n statePlaceholder = \"Selecione o estado\",\n cityPlaceholder = \"Selecione a cidade\",\n disabled = false,\n layout = \"row\",\n}: BrazilStateCitySelectProps): ReactElement {\n const [uf, setUf] = useState<UF | null>(defaultUf ?? null);\n const [city, setCity] = useState<string | null>(defaultCity ?? null);\n\n const stateOptions = useMemo(\n () => listStates().map((s) => ({ value: s.uf, label: s.name })),\n [],\n );\n const cityOptions = useMemo(() => (uf ? cityChoices(uf) : []), [uf]);\n\n function handleUf(next: string): void {\n const nextUf = normalizeUf(next);\n setUf(nextUf);\n setCity(null);\n onChange?.({ uf: nextUf, city: null });\n }\n\n function handleCity(next: string): void {\n const nextCity = next || null;\n setCity(nextCity);\n onChange?.({ uf, city: nextCity });\n }\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: layout === \"row\" ? \"row\" : \"column\",\n gap: \"var(--tempest-space-3, 12px)\",\n flexWrap: \"wrap\",\n }}\n >\n <Select\n label={stateLabel}\n placeholder={statePlaceholder}\n options={stateOptions}\n value={uf ?? \"\"}\n disabled={disabled}\n onChange={(e) => handleUf(e.target.value)}\n style={{ minWidth: 0 }}\n />\n <Select\n label={cityLabel}\n placeholder={cityPlaceholder}\n options={cityOptions}\n value={city ?? \"\"}\n disabled={disabled || !uf}\n onChange={(e) => handleCity(e.target.value)}\n style={{ minWidth: 0 }}\n />\n </div>\n );\n}\n"],"mappings":";;;;;AAiDA,SAAgB,EAAsB,EAClC,cACA,gBACA,aACA,gBAAa,UACb,eAAY,UACZ,sBAAmB,sBACnB,qBAAkB,sBAClB,cAAW,IACX,YAAS,SACgC;CACzC,IAAM,CAAC,GAAI,KAAS,EAAoB,KAAa,IAAI,GACnD,CAAC,GAAM,KAAW,EAAwB,KAAe,IAAI,GAE7D,IAAe,QACX,EAAW,CAAC,CAAC,KAAK,OAAO;EAAE,OAAO,EAAE;EAAI,OAAO,EAAE;CAAK,EAAE,GAC9D,CAAC,CACL,GACM,IAAc,QAAe,IAAK,EAAY,CAAE,IAAI,CAAC,GAAI,CAAC,CAAE,CAAC;CAEnE,SAAS,EAAS,GAAoB;EAClC,IAAM,IAAS,EAAY,CAAI;EAG/B,AAFA,EAAM,CAAM,GACZ,EAAQ,IAAI,GACZ,IAAW;GAAE,IAAI;GAAQ,MAAM;EAAK,CAAC;CACzC;CAEA,SAAS,EAAW,GAAoB;EACpC,IAAM,IAAW,KAAQ;EAEzB,AADA,EAAQ,CAAQ,GAChB,IAAW;GAAE;GAAI,MAAM;EAAS,CAAC;CACrC;CAEA,OACI,kBAAC,OAAD;EACI,OAAO;GACH,SAAS;GACT,eAAe,MAAW,QAAQ,QAAQ;GAC1C,KAAK;GACL,UAAU;EACd;EANJ,UAAA,CAQI,kBAAC,GAAD;GACI,OAAO;GACP,aAAa;GACb,SAAS;GACT,OAAO,KAAM;GACH;GACV,WAAW,MAAM,EAAS,EAAE,OAAO,KAAK;GACxC,OAAO,EAAE,UAAU,EAAE;EACxB,CAAA,GACD,kBAAC,GAAD;GACI,OAAO;GACP,aAAa;GACb,SAAS;GACT,OAAO,KAAQ;GACf,UAAU,KAAY,CAAC;GACvB,WAAW,MAAM,EAAW,EAAE,OAAO,KAAK;GAC1C,OAAO,EAAE,UAAU,EAAE;EACxB,CAAA,CACA;;AAEb"}
1
+ {"version":3,"file":"BrazilStateCitySelect.js","names":[],"sources":["../../src/br/BrazilStateCitySelect.tsx"],"sourcesContent":["/**\n * @tempest-limits props-count — two dependent selects in one control, so every knob\n * comes in pairs: stateLabel and cityLabel, statePlaceholder and cityPlaceholder,\n * defaultUf and defaultCity. The pairing is the feature — the city list is derived\n * from the chosen UF, which is exactly what a caller wiring two separate selects has\n * to reimplement.\n */\nimport { useMemo, useState, type ReactElement } from \"react\";\nimport { Select } from \"@/components/Select\";\nimport {\n administrativeRegionsByUf,\n listStates,\n municipalitiesByUf,\n normalizeUf,\n resolveMunicipality,\n type Choice,\n type UF,\n} from \"./locations\";\n\n/** Current selection emitted by {@link BrazilStateCitySelect}. */\nexport interface BrazilStateCitySelection {\n /** Selected federative unit, or `null` when none. */\n uf: UF | null;\n /** Selected city, or `null` when none. */\n city: string | null;\n /**\n * IBGE code of the selected municipality, or `null` when none is selected.\n *\n * This is the value to store. It survives the renames `city` does not, and\n * it is what `geocodeMunicipality` and every other dataset here join on. A\n * DF administrative region carries Brasília's code, because that is the\n * municipality it is part of.\n */\n municipalityId: string | null;\n}\n\nexport interface BrazilStateCitySelectProps {\n /** Pre-selected UF (uncontrolled initial value). */\n defaultUf?: UF;\n /** Pre-selected city (uncontrolled initial value). */\n defaultCity?: string;\n /** Fired whenever the state or city changes. */\n onChange?: (selection: BrazilStateCitySelection) => void;\n /** Label for the state select. Default: `\"Estado\"`. */\n stateLabel?: string;\n /** Label for the city select. Default: `\"Cidade\"`. */\n cityLabel?: string;\n /** Placeholder for the state select. Default: `\"Selecione o estado\"`. */\n statePlaceholder?: string;\n /** Placeholder for the city select. Default: `\"Selecione a cidade\"`. */\n cityPlaceholder?: string;\n /** Disable both selects. */\n disabled?: boolean;\n /** Layout of the two selects. Default: `\"row\"`. */\n layout?: \"row\" | \"column\";\n}\n\n/**\n * Cascading Estado → Cidade selector backed by the bundled BR locations data —\n * pick a state and the city list narrows to that UF's municipalities. No\n * network, no external API. Complements {@link BrazilMap} (wire the map's\n * `onSelect` to drive the same UF).\n *\n * @example\n * <BrazilStateCitySelect onChange={({ uf, city }) => console.log(uf, city)} />\n */\n/**\n * The pickable places of a federative unit: its municipalities, plus the DF's\n * administrative regions.\n *\n * The DF has one municipality and nobody there writes \"Brasília\" in an address\n * field — they write Ceilândia, Taguatinga, Gama. Offering only the municipality\n * would be faithful to IBGE and useless in a form, so the 35 regions are listed\n * beside it and every one of them resolves to Brasília's code.\n *\n * @param uf - The selected federative unit.\n * @returns `{ value, label }` options, alphabetically, value === label.\n */\nfunction placeChoices(uf: UF): Choice[] {\n const names = [\n ...municipalitiesByUf(uf).map((m) => m.name),\n ...administrativeRegionsByUf(uf).map((r) => r.name),\n ].sort((a, b) => a.localeCompare(b, \"pt-BR\"));\n return names.map((name) => ({ value: name, label: name }));\n}\n\nexport function BrazilStateCitySelect({\n defaultUf,\n defaultCity,\n onChange,\n stateLabel = \"Estado\",\n cityLabel = \"Cidade\",\n statePlaceholder = \"Selecione o estado\",\n cityPlaceholder = \"Selecione a cidade\",\n disabled = false,\n layout = \"row\",\n}: BrazilStateCitySelectProps): ReactElement {\n const [uf, setUf] = useState<UF | null>(defaultUf ?? null);\n const [city, setCity] = useState<string | null>(defaultCity ?? null);\n\n const stateOptions = useMemo(\n () => listStates().map((s) => ({ value: s.uf, label: s.name })),\n [],\n );\n const cityOptions = useMemo(() => (uf ? placeChoices(uf) : []), [uf]);\n\n function handleUf(next: string): void {\n const nextUf = normalizeUf(next);\n setUf(nextUf);\n setCity(null);\n onChange?.({ uf: nextUf, city: null, municipalityId: null });\n }\n\n function handleCity(next: string): void {\n const nextCity = next || null;\n setCity(nextCity);\n onChange?.({\n uf,\n city: nextCity,\n municipalityId: uf && nextCity ? (resolveMunicipality(uf, nextCity)?.id ?? null) : null,\n });\n }\n\n return (\n <div\n style={{\n display: \"flex\",\n flexDirection: layout === \"row\" ? \"row\" : \"column\",\n gap: \"var(--tempest-space-3, 12px)\",\n flexWrap: \"wrap\",\n }}\n >\n <Select\n label={stateLabel}\n placeholder={statePlaceholder}\n options={stateOptions}\n value={uf ?? \"\"}\n disabled={disabled}\n onChange={(e) => handleUf(e.target.value)}\n style={{ minWidth: 0 }}\n />\n <Select\n label={cityLabel}\n placeholder={cityPlaceholder}\n options={cityOptions}\n value={city ?? \"\"}\n disabled={disabled || !uf}\n onChange={(e) => handleCity(e.target.value)}\n style={{ minWidth: 0 }}\n />\n </div>\n );\n}\n"],"mappings":";;;;;AA8EA,SAAS,EAAa,GAAkB;CAKpC,OAJc,CACV,GAAG,EAAmB,CAAE,CAAC,CAAC,KAAK,MAAM,EAAE,IAAI,GAC3C,GAAG,EAA0B,CAAE,CAAC,CAAC,KAAK,MAAM,EAAE,IAAI,CACtD,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,cAAc,GAAG,OAAO,CACpC,CAAA,CAAM,KAAK,OAAU;EAAE,OAAO;EAAM,OAAO;CAAK,EAAE;AAC7D;AAEA,SAAgB,EAAsB,EAClC,cACA,gBACA,aACA,gBAAa,UACb,eAAY,UACZ,sBAAmB,sBACnB,qBAAkB,sBAClB,cAAW,IACX,YAAS,SACgC;CACzC,IAAM,CAAC,GAAI,KAAS,EAAoB,KAAa,IAAI,GACnD,CAAC,G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