@spencerboucher/switchyard 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +20 -16
  2. package/dist/policies/worker.js +1866 -1777
  3. package/dist/switchyard.mjs +5526 -4684
  4. package/package.json +1 -1
  5. package/web-dist/assets/AutomationView-DwZ_2m9J.js +2 -0
  6. package/web-dist/assets/AutomationView-DwZ_2m9J.js.map +1 -0
  7. package/web-dist/assets/Checkbox-DR78wXsg.js +2 -0
  8. package/web-dist/assets/{Checkbox-BnRsg6ki.js.map → Checkbox-DR78wXsg.js.map} +1 -1
  9. package/web-dist/assets/DangerZone-CBnW9h0p.js +2 -0
  10. package/web-dist/assets/{DangerZone-BicyqXv8.js.map → DangerZone-CBnW9h0p.js.map} +1 -1
  11. package/web-dist/assets/Field-DS2BMoqA.js +2 -0
  12. package/web-dist/assets/{Field-Cp-08kpe.js.map → Field-DS2BMoqA.js.map} +1 -1
  13. package/web-dist/assets/{Markdown-BPWc6K6m.js → Markdown-BIO6MBTM.js} +7 -7
  14. package/web-dist/assets/{Markdown-BPWc6K6m.js.map → Markdown-BIO6MBTM.js.map} +1 -1
  15. package/web-dist/assets/NavigationEditor-C0J7vDXL.js +2 -0
  16. package/web-dist/assets/NavigationEditor-C0J7vDXL.js.map +1 -0
  17. package/web-dist/assets/Overlay-DPZqU_vB.js +2 -0
  18. package/web-dist/assets/Overlay-DPZqU_vB.js.map +1 -0
  19. package/web-dist/assets/Priority-0hv1Vpg7.js +2 -0
  20. package/web-dist/assets/{Priority-ZGpTH645.js.map → Priority-0hv1Vpg7.js.map} +1 -1
  21. package/web-dist/assets/RadioCards-CN5xELnc.js +2 -0
  22. package/web-dist/assets/RadioCards-CN5xELnc.js.map +1 -0
  23. package/web-dist/assets/ScopeSelect-BaJjip1Y.js +2 -0
  24. package/web-dist/assets/ScopeSelect-BaJjip1Y.js.map +1 -0
  25. package/web-dist/assets/SegmentedControl-CRmhE-Kn.js +2 -0
  26. package/web-dist/assets/SegmentedControl-CRmhE-Kn.js.map +1 -0
  27. package/web-dist/assets/Select-CN7M29ap.js +2 -0
  28. package/web-dist/assets/{Select-DHRR7IAK.js.map → Select-CN7M29ap.js.map} +1 -1
  29. package/web-dist/assets/Switch-CZMY83Fw.js +2 -0
  30. package/web-dist/assets/{Switch-D5pVfZgf.js.map → Switch-CZMY83Fw.js.map} +1 -1
  31. package/web-dist/assets/Tabs-_1w3hoAR.js +2 -0
  32. package/web-dist/assets/Tabs-_1w3hoAR.js.map +1 -0
  33. package/web-dist/assets/TextLink-BpF2vLiL.js +2 -0
  34. package/web-dist/assets/{TextLink-BGtYWCW9.js.map → TextLink-BpF2vLiL.js.map} +1 -1
  35. package/web-dist/assets/UINodeRenderer-DqIkLhF8.js +4 -0
  36. package/web-dist/assets/UINodeRenderer-DqIkLhF8.js.map +1 -0
  37. package/web-dist/assets/UnfilteredNote-22-Qjb-f.js +2 -0
  38. package/web-dist/assets/UnfilteredNote-22-Qjb-f.js.map +1 -0
  39. package/web-dist/assets/api-RftVSu44.js +2 -0
  40. package/web-dist/assets/api-RftVSu44.js.map +1 -0
  41. package/web-dist/assets/{arrow-down-Dn3KG_JI.js → arrow-down-CzjHSpfM.js} +2 -2
  42. package/web-dist/assets/{arrow-down-Dn3KG_JI.js.map → arrow-down-CzjHSpfM.js.map} +1 -1
  43. package/web-dist/assets/{arrow-up-BiPtOqqy.js → arrow-up-B4YU8Bg0.js} +2 -2
  44. package/web-dist/assets/{arrow-up-BiPtOqqy.js.map → arrow-up-B4YU8Bg0.js.map} +1 -1
  45. package/web-dist/assets/attention-CEgIsUuq.js +2 -0
  46. package/web-dist/assets/attention-CEgIsUuq.js.map +1 -0
  47. package/web-dist/assets/automations-DnydDML9.js +2 -0
  48. package/web-dist/assets/{automations-IX9DQNk8.js.map → automations-DnydDML9.js.map} +1 -1
  49. package/web-dist/assets/board-BPxxc8G4.js +6 -0
  50. package/web-dist/assets/board-BPxxc8G4.js.map +1 -0
  51. package/web-dist/assets/{calendar-clock-DVlat602.js → calendar-clock-B3bQkNKq.js} +2 -2
  52. package/web-dist/assets/{calendar-clock-DVlat602.js.map → calendar-clock-B3bQkNKq.js.map} +1 -1
  53. package/web-dist/assets/chevron-right-DuAbbYQ-.js +2 -0
  54. package/web-dist/assets/{chevron-right-BM1IJI2z.js.map → chevron-right-DuAbbYQ-.js.map} +1 -1
  55. package/web-dist/assets/code-D5IB7jTT.js +28 -0
  56. package/web-dist/assets/code-D5IB7jTT.js.map +1 -0
  57. package/web-dist/assets/{core.esm-C4dCvG0s.js → core.esm-BbOnWvFK.js} +2 -2
  58. package/web-dist/assets/{core.esm-C4dCvG0s.js.map → core.esm-BbOnWvFK.js.map} +1 -1
  59. package/web-dist/assets/describe-DWsoiUix.js +5 -0
  60. package/web-dist/assets/describe-DWsoiUix.js.map +1 -0
  61. package/web-dist/assets/enroll-CV77Sk6h.js +2 -0
  62. package/web-dist/assets/{enroll-GUEF5Uxu.js.map → enroll-CV77Sk6h.js.map} +1 -1
  63. package/web-dist/assets/git-branch-Dr8PvfHN.js +2 -0
  64. package/web-dist/assets/git-branch-Dr8PvfHN.js.map +1 -0
  65. package/web-dist/assets/grip-vertical-Bc5pJHHF.js +2 -0
  66. package/web-dist/assets/grip-vertical-Bc5pJHHF.js.map +1 -0
  67. package/web-dist/assets/{hand-B6lvj014.js → hand-B2TrADIv.js} +2 -2
  68. package/web-dist/assets/{hand-B6lvj014.js.map → hand-B2TrADIv.js.map} +1 -1
  69. package/web-dist/assets/haptics-O69vKVoK.js +2 -0
  70. package/web-dist/assets/haptics-O69vKVoK.js.map +1 -0
  71. package/web-dist/assets/index-BXQwol8u.css +2 -0
  72. package/web-dist/assets/index-cmIcNnnF.js +17 -0
  73. package/web-dist/assets/index-cmIcNnnF.js.map +1 -0
  74. package/web-dist/assets/{link-2-CCq9WzMy.js → link-2-M5ENDPWT.js} +2 -2
  75. package/web-dist/assets/{link-2-CCq9WzMy.js.map → link-2-M5ENDPWT.js.map} +1 -1
  76. package/web-dist/assets/logic-CG2E-voG.js +2 -0
  77. package/web-dist/assets/{logic-BnSIy9_P.js.map → logic-CG2E-voG.js.map} +1 -1
  78. package/web-dist/assets/logic-D_vBBkcD.js +4 -0
  79. package/web-dist/assets/logic-D_vBBkcD.js.map +1 -0
  80. package/web-dist/assets/more-CVjg2O5h.js +2 -0
  81. package/web-dist/assets/more-CVjg2O5h.js.map +1 -0
  82. package/web-dist/assets/pencil-y_4AgVa2.js +2 -0
  83. package/web-dist/assets/pencil-y_4AgVa2.js.map +1 -0
  84. package/web-dist/assets/{play-NHO6U6cY.js → play-CYKX2aVL.js} +2 -2
  85. package/web-dist/assets/{play-NHO6U6cY.js.map → play-CYKX2aVL.js.map} +1 -1
  86. package/web-dist/assets/{plus-C83uJhbf.js → plus-B6uH1yKa.js} +2 -2
  87. package/web-dist/assets/{plus-C83uJhbf.js.map → plus-B6uH1yKa.js.map} +1 -1
  88. package/web-dist/assets/policyLogic-CioD2rMm.js +2 -0
  89. package/web-dist/assets/{policyLogic-DqKyFQEW.js.map → policyLogic-CioD2rMm.js.map} +1 -1
  90. package/web-dist/assets/prefs-V29Ms2ZL.js +2 -0
  91. package/web-dist/assets/prefs-V29Ms2ZL.js.map +1 -0
  92. package/web-dist/assets/queue-BGK9c062.js +2 -0
  93. package/web-dist/assets/queue-BGK9c062.js.map +1 -0
  94. package/web-dist/assets/repo-CuL_qbqU.js +5 -0
  95. package/web-dist/assets/repo-CuL_qbqU.js.map +1 -0
  96. package/web-dist/assets/{rotate-ccw-BRrlVEAQ.js → rotate-ccw-DvfmNYNE.js} +2 -2
  97. package/web-dist/assets/{rotate-ccw-BRrlVEAQ.js.map → rotate-ccw-DvfmNYNE.js.map} +1 -1
  98. package/web-dist/assets/{search-C5H14z0D.js → search-GTFKEqAS.js} +2 -2
  99. package/web-dist/assets/{search-C5H14z0D.js.map → search-GTFKEqAS.js.map} +1 -1
  100. package/web-dist/assets/selection-CAMJBh5A.js +9 -0
  101. package/web-dist/assets/selection-CAMJBh5A.js.map +1 -0
  102. package/web-dist/assets/settings-o7k_MPK7.js +9 -0
  103. package/web-dist/assets/settings-o7k_MPK7.js.map +1 -0
  104. package/web-dist/assets/states-BUWwUyu-.js +60 -0
  105. package/web-dist/assets/states-BUWwUyu-.js.map +1 -0
  106. package/web-dist/assets/{terminal-CATQN_17.js → terminal-DGVFZER3.js} +2 -2
  107. package/web-dist/assets/{terminal-CATQN_17.js.map → terminal-DGVFZER3.js.map} +1 -1
  108. package/web-dist/assets/terminal-login-Gy6aLzgC.js +2 -0
  109. package/web-dist/assets/{terminal-login-BdkmJdOO.js.map → terminal-login-Gy6aLzgC.js.map} +1 -1
  110. package/web-dist/assets/useBreakpoint-DoLUoCMf.js +2 -0
  111. package/web-dist/assets/useBreakpoint-DoLUoCMf.js.map +1 -0
  112. package/web-dist/assets/useIndicator-BKqIsw2Q.js +2 -0
  113. package/web-dist/assets/useIndicator-BKqIsw2Q.js.map +1 -0
  114. package/web-dist/assets/useNow-BS_9T7IY.js +2 -0
  115. package/web-dist/assets/useNow-BS_9T7IY.js.map +1 -0
  116. package/web-dist/assets/useResource-CPN6cDQ5.js +2 -0
  117. package/web-dist/assets/useResource-CPN6cDQ5.js.map +1 -0
  118. package/web-dist/assets/useSwipeTabs-XRK0_O6T.js +2 -0
  119. package/web-dist/assets/useSwipeTabs-XRK0_O6T.js.map +1 -0
  120. package/web-dist/assets/workboard-FE6bAMnW.js +3 -0
  121. package/web-dist/assets/workboard-FE6bAMnW.js.map +1 -0
  122. package/web-dist/index.html +7 -7
  123. package/web-dist/sw.js +1 -1
  124. package/web-dist/sw.js.map +1 -1
  125. package/web-dist/assets/AutomationView-B4O_teaB.js +0 -2
  126. package/web-dist/assets/AutomationView-B4O_teaB.js.map +0 -1
  127. package/web-dist/assets/Button-C7TQGuSX.js +0 -2
  128. package/web-dist/assets/Button-C7TQGuSX.js.map +0 -1
  129. package/web-dist/assets/Card-DzHrwFrv.js +0 -2
  130. package/web-dist/assets/Card-DzHrwFrv.js.map +0 -1
  131. package/web-dist/assets/Checkbox-BnRsg6ki.js +0 -2
  132. package/web-dist/assets/DangerZone-BicyqXv8.js +0 -2
  133. package/web-dist/assets/Field-Cp-08kpe.js +0 -2
  134. package/web-dist/assets/Priority-ZGpTH645.js +0 -2
  135. package/web-dist/assets/SegmentedControl-Cvkz7C_A.js +0 -2
  136. package/web-dist/assets/SegmentedControl-Cvkz7C_A.js.map +0 -1
  137. package/web-dist/assets/Select-DHRR7IAK.js +0 -2
  138. package/web-dist/assets/Switch-D5pVfZgf.js +0 -2
  139. package/web-dist/assets/Tabs-2GilVMsH.js +0 -2
  140. package/web-dist/assets/Tabs-2GilVMsH.js.map +0 -1
  141. package/web-dist/assets/TextLink-BGtYWCW9.js +0 -2
  142. package/web-dist/assets/UINodeRenderer-BaANWHvJ.js +0 -4
  143. package/web-dist/assets/UINodeRenderer-BaANWHvJ.js.map +0 -1
  144. package/web-dist/assets/UnfilteredNote-zVO8ajSi.js +0 -2
  145. package/web-dist/assets/UnfilteredNote-zVO8ajSi.js.map +0 -1
  146. package/web-dist/assets/ViewSelect-C9gNftWK.js +0 -2
  147. package/web-dist/assets/ViewSelect-C9gNftWK.js.map +0 -1
  148. package/web-dist/assets/api-DMrk4xwq.js +0 -2
  149. package/web-dist/assets/api-DMrk4xwq.js.map +0 -1
  150. package/web-dist/assets/attention-B9uawu1d.js +0 -2
  151. package/web-dist/assets/attention-B9uawu1d.js.map +0 -1
  152. package/web-dist/assets/automations-IX9DQNk8.js +0 -2
  153. package/web-dist/assets/board-BUAI4L7M.js +0 -6
  154. package/web-dist/assets/board-BUAI4L7M.js.map +0 -1
  155. package/web-dist/assets/check-CEnbWw4D.js +0 -2
  156. package/web-dist/assets/check-CEnbWw4D.js.map +0 -1
  157. package/web-dist/assets/chevron-right-BM1IJI2z.js +0 -2
  158. package/web-dist/assets/code-Dav4E15n.js +0 -25
  159. package/web-dist/assets/code-Dav4E15n.js.map +0 -1
  160. package/web-dist/assets/describe-B66LJTqU.js +0 -2
  161. package/web-dist/assets/describe-B66LJTqU.js.map +0 -1
  162. package/web-dist/assets/describe-BeFxHr2Y.js +0 -5
  163. package/web-dist/assets/describe-BeFxHr2Y.js.map +0 -1
  164. package/web-dist/assets/enroll-GUEF5Uxu.js +0 -2
  165. package/web-dist/assets/external-link-B3hnazCa.js +0 -2
  166. package/web-dist/assets/external-link-B3hnazCa.js.map +0 -1
  167. package/web-dist/assets/index-BUZpNu-R.js +0 -22
  168. package/web-dist/assets/index-BUZpNu-R.js.map +0 -1
  169. package/web-dist/assets/index-C9iuCGwg.css +0 -2
  170. package/web-dist/assets/keyboardLayers-BZOygMAH.js +0 -2
  171. package/web-dist/assets/keyboardLayers-BZOygMAH.js.map +0 -1
  172. package/web-dist/assets/logic-BBQ4d1GC.js +0 -4
  173. package/web-dist/assets/logic-BBQ4d1GC.js.map +0 -1
  174. package/web-dist/assets/logic-BnSIy9_P.js +0 -2
  175. package/web-dist/assets/more-C1oPXLVM.js +0 -2
  176. package/web-dist/assets/more-C1oPXLVM.js.map +0 -1
  177. package/web-dist/assets/pencil-DeML-0z2.js +0 -2
  178. package/web-dist/assets/pencil-DeML-0z2.js.map +0 -1
  179. package/web-dist/assets/policyLogic-DqKyFQEW.js +0 -2
  180. package/web-dist/assets/queue-DWSd1kia.js +0 -2
  181. package/web-dist/assets/queue-DWSd1kia.js.map +0 -1
  182. package/web-dist/assets/repo-DRwGWCut.js +0 -2
  183. package/web-dist/assets/repo-DRwGWCut.js.map +0 -1
  184. package/web-dist/assets/settings-B0IbaTOd.js +0 -12
  185. package/web-dist/assets/settings-B0IbaTOd.js.map +0 -1
  186. package/web-dist/assets/states-hyf_ATdQ.js +0 -58
  187. package/web-dist/assets/states-hyf_ATdQ.js.map +0 -1
  188. package/web-dist/assets/terminal-login-BdkmJdOO.js +0 -2
  189. package/web-dist/assets/timer-DFrvOKOy.js +0 -2
  190. package/web-dist/assets/timer-DFrvOKOy.js.map +0 -1
  191. package/web-dist/assets/useBreakpoint-BYCN9s8X.js +0 -2
  192. package/web-dist/assets/useBreakpoint-BYCN9s8X.js.map +0 -1
  193. package/web-dist/assets/useNow-DXyC-YfE.js +0 -2
  194. package/web-dist/assets/useNow-DXyC-YfE.js.map +0 -1
  195. package/web-dist/assets/useResource-DYNGG9XS.js +0 -2
  196. package/web-dist/assets/useResource-DYNGG9XS.js.map +0 -1
  197. package/web-dist/assets/workboard-BJCZsLp5.js +0 -3
  198. package/web-dist/assets/workboard-BJCZsLp5.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import{o as e}from"./Button-C7TQGuSX.js";var t={name:`link-2`,size:24,node:[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]};t.node;var n=e(t);export{n as t};
2
- //# sourceMappingURL=link-2-CCq9WzMy.js.map
1
+ import{D as e}from"./states-BUWwUyu-.js";var t={name:`link-2`,size:24,node:[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]};t.node;var n=e(t);export{n as t};
2
+ //# sourceMappingURL=link-2-M5ENDPWT.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"link-2-CCq9WzMy.js","names":["createLucideIcon","__iconData","Link2"],"sources":["../../../../node_modules/.pnpm/lucide-react@1.61.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/link-2.mjs"],"sourcesContent":["/**\n * @license lucide-react v1.61.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"link-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M9 17H7A5 5 0 0 1 7 7h2\", key: \"8i5ue5\" }],\n [\"path\", { d: \"M15 7h2a5 5 0 1 1 0 10h-2\", key: \"1b9ql8\" }],\n [\"line\", { x1: \"8\", x2: \"16\", y1: \"12\", y2: \"12\", key: \"1jonct\" }]\n ]\n};\n__iconData.node;\nconst Link2 = createLucideIcon(__iconData);\n\nexport { __iconData, Link2 as default };\n//# sourceMappingURL=link-2.mjs.map\n"],"ignoreList":[0],"mappings":"A,yCASA,IAAMC,EAAa,CACjB,KAAM,SACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,0BAA2B,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EAAG,4BAA6B,IAAK,QAAS,CAAC,EAC1D,CAAC,OAAQ,CAAE,GAAI,IAAK,GAAI,KAAM,GAAI,KAAM,GAAI,KAAM,IAAK,QAAS,CAAC,CACnE,CACF,EACAA,EAAW,KACX,IAAMC,EAAQF,EAAiBC,CAAU,E"}
1
+ {"version":3,"file":"link-2-M5ENDPWT.js","names":["createLucideIcon","__iconData","Link2"],"sources":["../../../../node_modules/.pnpm/lucide-react@1.61.0_@types+react@19.3.0_react@19.3.1/node_modules/lucide-react/dist/esm/icons/link-2.mjs"],"sourcesContent":["/**\n * @license lucide-react v1.61.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"link-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M9 17H7A5 5 0 0 1 7 7h2\", key: \"8i5ue5\" }],\n [\"path\", { d: \"M15 7h2a5 5 0 1 1 0 10h-2\", key: \"1b9ql8\" }],\n [\"line\", { x1: \"8\", x2: \"16\", y1: \"12\", y2: \"12\", key: \"1jonct\" }]\n ]\n};\n__iconData.node;\nconst Link2 = createLucideIcon(__iconData);\n\nexport { __iconData, Link2 as default };\n//# sourceMappingURL=link-2.mjs.map\n"],"ignoreList":[0],"mappings":"A,yCASA,IAAMC,EAAa,CACjB,KAAM,SACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,0BAA2B,IAAK,QAAS,CAAC,EACxD,CAAC,OAAQ,CAAE,EAAG,4BAA6B,IAAK,QAAS,CAAC,EAC1D,CAAC,OAAQ,CAAE,GAAI,IAAK,GAAI,KAAM,GAAI,KAAM,GAAI,KAAM,IAAK,QAAS,CAAC,CACnE,CACF,EACAA,EAAW,KACX,IAAMC,EAAQF,EAAiBC,CAAU,E"}
@@ -0,0 +1,2 @@
1
+ import{fn as e,hn as t}from"./states-BUWwUyu-.js";function n(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function r(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function i(){return a.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var a={stubThis:e=>e};function o(e){let{id:t}=e;return{...e,id:r(t),transports:e.transports,type:e.type}}function s(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var c=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function l({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new c({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new c({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new c({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new c({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new c({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new c({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new c({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var u=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},d=[`cross-platform`,`platform`];function f(e){if(e&&!(d.indexOf(e)<0))return e}async function p(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:a=!1}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let s={...t,challenge:r(t.challenge),user:{...t.user,id:r(t.user.id)},excludeCredentials:t.excludeCredentials?.map(o)},c={};a&&(c.mediation=`conditional`),c.publicKey=s,c.signal=u.createNewAbortSignal();let d;try{d=await navigator.credentials.create(c)}catch(e){throw l({error:e,options:c})}if(!d)throw Error(`Registration was not completed`);let{id:p,rawId:h,response:g,type:_}=d,v;typeof g.getTransports==`function`&&(v=g.getTransports());let y;if(typeof g.getPublicKeyAlgorithm==`function`)try{y=g.getPublicKeyAlgorithm()}catch(e){m(`getPublicKeyAlgorithm()`,e)}let b;if(typeof g.getPublicKey==`function`)try{let e=g.getPublicKey();e!==null&&(b=n(e))}catch(e){m(`getPublicKey()`,e)}let x;if(typeof g.getAuthenticatorData==`function`)try{x=n(g.getAuthenticatorData())}catch(e){m(`getAuthenticatorData()`,e)}return{id:p,rawId:n(h),response:{attestationObject:n(g.attestationObject),clientDataJSON:n(g.clientDataJSON),transports:v,publicKeyAlgorithm:y,publicKey:b,authenticatorData:x},type:_,clientExtensionResults:d.getClientExtensionResults(),authenticatorAttachment:f(d.authenticatorAttachment)}}function m(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function h(){if(!i())return g.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?g.stubThis(new Promise(e=>e(!1))):g.stubThis(e.isConditionalMediationAvailable())}var g={stubThis:e=>e};function _({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new c({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new c({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!s(t))return new c({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new c({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new c({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function v(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:a=!1,verifyBrowserAutofillInput:s=!0}=e;if(!i())throw Error(`WebAuthn is not supported in this browser`);let c;t.allowCredentials?.length!==0&&(c=t.allowCredentials?.map(o));let l={...t,challenge:r(t.challenge),allowCredentials:c},d={};if(a){if(!await h())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&s)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');d.mediation=`conditional`,l.allowCredentials=[]}d.publicKey=l,d.signal=u.createNewAbortSignal();let p;try{p=await navigator.credentials.get(d)}catch(e){throw _({error:e,options:d})}if(!p)throw Error(`Authentication was not completed`);let{id:m,rawId:g,response:v,type:y}=p,b;return v.userHandle&&(b=n(v.userHandle)),{id:m,rawId:n(g),response:{authenticatorData:n(v.authenticatorData),clientDataJSON:n(v.clientDataJSON),signature:n(v.signature),userHandle:b},type:y,clientExtensionResults:p.getClientExtensionResults(),authenticatorAttachment:f(p.authenticatorAttachment)}}var y=t(e(),1);function b(e){return e instanceof Error&&(e.name===`NotAllowedError`||e.name===`AbortError`)}function x(){let[e,t]=(0,y.useState)(!1),n=(0,y.useRef)(0),r=(0,y.useRef)(!1),i=(0,y.useCallback)(e=>{r.current=e,t(e)},[]),a=(0,y.useCallback)(()=>{n.current++,u.cancelCeremony(),r.current=!1,t(!1)},[]),o=(0,y.useCallback)(async e=>{let t=++n.current;i(!0);try{let r=await e();return n.current===t?(i(!1),{ok:!0,value:r}):{ok:!1,canceled:!0}}catch(e){if(n.current!==t||(i(!1),b(e)))return{ok:!1,canceled:!0};throw e}},[i]);return(0,y.useEffect)(()=>()=>{r.current&&(n.current++,u.cancelCeremony())},[]),{waiting:e,run:o,cancel:a}}var S=2e3;function C(e){return{phase:`waiting`,startedAt:e,message:null}}function w(e,t){if(e.phase!==`waiting`)return e;if(t.type===`cancel`)return{...e,phase:`canceled`};if(t.now-e.startedAt>=6e5&&t.type!==`claim`)return{...e,phase:`timeout`};switch(t.type){case`tick`:return e;case`claim`:return t.result.status===`done`?{...e,phase:`done`}:t.now-e.startedAt>=6e5?{...e,phase:`timeout`}:e;case`claim_error`:return t.code===`unauthorized`||t.code===`invalid_request`?{...e,phase:`failed`,message:t.message}:e}}function T(e,t){return e.phase===`waiting`&&t}var E=`This account is not allowed to sign in to this server.`,D={enrollment_expired:"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.",enrollment_used:"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.",invalid_request:`The sign-in request was rejected. Try again.`,network:`Could not reach the coordinator. Check your connection and try again.`,rate_limited:`Too many attempts. Wait a minute and try again.`,unsupported_capability:`This sign-in method is not available on this server.`,unauthorized:`That sign-in was not accepted. Try again, or use another sign-in method.`};function O(e,t){let n=t?.trim()||null;switch(e){case`forbidden`:return n??E;case`oidc_failed`:return`Single sign-on failed: ${n??`the identity provider returned an error.`}`;case`unsupported_capability`:return n??D.unsupported_capability;default:return D[e]??n??`Sign-in failed (${e}).`}}function k(e){switch(e){case`enrollment_expired`:return`Sign-in link expired`;case`enrollment_used`:return`Sign-in link already used`;case`forbidden`:return`Not allowed`;case`oidc_failed`:return`Single sign-on failed`;case`rate_limited`:return`Too many attempts`;default:return`Sign-in failed`}}function A(e=navigator.userAgent){let t=/iPhone/.test(e)?`iPhone`:/iPad/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1?`iPad`:/Android/.test(e)?`Android`:/Macintosh|Mac OS X/.test(e)?`Mac`:/Windows/.test(e)?`Windows`:/Linux/.test(e)?`Linux`:`device`;return`${/Edg\//.test(e)?`Edge`:/Firefox\/|FxiOS/.test(e)?`Firefox`:/Chrome\/|CriOS/.test(e)?`Chrome`:/Safari\//.test(e)?`Safari`:`Browser`} on ${t}`}export{k as a,C as c,p as d,i as f,O as i,x as l,S as n,w as o,A as r,T as s,D as t,v as u};
2
+ //# sourceMappingURL=logic-CG2E-voG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"logic-BnSIy9_P.js","names":["useState","useRef","useCallback","__toESM","require_react","bufferToBase64URLString","bytes","buffer","str","charCode","base64URLStringToBuffer","base64","base64URLString","padLength","padded","binary","i","browserSupportsWebAuthn","_browserSupportsWebAuthnInternals","value","toPublicKeyCredentialDescriptor","descriptor","id","isValidDomain","hostname","WebAuthnError","message","name","cause","code","identifyRegistrationError","options","publicKey","error","param","effectiveDomain","WebAuthnAbortService","abortError","newController","attachments","toAuthenticatorAttachment","attachment","startRegistration","optionsJSON","createOptions","useAutoRegister","credential","err","transports","response","responsePublicKeyAlgorithm","warnOnBrokenImplementation","responsePublicKey","_publicKey","responseAuthenticatorData","rawId","methodName","browserSupportsWebAuthnAutofill","_browserSupportsWebAuthnAutofillInternals","resolve","globalPublicKeyCredential","identifyAuthenticationError","startAuthentication","allowCredentials","getOptions","useBrowserAutofill","verifyBrowserAutofillInput","userHandle","import_react","isCanceledCeremony","usePasskeyCeremony","waiting","setWaiting","token","waitingRef","set","v","cancel","run","mine","fn","HANDOFF_POLL_MS","startHandoff","now","handoffReduce","state","event","shouldPoll","visible","GENERIC_FORBIDDEN","ERROR_TEXT","enrollErrorText","d","detail","enrollErrorTitle","defaultDeviceName","device","ua"],"sources":["../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/bufferToBase64URLString.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/base64URLStringToBuffer.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthn.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toPublicKeyCredentialDescriptor.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/isValidDomain.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyRegistrationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnAbortService.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toAuthenticatorAttachment.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startRegistration.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthnAutofill.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyAuthenticationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startAuthentication.js","../../src/app/passkeyCeremony.ts","../../src/features/enroll/logic.ts"],"sourcesContent":["/**\n * Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various\n * credential response ArrayBuffers to string for sending back to the server as JSON.\n *\n * Helper method to compliment `base64URLStringToBuffer`\n */\nexport function bufferToBase64URLString(buffer) {\n const bytes = new Uint8Array(buffer);\n let str = '';\n for (const charCode of bytes) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n return base64String.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n","/**\n * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a\n * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or\n * excludeCredentials\n *\n * Helper method to compliment `bufferToBase64URLString`\n */\nexport function base64URLStringToBuffer(base64URLString) {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, '=');\n // Convert to a binary string\n const binary = atob(padded);\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * Determine if the browser is capable of Webauthn\n */\nexport function browserSupportsWebAuthn() {\n return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== undefined &&\n typeof globalThis.PublicKeyCredential === 'function');\n}\n/**\n * Make it possible to stub the return value during testing\n * @ignore Don't include this in docs output\n */\nexport const _browserSupportsWebAuthnInternals = {\n stubThis: (value) => value,\n};\n","import { base64URLStringToBuffer } from './base64URLStringToBuffer.js';\nexport function toPublicKeyCredentialDescriptor(descriptor) {\n const { id } = descriptor;\n return {\n ...descriptor,\n id: base64URLStringToBuffer(id),\n transports: descriptor.transports,\n type: descriptor.type,\n };\n}\n","/**\n * A simple test to determine if a hostname is a properly-formatted domain name\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex was originally sourced from here, then remixed to add punycode support:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n */\nexport function isValidDomain(hostname) {\n return (\n // Consider localhost valid as well since it's okay wrt Secure Contexts\n hostname === 'localhost' ||\n // Support punycode (ACE) or ascii labels and domains\n /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname));\n}\n","/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n constructor({ message, code, cause, name, }) {\n // @ts-ignore: help Rollup understand that `cause` is okay to set\n super(message, { cause });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name ?? cause.name;\n this.code = code;\n }\n}\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`\n */\nexport function identifyRegistrationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Registration ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'ConstraintError') {\n if (publicKey.authenticatorSelection?.requireResidentKey === true) {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n return new WebAuthnError({\n message: 'Discoverable credentials were required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n cause: error,\n });\n }\n else if (\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n options.mediation === 'conditional' &&\n publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n return new WebAuthnError({\n message: 'User verification was required during automatic registration but it could not be performed',\n code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n cause: error,\n });\n }\n else if (publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n return new WebAuthnError({\n message: 'User verification was required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n cause: error,\n });\n }\n }\n else if (error.name === 'InvalidStateError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n return new WebAuthnError({\n message: 'The authenticator was previously registered',\n code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n cause: error,\n });\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'NotSupportedError') {\n const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');\n if (validPubKeyCredParams.length === 0) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n return new WebAuthnError({\n message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n cause: error,\n });\n }\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n return new WebAuthnError({\n message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rp.id !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'TypeError') {\n if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n return new WebAuthnError({\n message: 'User ID was not between 1 and 64 characters',\n code: 'ERROR_INVALID_USER_ID_LENGTH',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new credential',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","class BaseWebAuthnAbortService {\n constructor() {\n Object.defineProperty(this, \"controller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n createNewAbortSignal() {\n // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n if (this.controller) {\n const abortError = new Error('Cancelling existing WebAuthn API call for new one');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n }\n const newController = new AbortController();\n this.controller = newController;\n return newController.signal;\n }\n cancelCeremony() {\n if (this.controller) {\n const abortError = new Error('Manually cancelling existing WebAuthn API call');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n this.controller = undefined;\n }\n }\n}\n/**\n * A service singleton to help ensure that only a single WebAuthn ceremony is active at a time.\n *\n * Users of **@simplewebauthn/browser** shouldn't typically need to use this, but it can help e.g.\n * developers building projects that use client-side routing to better control the behavior of\n * their UX in response to router navigation events.\n */\nexport const WebAuthnAbortService = new BaseWebAuthnAbortService();\n","const attachments = ['cross-platform', 'platform'];\n/**\n * If possible coerce a `string` value into a known `AuthenticatorAttachment`\n */\nexport function toAuthenticatorAttachment(attachment) {\n if (!attachment) {\n return;\n }\n if (attachments.indexOf(attachment) < 0) {\n return;\n }\n return attachment;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyRegistrationError } from '../helpers/identifyRegistrationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"registration\" via WebAuthn attestation\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`\n * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.\n */\nexport async function startRegistration(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useAutoRegister = false } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n user: {\n ...optionsJSON.user,\n id: base64URLStringToBuffer(optionsJSON.user.id),\n },\n excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),\n };\n // Prepare options for `.create()`\n const createOptions = {};\n /**\n * Try to use conditional create to register a passkey for the user with the password manager\n * the user just used to authenticate with. The user won't be shown any prominent UI by the\n * browser.\n */\n if (useAutoRegister) {\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n createOptions.mediation = 'conditional';\n }\n // Finalize options\n createOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n createOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete attestation\n let credential;\n try {\n credential = (await navigator.credentials.create(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n createOptions));\n }\n catch (err) {\n throw identifyRegistrationError({ error: err, options: createOptions });\n }\n if (!credential) {\n throw new Error('Registration was not completed');\n }\n const { id, rawId, response, type } = credential;\n // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required\n let transports = undefined;\n if (typeof response.getTransports === 'function') {\n transports = response.getTransports();\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responsePublicKeyAlgorithm = undefined;\n if (typeof response.getPublicKeyAlgorithm === 'function') {\n try {\n responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);\n }\n }\n let responsePublicKey = undefined;\n if (typeof response.getPublicKey === 'function') {\n try {\n const _publicKey = response.getPublicKey();\n if (_publicKey !== null) {\n responsePublicKey = bufferToBase64URLString(_publicKey);\n }\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKey()', error);\n }\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responseAuthenticatorData;\n if (typeof response.getAuthenticatorData === 'function') {\n try {\n responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());\n }\n catch (error) {\n warnOnBrokenImplementation('getAuthenticatorData()', error);\n }\n }\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n attestationObject: bufferToBase64URLString(response.attestationObject),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n transports,\n publicKeyAlgorithm: responsePublicKeyAlgorithm,\n publicKey: responsePublicKey,\n authenticatorData: responseAuthenticatorData,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n/**\n * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API\n * calls\n */\nfunction warnOnBrokenImplementation(methodName, cause) {\n console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\\n`, cause);\n}\n","import { browserSupportsWebAuthn } from './browserSupportsWebAuthn.js';\n/**\n * Determine if the browser supports conditional UI, so that WebAuthn credentials can\n * be shown to the user in the browser's typical password autofill popup.\n */\nexport function browserSupportsWebAuthnAutofill() {\n if (!browserSupportsWebAuthn()) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n /**\n * I don't like the `as unknown` here but there's a `declare var PublicKeyCredential` in\n * TS' DOM lib that's making it difficult for me to just go `as PublicKeyCredentialFuture` as I\n * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types\n * have a chance to catch up.\n */\n const globalPublicKeyCredential = globalThis\n .PublicKeyCredential;\n if (globalPublicKeyCredential?.isConditionalMediationAvailable === undefined) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable());\n}\n// Make it possible to stub the return value during testing\nexport const _browserSupportsWebAuthnAutofillInternals = {\n stubThis: (value) => value,\n};\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`\n */\nexport function identifyAuthenticationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Authentication ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rpId !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyAuthenticationError } from '../helpers/identifyAuthenticationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"login\" via WebAuthn assertion\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`\n * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.\n * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.\n */\nexport async function startAuthentication(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to avoid passing empty array to avoid blocking retrieval\n // of public key\n let allowCredentials;\n if (optionsJSON.allowCredentials?.length !== 0) {\n allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n allowCredentials,\n };\n // Prepare options for `.get()`\n const getOptions = {};\n /**\n * Set up the page to prompt the user to select a credential for authentication via the browser's\n * input autofill mechanism.\n */\n if (useBrowserAutofill) {\n if (!(await browserSupportsWebAuthnAutofill())) {\n throw Error('Browser does not support WebAuthn autofill');\n }\n // Check for an <input> with \"webauthn\" in its `autocomplete` attribute\n const eligibleInputs = document.querySelectorAll(\"input[autocomplete$='webauthn']\");\n // WebAuthn autofill requires at least one valid input\n if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {\n throw Error('No <input> with \"webauthn\" as the only or last value in its `autocomplete` attribute was detected');\n }\n // `CredentialMediationRequirement` doesn't know about \"conditional\" yet as of\n // typescript@4.6.3\n getOptions.mediation = 'conditional';\n // Conditional UI requires an empty allow list\n publicKey.allowCredentials = [];\n }\n // Finalize options\n getOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n getOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete assertion\n let credential;\n try {\n credential = (await navigator.credentials.get(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n getOptions));\n }\n catch (err) {\n throw identifyAuthenticationError({ error: err, options: getOptions });\n }\n if (!credential) {\n throw new Error('Authentication was not completed');\n }\n const { id, rawId, response, type } = credential;\n let userHandle = undefined;\n if (response.userHandle) {\n userHandle = bufferToBase64URLString(response.userHandle);\n }\n // Convert values to base64 to make it easier to send back to the server\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n authenticatorData: bufferToBase64URLString(response.authenticatorData),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n signature: bufferToBase64URLString(response.signature),\n userHandle,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n","import { WebAuthnAbortService } from \"@simplewebauthn/browser\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** A dismissed or aborted passkey prompt. */\nexport function isCanceledCeremony(err: unknown): boolean {\n return err instanceof Error && (err.name === \"NotAllowedError\" || err.name === \"AbortError\");\n}\n\n/**\n * Runs a WebAuthn ceremony the user can cancel at once. Some authenticator UIs never reject when\n * their popup closes, so Cancel does not wait for the browser: it resets and ignores the late result.\n */\nexport function usePasskeyCeremony() {\n const [waiting, setWaiting] = useState(false);\n const token = useRef(0);\n const waitingRef = useRef(false);\n\n const set = useCallback((v: boolean) => {\n waitingRef.current = v;\n setWaiting(v);\n }, []);\n\n const cancel = useCallback(() => {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n waitingRef.current = false;\n setWaiting(false);\n }, []);\n\n const run = useCallback(\n async <T>(\n fn: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; canceled: true }> => {\n const mine = ++token.current;\n set(true);\n try {\n const value = await fn();\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n return { ok: true, value };\n } catch (err) {\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n if (isCanceledCeremony(err)) return { ok: false, canceled: true };\n throw err;\n }\n },\n [set],\n );\n\n useEffect(\n () => () => {\n if (waitingRef.current) {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n }\n },\n [],\n );\n\n return { waiting, run, cancel };\n}\n","import type { OidcClaimResponse } from \"@switchyard/protocol\";\n\n/** How often the PWA polls `POST /api/auth/oidc/claim` while the screen is visible. */\nexport const HANDOFF_POLL_MS = 2000;\n/** How long a handoff waits before giving up (the coordinator flow lives 10 minutes). */\nexport const HANDOFF_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport type HandoffPhase = \"waiting\" | \"done\" | \"timeout\" | \"failed\" | \"canceled\";\n\nexport interface HandoffState {\n phase: HandoffPhase;\n startedAt: number;\n /** Set when `phase` is `failed`. */\n message: string | null;\n}\n\nexport type HandoffEvent =\n | { type: \"claim\"; result: OidcClaimResponse; now: number }\n | { type: \"claim_error\"; code: string; message: string; now: number }\n | { type: \"tick\"; now: number }\n | { type: \"cancel\" };\n\nexport function startHandoff(now: number): HandoffState {\n return { phase: \"waiting\", startedAt: now, message: null };\n}\n\n/**\n * Pure state machine for the PWA single sign-on handoff. Terminal phases\n * never change. A transient error (network, server hiccup) keeps waiting;\n * an expired or unknown flow (`unauthorized`, `invalid_request`) fails.\n */\nexport function handoffReduce(state: HandoffState, event: HandoffEvent): HandoffState {\n if (state.phase !== \"waiting\") return state;\n if (event.type === \"cancel\") return { ...state, phase: \"canceled\" };\n if (event.now - state.startedAt >= HANDOFF_TIMEOUT_MS && event.type !== \"claim\") {\n return { ...state, phase: \"timeout\" };\n }\n switch (event.type) {\n case \"tick\":\n return state;\n case \"claim\":\n if (event.result.status === \"done\") return { ...state, phase: \"done\" };\n return event.now - state.startedAt >= HANDOFF_TIMEOUT_MS\n ? { ...state, phase: \"timeout\" }\n : state;\n case \"claim_error\":\n if (event.code === \"unauthorized\" || event.code === \"invalid_request\") {\n return { ...state, phase: \"failed\", message: event.message };\n }\n return state;\n }\n}\n\n/** Whether a poll should run now: still waiting and the page is visible. */\nexport function shouldPoll(state: HandoffState, visible: boolean): boolean {\n return state.phase === \"waiting\" && visible;\n}\n\nconst GENERIC_FORBIDDEN = \"This account is not allowed to sign in to this server.\";\n\n/** Static texts for coordinator error codes shown on /sign-in. */\nexport const ERROR_TEXT: Record<string, string> = {\n enrollment_expired:\n \"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.\",\n enrollment_used:\n \"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.\",\n invalid_request: \"The sign-in request was rejected. Try again.\",\n network: \"Could not reach the coordinator. Check your connection and try again.\",\n rate_limited: \"Too many attempts. Wait a minute and try again.\",\n unsupported_capability: \"This sign-in method is not available on this server.\",\n unauthorized: \"That sign-in was not accepted. Try again, or use another sign-in method.\",\n};\n\n/**\n * Message for an error code, with the coordinator's `detail` where it is the\n * useful part (`/sign-in?error=forbidden&detail=Signed in as ...`).\n */\nexport function enrollErrorText(code: string, detail?: string | null): string {\n const d = detail?.trim() || null;\n switch (code) {\n case \"forbidden\":\n return d ?? GENERIC_FORBIDDEN;\n case \"oidc_failed\":\n return `Single sign-on failed: ${d ?? \"the identity provider returned an error.\"}`;\n case \"unsupported_capability\":\n return d ?? (ERROR_TEXT.unsupported_capability as string);\n default:\n return ERROR_TEXT[code] ?? d ?? `Sign-in failed (${code}).`;\n }\n}\n\n/** Short heading for an error alert. */\nexport function enrollErrorTitle(code: string): string {\n switch (code) {\n case \"enrollment_expired\":\n return \"Sign-in link expired\";\n case \"enrollment_used\":\n return \"Sign-in link already used\";\n case \"forbidden\":\n return \"Not allowed\";\n case \"oidc_failed\":\n return \"Single sign-on failed\";\n case \"rate_limited\":\n return \"Too many attempts\";\n default:\n return \"Sign-in failed\";\n }\n}\n\n/** A readable default device name from the user agent, e.g. \"Safari on iPhone\". */\nexport function defaultDeviceName(ua: string = navigator.userAgent): string {\n const device = /iPhone/.test(ua)\n ? \"iPhone\"\n : /iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)\n ? \"iPad\"\n : /Android/.test(ua)\n ? \"Android\"\n : /Macintosh|Mac OS X/.test(ua)\n ? \"Mac\"\n : /Windows/.test(ua)\n ? \"Windows\"\n : /Linux/.test(ua)\n ? \"Linux\"\n : \"device\";\n const browser = /Edg\\//.test(ua)\n ? \"Edge\"\n : /Firefox\\/|FxiOS/.test(ua)\n ? \"Firefox\"\n : /Chrome\\/|CriOS/.test(ua)\n ? \"Chrome\"\n : /Safari\\//.test(ua)\n ? \"Safari\"\n : \"Browser\";\n return `${browser} on ${device}`;\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12],"mappings":"A,gDAMA,SAAgBK,EAAwB,EAAQ,CAC5C,IAAMC,EAAQ,IAAI,WAAWC,CAAM,EAC/BC,EAAM,GACV,IAAK,IAAMC,KAAYH,EACnB,GAAO,OAAO,aAAaG,CAAQ,EAGvC,OADqB,KAAKD,CACR,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,KAAM,EAAE,CAChF,CCPA,SAAgBE,EAAwB,EAAiB,CAErD,IAAMC,EAASC,EAAgB,QAAQ,KAAM,GAAG,CAAC,CAAC,QAAQ,KAAM,GAAG,EAQ7DC,GAAa,EAAKF,EAAO,OAAS,GAAM,EACxCG,EAASH,EAAO,OAAOA,EAAO,OAASE,EAAW,GAAG,EAErDE,EAAS,KAAKD,CAAM,EAEpBP,EAAS,IAAI,YAAYQ,EAAO,MAAM,EACtCT,EAAQ,IAAI,WAAWC,CAAM,EACnC,IAAK,IAAIS,EAAI,EAAGA,EAAID,EAAO,OAAQ,IAC/B,EAAMC,GAAKD,EAAO,WAAWC,CAAC,EAElC,OAAOT,CACX,CCzBA,SAAgBU,GAA0B,CACtC,OAAOC,EAAkC,SAAS,YAAY,sBAAwB,IAAA,IAClF,OAAO,WAAW,qBAAwB,UAAU,CAC5D,CAKA,IAAaA,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ACvB,UACA,iBAAiB,KAAKA,CAAE,EACtB,SACA,WAAW,KAAKA,CAAE,EAChB,SACA,UACQ,MAAMD,GAC1B,C"}
1
+ {"version":3,"file":"logic-CG2E-voG.js","names":["useState","useRef","useCallback","require_react","__toESM","bufferToBase64URLString","bytes","buffer","str","charCode","base64URLStringToBuffer","base64","base64URLString","padLength","padded","binary","i","browserSupportsWebAuthn","_browserSupportsWebAuthnInternals","value","toPublicKeyCredentialDescriptor","descriptor","id","isValidDomain","hostname","WebAuthnError","message","name","cause","code","identifyRegistrationError","options","publicKey","error","param","effectiveDomain","WebAuthnAbortService","abortError","newController","attachments","toAuthenticatorAttachment","attachment","startRegistration","optionsJSON","createOptions","useAutoRegister","credential","err","transports","response","responsePublicKeyAlgorithm","warnOnBrokenImplementation","responsePublicKey","_publicKey","responseAuthenticatorData","rawId","methodName","browserSupportsWebAuthnAutofill","_browserSupportsWebAuthnAutofillInternals","resolve","globalPublicKeyCredential","identifyAuthenticationError","startAuthentication","allowCredentials","getOptions","useBrowserAutofill","verifyBrowserAutofillInput","userHandle","import_react","isCanceledCeremony","usePasskeyCeremony","waiting","setWaiting","token","waitingRef","set","v","cancel","run","mine","fn","HANDOFF_POLL_MS","startHandoff","now","handoffReduce","state","event","shouldPoll","visible","GENERIC_FORBIDDEN","ERROR_TEXT","enrollErrorText","d","detail","enrollErrorTitle","defaultDeviceName","device","ua"],"sources":["../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/bufferToBase64URLString.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/base64URLStringToBuffer.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthn.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toPublicKeyCredentialDescriptor.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/isValidDomain.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyRegistrationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/webAuthnAbortService.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/toAuthenticatorAttachment.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startRegistration.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/browserSupportsWebAuthnAutofill.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/helpers/identifyAuthenticationError.js","../../../../node_modules/.pnpm/@simplewebauthn+browser@14.0.0/node_modules/@simplewebauthn/browser/esm/methods/startAuthentication.js","../../src/app/passkeyCeremony.ts","../../src/features/enroll/logic.ts"],"sourcesContent":["/**\n * Convert the given array buffer into a Base64URL-encoded string. Ideal for converting various\n * credential response ArrayBuffers to string for sending back to the server as JSON.\n *\n * Helper method to compliment `base64URLStringToBuffer`\n */\nexport function bufferToBase64URLString(buffer) {\n const bytes = new Uint8Array(buffer);\n let str = '';\n for (const charCode of bytes) {\n str += String.fromCharCode(charCode);\n }\n const base64String = btoa(str);\n return base64String.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n","/**\n * Convert from a Base64URL-encoded string to an Array Buffer. Best used when converting a\n * credential ID from a JSON string to an ArrayBuffer, like in allowCredentials or\n * excludeCredentials\n *\n * Helper method to compliment `bufferToBase64URLString`\n */\nexport function base64URLStringToBuffer(base64URLString) {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, '=');\n // Convert to a binary string\n const binary = atob(padded);\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * Determine if the browser is capable of Webauthn\n */\nexport function browserSupportsWebAuthn() {\n return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== undefined &&\n typeof globalThis.PublicKeyCredential === 'function');\n}\n/**\n * Make it possible to stub the return value during testing\n * @ignore Don't include this in docs output\n */\nexport const _browserSupportsWebAuthnInternals = {\n stubThis: (value) => value,\n};\n","import { base64URLStringToBuffer } from './base64URLStringToBuffer.js';\nexport function toPublicKeyCredentialDescriptor(descriptor) {\n const { id } = descriptor;\n return {\n ...descriptor,\n id: base64URLStringToBuffer(id),\n transports: descriptor.transports,\n type: descriptor.type,\n };\n}\n","/**\n * A simple test to determine if a hostname is a properly-formatted domain name\n *\n * A \"valid domain\" is defined here: https://url.spec.whatwg.org/#valid-domain\n *\n * Regex was originally sourced from here, then remixed to add punycode support:\n * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html\n */\nexport function isValidDomain(hostname) {\n return (\n // Consider localhost valid as well since it's okay wrt Secure Contexts\n hostname === 'localhost' ||\n // Support punycode (ACE) or ascii labels and domains\n /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname));\n}\n","/**\n * A custom Error used to return a more nuanced error detailing _why_ one of the eight documented\n * errors in the spec was raised after calling `navigator.credentials.create()` or\n * `navigator.credentials.get()`:\n *\n * - `AbortError`\n * - `ConstraintError`\n * - `InvalidStateError`\n * - `NotAllowedError`\n * - `NotSupportedError`\n * - `SecurityError`\n * - `TypeError`\n * - `UnknownError`\n *\n * Error messages were determined through investigation of the spec to determine under which\n * scenarios a given error would be raised.\n */\nexport class WebAuthnError extends Error {\n constructor({ message, code, cause, name, }) {\n // @ts-ignore: help Rollup understand that `cause` is okay to set\n super(message, { cause });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name ?? cause.name;\n this.code = code;\n }\n}\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.create()`\n */\nexport function identifyRegistrationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Registration ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'ConstraintError') {\n if (publicKey.authenticatorSelection?.requireResidentKey === true) {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 4)\n return new WebAuthnError({\n message: 'Discoverable credentials were required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',\n cause: error,\n });\n }\n else if (\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n options.mediation === 'conditional' &&\n publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://w3c.github.io/webauthn/#sctn-createCredential (Step 22.4)\n return new WebAuthnError({\n message: 'User verification was required during automatic registration but it could not be performed',\n code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',\n cause: error,\n });\n }\n else if (publicKey.authenticatorSelection?.userVerification === 'required') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 5)\n return new WebAuthnError({\n message: 'User verification was required but no available authenticator supported it',\n code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',\n cause: error,\n });\n }\n }\n else if (error.name === 'InvalidStateError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 20)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 3)\n return new WebAuthnError({\n message: 'The authenticator was previously registered',\n code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',\n cause: error,\n });\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'NotSupportedError') {\n const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');\n if (validPubKeyCredParams.length === 0) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 10)\n return new WebAuthnError({\n message: 'No entry in pubKeyCredParams was of type \"public-key\"',\n code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',\n cause: error,\n });\n }\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 2)\n return new WebAuthnError({\n message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',\n code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 7)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rp.id !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 8)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rp.id}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'TypeError') {\n if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 5)\n return new WebAuthnError({\n message: 'User ID was not between 1 and 64 characters',\n code: 'ERROR_INVALID_USER_ID_LENGTH',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-make-cred (Step 8)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new credential',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","class BaseWebAuthnAbortService {\n constructor() {\n Object.defineProperty(this, \"controller\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n }\n createNewAbortSignal() {\n // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()\n if (this.controller) {\n const abortError = new Error('Cancelling existing WebAuthn API call for new one');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n }\n const newController = new AbortController();\n this.controller = newController;\n return newController.signal;\n }\n cancelCeremony() {\n if (this.controller) {\n const abortError = new Error('Manually cancelling existing WebAuthn API call');\n abortError.name = 'AbortError';\n this.controller.abort(abortError);\n this.controller = undefined;\n }\n }\n}\n/**\n * A service singleton to help ensure that only a single WebAuthn ceremony is active at a time.\n *\n * Users of **@simplewebauthn/browser** shouldn't typically need to use this, but it can help e.g.\n * developers building projects that use client-side routing to better control the behavior of\n * their UX in response to router navigation events.\n */\nexport const WebAuthnAbortService = new BaseWebAuthnAbortService();\n","const attachments = ['cross-platform', 'platform'];\n/**\n * If possible coerce a `string` value into a known `AuthenticatorAttachment`\n */\nexport function toAuthenticatorAttachment(attachment) {\n if (!attachment) {\n return;\n }\n if (attachments.indexOf(attachment) < 0) {\n return;\n }\n return attachment;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyRegistrationError } from '../helpers/identifyRegistrationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"registration\" via WebAuthn attestation\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`\n * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.\n */\nexport async function startRegistration(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useAutoRegister = false } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n user: {\n ...optionsJSON.user,\n id: base64URLStringToBuffer(optionsJSON.user.id),\n },\n excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),\n };\n // Prepare options for `.create()`\n const createOptions = {};\n /**\n * Try to use conditional create to register a passkey for the user with the password manager\n * the user just used to authenticate with. The user won't be shown any prominent UI by the\n * browser.\n */\n if (useAutoRegister) {\n // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024\n createOptions.mediation = 'conditional';\n }\n // Finalize options\n createOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n createOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete attestation\n let credential;\n try {\n credential = (await navigator.credentials.create(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n createOptions));\n }\n catch (err) {\n throw identifyRegistrationError({ error: err, options: createOptions });\n }\n if (!credential) {\n throw new Error('Registration was not completed');\n }\n const { id, rawId, response, type } = credential;\n // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required\n let transports = undefined;\n if (typeof response.getTransports === 'function') {\n transports = response.getTransports();\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responsePublicKeyAlgorithm = undefined;\n if (typeof response.getPublicKeyAlgorithm === 'function') {\n try {\n responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);\n }\n }\n let responsePublicKey = undefined;\n if (typeof response.getPublicKey === 'function') {\n try {\n const _publicKey = response.getPublicKey();\n if (_publicKey !== null) {\n responsePublicKey = bufferToBase64URLString(_publicKey);\n }\n }\n catch (error) {\n warnOnBrokenImplementation('getPublicKey()', error);\n }\n }\n // L3 says this is required, but browser and webview support are still not guaranteed.\n let responseAuthenticatorData;\n if (typeof response.getAuthenticatorData === 'function') {\n try {\n responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());\n }\n catch (error) {\n warnOnBrokenImplementation('getAuthenticatorData()', error);\n }\n }\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n attestationObject: bufferToBase64URLString(response.attestationObject),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n transports,\n publicKeyAlgorithm: responsePublicKeyAlgorithm,\n publicKey: responsePublicKey,\n authenticatorData: responseAuthenticatorData,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n/**\n * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API\n * calls\n */\nfunction warnOnBrokenImplementation(methodName, cause) {\n console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\\n`, cause);\n}\n","import { browserSupportsWebAuthn } from './browserSupportsWebAuthn.js';\n/**\n * Determine if the browser supports conditional UI, so that WebAuthn credentials can\n * be shown to the user in the browser's typical password autofill popup.\n */\nexport function browserSupportsWebAuthnAutofill() {\n if (!browserSupportsWebAuthn()) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n /**\n * I don't like the `as unknown` here but there's a `declare var PublicKeyCredential` in\n * TS' DOM lib that's making it difficult for me to just go `as PublicKeyCredentialFuture` as I\n * want. I think I'm fine with this for now since it's _supposed_ to be temporary, until TS types\n * have a chance to catch up.\n */\n const globalPublicKeyCredential = globalThis\n .PublicKeyCredential;\n if (globalPublicKeyCredential?.isConditionalMediationAvailable === undefined) {\n return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false)));\n }\n return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable());\n}\n// Make it possible to stub the return value during testing\nexport const _browserSupportsWebAuthnAutofillInternals = {\n stubThis: (value) => value,\n};\n","import { isValidDomain } from './isValidDomain.js';\nimport { WebAuthnError } from './webAuthnError.js';\n/**\n * Attempt to intuit _why_ an error was raised after calling `navigator.credentials.get()`\n */\nexport function identifyAuthenticationError({ error, options, }) {\n const { publicKey } = options;\n if (!publicKey) {\n throw Error('options was missing required publicKey property');\n }\n if (error.name === 'AbortError') {\n if (options.signal instanceof AbortSignal) {\n // https://www.w3.org/TR/webauthn-2/#sctn-createCredential (Step 16)\n return new WebAuthnError({\n message: 'Authentication ceremony was sent an abort signal',\n code: 'ERROR_CEREMONY_ABORTED',\n cause: error,\n });\n }\n }\n else if (error.name === 'NotAllowedError') {\n /**\n * Pass the error directly through. Platforms are overloading this error beyond what the spec\n * defines and we don't want to overwrite potentially useful error messages.\n */\n return new WebAuthnError({\n message: error.message,\n code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',\n cause: error,\n });\n }\n else if (error.name === 'SecurityError') {\n const effectiveDomain = globalThis.location.hostname;\n if (!isValidDomain(effectiveDomain)) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 5)\n return new WebAuthnError({\n message: `${globalThis.location.hostname} is an invalid domain`,\n code: 'ERROR_INVALID_DOMAIN',\n cause: error,\n });\n }\n else if (publicKey.rpId !== effectiveDomain) {\n // https://www.w3.org/TR/webauthn-2/#sctn-discover-from-external-source (Step 6)\n return new WebAuthnError({\n message: `The RP ID \"${publicKey.rpId}\" is invalid for this domain`,\n code: 'ERROR_INVALID_RP_ID',\n cause: error,\n });\n }\n }\n else if (error.name === 'UnknownError') {\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 1)\n // https://www.w3.org/TR/webauthn-2/#sctn-op-get-assertion (Step 12)\n return new WebAuthnError({\n message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',\n code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',\n cause: error,\n });\n }\n return error;\n}\n","import { bufferToBase64URLString } from '../helpers/bufferToBase64URLString.js';\nimport { base64URLStringToBuffer } from '../helpers/base64URLStringToBuffer.js';\nimport { browserSupportsWebAuthn } from '../helpers/browserSupportsWebAuthn.js';\nimport { browserSupportsWebAuthnAutofill } from '../helpers/browserSupportsWebAuthnAutofill.js';\nimport { toPublicKeyCredentialDescriptor } from '../helpers/toPublicKeyCredentialDescriptor.js';\nimport { identifyAuthenticationError } from '../helpers/identifyAuthenticationError.js';\nimport { WebAuthnAbortService } from '../helpers/webAuthnAbortService.js';\nimport { toAuthenticatorAttachment } from '../helpers/toAuthenticatorAttachment.js';\n/**\n * Begin authenticator \"login\" via WebAuthn assertion\n *\n * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`\n * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.\n * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.\n */\nexport async function startAuthentication(options) {\n // @ts-ignore: Intentionally check for old call structure to warn about improper API call\n if (!options.optionsJSON && options.challenge) {\n console.warn('startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.');\n // @ts-ignore: Reassign the options, passed in as a positional argument, to the expected variable\n options = { optionsJSON: options };\n }\n const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;\n if (!browserSupportsWebAuthn()) {\n throw new Error('WebAuthn is not supported in this browser');\n }\n // We need to avoid passing empty array to avoid blocking retrieval\n // of public key\n let allowCredentials;\n if (optionsJSON.allowCredentials?.length !== 0) {\n allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);\n }\n // We need to convert some values to Uint8Arrays before passing the credentials to the navigator\n const publicKey = {\n ...optionsJSON,\n challenge: base64URLStringToBuffer(optionsJSON.challenge),\n allowCredentials,\n };\n // Prepare options for `.get()`\n const getOptions = {};\n /**\n * Set up the page to prompt the user to select a credential for authentication via the browser's\n * input autofill mechanism.\n */\n if (useBrowserAutofill) {\n if (!(await browserSupportsWebAuthnAutofill())) {\n throw Error('Browser does not support WebAuthn autofill');\n }\n // Check for an <input> with \"webauthn\" in its `autocomplete` attribute\n const eligibleInputs = document.querySelectorAll(\"input[autocomplete$='webauthn']\");\n // WebAuthn autofill requires at least one valid input\n if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {\n throw Error('No <input> with \"webauthn\" as the only or last value in its `autocomplete` attribute was detected');\n }\n // `CredentialMediationRequirement` doesn't know about \"conditional\" yet as of\n // typescript@4.6.3\n getOptions.mediation = 'conditional';\n // Conditional UI requires an empty allow list\n publicKey.allowCredentials = [];\n }\n // Finalize options\n getOptions.publicKey = publicKey;\n // Set up the ability to cancel this request if the user attempts another\n getOptions.signal = WebAuthnAbortService.createNewAbortSignal();\n // Wait for the user to complete assertion\n let credential;\n try {\n credential = (await navigator.credentials.get(\n // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+\n getOptions));\n }\n catch (err) {\n throw identifyAuthenticationError({ error: err, options: getOptions });\n }\n if (!credential) {\n throw new Error('Authentication was not completed');\n }\n const { id, rawId, response, type } = credential;\n let userHandle = undefined;\n if (response.userHandle) {\n userHandle = bufferToBase64URLString(response.userHandle);\n }\n // Convert values to base64 to make it easier to send back to the server\n return {\n id,\n rawId: bufferToBase64URLString(rawId),\n response: {\n authenticatorData: bufferToBase64URLString(response.authenticatorData),\n clientDataJSON: bufferToBase64URLString(response.clientDataJSON),\n signature: bufferToBase64URLString(response.signature),\n userHandle,\n },\n type,\n clientExtensionResults: credential.getClientExtensionResults(),\n authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),\n };\n}\n","import { WebAuthnAbortService } from \"@simplewebauthn/browser\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** A dismissed or aborted passkey prompt. */\nexport function isCanceledCeremony(err: unknown): boolean {\n return err instanceof Error && (err.name === \"NotAllowedError\" || err.name === \"AbortError\");\n}\n\n/**\n * Runs a WebAuthn ceremony the user can cancel at once. Some authenticator UIs never reject when\n * their popup closes, so Cancel does not wait for the browser: it resets and ignores the late result.\n */\nexport function usePasskeyCeremony() {\n const [waiting, setWaiting] = useState(false);\n const token = useRef(0);\n const waitingRef = useRef(false);\n\n const set = useCallback((v: boolean) => {\n waitingRef.current = v;\n setWaiting(v);\n }, []);\n\n const cancel = useCallback(() => {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n waitingRef.current = false;\n setWaiting(false);\n }, []);\n\n const run = useCallback(\n async <T>(\n fn: () => Promise<T>,\n ): Promise<{ ok: true; value: T } | { ok: false; canceled: true }> => {\n const mine = ++token.current;\n set(true);\n try {\n const value = await fn();\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n return { ok: true, value };\n } catch (err) {\n if (token.current !== mine) return { ok: false, canceled: true };\n set(false);\n if (isCanceledCeremony(err)) return { ok: false, canceled: true };\n throw err;\n }\n },\n [set],\n );\n\n useEffect(\n () => () => {\n if (waitingRef.current) {\n token.current++;\n WebAuthnAbortService.cancelCeremony();\n }\n },\n [],\n );\n\n return { waiting, run, cancel };\n}\n","import type { OidcClaimResponse } from \"@switchyard/protocol\";\n\n/** How often the PWA polls `POST /api/auth/oidc/claim` while the screen is visible. */\nexport const HANDOFF_POLL_MS = 2000;\n/** How long a handoff waits before giving up (the coordinator flow lives 10 minutes). */\nexport const HANDOFF_TIMEOUT_MS = 10 * 60 * 1000;\n\nexport type HandoffPhase = \"waiting\" | \"done\" | \"timeout\" | \"failed\" | \"canceled\";\n\nexport interface HandoffState {\n phase: HandoffPhase;\n startedAt: number;\n /** Set when `phase` is `failed`. */\n message: string | null;\n}\n\nexport type HandoffEvent =\n | { type: \"claim\"; result: OidcClaimResponse; now: number }\n | { type: \"claim_error\"; code: string; message: string; now: number }\n | { type: \"tick\"; now: number }\n | { type: \"cancel\" };\n\nexport function startHandoff(now: number): HandoffState {\n return { phase: \"waiting\", startedAt: now, message: null };\n}\n\n/**\n * Pure state machine for the PWA single sign-on handoff. Terminal phases\n * never change. A transient error (network, server hiccup) keeps waiting;\n * an expired or unknown flow (`unauthorized`, `invalid_request`) fails.\n */\nexport function handoffReduce(state: HandoffState, event: HandoffEvent): HandoffState {\n if (state.phase !== \"waiting\") return state;\n if (event.type === \"cancel\") return { ...state, phase: \"canceled\" };\n if (event.now - state.startedAt >= HANDOFF_TIMEOUT_MS && event.type !== \"claim\") {\n return { ...state, phase: \"timeout\" };\n }\n switch (event.type) {\n case \"tick\":\n return state;\n case \"claim\":\n if (event.result.status === \"done\") return { ...state, phase: \"done\" };\n return event.now - state.startedAt >= HANDOFF_TIMEOUT_MS\n ? { ...state, phase: \"timeout\" }\n : state;\n case \"claim_error\":\n if (event.code === \"unauthorized\" || event.code === \"invalid_request\") {\n return { ...state, phase: \"failed\", message: event.message };\n }\n return state;\n }\n}\n\n/** Whether a poll should run now: still waiting and the page is visible. */\nexport function shouldPoll(state: HandoffState, visible: boolean): boolean {\n return state.phase === \"waiting\" && visible;\n}\n\nconst GENERIC_FORBIDDEN = \"This account is not allowed to sign in to this server.\";\n\n/** Static texts for coordinator error codes shown on /sign-in. */\nexport const ERROR_TEXT: Record<string, string> = {\n enrollment_expired:\n \"This sign-in link has expired. Links are valid for 10 minutes. Run `switchyard pair` on the server for a new one.\",\n enrollment_used:\n \"This sign-in link was already used. Each link signs in one browser. Run `switchyard pair` on the server for a new one.\",\n invalid_request: \"The sign-in request was rejected. Try again.\",\n network: \"Could not reach the coordinator. Check your connection and try again.\",\n rate_limited: \"Too many attempts. Wait a minute and try again.\",\n unsupported_capability: \"This sign-in method is not available on this server.\",\n unauthorized: \"That sign-in was not accepted. Try again, or use another sign-in method.\",\n};\n\n/**\n * Message for an error code, with the coordinator's `detail` where it is the\n * useful part (`/sign-in?error=forbidden&detail=Signed in as ...`).\n */\nexport function enrollErrorText(code: string, detail?: string | null): string {\n const d = detail?.trim() || null;\n switch (code) {\n case \"forbidden\":\n return d ?? GENERIC_FORBIDDEN;\n case \"oidc_failed\":\n return `Single sign-on failed: ${d ?? \"the identity provider returned an error.\"}`;\n case \"unsupported_capability\":\n return d ?? (ERROR_TEXT.unsupported_capability as string);\n default:\n return ERROR_TEXT[code] ?? d ?? `Sign-in failed (${code}).`;\n }\n}\n\n/** Short heading for an error alert. */\nexport function enrollErrorTitle(code: string): string {\n switch (code) {\n case \"enrollment_expired\":\n return \"Sign-in link expired\";\n case \"enrollment_used\":\n return \"Sign-in link already used\";\n case \"forbidden\":\n return \"Not allowed\";\n case \"oidc_failed\":\n return \"Single sign-on failed\";\n case \"rate_limited\":\n return \"Too many attempts\";\n default:\n return \"Sign-in failed\";\n }\n}\n\n/** A readable default device name from the user agent, e.g. \"Safari on iPhone\". */\nexport function defaultDeviceName(ua: string = navigator.userAgent): string {\n const device = /iPhone/.test(ua)\n ? \"iPhone\"\n : /iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)\n ? \"iPad\"\n : /Android/.test(ua)\n ? \"Android\"\n : /Macintosh|Mac OS X/.test(ua)\n ? \"Mac\"\n : /Windows/.test(ua)\n ? \"Windows\"\n : /Linux/.test(ua)\n ? \"Linux\"\n : \"device\";\n const browser = /Edg\\//.test(ua)\n ? \"Edge\"\n : /Firefox\\/|FxiOS/.test(ua)\n ? \"Firefox\"\n : /Chrome\\/|CriOS/.test(ua)\n ? \"Chrome\"\n : /Safari\\//.test(ua)\n ? \"Safari\"\n : \"Browser\";\n return `${browser} on ${device}`;\n}\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12],"mappings":"A,kDAMA,SAAgBK,EAAwB,EAAQ,CAC5C,IAAMC,EAAQ,IAAI,WAAWC,CAAM,EAC/BC,EAAM,GACV,IAAK,IAAMC,KAAYH,EACnB,GAAO,OAAO,aAAaG,CAAQ,EAGvC,OADqB,KAAKD,CACR,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,MAAO,GAAG,CAAC,CAAC,QAAQ,KAAM,EAAE,CAChF,CCPA,SAAgBE,EAAwB,EAAiB,CAErD,IAAMC,EAASC,EAAgB,QAAQ,KAAM,GAAG,CAAC,CAAC,QAAQ,KAAM,GAAG,EAQ7DC,GAAa,EAAKF,EAAO,OAAS,GAA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ACT,QACE,MAAO,gBACX,CACF,CAGA,SAAgBkE,EAAkB,EAAa,UAAU,UAAmB,CAC1E,IAAMC,EAAS,SAAS,KAAKC,CAAE,EAC3B,SACA,OAAO,KAAKA,CAAE,GAAM,YAAY,KAAKA,CAAE,GAAK,UAAU,eAAiB,EACrE,OACA,UAAU,KAAKA,CAAE,EACf,UACA,qBAAqB,KAAKA,CAAE,EAC1B,MACA,UAAU,KAAKA,CAAE,EACf,UACA,QAAQ,KAAKA,CAAE,EACb,QACA,SAUd,MAAO,GATS,QAAQ,KAAKA,CAAE,EAC3B,OACA,kBAAkB,KAAKA,CAAE,EACvB,UACA,iBAAiB,KAAKA,CAAE,EACtB,SACA,WAAW,KAAKA,CAAE,EAChB,SACA,UACQ,MAAMD,GAC1B,C"}
@@ -0,0 +1,4 @@
1
+ import{Kt as e,Qt as t,St as n,W as r,Yt as i,Zt as a,_ as o,d as s,fn as c,g as l,hn as u,m as d,n as f,un as p,v as m}from"./states-BUWwUyu-.js";import{_ as h,g,i as _,m as v,n as y,p as b,t as x,u as S,v as C}from"./Overlay-DPZqU_vB.js";import{Bt as w,H as T,Ht as E,O as D,Rt as O,U as k,Vt as A,Wt as j,mt as M,y as N,z as P}from"./selection-CAMJBh5A.js";import{t as F}from"./arrow-up-B4YU8Bg0.js";import{t as I}from"./UINodeRenderer-DqIkLhF8.js";import{t as L}from"./Field-DS2BMoqA.js";import{t as R}from"./useBreakpoint-DoLUoCMf.js";import{$ as ee,G as z,K as B,W as V}from"./index-cmIcNnnF.js";import{t as H}from"./TextLink-BpF2vLiL.js";import{n as U,t as te}from"./Markdown-BIO6MBTM.js";import{t as W}from"./haptics-O69vKVoK.js";import{a as G,n as ne,t as K}from"./api-RftVSu44.js";var q=u(c(),1),re=`An extension opened a terminal-only dialog. In RPC mode Pi gave it no answer, so the extension continued without one.`,ie=[{id:`abort`,label:`Stop the run`,tone:`danger`},{id:`message`,label:`Send a message to Pi`,tone:`primary`}];function ae(e){if(e.t===`actions`)return e;if(e.t===`section`)for(let t of e.children){let e=ae(t);if(e)return e}return null}function oe(e){return e.state===`unsupported`||e.source.kind===`unsupported_custom`}function se(e){let t=(ae(e.presentation)?.actions??[]).filter(e=>e.id===`abort`||e.id===`message`).map(e=>({id:e.id,label:e.label,tone:e.tone==="default"?`secondary`:e.tone??(e.id===`abort`?`danger`:`primary`)}));return{answerable:e.state===`unsupported`&&e.resolution===null,actions:t.length>0?t:ie,copy:re}}function ce(e){return e===`running`||e===`waiting_input`?`followUp`:`prompt`}var J=d();function Y(e){switch(e.t){case`form`:case`confirm`:case`actions`:return!0;case`list`:return e.items.some(Y);case`section`:return e.children.some(Y);case`tabs`:return e.tabs.some(e=>e.children.some(Y));default:return!1}}function X(e){return e===`host`?`the host`:e===`pi`?`Pi`:`a device`}function le({interaction:e,readOnlyReason:n,className:o,onAnswered:c,id:u,sticky:d,flush:p,mode:h=`card`,keys:g=!0,planAnchorId:_}){let v=r(e=>e.upsertInteraction),[y,b]=(0,q.useState)(!1),[x,S]=(0,q.useState)(null),[C,w]=(0,q.useState)(null),[T,E]=(0,q.useState)(null),[D,O]=(0,q.useState)(null),k=D&&D.id===e.id&&D.revision>e.revision?D:e,A=k.state===`pending`,j=oe(k),M=r(e=>e.sessions[k.sessionId]?.runtime),[N,P]=(0,q.useState)(!1),[F,L]=(0,q.useState)(``),z=async e=>{b(!0),S(null),E(e);try{let t=await i(`/api/interactions/${encodeURIComponent(k.id)}/answer`,{revision:k.revision,response:e});return t?.interaction&&(v(t.interaction),O(t.interaction),c?.(t.interaction)),!0}catch(e){if(t(e,`already_answered`)){let t=e.details?.interaction;t&&(v(t),O(t)),w(t?.resolution?.summary??`answered on another device`)}else S(e);return!1}finally{b(!1)}},B=async()=>{let e=F.trim();if(e){b(!0),S(null);try{await i(`/api/sessions/${encodeURIComponent(k.sessionId)}/prompt`,{text:e,mode:ce(M)})}catch(e){S(e),b(!1);return}b(!1),await z({kind:`action`,actionId:`message`})&&(P(!1),L(``))}},V=R();if(A&&!C&&!j&&he(k.presentation))return(0,J.jsx)(ye,{id:u,interaction:k,node:k.presentation,onRespond:e=>void z(e),busy:y,disabled:!!n,disabledReason:n??null,part:h===`reader`?`reader`:h===`dock`?`answers`:`all`,planAnchorId:_,mobile:V===`mobile`,sticky:d??!0,flush:p??!1,className:o});let H=h===`dock`;return(0,J.jsxs)(`article`,{id:u,"aria-label":`Question: ${k.title}`,className:m(H?`flex min-w-0 flex-col gap-2`:`flex min-w-0 flex-col gap-3 border-l-2 py-1 pl-3`,!H&&(A?`border-warning`:`border-border`),o),children:[H?(0,J.jsx)(`h3`,{className:`text-sm font-semibold break-words`,children:k.title}):(0,J.jsxs)(`header`,{className:`flex min-w-0 flex-wrap items-start gap-2`,children:[(0,J.jsx)(`h3`,{className:`min-w-0 flex-1 text-sm font-semibold break-words`,children:k.title}),(0,J.jsx)(ee,{kind:`interaction`,value:k.state,size:`sm`})]}),C&&(0,J.jsxs)(`p`,{role:`status`,className:`rounded-md bg-surface-2 px-3 py-2 text-sm`,children:[`Already answered: `,C]}),j?(0,J.jsx)(ue,{interaction:k,readOnlyReason:n??null,busy:y,answered:C!==null,composing:N,message:F,setMessage:L,onAction:e=>{e===`message`?P(!0):z({kind:`action`,actionId:e})},onSend:()=>void B(),onCancelMessage:()=>P(!1)}):A&&!C?(0,J.jsxs)(J.Fragment,{children:[n&&(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:n}),(0,J.jsx)(I,{node:k.presentation,onRespond:e=>void z(e),busy:y,disabled:!!n,dock:H?{title:k.title,keys:g&&k.kind===`question`}:void 0}),!n&&!Y(k.presentation)&&(0,J.jsx)(`div`,{children:(0,J.jsx)(s,{busy:y,onClick:()=>void z({kind:`cancel`}),children:`Dismiss`})}),y&&(0,J.jsx)(`p`,{role:`status`,className:`text-sm text-muted`,children:`Sending answer… waiting for the host to confirm.`})]}):C?null:k.resolution?(0,J.jsxs)(`p`,{className:`text-sm text-muted`,children:[k.state===`resolved`?`Answered`:`Closed`,` by`,` `,X(k.resolution.by),` `,l(k.resolution.at),`:`,` `,(0,J.jsx)(`span`,{className:`text-text`,children:k.resolution.summary})]}):(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:k.state===`expired`?`This question expired before it was answered (Pi closed the dialog).`:`This question was canceled.`}),x!==null&&(0,J.jsx)(f,{compact:!0,title:`Answer not delivered`,error:a(x),onRetry:T?()=>void z(T):void 0})]})}function ue({interaction:e,readOnlyReason:t,busy:n,answered:r,composing:i,message:a,setMessage:o,onAction:c,onSend:u,onCancelMessage:d}){let f=se(e);return(0,J.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:f.copy}),e.resolution?(0,J.jsxs)(`p`,{className:`text-sm text-muted`,children:[`Chosen by `,X(e.resolution.by),` `,l(e.resolution.at),`: `,(0,J.jsx)(`span`,{className:`text-text`,children:e.resolution.summary})]}):!f.answerable||r?null:t?(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:t}):i?(0,J.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,J.jsx)(V,{"aria-label":`Message for Pi`,value:a,onChange:e=>o(e.target.value),rows:3,autoFocus:!0,placeholder:`Tell Pi what to do instead`}),(0,J.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,J.jsx)(s,{variant:`primary`,busy:n,disabled:!a.trim(),onClick:u,children:`Send message`}),(0,J.jsx)(s,{disabled:n,onClick:d,children:`Cancel`})]})]}):(0,J.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:f.actions.map(e=>(0,J.jsx)(s,{variant:e.tone,busy:n&&e.id===`abort`,disabled:n,onClick:()=>c(e.id),children:e.label},e.id))})]})}function de(e){if(e.t!==`section`||e.children.length<2)return null;let t=e.children[e.children.length-1];if(t?.t!==`actions`)return null;let n=e.children.slice(0,-1);return n.some(Y)?null:{body:{...e,children:n},actions:t}}function fe(e,t){let n=window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;e?.scrollIntoView({behavior:n?`auto`:`smooth`,block:t})}function pe(e){let[t,n]=(0,q.useState)(!0);return(0,q.useEffect)(()=>{let t=e.current;if(!t||typeof IntersectionObserver>`u`)return;let r=new IntersectionObserver(([e])=>n(!!e?.isIntersecting));return r.observe(t),()=>r.disconnect()},[e]),t}function me(e){if(e.t===`markdown`)return e.text;if(e.t===`section`)for(let t of e.children){let e=me(t);if(e!==null)return e}return null}function he(e){if(!de(e))return!1;let t=me(e);return t!==null&&(t.length>=400||t.split(`
2
+ `).length>=12)}function ge(e){let t=/^\s*#{1,6}\s+(.+?)\s*(?:\n+|$)/.exec(e);return t?.[1]?{title:t[1],rest:e.slice(t[0].length)}:{title:null,rest:e}}function _e(e){let t=[],n=!1;for(let r of e.split(`
3
+ `)){/^\s*```/.test(r)&&(n=!n);let e=n?null:/^##\s+(.+?)\s*$/.exec(r);e?.[1]&&t.push({text:e[1],id:U(e[1])})}return t}function ve(e,t){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(null),o=e.join(`|`);(0,q.useEffect)(()=>{if(typeof IntersectionObserver>`u`||!e.length)return;let n=e.map(e=>t.current?.querySelector(`#${CSS.escape(e)}`)).filter(e=>!!e),i=new IntersectionObserver(e=>{for(let t of e)t.isIntersecting&&r(t.target.id)},{rootMargin:`-56px 0px -70% 0px`});for(let e of n)i.observe(e);let o=()=>a(null);return window.addEventListener(`wheel`,o,{passive:!0}),window.addEventListener(`touchmove`,o,{passive:!0}),window.addEventListener(`keydown`,o),()=>{i.disconnect(),window.removeEventListener(`wheel`,o),window.removeEventListener(`touchmove`,o),window.removeEventListener(`keydown`,o)}},[o,t]);let s=i??n;return(0,q.useEffect)(()=>{let e=t.current;if(e){for(let t of e.querySelectorAll(`h2[data-active]`))delete t.dataset.active;if(s){let t=e.querySelector(`#${CSS.escape(s)}`);t&&(t.dataset.active=`true`)}}},[s,o,t]),[s,a]}function ye({id:e,interaction:t,node:n,onRespond:r,busy:i,disabled:a,disabledReason:o,part:c,planAnchorId:l,mobile:u,sticky:d,flush:f,className:p}){let h=(0,q.useRef)(null),g=(0,q.useRef)(null),v=(0,q.useRef)(null),y=pe(v),[b,x]=(0,q.useState)(!1),C=de(n),{title:w,rest:T}=ge((C?.body.t===`section`?C.body.children.find(e=>e.t===`markdown`):void 0)?.text??``),E=_e(T),[D,O]=ve(E.map(e=>e.id),h);if(C?.body.t!==`section`)return null;let k=C.actions.actions,A=C.body.children.find(e=>e.t===`section`),j=t.title,M=w??j,N=e=>{x(!1),r({kind:`action`,actionId:e})},P=(e,t)=>e===0||t===`primary`?`primary`:t===`danger`?`danger`:`secondary`,L=!a&&!y,R=`h-auto! min-h-9 min-w-0 py-1.5 text-left leading-tight whitespace-normal!`,z=e=>fe(e,`start`),B=()=>c===`answers`?l?document.getElementById(l):null:g.current,V=c!==`answers`||l!==void 0,U=u?(0,J.jsxs)(J.Fragment,{children:[V&&(0,J.jsx)(S,{label:`Plan start`,icon:(0,J.jsx)(F,{className:`size-4`}),variant:`secondary`,onClick:()=>z(B())}),k.length>2?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(s,{variant:`primary`,disabled:i,className:m(R,`flex-1`),onClick:()=>N(k[0].id),children:k[0].label}),(0,J.jsxs)(s,{variant:`secondary`,onClick:()=>x(!0),children:[`More (`,k.length-1,`)`]})]}):k.map((e,t)=>(0,J.jsx)(s,{variant:P(t,e.tone),disabled:i,className:m(R,`flex-1`),onClick:()=>N(e.id),children:e.label},e.id))]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`max-w-[16rem] min-w-0 shrink truncate text-sm font-medium`,title:j,children:j}),(0,J.jsx)(`div`,{className:`grid min-w-0 flex-1 grid-cols-[repeat(auto-fit,minmax(11rem,1fr))] gap-2`,children:k.map((e,t)=>(0,J.jsx)(s,{variant:P(t,e.tone),disabled:i,className:m(R,`w-full md:text-center`),onClick:()=>N(e.id),children:e.label},e.id))}),V&&(0,J.jsx)(S,{label:`Plan start`,icon:(0,J.jsx)(F,{className:`size-4`}),variant:`secondary`,size:`sm`,onClick:()=>z(B())})]}),W=(0,J.jsx)(_,{open:b,onClose:()=>x(!1),title:j,children:(0,J.jsx)(`div`,{className:`flex flex-col gap-2`,children:k.map((e,t)=>(0,J.jsx)(s,{block:!0,variant:P(t,e.tone),disabled:i,className:R,onClick:()=>N(e.id),children:e.label},e.id))})});if(c===`answers`)return(0,J.jsxs)(`article`,{"aria-label":`Question: ${j}`,"data-testid":`plan-answers`,className:m(`flex min-w-0 flex-col gap-2`,p),children:[u&&(0,J.jsx)(`p`,{className:`text-sm font-medium`,children:j}),o?(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:o}):(0,J.jsx)(`div`,{"data-testid":`answer-bar`,className:`flex min-w-0 items-center gap-2 md:gap-3`,children:U}),W]});let G=c===`reader`;return(0,J.jsxs)(`article`,{id:e,"data-testid":`document-interaction`,"aria-label":`Question: ${j}`,className:m(`w-full min-w-0 self-stretch border-t border-border`,p),children:[(0,J.jsxs)(`header`,{className:m(`z-10 flex min-w-0 items-center gap-2 border-b border-border bg-bg px-4 py-2 md:px-6`,d&&(f?`md:sticky md:top-0`:`max-md:static md:sticky md:-top-3`)),children:[(0,J.jsx)(`h3`,{className:`min-w-0 flex-1 truncate text-[15px] leading-snug font-semibold md:text-sm`,children:M}),u&&!G&&(0,J.jsx)(ee,{kind:`interaction`,value:t.state,size:`sm`,className:`[&>span]:sr-only`}),!G&&!a&&!y&&(0,J.jsx)(H,{size:`xs`,className:`shrink-0`,onClick:()=>fe(v.current,`center`),children:`Jump to options ↓`})]}),A&&(0,J.jsx)(`aside`,{className:`mx-4 mt-3 rounded-md bg-warning-soft px-3 py-2 text-sm md:mx-6`,children:(0,J.jsx)(I,{node:A})}),(0,J.jsxs)(`div`,{className:`px-4 py-4 md:grid md:grid-cols-[13rem_minmax(0,1fr)] 2xl:grid-cols-[15rem_minmax(0,1fr)] md:gap-8 md:px-6`,children:[E.length>0&&(0,J.jsx)(`nav`,{"aria-label":`Plan sections`,className:`hidden md:block`,children:(0,J.jsxs)(`ol`,{className:`sticky top-16 flex flex-col gap-0.5 border-l border-border text-sm`,children:[(0,J.jsx)(`li`,{children:(0,J.jsx)(`button`,{type:`button`,className:`-ml-px block w-full truncate border-l-2 border-transparent py-1 pl-3 text-left text-muted hover:text-text`,onClick:()=>z(g.current),children:`Start`})}),E.map(e=>(0,J.jsx)(`li`,{children:(0,J.jsx)(`button`,{type:`button`,"aria-current":D===e.id,className:`-ml-px block w-full truncate border-l-2 border-transparent py-1 pl-3 text-left text-muted hover:text-text aria-[current=true]:border-accent aria-[current=true]:text-text`,onClick:()=>{O(e.id),z(h.current?.querySelector(`#${CSS.escape(e.id)}`)??null)},children:e.text})},e.id))]})}),(0,J.jsx)(`div`,{ref:g,className:`min-w-0 scroll-mt-14`,children:(0,J.jsx)(`div`,{ref:h,className:`sy-prose-compact max-w-[80ch] min-w-0 2xl:max-w-[100ch] min-[1800px]:text-base [&_h2]:scroll-mt-14`,children:(0,J.jsx)(te,{text:T,headingIds:!0,className:`text-inherit`})})})]}),!G&&(0,J.jsxs)(`section`,{ref:v,"data-testid":`plan-options`,"aria-label":j,className:`border-t border-border px-4 py-3 md:px-6`,children:[(0,J.jsx)(`p`,{className:`mb-2 text-sm font-medium`,children:j}),!a&&(0,J.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2 md:flex-row md:flex-wrap`,children:k.map((e,t)=>(0,J.jsx)(s,{variant:P(t,e.tone),size:`md`,disabled:i,className:m(R,`md:text-center`),onClick:()=>N(e.id),children:e.label},e.id))}),(0,J.jsx)(H,{size:`xs`,className:`mt-2`,icon:(0,J.jsx)(F,{"aria-hidden":!0,className:`size-3.5`}),onClick:()=>z(g.current),children:`Back to the plan start`})]}),!G&&L&&(0,J.jsx)(`div`,{"data-testid":`answer-bar`,className:m(`z-10 flex min-w-0 items-center gap-2 border-t border-border bg-bg px-4 py-2 md:gap-3 md:px-6`,d&&!f?`sticky -bottom-3`:`sticky bottom-0`),children:U}),!G&&W]})}var be={red:`bg-[#e5484d] text-white`,orange:`bg-[#f76b15] text-white`,blue:`bg-[#0090ff] text-white`,gray:`bg-[#6e7681] text-white`,green:`bg-[#30a46c] text-white`},xe=`transform 260ms cubic-bezier(0.2, 0.9, 0.25, 1)`,Se=`input, textarea, select, [contenteditable], [data-no-swipe]`,Z=null;function Ce({leading:e=[],trailing:t=[],disabled:n,children:r,className:i,contentClassName:a}){let o=(0,q.useRef)(null),s=(0,q.useRef)(null),c=(0,q.useRef)(!1),[l,u]=(0,q.useState)(0),[d,f]=(0,q.useState)(!1),p=(0,q.useRef)(0),_=(0,q.useRef)({leading:e,trailing:t});_.current={leading:e,trailing:t};let y=!n&&(e.length>0||t.length>0),x=()=>o.current?.offsetWidth||320,S=(e,t)=>{let n=o.current;n&&(n.style.transition=t?xe:`none`,n.style.transform=e===0?``:`translateX(${e}px)`),p.current=e,u(e)},w=(0,q.useRef)(()=>{});w.current=()=>{S(0,!0),f(!1),Z===T&&(Z=null)};let[T]=(0,q.useState)(()=>()=>w.current()),E=async(e,t)=>{if(W(),e.removes){let n=x();f(!0),S(t===`leading`?n:-n,!0);try{await e.onAction()}catch{w.current();return}let r=o.current?.parentElement;r&&!window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches&&r.animate?.([{height:`${r.offsetHeight}px`},{height:`0px`}],{duration:220,easing:`cubic-bezier(0.2, 0.8, 0.2, 1)`,fill:`forwards`})}else w.current(),await e.onAction()},D=l!==0;(0,q.useEffect)(()=>{if(!D)return;let e=e=>{o.current?.parentElement?.contains(e.target)||s.current||w.current()};return document.addEventListener(`pointerdown`,e,!0),()=>document.removeEventListener(`pointerdown`,e,!0)},[D]),(0,q.useEffect)(()=>()=>{Z===T&&(Z=null)},[T]);let O=e=>{y&&e.isPrimary&&(e.pointerType===`touch`||e.pointerType===`pen`)&&(e.target.closest(Se)||(c.current=!1,s.current={id:e.pointerId,x:e.clientX,y:e.clientY,axis:null,start:p.current,raw:p.current,full:!1,samples:[]}))},k=e=>{let t=s.current;if(!t||e.pointerId!==t.id)return;let n=e.clientX-t.x;if(t.axis===null){if(t.axis=v(n,e.clientY-t.y),t.axis===null)return;if(t.axis===`y`){s.current=null;return}c.current=!0,e.currentTarget.setPointerCapture?.(e.pointerId),Z&&Z!==T&&Z()}let{leading:r,trailing:i}=_.current,a=x(),o=t.start+n;o>0&&r.length===0&&(o=g(o,a)*.15),o<0&&i.length===0&&(o=g(o,a)*.15),t.raw=o,t.samples.push({t:e.timeStamp,v:o}),t.samples=t.samples.slice(-12);let l=(o>0?r.length:i.length)*76,u=l>0&&Math.abs(o)>=b(a,l);u!==t.full&&(t.full=u,f(u),W()),S(o,!1)},A=e=>{let t=s.current;if(s.current=null,t?.axis!==`x`)return;let{leading:n,trailing:r}=_.current;if(e.type===`pointercancel`)return w.current();let i=h(t.raw,C(t.samples),{width:x(),reveal:{leading:n.length*76,trailing:r.length*76},fullSwipe:{leading:!0,trailing:!0}});if(i.kind===`close`)return w.current();let a=i.side===`leading`?n:r,o=a[0];if(!o)return w.current();if(i.kind===`commit`)return void E(o,i.side);f(!1),S((i.side===`leading`?1:-1)*a.length*76,!0),Z=T},j=l>0?`leading`:`trailing`,M=l>0?e:t,N=j===`trailing`?[...M].reverse():M;return(0,J.jsxs)(`div`,{className:m(`relative overflow-hidden`,i),"data-swipe-row":!0,children:[l!==0&&M.length>0&&(0,J.jsx)(`div`,{"aria-hidden":!0,className:m(`absolute inset-y-0 flex`,j===`leading`?`left-0`:`right-0`),style:{width:Math.abs(l)},children:N.map(e=>{let t=e===M[0];return(0,J.jsxs)(`button`,{type:`button`,tabIndex:-1,"data-swipe-action":e.id,onClick:()=>void E(e,j),style:{flexGrow:d?+!!t:1,flexBasis:0},className:m(`flex min-w-0 flex-col items-center justify-center gap-1 overflow-hidden text-xs font-semibold whitespace-nowrap transition-[flex-grow] duration-200`,be[e.tone],d&&t&&(j===`leading`?`items-start pl-6`:`items-end pr-6`)),children:[e.icon,e.label]},e.id)})}),(0,J.jsx)(`div`,{ref:o,className:m(`relative touch-pan-y bg-surface`,a),onPointerDown:O,onPointerMove:k,onPointerUp:A,onPointerCancel:A,onClickCapture:e=>{c.current?(c.current=!1,e.preventDefault(),e.stopPropagation()):p.current!==0&&(e.preventDefault(),e.stopPropagation(),w.current())},children:r})]})}function we(e){let t=r(e=>e.issues);return(0,q.useMemo)(()=>{let n=Object.values(t),r=e?A(n)(e):null;return{linked:r,candidates:e&&!r?n.filter(t=>w(t,e,n)===null).sort(O):[],canUnlink:!!r&&E(r)===null}},[t,e])}function Te({open:e,onClose:t,workspace:n,candidates:r}){let[i,o]=(0,q.useState)(null),[c,l]=(0,q.useState)(null),u=()=>{l(null),t()},d=async e=>{if(!i){o(e.id),l(null);try{await ne(e.id,n.id),B.success(`Linked to #${e.number}`),u()}catch(e){l(e)}finally{o(null)}}};return(0,J.jsx)(y,{open:e,onClose:u,title:`Link to issue`,description:`Link ${n.branch} to an issue that has no branch yet. Its sessions then stay in the issue's scope.`,footer:(0,J.jsx)(s,{onClick:u,children:`Cancel`}),children:(0,J.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[c!==null&&(0,J.jsx)(f,{compact:!0,title:`Could not link`,error:a(c)}),r.length===0&&(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:`No issue without a branch in this project.`}),(0,J.jsx)(`ul`,{className:`flex min-w-0 flex-col gap-1`,children:r.map(e=>(0,J.jsx)(`li`,{className:`min-w-0`,children:(0,J.jsxs)(`button`,{type:`button`,disabled:!!i,"aria-busy":i===e.id,onClick:()=>void d(e),className:`tap flex w-full min-w-0 flex-col rounded-md px-2 py-1.5 text-left hover:bg-surface-2 disabled:opacity-55`,children:[(0,J.jsxs)(`span`,{className:`truncate text-sm`,children:[`#`,e.number,` `,e.title]}),(0,J.jsxs)(`span`,{className:`truncate text-xs text-muted`,children:[e.repository,e.board?.priority?` · ${e.board.priority.name}`:``]})]})},e.id))})]})})}var Ee=[];function De(e,n,i){let o=i&&!!e&&!n,[s,c]=(0,q.useState)(null);return(0,q.useEffect)(()=>{if(!o||!e)return;let n=new AbortController;return c({id:e,lookup:{state:`loading`}}),K.get(e,n.signal).then(e=>{r.getState().upsertSessionIfMissing(e),c(null)},r=>{n.signal.aborted||c({id:e,lookup:t(r,`not_found`)?{state:`missing`}:{state:`error`,error:a(r)}})}),()=>n.abort()},[o,e]),o?s?.id===e?s.lookup:{state:`loading`}:{state:`idle`}}function Oe(e){let t=r(t=>e?t.hosts[e.hostId]:void 0),n=r(t=>e?.projectId?t.projects[e.projectId]:void 0),i=r(t=>e?.workspaceId?t.workspaces[e.workspaceId]:void 0),a=r(e=>e.runs),o=r(e=>e.tasks),s=r(t=>e?t.adapters[e.hostId]??Ee:Ee);return(0,q.useMemo)(()=>{if(!e)return null;let r=M(a,e),c=e.taskId??r?.taskId??null;return{session:e,host:t,hostName:t?.name??`Unknown host`,link:P(t,e),project:n,workspace:i,run:r,task:c?o[c]:void 0,control:N(r),adapters:s}},[e,t,n,i,a,o,s])}function Q(e,t={}){let[n,r]=(0,q.useState)(!1),[i,o]=(0,q.useState)(null),s=(0,q.useRef)(e);s.current=e;let c=(0,q.useRef)(t);c.current=t;let l=(0,q.useRef)(!0);return(0,q.useEffect)(()=>(l.current=!0,()=>{l.current=!1}),[]),{run:(0,q.useCallback)(async(...e)=>{r(!0),o(null);try{let t=await s.current(...e),{success:n}=c.current,r=typeof n==`function`?n(t):n;return r&&B.success(r),!0}catch(e){return l.current&&o(e),c.current.errorToast&&B.error(a(e)),!1}finally{l.current&&r(!1)}},[]),busy:n,error:i,reset:(0,q.useCallback)(()=>o(null),[])}}function ke(e,t=1e3){let[n,r]=(0,q.useState)(()=>Date.now());return(0,q.useEffect)(()=>{if(!e)return;r(Date.now());let n=setInterval(()=>r(Date.now()),t);return()=>clearInterval(n)},[e,t]),n}function Ae(){let e=(0,q.useRef)(null),[t,n]=(0,q.useState)(0);return(0,q.useLayoutEffect)(()=>{let t=e.current;if(!t)return;n(t.clientWidth);let r=new ResizeObserver(([e])=>{e&&n(e.contentRect.width)});return r.observe(t),()=>r.disconnect()},[]),[e,t]}function $({label:e,value:t}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`dt`,{className:`text-muted`,children:e}),(0,J.jsx)(`dd`,{className:`min-w-0 font-mono text-xs break-all`,children:t})]})}function je({session:e,hostLabel:t,open:n,onClose:r}){let i=D(e),a=e.stats;return(0,J.jsx)(y,{open:n,onClose:r,title:`Session info`,children:(0,J.jsxs)(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-2 text-sm`,children:[(0,J.jsx)($,{label:`Switchyard session`,value:e.id}),(0,J.jsx)($,{label:`Pi session id`,value:e.nativeHandle?.sessionId??`Not started`}),(0,J.jsx)($,{label:`Session file`,value:e.nativeHandle?.sessionFile??`None yet`}),(0,J.jsx)($,{label:`Host`,value:t}),(0,J.jsx)($,{label:`Working directory`,value:e.cwd}),(0,J.jsx)($,{label:`Origin`,value:e.provenance}),(0,J.jsx)($,{label:`Profile`,value:e.profileSnapshot.name}),(0,J.jsx)($,{label:`Created`,value:o(e.createdAt)}),a?.tokens!=null&&(0,J.jsx)($,{label:`Tokens`,value:a.tokens.toLocaleString(`en-US`)}),a?.costUsd!=null&&(0,J.jsx)($,{label:`Cost`,value:`$${a.costUsd.toFixed(2)}`}),i&&(0,J.jsx)($,{label:`Context`,value:`${i.label} (${i.detail})`})]})})}function Me(t){let{session:o,run:c,control:l}=t,u=p(),[d,m]=(0,q.useState)(null),[h,g]=(0,q.useState)(o.title),_=we(o.provenance===`subagent`?null:t.workspace),v=r(e=>e.attention),b=(0,q.useMemo)(()=>Object.values(v).filter(e=>e.sessionId===o.id&&!e.resolvedAt&&n(e.reason)),[v,o.id]),S=r(e=>{if(o.provenance===`subagent`||o.archivedAt)return!1;let t=Object.values(e.sessions).filter(e=>e.archivedAt===null&&e.provenance!==`subagent`&&(o.workspaceId?e.workspaceId===o.workspaceId:e.workspaceId===null&&e.hostId===o.hostId&&e.cwd===o.cwd));return j(t)?.id===o.id}),C=Q(()=>K.takeover(o.id),{success:`You have control. Automatic continuations are paused.`,errorToast:!0}),w=Q(()=>K.returnToAutomation(o.id),{success:`Returned to automation.`,errorToast:!0}),E=Q(()=>K.stop(o.id),{success:`Session stopped.`}),D=Q(()=>K.resume(o.id),{success:`Session resumed.`,errorToast:!0}),O=Q(e=>K.rename(o.id,e),{success:`Session renamed.`}),A=Q(()=>K.cacheAlert(o.id,!o.cacheAlert),{errorToast:!0}),M=Q(()=>K.archive(o.id),{success:`Session archived.`}),N=Q(()=>K.unarchive(o.id),{success:`Session unarchived.`,errorToast:!0}),P=t.link===`connected`,F=()=>{m(null),E.reset(),O.reset(),M.reset()},I=T(o)?`Stop the session before archiving it`:null,R=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(x,{open:d===`stop`,onClose:F,title:`Stop this session?`,description:`Stops the current execution and clears queued messages.`,confirmLabel:`Stop session`,busy:E.busy,error:E.error,errorTitle:`Could not stop`,onConfirm:()=>void E.run().then(e=>e&&m(null)),children:(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:c?`The task keeps its run, marked interrupted and blocked (Stopped by user). Automation settings are unchanged.`:`Pi stays available; you can send a new message afterwards.`})}),(0,J.jsx)(y,{open:d===`rename`,onClose:F,title:`Rename session`,footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(s,{onClick:F,children:`Cancel`}),(0,J.jsx)(s,{variant:`primary`,type:`submit`,form:`sy-rename-form`,busy:O.busy,disabled:!h.trim(),children:`Save`})]}),children:(0,J.jsxs)(`form`,{id:`sy-rename-form`,onSubmit:e=>{e.preventDefault(),h.trim()&&O.run(h.trim()).then(e=>e&&m(null))},className:`flex flex-col gap-2`,children:[(0,J.jsx)(L,{id:`sy-rename-input`,label:`Title`,children:(0,J.jsx)(z,{id:`sy-rename-input`,value:h,maxLength:200,onChange:e=>g(e.target.value)})}),O.error!==null&&(0,J.jsx)(f,{compact:!0,title:`Could not rename`,error:a(O.error)})]})}),(0,J.jsx)(x,{open:d===`archive`,onClose:F,title:`Archive this session?`,description:`It leaves the navigator. The Pi session file stays on the host.`,danger:!1,confirmLabel:`Archive`,busy:M.busy,error:M.error,errorTitle:`Could not archive`,onConfirm:()=>void M.run().then(e=>{e&&(m(null),u(`/code`))}),children:o.runtime===`idle`&&(0,J.jsx)(`p`,{className:`text-sm text-muted`,children:`The idle Pi process is stopped first.`})}),t.workspace&&(0,J.jsx)(Te,{open:d===`link`,onClose:F,workspace:t.workspace,candidates:_.candidates}),(0,J.jsx)(je,{session:o,hostLabel:`${t.hostName} (${t.link})`,open:d===`info`,onClose:F})]});return{canTakeover:l===`automation`,canReturn:l===`human`,canStop:T(o)&&P,canResume:!k(o)&&!!o.nativeHandle&&!o.readOnly&&P,archiveBlocked:I,takeover:()=>void C.run(),returnToAutomation:()=>void w.run(),requestStop:()=>m(`stop`),resume:()=>void D.run(),openRename:()=>{g(o.title),m(`rename`)},requestArchive:()=>{I?B.info(I):m(`archive`)},openInfo:()=>m(`info`),toggleCacheAlert:()=>void A.run(),unarchive:()=>void N.run(),dismissAttention:b.length>0?()=>{Promise.all(b.map(Ne)).then(()=>B.success(`Cleared. A question Pi is still waiting on stays.`)).catch(e=>B.error(a(e)))}:null,setPinned:(t,n)=>{let r=`/api/scopes/${encodeURIComponent(t)}/sessions/${encodeURIComponent(o.id)}`;(n?i(r):e(r)).catch(e=>B.error(a(e)))},isPrimary:S,setPrimary:e=>{K.setPrimary(o.id,e).catch(e=>B.error(a(e)))},newInBranch:o.projectId&&o.workspaceId?()=>{K.createSession({projectId:o.projectId,workspace:{existingId:o.workspaceId},prompt:``}).then(e=>{r.getState().upsertSessionIfMissing(e),u(`/code/${encodeURIComponent(e.id)}`)}).catch(e=>B.error(a(e)))}:null,issueLink:t.workspace&&o.provenance!==`subagent`?{..._,open:()=>m(`link`),unlink:()=>{let e=_.linked;e&&G(e.id).then(()=>B.success(`Unlinked from #${e.number}`)).catch(e=>B.error(a(e)))}}:null,busy:{takeover:C.busy,ret:w.busy,stop:E.busy,resume:D.busy,unarchive:N.busy},dialogs:R}}async function Ne(e){let t=await i(`/api/attention/${encodeURIComponent(e.id)}/dismiss`),n=t&&typeof t==`object`&&`id`in t?t:{...e,resolvedAt:new Date().toISOString()};return r.setState(t=>t.attention[e.id]?{attention:{...t.attention,[e.id]:n}}:{}),n}var Pe=[`needs_input`,`failed`,`ready_for_review`,`unsupported_interaction`,`host_unreachable`,`cache_expiring`];function Fe(e){let t=Object.fromEntries(Pe.map(e=>[e,[]]));for(let n of e)t[n.reason]?.push(n);return t}var Ie={dismiss:`Marks it as seen and moves it to Dismissed; it stays open, and a question keeps flagging its session.`,clear:`Resolves it now: the session loses this flag and the item moves to History.`,clearNeedsInput:`Removes this session's Needs input flag and moves it to History; a question Pi is still waiting on stays.`};function Le(e){return e===`dismissed`||e===`history`?e:`open`}function Re(e,t){return t===`history`?[]:e.filter(e=>t===`open`?!e.acknowledgedAt:!!e.acknowledgedAt)}function ze(e,t,n){return[e?.name,t?.title,n&&n.title!==t?.title?n.title:null].filter(Boolean).join(` · `)||`Switchyard`}export{X as _,Le as a,Me as c,Q as d,ke as f,le as g,Ce as h,Fe as i,je as l,De as m,Pe as n,Re as o,Oe as p,ze as r,Ne as s,Ie as t,Ae as u,he as v,oe as y};
4
+ //# sourceMappingURL=logic-D_vBBkcD.js.map