@tempoxyz/id 0.0.0-pr-293.sha-db2bcd0 → 0.0.0-pr-293.sha-e314a6e

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 (377) hide show
  1. package/dist/app/client/assets/Account-BYLpNFf3.css +1 -0
  2. package/dist/app/client/assets/Account-DKlYpUaF.js +1 -0
  3. package/dist/app/client/assets/Amount-ZdtluGf-.css +1 -0
  4. package/dist/app/client/assets/Amount-uCaXmEC1.js +1 -0
  5. package/dist/app/client/assets/{Approval-lMS61Hor.js → Approval-_VTK0bIA.js} +1 -1
  6. package/dist/app/client/assets/{Authentication-CNU_hdsE.js → Authentication-CcZraW4V.js} +1 -1
  7. package/dist/app/client/assets/Callout-Cpp2tekO.js +1 -0
  8. package/dist/app/client/assets/Callout-DBfEmP7q.css +1 -0
  9. package/dist/app/client/assets/{Chain-CgM0gkul.js → Chain-BaJbQHEq.js} +1 -1
  10. package/dist/app/client/assets/{Check-l6Xt-h8M.js → Check-T-Kf-w2J.js} +1 -1
  11. package/dist/app/client/assets/{ChevronRight-Dgx1CBfS.js → ChevronRight-Cb0izsfB.js} +1 -1
  12. package/dist/app/client/assets/{ChooseAccount-DKQvWYym.js → ChooseAccount-BbdtokuQ.js} +1 -1
  13. package/dist/app/client/assets/{Client-B3HiaUR7.js → Client-XdlKOIjT.js} +1 -1
  14. package/dist/app/client/assets/{Close-CHeDbDyp.js → Close-9qiwSZoT.js} +1 -1
  15. package/dist/app/client/assets/{Cloud-BnBzwFJQ.js → Cloud-yU0Kxv28.js} +1 -1
  16. package/dist/app/client/assets/CodeInput-BqRteSwD.css +1 -0
  17. package/dist/app/client/assets/CodeInput-C8ad0edh.js +1 -0
  18. package/dist/app/client/assets/Deposit-CclrAoXL.css +1 -0
  19. package/dist/app/client/assets/Deposit-b5yx-L71.js +1 -0
  20. package/dist/app/client/assets/DevTools-BYkmtuV5.css +1 -0
  21. package/dist/app/client/assets/DevTools-Cgd0Ogan.js +1 -0
  22. package/dist/app/client/assets/{DeviceApproval-DKQklicf.js → DeviceApproval-CGdmL9U5.js} +1 -1
  23. package/dist/app/client/assets/{Fingerprint-CVLZp0fE.js → Fingerprint-081gQp_i.js} +1 -1
  24. package/dist/app/client/assets/{Globe-RAkdkLVn.js → Globe-D4HEnXoi.js} +1 -1
  25. package/dist/app/client/assets/Grant-5a-n1gJH.css +1 -0
  26. package/dist/app/client/assets/Grant-C-7ibHJb.js +1 -0
  27. package/dist/app/client/assets/Hex-C9KeV7_9.css +1 -0
  28. package/dist/app/client/assets/Hex-COpLAksw.js +10 -0
  29. package/dist/app/client/assets/IconChip-Cr71cqFZ.js +1 -0
  30. package/dist/app/client/assets/IconChip-yqaQ2y_d.css +1 -0
  31. package/dist/app/client/assets/InputGroup-BMExR1w7.js +1 -0
  32. package/dist/app/client/assets/InputGroup-BlZvt9In.css +1 -0
  33. package/dist/app/client/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  34. package/dist/app/client/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  35. package/dist/app/client/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  36. package/dist/app/client/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  37. package/dist/app/client/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  38. package/dist/app/client/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  39. package/dist/app/client/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  40. package/dist/app/client/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  41. package/dist/app/client/assets/Loader-CVy-jQh9.js +1 -0
  42. package/dist/app/client/assets/{PopoverPopup-AaR182Lw.js → PopoverPopup-CQv00nl_.js} +1 -1
  43. package/dist/app/client/assets/Rows-CT3nC-Gp.js +1 -0
  44. package/dist/app/client/assets/Rows-DPGTUdA8.css +1 -0
  45. package/dist/app/client/assets/{Separator-C1NRk_mW.js → Separator-Doxz2kha.js} +1 -1
  46. package/dist/app/client/assets/SignIn-D2D3rbzT.js +1 -0
  47. package/dist/app/client/assets/SignIn-mlBTwUq4.css +1 -0
  48. package/dist/app/client/assets/Stack-D7Yt22Ed.css +1 -0
  49. package/dist/app/client/assets/Stack-qm24zmlV.js +1 -0
  50. package/dist/app/client/assets/ToolbarRootContext-Ctu7JTLk.js +1 -0
  51. package/dist/app/client/assets/Tooltip-arQraM0D.js +1 -0
  52. package/dist/app/client/assets/Tooltip-d3y9ESUJ.css +1 -0
  53. package/dist/app/client/assets/___-I98bns4o.css +1 -0
  54. package/dist/app/client/assets/___.flows-8Dmgeehd.js +5 -0
  55. package/dist/app/client/assets/{authorize-BQ1QbDZ8.js → authorize-DAtsqrNM.js} +1 -1
  56. package/dist/app/client/assets/{choose-account-Da0fLaYb.js → choose-account-DEFRgijo.js} +1 -1
  57. package/dist/app/client/assets/{deposit-CwKR_KjX.js → deposit--QiYWQfo.js} +1 -1
  58. package/dist/app/client/assets/{device-CCwq2oAs.js → device-Bq9xs5K6.js} +1 -1
  59. package/dist/app/client/assets/{error-Dj24A5n4.js → error-IQXxc1eM.js} +1 -1
  60. package/dist/app/client/assets/{getPseudoElementBounds-DH_jjqMh.js → getPseudoElementBounds-4olojy3W.js} +1 -1
  61. package/dist/app/client/assets/index-CyFheDuU.js +13 -0
  62. package/dist/app/client/assets/index-DSkPoKOK.css +1 -0
  63. package/dist/app/client/assets/{lazyRouteComponent-108fI1-o.js → lazyRouteComponent-Dz0rIGYN.js} +1 -1
  64. package/dist/app/client/assets/{login--cK4-SN_.js → login-B0BjHqjo.js} +1 -1
  65. package/dist/app/client/assets/pathUSD-BMh6ajrW.css +1 -0
  66. package/dist/app/client/assets/pathUSD-DuAfAKZZ.js +1 -0
  67. package/dist/app/client/assets/{removable-CZFK4Sbw.js → removable-CbJQgeuY.js} +1 -1
  68. package/dist/app/client/assets/{routes-BEKA6M9o.js → routes-BkBTe_Iu.js} +1 -1
  69. package/dist/app/client/assets/{suspense-ClIj0Mjn.js → suspense-Djz3yPi6.js} +1 -1
  70. package/dist/app/client/assets/useNavigate-B3GfD6JV.js +1 -0
  71. package/dist/app/client/assets/{useRegisterFieldControl-r_mKBm9D.js → useRegisterFieldControl-C8uwO_R4.js} +1 -1
  72. package/dist/app/client/assets/zyzz-DYC-X0_B.css +1 -0
  73. package/dist/app/client/assets/zyzz.config-DJRBo25J.js +2 -0
  74. package/dist/app/server/.vite/manifest.json +640 -608
  75. package/dist/app/server/assets/Account-BYLpNFf3.css +1 -0
  76. package/dist/app/server/assets/Account-g1_Uaj86.js +2 -0
  77. package/dist/app/server/assets/Account-g1_Uaj86.js.map +1 -0
  78. package/dist/app/server/assets/Amount-BXSuv2fx.js +2 -0
  79. package/dist/app/server/assets/Amount-BXSuv2fx.js.map +1 -0
  80. package/dist/app/server/assets/Amount-ZdtluGf-.css +1 -0
  81. package/dist/app/server/assets/{Approval-DhLkTvkI.js → Approval-DA8fDZIl.js} +2 -2
  82. package/dist/app/server/assets/{Approval-DhLkTvkI.js.map → Approval-DA8fDZIl.js.map} +1 -1
  83. package/dist/app/server/assets/{Authentication-Odm8-gfs.js → Authentication-BJgy8lyC.js} +2 -2
  84. package/dist/app/server/assets/{Authentication-Odm8-gfs.js.map → Authentication-BJgy8lyC.js.map} +1 -1
  85. package/dist/app/server/assets/{Authentication-DLWMd2mA.js → Authentication-CsSh3HGu.js} +2 -2
  86. package/dist/app/server/assets/{Authentication-DLWMd2mA.js.map → Authentication-CsSh3HGu.js.map} +1 -1
  87. package/dist/app/server/assets/Callout-DBfEmP7q.css +1 -0
  88. package/dist/app/server/assets/Callout-DlcQ5BUo.js +2 -0
  89. package/dist/app/server/assets/Callout-DlcQ5BUo.js.map +1 -0
  90. package/dist/app/server/assets/{Chain-CQgBRAXx.js → Chain-C9RGZDJm.js} +2 -2
  91. package/dist/app/server/assets/{Chain-CQgBRAXx.js.map → Chain-C9RGZDJm.js.map} +1 -1
  92. package/dist/app/server/assets/{Check-BwwQ6kDn.js → Check-CQIa-Y5d.js} +2 -2
  93. package/dist/app/server/assets/{Check-BwwQ6kDn.js.map → Check-CQIa-Y5d.js.map} +1 -1
  94. package/dist/app/server/assets/{ChevronRight-B_ft-uyS.js → ChevronRight-wzF9Mh2e.js} +2 -2
  95. package/dist/app/server/assets/{ChevronRight-B_ft-uyS.js.map → ChevronRight-wzF9Mh2e.js.map} +1 -1
  96. package/dist/app/server/assets/{ChooseAccount-FJJ2kRPk.js → ChooseAccount-De_YweJM.js} +2 -2
  97. package/dist/app/server/assets/{ChooseAccount-FJJ2kRPk.js.map → ChooseAccount-De_YweJM.js.map} +1 -1
  98. package/dist/app/server/assets/{Client-D3gnMDTr.js → Client-BAXSFa9e.js} +2 -2
  99. package/dist/app/server/assets/{Client-D3gnMDTr.js.map → Client-BAXSFa9e.js.map} +1 -1
  100. package/dist/app/server/assets/{ClientOnly-CbQVNHub.js → ClientOnly-B8k5xDwz.js} +2 -2
  101. package/dist/app/server/assets/{ClientOnly-CbQVNHub.js.map → ClientOnly-B8k5xDwz.js.map} +1 -1
  102. package/dist/app/server/assets/{Close-ChRMz-uR.js → Close-C74hwnOn.js} +2 -2
  103. package/dist/app/server/assets/{Close-ChRMz-uR.js.map → Close-C74hwnOn.js.map} +1 -1
  104. package/dist/app/server/assets/{Cloud-C3_mtq_Y.js → Cloud-CYXeneSe.js} +2 -2
  105. package/dist/app/server/assets/{Cloud-C3_mtq_Y.js.map → Cloud-CYXeneSe.js.map} +1 -1
  106. package/dist/app/server/assets/CodeInput-BqRteSwD.css +1 -0
  107. package/dist/app/server/assets/CodeInput-DdkMKOyq.js +2 -0
  108. package/dist/app/server/assets/CodeInput-DdkMKOyq.js.map +1 -0
  109. package/dist/app/server/assets/{Credential-D82PNwyx.js → Credential-DXcfPJEP.js} +2 -2
  110. package/dist/app/server/assets/{Credential-D82PNwyx.js.map → Credential-DXcfPJEP.js.map} +1 -1
  111. package/dist/app/server/assets/Deposit-CclrAoXL.css +1 -0
  112. package/dist/app/server/assets/Deposit-DOp5HCDX.js +2 -0
  113. package/dist/app/server/assets/Deposit-DOp5HCDX.js.map +1 -0
  114. package/dist/app/server/assets/DevTools-BYkmtuV5.css +1 -0
  115. package/dist/app/server/assets/DevTools-CxdPUN3V.js +2 -0
  116. package/dist/app/server/assets/DevTools-CxdPUN3V.js.map +1 -0
  117. package/dist/app/server/assets/{DeviceApproval-BhWgrv9l.js → DeviceApproval-o7T8XlX3.js} +2 -2
  118. package/dist/app/server/assets/{DeviceApproval-BhWgrv9l.js.map → DeviceApproval-o7T8XlX3.js.map} +1 -1
  119. package/dist/app/server/assets/{ExecutionError-DSSCSoHl.js → ExecutionError-DoRNvh3D.js} +2 -2
  120. package/dist/app/server/assets/{ExecutionError-DSSCSoHl.js.map → ExecutionError-DoRNvh3D.js.map} +1 -1
  121. package/dist/app/server/assets/{Faucet-Cv-nQMBR.js → Faucet-jp6zNWHE.js} +2 -2
  122. package/dist/app/server/assets/{Faucet-Cv-nQMBR.js.map → Faucet-jp6zNWHE.js.map} +1 -1
  123. package/dist/app/server/assets/{Fingerprint-B0Iay4Ws.js → Fingerprint-CAqjOS3T.js} +2 -2
  124. package/dist/app/server/assets/{Fingerprint-B0Iay4Ws.js.map → Fingerprint-CAqjOS3T.js.map} +1 -1
  125. package/dist/app/server/assets/{Globe-C6rnzTY0.js → Globe-BZ_5dGqa.js} +2 -2
  126. package/dist/app/server/assets/{Globe-C6rnzTY0.js.map → Globe-BZ_5dGqa.js.map} +1 -1
  127. package/dist/app/server/assets/Grant-5a-n1gJH.css +1 -0
  128. package/dist/app/{client/assets/Grant-DurkleN7.js → server/assets/Grant-BwOC2P94.js} +2 -1
  129. package/dist/app/server/assets/Grant-BwOC2P94.js.map +1 -0
  130. package/dist/app/server/assets/Hex-67thYs-f.js +11 -0
  131. package/dist/app/server/assets/Hex-67thYs-f.js.map +1 -0
  132. package/dist/app/server/assets/Hex-C9KeV7_9.css +1 -0
  133. package/dist/app/server/assets/IconChip-Cmufss8d.js +2 -0
  134. package/dist/app/server/assets/IconChip-Cmufss8d.js.map +1 -0
  135. package/dist/app/server/assets/IconChip-yqaQ2y_d.css +1 -0
  136. package/dist/app/server/assets/InputGroup-BlZvt9In.css +1 -0
  137. package/dist/app/server/assets/InputGroup-Bn2KM9pd.js +2 -0
  138. package/dist/app/server/assets/InputGroup-Bn2KM9pd.js.map +1 -0
  139. package/dist/app/server/assets/Inter-cyrillic-e3OmmzmJ.woff2 +0 -0
  140. package/dist/app/server/assets/Inter-cyrillic-ext-DOWZeO4Q.woff2 +0 -0
  141. package/dist/app/server/assets/Inter-greek-BD3ujQlX.woff2 +0 -0
  142. package/dist/app/server/assets/Inter-greek-ext-CXEwbus4.woff2 +0 -0
  143. package/dist/app/server/assets/Inter-latin-BDFm4vTb.woff2 +0 -0
  144. package/dist/app/server/assets/Inter-latin-ext-E7a9JEPe.woff2 +0 -0
  145. package/dist/app/server/assets/Inter-symbols-DEch7Rxr.woff2 +0 -0
  146. package/dist/app/server/assets/Inter-vietnamese-Bg9723vR.woff2 +0 -0
  147. package/dist/app/server/assets/Loader-DvDbd8kj.js +2 -0
  148. package/dist/app/server/assets/{Loader-Ivf5dWFl.js.map → Loader-DvDbd8kj.js.map} +1 -1
  149. package/dist/app/server/assets/{Match-DusFDz9D.js → Match-C65vhhhD.js} +2 -2
  150. package/dist/app/server/assets/{Match-DusFDz9D.js.map → Match-C65vhhhD.js.map} +1 -1
  151. package/dist/app/server/assets/PopoverPopup-kuWGUSYM.js +2 -0
  152. package/dist/app/server/assets/{PopoverPopup-D98JOZVe.js.map → PopoverPopup-kuWGUSYM.js.map} +1 -1
  153. package/dist/app/server/assets/Rows-DPGTUdA8.css +1 -0
  154. package/dist/app/server/assets/Rows-eTPur_py.js +2 -0
  155. package/dist/app/server/assets/Rows-eTPur_py.js.map +1 -0
  156. package/dist/app/server/assets/{Separator-B6od-9JY.js → Separator-BPNenixO.js} +2 -2
  157. package/dist/app/server/assets/{Separator-B6od-9JY.js.map → Separator-BPNenixO.js.map} +1 -1
  158. package/dist/app/server/assets/SignIn-CVPZSR-8.js +2 -0
  159. package/dist/app/server/assets/SignIn-CVPZSR-8.js.map +1 -0
  160. package/dist/app/server/assets/SignIn-mlBTwUq4.css +1 -0
  161. package/dist/app/server/assets/Stack-D7Yt22Ed.css +1 -0
  162. package/dist/app/server/assets/Stack-DQMZBUUB.js +2 -0
  163. package/dist/app/server/assets/Stack-DQMZBUUB.js.map +1 -0
  164. package/dist/app/server/assets/ToolbarRootContext-5168W3t4.js +2 -0
  165. package/dist/app/server/assets/{ToolbarRootContext-BCmWBQ7n.js.map → ToolbarRootContext-5168W3t4.js.map} +1 -1
  166. package/dist/app/server/assets/Tooltip-DR3nssae.js +2 -0
  167. package/dist/app/server/assets/Tooltip-DR3nssae.js.map +1 -0
  168. package/dist/app/server/assets/Tooltip-d3y9ESUJ.css +1 -0
  169. package/dist/app/server/assets/___-I98bns4o.css +1 -0
  170. package/dist/app/server/assets/___.flows-D_J822MU.js +6 -0
  171. package/dist/app/server/assets/___.flows-D_J822MU.js.map +1 -0
  172. package/dist/app/server/assets/_tanstack-start-manifest_v-DQjMcFpU.js +1 -0
  173. package/dist/app/server/assets/{_zyzz__2Fhome_2Frunner_2Fwork_2Fid_2Fid_2Fsrc_2Fapp_2Froutes_2F_5B__5D.flows.tsx-Drf_Iqhc.js → _zyzz__2Fhome_2Frunner_2Fwork_2Fid_2Fid_2Fsrc_2Fapp_2Froutes_2F_5B__5D.flows.tsx-EmCsnNUQ.js} +2 -2
  174. package/dist/app/server/assets/{_zyzz__2Fhome_2Frunner_2Fwork_2Fid_2Fid_2Fsrc_2Fapp_2Froutes_2F_5B__5D.flows.tsx-Drf_Iqhc.js.map → _zyzz__2Fhome_2Frunner_2Fwork_2Fid_2Fid_2Fsrc_2Fapp_2Froutes_2F_5B__5D.flows.tsx-EmCsnNUQ.js.map} +1 -1
  175. package/dist/app/server/assets/{accessKey-CxNqjouy.js → accessKey-DlBe71R7.js} +4 -4
  176. package/dist/app/server/assets/{accessKey-CxNqjouy.js.map → accessKey-DlBe71R7.js.map} +1 -1
  177. package/dist/app/server/assets/{authorize-D_5EG0WN.js → authorize-C3nY01zc.js} +2 -2
  178. package/dist/app/server/assets/{authorize-D_5EG0WN.js.map → authorize-C3nY01zc.js.map} +1 -1
  179. package/dist/app/server/assets/{authorize-pZETCSux.js → authorize-C9tfZ34z.js} +2 -2
  180. package/dist/app/server/assets/{authorize-pZETCSux.js.map → authorize-C9tfZ34z.js.map} +1 -1
  181. package/dist/app/server/assets/{authorize-DXYo-K2n-08rIhXFT.js → authorize-DXYo-K2n-Bc8o9t1x.js} +2 -2
  182. package/dist/app/server/assets/{authorize-DXYo-K2n-08rIhXFT.js.map → authorize-DXYo-K2n-Bc8o9t1x.js.map} +1 -1
  183. package/dist/app/server/assets/{choose-account-BOPrs9l7.js → choose-account-DNfcLweT.js} +2 -2
  184. package/dist/app/server/assets/{choose-account-BOPrs9l7.js.map → choose-account-DNfcLweT.js.map} +1 -1
  185. package/dist/app/server/assets/{choose-account-MDW4jp29.js → choose-account-Lq0qFqBr.js} +2 -2
  186. package/dist/app/server/assets/{choose-account-MDW4jp29.js.map → choose-account-Lq0qFqBr.js.map} +1 -1
  187. package/dist/app/server/assets/{core-Dxqe4Tzf.js → core-Ci_AVqAl.js} +2 -2
  188. package/dist/app/server/assets/{core-Dxqe4Tzf.js.map → core-Ci_AVqAl.js.map} +1 -1
  189. package/dist/app/server/assets/default-u_dwuiYb-D3URkhAV.js +2 -0
  190. package/dist/app/server/assets/{default-u_dwuiYb-BZX-cEte.js.map → default-u_dwuiYb-D3URkhAV.js.map} +1 -1
  191. package/dist/app/server/assets/{deposit-AgLrOoA3.js → deposit-Ch8VqCtG.js} +2 -2
  192. package/dist/app/server/assets/{deposit-AgLrOoA3.js.map → deposit-Ch8VqCtG.js.map} +1 -1
  193. package/dist/app/server/assets/{deposit-Cjt69KmJ.js → deposit-xQrouL3f.js} +2 -2
  194. package/dist/app/server/assets/{deposit-Cjt69KmJ.js.map → deposit-xQrouL3f.js.map} +1 -1
  195. package/dist/app/server/assets/{device-TEgIth9V.js → device-BAsgIC7D.js} +2 -2
  196. package/dist/app/server/assets/{device-TEgIth9V.js.map → device-BAsgIC7D.js.map} +1 -1
  197. package/dist/app/server/assets/{device-DO_RH0Or.js → device-BV99aHMG.js} +2 -2
  198. package/dist/app/server/assets/{device-DO_RH0Or.js.map → device-BV99aHMG.js.map} +1 -1
  199. package/dist/app/server/assets/dist-BhIyCFP8.js +1 -0
  200. package/dist/app/server/assets/{dist-C9wLcfH8.js → dist-C-Rzwa6V.js} +2 -2
  201. package/dist/app/server/assets/{dist-C9wLcfH8.js.map → dist-C-Rzwa6V.js.map} +1 -1
  202. package/dist/app/server/assets/{dist-SBl0rlY-.js → dist-CJN10pUl.js} +2 -2
  203. package/dist/app/server/assets/{dist-SBl0rlY-.js.map → dist-CJN10pUl.js.map} +1 -1
  204. package/dist/app/server/assets/{effect-QlVUlMFu-aB2jdYth.js → effect-QlVUlMFu-svPBY1dH.js} +2 -2
  205. package/dist/app/server/assets/{effect-QlVUlMFu-aB2jdYth.js.map → effect-QlVUlMFu-svPBY1dH.js.map} +1 -1
  206. package/dist/app/server/assets/{error-BDVg4EUJ.js → error-CHeOE_lh.js} +2 -2
  207. package/dist/app/server/assets/{error-BDVg4EUJ.js.map → error-CHeOE_lh.js.map} +1 -1
  208. package/dist/app/server/assets/{error-Yg6jqry-.js → error-PecJkSHO.js} +2 -2
  209. package/dist/app/server/assets/{error-Yg6jqry-.js.map → error-PecJkSHO.js.map} +1 -1
  210. package/dist/app/server/assets/{factory-BPswjDEW.js → factory-Bs0vLkBr.js} +2 -2
  211. package/dist/app/server/assets/{factory-BPswjDEW.js.map → factory-Bs0vLkBr.js.map} +1 -1
  212. package/dist/app/server/assets/getPseudoElementBounds-DIn3v91B.js +2 -0
  213. package/dist/app/server/assets/{getPseudoElementBounds-BdqJhx6M.js.map → getPseudoElementBounds-DIn3v91B.js.map} +1 -1
  214. package/dist/app/server/assets/{index-CLddUTqr-Bavq3Qss.js → index-CLddUTqr-CmUyZRXY.js} +2 -2
  215. package/dist/app/server/assets/{index-CLddUTqr-Bavq3Qss.js.map → index-CLddUTqr-CmUyZRXY.js.map} +1 -1
  216. package/dist/app/server/assets/{index-DZEfthgZ--TkOBRwP.js → index-DZEfthgZ-Bkf7F_aP.js} +2 -2
  217. package/dist/app/server/assets/{index-DZEfthgZ--TkOBRwP.js.map → index-DZEfthgZ-Bkf7F_aP.js.map} +1 -1
  218. package/dist/app/server/assets/{kysely-adapter-BVql8na5.js → kysely-adapter-DhztbDJz.js} +1 -1
  219. package/dist/app/server/assets/{lazyRouteComponent-BXabRVTE.js → lazyRouteComponent-DOSE663E.js} +2 -2
  220. package/dist/app/server/assets/{lazyRouteComponent-BXabRVTE.js.map → lazyRouteComponent-DOSE663E.js.map} +1 -1
  221. package/dist/app/server/assets/{login-BR3Vh4Jw.js → login-6K4ND-gN.js} +2 -2
  222. package/dist/app/server/assets/{login-BR3Vh4Jw.js.map → login-6K4ND-gN.js.map} +1 -1
  223. package/dist/app/server/assets/{login-DtRzF4FQ.js → login-CGq85v-9.js} +2 -2
  224. package/dist/app/server/assets/{login-DtRzF4FQ.js.map → login-CGq85v-9.js.map} +1 -1
  225. package/dist/app/server/assets/{matchContext-Cuq8aYzA.js → matchContext-BHbopc_c.js} +2 -2
  226. package/dist/app/server/assets/{matchContext-Cuq8aYzA.js.map → matchContext-BHbopc_c.js.map} +1 -1
  227. package/dist/app/server/assets/{mutation-BseSOMT8.js → mutation-D0MCZKRo.js} +2 -2
  228. package/dist/app/server/assets/{mutation-BseSOMT8.js.map → mutation-D0MCZKRo.js.map} +1 -1
  229. package/dist/app/server/assets/pathUSD-BMh6ajrW.css +1 -0
  230. package/dist/app/server/assets/pathUSD-DqRWfB70.js +2 -0
  231. package/dist/app/server/assets/pathUSD-DqRWfB70.js.map +1 -0
  232. package/dist/app/server/assets/{query-lzX3sTGO.js → query-BfAOtP6H.js} +2 -2
  233. package/dist/app/server/assets/{query-lzX3sTGO.js.map → query-BfAOtP6H.js.map} +1 -1
  234. package/dist/app/server/assets/react-dom-BbDIEd_j.css +1 -0
  235. package/dist/app/server/assets/{react-dom-DtwtyQPy.js → react-dom-pSpaua7D.js} +1 -1
  236. package/dist/app/server/assets/{react-dom-DtwtyQPy.js.map → react-dom-pSpaua7D.js.map} +1 -1
  237. package/dist/app/server/assets/{removable-HVB1MGzn.js → removable-BIS_RRBc.js} +2 -2
  238. package/dist/app/server/assets/{removable-HVB1MGzn.js.map → removable-BIS_RRBc.js.map} +1 -1
  239. package/dist/app/server/assets/{resolveError-DSqzEjUE.js → resolveError-DPXmbkOB.js} +2 -2
  240. package/dist/app/server/assets/{resolveError-DSqzEjUE.js.map → resolveError-DPXmbkOB.js.map} +1 -1
  241. package/dist/app/server/assets/{router-uhTdTHZE.js → router-nrTsbXpb.js} +2 -2
  242. package/dist/app/server/assets/router-nrTsbXpb.js.map +1 -0
  243. package/dist/app/server/assets/routes-BgiIzrOt.css +1 -0
  244. package/dist/app/server/assets/{routes-CeDOMpI-.js → routes-ClVSwEtU.js} +2 -2
  245. package/dist/app/server/assets/{routes-CeDOMpI-.js.map → routes-ClVSwEtU.js.map} +1 -1
  246. package/dist/app/server/assets/routes-DM3C9lXZ.js +2 -0
  247. package/dist/app/server/assets/routes-DM3C9lXZ.js.map +1 -0
  248. package/dist/app/server/assets/{schemas-fV27l6kI.js → schemas-CFw4XgfH.js} +2 -2
  249. package/dist/app/server/assets/{schemas-fV27l6kI.js.map → schemas-CFw4XgfH.js.map} +1 -1
  250. package/dist/app/server/assets/{secp256k1-5tp4GQIt.js → secp256k1-BmATpikU.js} +2 -2
  251. package/dist/app/server/assets/{secp256k1-5tp4GQIt.js.map → secp256k1-BmATpikU.js.map} +1 -1
  252. package/dist/app/server/assets/{sury-CWZTCd75-BPXRo6iz.js → sury-CWZTCd75-B2_9nmQ-.js} +2 -2
  253. package/dist/app/server/assets/{sury-CWZTCd75-BPXRo6iz.js.map → sury-CWZTCd75-B2_9nmQ-.js.map} +1 -1
  254. package/dist/app/server/assets/{suspense-CVCU9Kbi.js → suspense-gv0MCXZ8.js} +2 -2
  255. package/dist/app/server/assets/{suspense-CVCU9Kbi.js.map → suspense-gv0MCXZ8.js.map} +1 -1
  256. package/dist/app/server/assets/{useNavigate-D9psnozp.js → useNavigate-gn6-bYOz.js} +2 -2
  257. package/dist/app/server/assets/{useNavigate-D9psnozp.js.map → useNavigate-gn6-bYOz.js.map} +1 -1
  258. package/dist/app/server/assets/useRegisterFieldControl-DMeVvRtG.js +2 -0
  259. package/dist/app/server/assets/{useRegisterFieldControl-UOdCWAKS.js.map → useRegisterFieldControl-DMeVvRtG.js.map} +1 -1
  260. package/dist/app/server/assets/{utils-Dst7Jy9U.js → utils-CJnLBS6t.js} +2 -2
  261. package/dist/app/server/assets/{utils-Dst7Jy9U.js.map → utils-CJnLBS6t.js.map} +1 -1
  262. package/dist/app/server/assets/{valibot--1zFm7rT-LDsJca69.js → valibot--1zFm7rT-DAm9l6Yd.js} +2 -2
  263. package/dist/app/server/assets/{valibot--1zFm7rT-LDsJca69.js.map → valibot--1zFm7rT-DAm9l6Yd.js.map} +1 -1
  264. package/dist/app/server/assets/{valibot-D_HTw1Gn-DY-tIZ72.js → valibot-D_HTw1Gn-B_uu9X0a.js} +2 -2
  265. package/dist/app/server/assets/{valibot-D_HTw1Gn-DY-tIZ72.js.map → valibot-D_HTw1Gn-B_uu9X0a.js.map} +1 -1
  266. package/dist/app/server/assets/{zod-Bwrt9trS-Cf4c1iF8.js → zod-Bwrt9trS-DDq3sdx6.js} +2 -2
  267. package/dist/app/server/assets/{zod-Bwrt9trS-Cf4c1iF8.js.map → zod-Bwrt9trS-DDq3sdx6.js.map} +1 -1
  268. package/dist/app/server/assets/{zod-DSgpEGAE-IkLVlUaZ.js → zod-DSgpEGAE-Dzlub58Z.js} +2 -2
  269. package/dist/app/server/assets/{zod-DSgpEGAE-IkLVlUaZ.js.map → zod-DSgpEGAE-Dzlub58Z.js.map} +1 -1
  270. package/dist/app/server/assets/zyzz-6R2K52xP.css +1 -0
  271. package/dist/app/server/assets/{zyzz.config-DYq-16_0.js → zyzz.config-CW977vYL.js} +3 -3
  272. package/dist/app/server/assets/zyzz.config-CW977vYL.js.map +1 -0
  273. package/dist/app/server/index.js +3 -3
  274. package/package.json +1 -1
  275. package/dist/app/client/assets/Account-DiXbQ7gq.css +0 -1
  276. package/dist/app/client/assets/Account-JXT-dSA8.js +0 -1
  277. package/dist/app/client/assets/Amount-C5uw89Ge.js +0 -1
  278. package/dist/app/client/assets/Amount-Ck6sPRDT.css +0 -1
  279. package/dist/app/client/assets/Callout-DE0CvxbE.css +0 -1
  280. package/dist/app/client/assets/Callout-D_dLrptL.js +0 -1
  281. package/dist/app/client/assets/CodeInput-CXbj-o_B.js +0 -1
  282. package/dist/app/client/assets/CodeInput-C_clyqA2.css +0 -1
  283. package/dist/app/client/assets/Deposit-CAkrtNYZ.css +0 -1
  284. package/dist/app/client/assets/Deposit-Cv7IQBO0.js +0 -1
  285. package/dist/app/client/assets/DevTools-CnWAfvO2.js +0 -1
  286. package/dist/app/client/assets/DevTools-DLG9O0YT.css +0 -1
  287. package/dist/app/client/assets/Grant-B6bmC4rh.css +0 -1
  288. package/dist/app/client/assets/Hex-BR5nHbFT.js +0 -10
  289. package/dist/app/client/assets/Hex-CriDfcNg.css +0 -1
  290. package/dist/app/client/assets/IconChip-BVqRSUpG.css +0 -1
  291. package/dist/app/client/assets/IconChip-ClKbN-8M.js +0 -1
  292. package/dist/app/client/assets/InputGroup-4QFqa-T2.css +0 -1
  293. package/dist/app/client/assets/InputGroup-CEI6gBId.js +0 -1
  294. package/dist/app/client/assets/Inter-Variable-DiVDrmQJ.woff2 +0 -0
  295. package/dist/app/client/assets/Loader-CtzJeMeX.js +0 -1
  296. package/dist/app/client/assets/Rows-DgpXomcK.js +0 -1
  297. package/dist/app/client/assets/Rows-oSTffNii.css +0 -1
  298. package/dist/app/client/assets/SignIn-CjGB1wk9.js +0 -1
  299. package/dist/app/client/assets/SignIn-Dz1G9XNf.css +0 -1
  300. package/dist/app/client/assets/Stack-90EFgtQe.js +0 -1
  301. package/dist/app/client/assets/Stack-CKvHhjzW.css +0 -1
  302. package/dist/app/client/assets/ToolbarRootContext-dnisUzmP.js +0 -1
  303. package/dist/app/client/assets/Tooltip-9TI_rDvs.css +0 -1
  304. package/dist/app/client/assets/Tooltip-C3H_9mgz.js +0 -1
  305. package/dist/app/client/assets/___-7yUISk6H.css +0 -1
  306. package/dist/app/client/assets/___.flows-DwoJPGMf.js +0 -5
  307. package/dist/app/client/assets/index-BXTO-7dr.css +0 -1
  308. package/dist/app/client/assets/index-CkKM7xlX.js +0 -13
  309. package/dist/app/client/assets/pathUSD-DY3ycgMd.js +0 -1
  310. package/dist/app/client/assets/pathUSD-Dn2NadYx.css +0 -1
  311. package/dist/app/client/assets/useNavigate-DsbQ8bTr.js +0 -1
  312. package/dist/app/client/assets/zyzz-MTPfhrAv.css +0 -1
  313. package/dist/app/client/assets/zyzz.config-ENEfJGzk.js +0 -2
  314. package/dist/app/server/assets/Account-BqjoGTzm.js +0 -2
  315. package/dist/app/server/assets/Account-BqjoGTzm.js.map +0 -1
  316. package/dist/app/server/assets/Account-DiXbQ7gq.css +0 -1
  317. package/dist/app/server/assets/Amount-Ck6sPRDT.css +0 -1
  318. package/dist/app/server/assets/Amount-CmypanEu.js +0 -2
  319. package/dist/app/server/assets/Amount-CmypanEu.js.map +0 -1
  320. package/dist/app/server/assets/Callout-DE0CvxbE.css +0 -1
  321. package/dist/app/server/assets/Callout-_eafmkya.js +0 -2
  322. package/dist/app/server/assets/Callout-_eafmkya.js.map +0 -1
  323. package/dist/app/server/assets/CodeInput-CRxIP0KX.js +0 -2
  324. package/dist/app/server/assets/CodeInput-CRxIP0KX.js.map +0 -1
  325. package/dist/app/server/assets/CodeInput-C_clyqA2.css +0 -1
  326. package/dist/app/server/assets/Deposit-CAkrtNYZ.css +0 -1
  327. package/dist/app/server/assets/Deposit-CiWidviP.js +0 -2
  328. package/dist/app/server/assets/Deposit-CiWidviP.js.map +0 -1
  329. package/dist/app/server/assets/DevTools-BJcNvNjx.js +0 -2
  330. package/dist/app/server/assets/DevTools-BJcNvNjx.js.map +0 -1
  331. package/dist/app/server/assets/DevTools-DLG9O0YT.css +0 -1
  332. package/dist/app/server/assets/Grant-B6bmC4rh.css +0 -1
  333. package/dist/app/server/assets/Grant-N8RQy7lZ.js +0 -2
  334. package/dist/app/server/assets/Grant-N8RQy7lZ.js.map +0 -1
  335. package/dist/app/server/assets/Hex-CriDfcNg.css +0 -1
  336. package/dist/app/server/assets/Hex-vNjxlXvk.js +0 -11
  337. package/dist/app/server/assets/Hex-vNjxlXvk.js.map +0 -1
  338. package/dist/app/server/assets/IconChip-BQdjH8i6.js +0 -2
  339. package/dist/app/server/assets/IconChip-BQdjH8i6.js.map +0 -1
  340. package/dist/app/server/assets/IconChip-BVqRSUpG.css +0 -1
  341. package/dist/app/server/assets/InputGroup-4QFqa-T2.css +0 -1
  342. package/dist/app/server/assets/InputGroup-BhUIBTgI.js +0 -2
  343. package/dist/app/server/assets/InputGroup-BhUIBTgI.js.map +0 -1
  344. package/dist/app/server/assets/Inter-Variable-DiVDrmQJ.woff2 +0 -0
  345. package/dist/app/server/assets/Loader-Ivf5dWFl.js +0 -2
  346. package/dist/app/server/assets/PopoverPopup-D98JOZVe.js +0 -2
  347. package/dist/app/server/assets/Rows-BuyZXkPa.js +0 -2
  348. package/dist/app/server/assets/Rows-BuyZXkPa.js.map +0 -1
  349. package/dist/app/server/assets/Rows-oSTffNii.css +0 -1
  350. package/dist/app/server/assets/SignIn-D7jl6zbw.js +0 -2
  351. package/dist/app/server/assets/SignIn-D7jl6zbw.js.map +0 -1
  352. package/dist/app/server/assets/SignIn-Dz1G9XNf.css +0 -1
  353. package/dist/app/server/assets/Stack-C3ecM7vx.js +0 -2
  354. package/dist/app/server/assets/Stack-C3ecM7vx.js.map +0 -1
  355. package/dist/app/server/assets/Stack-CKvHhjzW.css +0 -1
  356. package/dist/app/server/assets/ToolbarRootContext-BCmWBQ7n.js +0 -2
  357. package/dist/app/server/assets/Tooltip-9TI_rDvs.css +0 -1
  358. package/dist/app/server/assets/Tooltip-D3NLigmC.js +0 -2
  359. package/dist/app/server/assets/Tooltip-D3NLigmC.js.map +0 -1
  360. package/dist/app/server/assets/___-7yUISk6H.css +0 -1
  361. package/dist/app/server/assets/___.flows-DRvHKxBR.js +0 -6
  362. package/dist/app/server/assets/___.flows-DRvHKxBR.js.map +0 -1
  363. package/dist/app/server/assets/_tanstack-start-manifest_v-BIobT_5u.js +0 -1
  364. package/dist/app/server/assets/default-u_dwuiYb-BZX-cEte.js +0 -2
  365. package/dist/app/server/assets/dist-k0uWU-Rh.js +0 -1
  366. package/dist/app/server/assets/getPseudoElementBounds-BdqJhx6M.js +0 -2
  367. package/dist/app/server/assets/pathUSD-CVs71wGH.js +0 -2
  368. package/dist/app/server/assets/pathUSD-CVs71wGH.js.map +0 -1
  369. package/dist/app/server/assets/pathUSD-Dn2NadYx.css +0 -1
  370. package/dist/app/server/assets/react-dom-bupMaze0.css +0 -1
  371. package/dist/app/server/assets/router-uhTdTHZE.js.map +0 -1
  372. package/dist/app/server/assets/routes-ZveUsG66.js +0 -2
  373. package/dist/app/server/assets/routes-ZveUsG66.js.map +0 -1
  374. package/dist/app/server/assets/routes-dxKeFXjL.css +0 -1
  375. package/dist/app/server/assets/useRegisterFieldControl-UOdCWAKS.js +0 -2
  376. package/dist/app/server/assets/zyzz-DuvTIyXM.css +0 -1
  377. package/dist/app/server/assets/zyzz.config-DYq-16_0.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import{A as e,D as t,E as n,O as r,_ as i,a,d as o,j as s,k as c,o as l,s as u,t as d,x as f,y as p}from"./assets/react-dom-DtwtyQPy.js";import{C as m,S as h,d as g,f as _,h as v,i as y,l as b,o as x,p as S,r as C,s as w,t as E,u as D,v as O,x as k}from"./assets/Match-DusFDz9D.js";import{a as A,n as j,r as M}from"./assets/utils-Dst7Jy9U.js";import"./assets/ClientOnly-CbQVNHub.js";import{r as ee}from"./assets/matchContext-Cuq8aYzA.js";import{a as N,c as P,d as te,f as ne,h as F,i as I,l as re,m as ie,n as ae,o as oe,p as se,r as ce,s as le,t as ue,u as de}from"./assets/cookie-d6FDU2Yq.js";import{$ as fe,Et as pe,Fn as L,Ft as me,G as he,K as ge,Ln as _e,Mn as ve,Nn as ye,Pn as be,Q as xe,Rn as Se,S as Ce,Sn as we,Tn as Te,Tt as Ee,U as De,Vt as Oe,W as ke,X as Ae,Y as je,_ as Me,_n as Ne,a as Pe,b as Fe,bn as Ie,fn as Le,ft as Re,g as ze,h as Be,hn as Ve,in as He,it as Ue,jn as We,k as Ge,nt as Ke,on as qe,pt as Je,sn as Ye,tt as Xe,ut as Ze,v as Qe,vn as $e,w as et,wn as tt,x as nt,y as rt,yn as it,z as at,zn as ot}from"./assets/accessKey-CxNqjouy.js";import{A as st,C as ct,M as lt,O as ut,S as dt,T as ft,i as pt,j as mt,s as ht,t as gt,y as _t,z as vt}from"./assets/Bytes-YtuDjUWf.js";import{H as yt,K as bt,V as xt,W as St,X as Ct,Y as wt,Z as Tt,z as Et}from"./assets/utils-C4ZXZIZW.js";import{a as Dt,c as Ot,o as kt,s as At,t as jt}from"./assets/secp256k1-5tp4GQIt.js";import{B as Mt,C as Nt,G as Pt,S as Ft,V as It,b as Lt,d as Rt,f as zt,i as Bt,n as Vt,p as Ht,r as Ut,s as Wt,u as Gt,w as Kt,x as qt,y as Jt}from"./assets/Authentication-Odm8-gfs.js";import{C as Yt,S as Xt,T as Zt,a as Qt,b as $t,c as en,d as tn,f as nn,g as rn,h as an,i as on,l as sn,m as cn,n as ln,o as un,p as dn,r as fn,s as pn,t as mn,u as hn,v as gn,w as _n,x as vn,y as yn}from"./assets/Chain-CQgBRAXx.js";import{Dt as bn,Gt as xn,L as Sn,Mt as Cn,O as wn,Ot as Tn,Pt as En,S as Dn,T as On,Tt as kn,Z as An,an as jn,b as Mn,dt as Nn,h as Pn,mt as Fn,ot as In,sn as Ln,t as Rn,ut as zn,v as Bn,xt as Vn,yt as Hn}from"./assets/call-BaWxWyrp.js";import{t as Un}from"./assets/Credential-D82PNwyx.js";import{C as Wn,D as Gn,E as Kn,O as qn,S as Jn,T as R,_ as Yn,a as Xn,b as Zn,c as Qn,d as $n,f as er,k as tr,l as nr,m as rr,o as ir,p as ar,s as or,u as sr,v as cr,w as lr,x as z}from"./assets/schemas-fV27l6kI.js";import{$ as ur,$t as dr,A as fr,At as pr,B as mr,Bt as hr,C as gr,Cn as _r,Ct as vr,D as yr,Dt as br,E as xr,Et as Sr,F as Cr,Ft as wr,G as Tr,Gt as Er,H as Dr,Ht as Or,I as kr,It as Ar,J as jr,Jt as Mr,K as Nr,Kt as Pr,L as Fr,Lt as Ir,M as Lr,Mt as Rr,N as zr,Nt as Br,O as Vr,Ot as Hr,P as Ur,Pt as Wr,Q as Gr,Qt as B,R as Kr,Rt as qr,S as Jr,Sn as Yr,St as Xr,T as Zr,Tt as Qr,U as $r,Ut as ei,V as ti,Vt as ni,W as ri,Wt as ii,X as ai,Xt as oi,Y as si,Yt as ci,Z as li,Zt as ui,_ as di,_n as fi,_t as pi,a as mi,an as hi,at as gi,b as _i,bn as vi,bt as yi,c as bi,cn as xi,ct as Si,d as Ci,dn as wi,dt as Ti,en as Ei,et as Di,f as Oi,fn as ki,ft as Ai,g as ji,gn as Mi,gt as Ni,h as Pi,hn as Fi,ht as Ii,i as Li,in as Ri,it as zi,j as Bi,jt as Vi,k as Hi,kt as Ui,l as Wi,ln as Gi,lt as Ki,m as qi,mn as Ji,mt as Yi,n as Xi,nn as Zi,nt as Qi,o as $i,on as ea,ot as ta,p as na,pn as ra,pt as ia,q as aa,qt as oa,r as sa,rn as ca,rt as la,s as ua,sn as da,st as fa,t as pa,tn as ma,tt as ha,u as ga,un as _a,ut as va,v as ya,vn as ba,vt as xa,w as Sa,wn as Ca,wt as wa,x as Ta,xn as Ea,xt as Da,y as Oa,yn as ka,yt as Aa,z as ja,zt as Ma}from"./assets/authorize-DXYo-K2n-08rIhXFT.js";import{A as Na,C as Pa,F as Fa,H as Ia,I as La,L as Ra,M as za,N as Ba,O as Va,P as Ha,V as Ua,W as Wa,X as Ga,_ as Ka,a as qa,b as V,g as Ja,h as Ya,i as Xa,j as Za,l as Qa,m as $a,nt as eo,o as to,s as no,t as ro,u as io,v as ao,w as oo,x as H,y as so}from"./assets/get-id-field-DS9IzViQ.js";import{a as co,c as lo,i as uo,l as fo,n as po,o as mo,r as ho,s as go,t as _o,u as vo}from"./assets/schema-check-DB26iPrr.js";import{n as yo,r as bo,t as xo}from"./assets/factory-BPswjDEW.js";import{c as So,i as Co,o as wo,s as To,t as Eo}from"./assets/ExecutionError-DSSCSoHl.js";import{a as Do,i as Oo,n as ko,o as Ao,r as jo,t as Mo}from"./assets/Faucet-Cv-nQMBR.js";import{t as No}from"./assets/decodeFunctionData-Y8BApZGI.js";import{n as Po}from"./assets/index-CLddUTqr-Bavq3Qss.js";import"./assets/dist-k0uWU-Rh.js";import{n as Fo}from"./assets/index-DZEfthgZ--TkOBRwP.js";import{c as Io}from"./assets/sqlite-introspector-DSCAP82F-Crx7Ny14.js";import{i as Lo,n as Ro,o as zo,r as Bo,s as Vo,t as Ho}from"./assets/dist-C9wLcfH8.js";import"cloudflare:workers";import Uo,{PassThrough as Wo,Readable as Go}from"node:stream";import{AsyncLocalStorage as Ko}from"node:async_hooks";import qo,{randomBytes as Jo,scrypt as eee}from"node:crypto";import Yo from"node:events";import Xo from"node:util";import Zo from"node:util/types";import Qo from"node:dns";import $o from"node:fs";import es from"node:net";import ts from"node:tls";import ns from"node:path";import rs from"node:string_decoder";function is(e){return Error(`[unenv] ${e} is not implemented yet!`)}var as=globalThis.performance?.timeOrigin??Date.now(),os=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-as,ss={name:`node`,entryType:`node`,startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},cs=class{__unenv__=!0;detail;entryType=`event`;name;startTime;constructor(e,t){this.name=e,this.startTime=t?.startTime||os(),this.detail=t?.detail}get duration(){return os()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ls=class extends cs{entryType=`mark`;constructor(){super(...arguments)}get duration(){return 0}},us=class extends cs{entryType=`measure`},ds=class extends cs{entryType=`resource`;serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType=``;name=``;nextHopProtocol=``;redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},fs=class{__unenv__=!0;getEntries(){return[]}getEntriesByName(e,t){return[]}getEntriesByType(e){return[]}},ps=class{__unenv__=!0;timeOrigin=as;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(e,t){throw is(`Performance.timerify`)}get nodeTiming(){return ss}eventLoopUtilization(){return{}}markResourceTiming(){return new ds(``)}onresourcetimingbufferfull=null;now(){return this.timeOrigin===as?os():Date.now()-this.timeOrigin}clearMarks(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`mark`)}clearMeasures(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`measure`)}clearResourceTimings(){this._entries=this._entries.filter(e=>e.entryType!==`resource`||e.entryType!==`navigation`)}getEntries(){return this._entries}getEntriesByName(e,t){return this._entries.filter(n=>n.name===e&&(!t||n.entryType===t))}getEntriesByType(e){return this._entries.filter(t=>t.entryType===e)}mark(e,t){let n=new ls(e,t);return this._entries.push(n),n}measure(e,t,n){let r,i;typeof t==`string`?(r=this.getEntriesByName(t,`mark`)[0]?.startTime,i=this.getEntriesByName(n,`mark`)[0]?.startTime):(r=Number.parseFloat(t?.start)||this.now(),i=Number.parseFloat(t?.end)||this.now());let a=new us(e,{startTime:r,detail:{start:r,end:i}});return this._entries.push(a),a}setResourceTimingBufferSize(e){this._resourceTimingBufferSize=e}addEventListener(e,t,n){throw is(`Performance.addEventListener`)}removeEventListener(e,t,n){throw is(`Performance.removeEventListener`)}dispatchEvent(e){throw is(`Performance.dispatchEvent`)}toJSON(){return this}},ms=class{__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(e){this._callback=e}takeRecords(){return[]}disconnect(){throw is(`PerformanceObserver.disconnect`)}observe(e){throw is(`PerformanceObserver.observe`)}bind(e){return e}runInAsyncScope(e,t,...n){return e.call(t,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},hs=globalThis.performance&&`addEventListener`in globalThis.performance?globalThis.performance:new ps;if(!(`__unenv__`in hs)){let e=ps.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!==`constructor`&&!(t in hs)){let n=Object.getOwnPropertyDescriptor(e,t);n&&Object.defineProperty(hs,t,n)}}globalThis.performance=hs,globalThis.Performance=ps,globalThis.PerformanceEntry=cs,globalThis.PerformanceMark=ls,globalThis.PerformanceMeasure=us,globalThis.PerformanceObserver=ms,globalThis.PerformanceObserverEntryList=fs,globalThis.PerformanceResourceTiming=ds;function gs(e){return e.replaceAll(`~`,`~~`).replaceAll(`\0`,`~0`).replaceAll(`�`,`~r`).replaceAll(`/`,`\0`)}function _s(e){return e}var vs=Symbol.asyncIterator,ys=Symbol.hasInstance,bs=Symbol.isConcatSpreadable,xs=Symbol.iterator,Ss=Symbol.match,Cs=Symbol.matchAll,ws=Symbol.replace,Ts=Symbol.search,Es=Symbol.species,Ds=Symbol.split,Os=Symbol.toPrimitive,ks=Symbol.toStringTag,As=Symbol.unscopables,js={0:`Symbol.asyncIterator`,1:`Symbol.hasInstance`,2:`Symbol.isConcatSpreadable`,3:`Symbol.iterator`,4:`Symbol.match`,5:`Symbol.matchAll`,6:`Symbol.replace`,7:`Symbol.search`,8:`Symbol.species`,9:`Symbol.split`,10:`Symbol.toPrimitive`,11:`Symbol.toStringTag`,12:`Symbol.unscopables`},Ms={[vs]:0,[ys]:1,[bs]:2,[xs]:3,[Ss]:4,[Cs]:5,[ws]:6,[Ts]:7,[Es]:8,[Ds]:9,[Os]:10,[ks]:11,[As]:12},Ns={0:vs,1:ys,2:bs,3:xs,4:Ss,5:Cs,6:ws,7:Ts,8:Es,9:Ds,10:Os,11:ks,12:As},Ps={2:`!0`,3:`!1`,1:`void 0`,0:`null`,4:`-0`,5:`1/0`,6:`-1/0`,7:`0/0`},Fs={2:!0,3:!1,1:void 0,0:null,4:-0,5:1/0,6:-1/0,7:NaN},Is={0:`Error`,1:`EvalError`,2:`RangeError`,3:`ReferenceError`,4:`SyntaxError`,5:`TypeError`,6:`URIError`},Ls={0:Error,1:EvalError,2:RangeError,3:ReferenceError,4:SyntaxError,5:TypeError,6:URIError};function Rs(e,t,n,r,i,a,o,s,c,l,u,d){return{t:e,i:t,s:n,c:r,m:i,p:a,e:o,a:s,f:c,b:l,o:u,l:d}}function zs(e){return Rs(2,void 0,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}var Bs=zs(2),Vs=zs(3),Hs=zs(1),Us=zs(0),Ws=zs(4),Gs=zs(5),Ks=zs(6),qs=zs(7),Js=64,Ys=/[\x00-\x07\x0b\x0e-\x1f<\u2028\u2029\ud800-\udfff]/;function Xs(e){switch(e){case`"`:return`\\"`;case`\\`:return`\\\\`;case`
1
+ import{A as e,D as t,E as n,O as r,_ as i,a,d as o,j as s,k as c,o as l,s as u,t as d,x as f,y as p}from"./assets/react-dom-pSpaua7D.js";import{C as m,S as h,d as g,f as _,h as v,i as y,l as b,o as x,p as S,r as C,s as w,t as E,u as D,v as O,x as k}from"./assets/Match-C65vhhhD.js";import{a as A,n as j,r as M}from"./assets/utils-CJnLBS6t.js";import"./assets/ClientOnly-B8k5xDwz.js";import{r as ee}from"./assets/matchContext-BHbopc_c.js";import{a as N,c as P,d as te,f as ne,h as F,i as I,l as re,m as ie,n as ae,o as oe,p as se,r as ce,s as le,t as ue,u as de}from"./assets/cookie-d6FDU2Yq.js";import{$ as fe,Et as pe,Fn as L,Ft as me,G as he,K as ge,Ln as _e,Mn as ve,Nn as ye,Pn as be,Q as xe,Rn as Se,S as Ce,Sn as we,Tn as Te,Tt as Ee,U as De,Vt as Oe,W as ke,X as Ae,Y as je,_ as Me,_n as Ne,a as Pe,b as Fe,bn as Ie,fn as Le,ft as Re,g as ze,h as Be,hn as Ve,in as He,it as Ue,jn as We,k as Ge,nt as Ke,on as qe,pt as Je,sn as Ye,tt as Xe,ut as Ze,v as Qe,vn as $e,w as et,wn as tt,x as nt,y as rt,yn as it,z as at,zn as ot}from"./assets/accessKey-DlBe71R7.js";import{A as st,C as ct,M as lt,O as ut,S as dt,T as ft,i as pt,j as mt,s as ht,t as gt,y as _t,z as vt}from"./assets/Bytes-YtuDjUWf.js";import{H as yt,K as bt,V as xt,W as St,X as Ct,Y as wt,Z as Tt,z as Et}from"./assets/utils-C4ZXZIZW.js";import{a as Dt,c as Ot,o as kt,s as At,t as jt}from"./assets/secp256k1-BmATpikU.js";import{B as Mt,C as Nt,G as Pt,S as Ft,V as It,b as Lt,d as Rt,f as zt,i as Bt,n as Vt,p as Ht,r as Ut,s as Wt,u as Gt,w as Kt,x as qt,y as Jt}from"./assets/Authentication-BJgy8lyC.js";import{C as Yt,S as Xt,T as Zt,a as Qt,b as $t,c as en,d as tn,f as nn,g as rn,h as an,i as on,l as sn,m as cn,n as ln,o as un,p as dn,r as fn,s as pn,t as mn,u as hn,v as gn,w as _n,x as vn,y as yn}from"./assets/Chain-C9RGZDJm.js";import{Dt as bn,Gt as xn,L as Sn,Mt as Cn,O as wn,Ot as Tn,Pt as En,S as Dn,T as On,Tt as kn,Z as An,an as jn,b as Mn,dt as Nn,h as Pn,mt as Fn,ot as In,sn as Ln,t as Rn,ut as zn,v as Bn,xt as Vn,yt as Hn}from"./assets/call-BaWxWyrp.js";import{t as Un}from"./assets/Credential-DXcfPJEP.js";import{C as Wn,D as Gn,E as Kn,O as qn,S as Jn,T as R,_ as Yn,a as Xn,b as Zn,c as Qn,d as $n,f as er,k as tr,l as nr,m as rr,o as ir,p as ar,s as or,u as sr,v as cr,w as lr,x as z}from"./assets/schemas-CFw4XgfH.js";import{$ as ur,$t as dr,A as fr,At as pr,B as mr,Bt as hr,C as gr,Cn as _r,Ct as vr,D as yr,Dt as br,E as xr,Et as Sr,F as Cr,Ft as wr,G as Tr,Gt as Er,H as Dr,Ht as Or,I as kr,It as Ar,J as jr,Jt as Mr,K as Nr,Kt as Pr,L as Fr,Lt as Ir,M as Lr,Mt as Rr,N as zr,Nt as Br,O as Vr,Ot as Hr,P as Ur,Pt as Wr,Q as Gr,Qt as B,R as Kr,Rt as qr,S as Jr,Sn as Yr,St as Xr,T as Zr,Tt as Qr,U as $r,Ut as ei,V as ti,Vt as ni,W as ri,Wt as ii,X as ai,Xt as oi,Y as si,Yt as ci,Z as li,Zt as ui,_ as di,_n as fi,_t as pi,a as mi,an as hi,at as gi,b as _i,bn as vi,bt as yi,c as bi,cn as xi,ct as Si,d as Ci,dn as wi,dt as Ti,en as Ei,et as Di,f as Oi,fn as ki,ft as Ai,g as ji,gn as Mi,gt as Ni,h as Pi,hn as Fi,ht as Ii,i as Li,in as Ri,it as zi,j as Bi,jt as Vi,k as Hi,kt as Ui,l as Wi,ln as Gi,lt as Ki,m as qi,mn as Ji,mt as Yi,n as Xi,nn as Zi,nt as Qi,o as $i,on as ea,ot as ta,p as na,pn as ra,pt as ia,q as aa,qt as oa,r as sa,rn as ca,rt as la,s as ua,sn as da,st as fa,t as pa,tn as ma,tt as ha,u as ga,un as _a,ut as va,v as ya,vn as ba,vt as xa,w as Sa,wn as Ca,wt as wa,x as Ta,xn as Ea,xt as Da,y as Oa,yn as ka,yt as Aa,z as ja,zt as Ma}from"./assets/authorize-DXYo-K2n-Bc8o9t1x.js";import{A as Na,C as Pa,F as Fa,H as Ia,I as La,L as Ra,M as za,N as Ba,O as Va,P as Ha,V as Ua,W as Wa,X as Ga,_ as Ka,a as qa,b as V,g as Ja,h as Ya,i as Xa,j as Za,l as Qa,m as $a,nt as eo,o as to,s as no,t as ro,u as io,v as ao,w as oo,x as H,y as so}from"./assets/get-id-field-DS9IzViQ.js";import{a as co,c as lo,i as uo,l as fo,n as po,o as mo,r as ho,s as go,t as _o,u as vo}from"./assets/schema-check-DB26iPrr.js";import{n as yo,r as bo,t as xo}from"./assets/factory-Bs0vLkBr.js";import{c as So,i as Co,o as wo,s as To,t as Eo}from"./assets/ExecutionError-DoRNvh3D.js";import{a as Do,i as Oo,n as ko,o as Ao,r as jo,t as Mo}from"./assets/Faucet-jp6zNWHE.js";import{t as No}from"./assets/decodeFunctionData-Y8BApZGI.js";import{n as Po}from"./assets/index-CLddUTqr-CmUyZRXY.js";import"./assets/dist-BhIyCFP8.js";import{n as Fo}from"./assets/index-DZEfthgZ-Bkf7F_aP.js";import{c as Io}from"./assets/sqlite-introspector-DSCAP82F-Crx7Ny14.js";import{i as Lo,n as Ro,o as zo,r as Bo,s as Vo,t as Ho}from"./assets/dist-C-Rzwa6V.js";import"cloudflare:workers";import Uo,{PassThrough as Wo,Readable as Go}from"node:stream";import{AsyncLocalStorage as Ko}from"node:async_hooks";import qo,{randomBytes as Jo,scrypt as eee}from"node:crypto";import Yo from"node:events";import Xo from"node:util";import Zo from"node:util/types";import Qo from"node:dns";import $o from"node:fs";import es from"node:net";import ts from"node:tls";import ns from"node:path";import rs from"node:string_decoder";function is(e){return Error(`[unenv] ${e} is not implemented yet!`)}var as=globalThis.performance?.timeOrigin??Date.now(),os=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-as,ss={name:`node`,entryType:`node`,startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},cs=class{__unenv__=!0;detail;entryType=`event`;name;startTime;constructor(e,t){this.name=e,this.startTime=t?.startTime||os(),this.detail=t?.detail}get duration(){return os()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ls=class extends cs{entryType=`mark`;constructor(){super(...arguments)}get duration(){return 0}},us=class extends cs{entryType=`measure`},ds=class extends cs{entryType=`resource`;serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType=``;name=``;nextHopProtocol=``;redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},fs=class{__unenv__=!0;getEntries(){return[]}getEntriesByName(e,t){return[]}getEntriesByType(e){return[]}},ps=class{__unenv__=!0;timeOrigin=as;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(e,t){throw is(`Performance.timerify`)}get nodeTiming(){return ss}eventLoopUtilization(){return{}}markResourceTiming(){return new ds(``)}onresourcetimingbufferfull=null;now(){return this.timeOrigin===as?os():Date.now()-this.timeOrigin}clearMarks(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`mark`)}clearMeasures(e){this._entries=e?this._entries.filter(t=>t.name!==e):this._entries.filter(e=>e.entryType!==`measure`)}clearResourceTimings(){this._entries=this._entries.filter(e=>e.entryType!==`resource`||e.entryType!==`navigation`)}getEntries(){return this._entries}getEntriesByName(e,t){return this._entries.filter(n=>n.name===e&&(!t||n.entryType===t))}getEntriesByType(e){return this._entries.filter(t=>t.entryType===e)}mark(e,t){let n=new ls(e,t);return this._entries.push(n),n}measure(e,t,n){let r,i;typeof t==`string`?(r=this.getEntriesByName(t,`mark`)[0]?.startTime,i=this.getEntriesByName(n,`mark`)[0]?.startTime):(r=Number.parseFloat(t?.start)||this.now(),i=Number.parseFloat(t?.end)||this.now());let a=new us(e,{startTime:r,detail:{start:r,end:i}});return this._entries.push(a),a}setResourceTimingBufferSize(e){this._resourceTimingBufferSize=e}addEventListener(e,t,n){throw is(`Performance.addEventListener`)}removeEventListener(e,t,n){throw is(`Performance.removeEventListener`)}dispatchEvent(e){throw is(`Performance.dispatchEvent`)}toJSON(){return this}},ms=class{__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(e){this._callback=e}takeRecords(){return[]}disconnect(){throw is(`PerformanceObserver.disconnect`)}observe(e){throw is(`PerformanceObserver.observe`)}bind(e){return e}runInAsyncScope(e,t,...n){return e.call(t,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},hs=globalThis.performance&&`addEventListener`in globalThis.performance?globalThis.performance:new ps;if(!(`__unenv__`in hs)){let e=ps.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!==`constructor`&&!(t in hs)){let n=Object.getOwnPropertyDescriptor(e,t);n&&Object.defineProperty(hs,t,n)}}globalThis.performance=hs,globalThis.Performance=ps,globalThis.PerformanceEntry=cs,globalThis.PerformanceMark=ls,globalThis.PerformanceMeasure=us,globalThis.PerformanceObserver=ms,globalThis.PerformanceObserverEntryList=fs,globalThis.PerformanceResourceTiming=ds;function gs(e){return e.replaceAll(`~`,`~~`).replaceAll(`\0`,`~0`).replaceAll(`�`,`~r`).replaceAll(`/`,`\0`)}function _s(e){return e}var vs=Symbol.asyncIterator,ys=Symbol.hasInstance,bs=Symbol.isConcatSpreadable,xs=Symbol.iterator,Ss=Symbol.match,Cs=Symbol.matchAll,ws=Symbol.replace,Ts=Symbol.search,Es=Symbol.species,Ds=Symbol.split,Os=Symbol.toPrimitive,ks=Symbol.toStringTag,As=Symbol.unscopables,js={0:`Symbol.asyncIterator`,1:`Symbol.hasInstance`,2:`Symbol.isConcatSpreadable`,3:`Symbol.iterator`,4:`Symbol.match`,5:`Symbol.matchAll`,6:`Symbol.replace`,7:`Symbol.search`,8:`Symbol.species`,9:`Symbol.split`,10:`Symbol.toPrimitive`,11:`Symbol.toStringTag`,12:`Symbol.unscopables`},Ms={[vs]:0,[ys]:1,[bs]:2,[xs]:3,[Ss]:4,[Cs]:5,[ws]:6,[Ts]:7,[Es]:8,[Ds]:9,[Os]:10,[ks]:11,[As]:12},Ns={0:vs,1:ys,2:bs,3:xs,4:Ss,5:Cs,6:ws,7:Ts,8:Es,9:Ds,10:Os,11:ks,12:As},Ps={2:`!0`,3:`!1`,1:`void 0`,0:`null`,4:`-0`,5:`1/0`,6:`-1/0`,7:`0/0`},Fs={2:!0,3:!1,1:void 0,0:null,4:-0,5:1/0,6:-1/0,7:NaN},Is={0:`Error`,1:`EvalError`,2:`RangeError`,3:`ReferenceError`,4:`SyntaxError`,5:`TypeError`,6:`URIError`},Ls={0:Error,1:EvalError,2:RangeError,3:ReferenceError,4:SyntaxError,5:TypeError,6:URIError};function Rs(e,t,n,r,i,a,o,s,c,l,u,d){return{t:e,i:t,s:n,c:r,m:i,p:a,e:o,a:s,f:c,b:l,o:u,l:d}}function zs(e){return Rs(2,void 0,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}var Bs=zs(2),Vs=zs(3),Hs=zs(1),Us=zs(0),Ws=zs(4),Gs=zs(5),Ks=zs(6),qs=zs(7),Js=64,Ys=/[\x00-\x07\x0b\x0e-\x1f<\u2028\u2029\ud800-\udfff]/;function Xs(e){switch(e){case`"`:return`\\"`;case`\\`:return`\\\\`;case`
2
2
  `:return`\\n`;case`\r`:return`\\r`;case`\b`:return`\\b`;case` `:return`\\t`;case`\f`:return`\\f`;case`<`:return`\\x3C`;case`\u2028`:return`\\u2028`;case`\u2029`:return`\\u2029`;default:return}}function Zs(e){if(e.length>=Js&&!Ys.test(e))return JSON.stringify(e).slice(1,-1);let t=``,n=0,r;for(let i=0,a=e.length;i<a;i++)r=Xs(e[i]),r&&(t+=e.slice(n,i)+r,n=i+1);return n===0?t=e:t+=e.slice(n),t}function Qs(e){switch(e){case`\\\\`:return`\\`;case`\\"`:return`"`;case`\\n`:return`
3
3
  `;case`\\r`:return`\r`;case`\\b`:return`\b`;case`\\t`:return` `;case`\\f`:return`\f`;case`\\x3C`:return`<`;case`\\u2028`:return`\u2028`;case`\\u2029`:return`\u2029`;default:return e}}function $s(e){return typeof e==`string`&&!e.includes(`\\`)?e:e.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g,Qs)}var{toString:tee}=Object.prototype,ec={parsing:1,serialization:2,deserialization:3};function tc(e){return`Seroval Error (step: ${ec[e]})`}var nc=(e,t)=>tc(e),rc=class extends Error{constructor(e,t){super(nc(e,t)),this.cause=t}},ic=class extends rc{constructor(e){super(`parsing`,e)}},ac=class extends rc{constructor(e){super(`deserialization`,e)}};function oc(e){return`Seroval Error (specific: ${e})`}var sc=class extends Error{constructor(e){super(oc(1)),this.value=e}},cc=class extends Error{constructor(e){super(oc(2))}},lc=class extends Error{constructor(e){super(oc(3))}},uc=class extends Error{constructor(e){super(oc(4))}},dc=class extends Error{constructor(e){super(oc(5)),this.value=e}},fc=class extends Error{constructor(e){super(oc(6))}},pc=class extends Error{constructor(e){super(oc(7))}},mc=class extends Error{constructor(e){super(oc(8))}},hc=class extends Error{constructor(e){super(oc(9))}},gc=`__SEROVAL_REFS__`,_c=`self.$R`;function vc(e){return e==null?`${_c}=${_c}||[]`:`(${_c}=${_c}||{})["${Zs(e)}"]=[]`}var yc=new Map,bc=new Map;function xc(e){return yc.has(e)}function Sc(e){return bc.has(e)}function Cc(e){if(xc(e))return yc.get(e);throw new dc(e)}function wc(e){if(Sc(e))return bc.get(e);throw new fc(e)}typeof globalThis<`u`?Object.defineProperty(globalThis,gc,{value:bc,configurable:!0,writable:!1,enumerable:!1}):typeof window<`u`?Object.defineProperty(window,gc,{value:bc,configurable:!0,writable:!1,enumerable:!1}):typeof self<`u`?Object.defineProperty(self,gc,{value:bc,configurable:!0,writable:!1,enumerable:!1}):typeof global<`u`&&Object.defineProperty(global,gc,{value:bc,configurable:!0,writable:!1,enumerable:!1});function Tc(e){return e instanceof EvalError?1:e instanceof RangeError?2:e instanceof ReferenceError?3:e instanceof SyntaxError?4:e instanceof TypeError?5:e instanceof URIError?6:0}function Ec(e){let t=Is[Tc(e)];return e.name===t?e.constructor.name===t?{}:{name:e.constructor.name}:{name:e.name}}function Dc(e,t){let n=Ec(e),r=Object.getOwnPropertyNames(e);for(let i=0,a=r.length,o;i<a;i++)o=r[i],o!==`name`&&o!==`message`&&(o===`stack`?t&4&&(n||={},n[o]=e[o]):(n||={},n[o]=e[o]));return n}function Oc(e){return Object.isFrozen(e)?3:Object.isSealed(e)?2:+!Object.isExtensible(e)}function kc(e){switch(e){case 1/0:return Gs;case-1/0:return Ks}return e===e?Object.is(e,-0)?Ws:Rs(0,void 0,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0):qs}function Ac(e){return Rs(1,void 0,Zs(e),void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function jc(e){return Rs(3,void 0,``+e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Mc(e){return Rs(4,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Nc(e,t){let n=t.valueOf();return Rs(5,e,n===n?t.toISOString():``,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Pc(e,t,n){return Rs(36,e,n.toString(),t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Fc(e,t){return Rs(6,e,void 0,Zs(t.source),t.flags,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Ic(e,t){return Rs(17,e,Ms[t],void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Lc(e,t){return Rs(18,e,Zs(Cc(t)),void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Rc(e,t,n){return Rs(25,e,n,Zs(t),void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function zc(e,t,n){return Rs(9,e,void 0,void 0,void 0,void 0,void 0,n,void 0,void 0,Oc(t),void 0)}function Bc(e,t){return Rs(21,e,void 0,void 0,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0)}var Vc=1e6;function Hc(e,t,n){if(t.length>Vc)throw new sc(t);return Rs(15,e,void 0,t.constructor.name,void 0,void 0,void 0,void 0,n,t.byteOffset,void 0,t.length)}function Uc(e,t,n){if(t.length>Vc)throw new sc(t);return Rs(16,e,void 0,t.constructor.name,void 0,void 0,void 0,void 0,n,t.byteOffset,void 0,t.length)}function Wc(e,t,n){if(t.byteLength>Vc)throw new sc(t);return Rs(20,e,void 0,void 0,void 0,void 0,void 0,void 0,n,t.byteOffset,void 0,t.byteLength)}function Gc(e,t,n){return Rs(13,e,Tc(t),void 0,Zs(t.message),n,void 0,void 0,void 0,void 0,void 0,void 0)}function Kc(e,t,n){return Rs(14,e,Tc(t),void 0,Zs(t.message),n,void 0,void 0,void 0,void 0,void 0,void 0)}function qc(e,t){return Rs(7,e,void 0,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0,void 0)}function Jc(e,t){return Rs(28,void 0,void 0,void 0,void 0,void 0,void 0,[e,t],void 0,void 0,void 0,void 0)}function Yc(e,t){return Rs(30,void 0,void 0,void 0,void 0,void 0,void 0,[e,t],void 0,void 0,void 0,void 0)}function Xc(e,t,n){return Rs(31,e,void 0,void 0,void 0,void 0,void 0,n,t,void 0,void 0,void 0)}function Zc(e,t){return Rs(32,e,void 0,void 0,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0)}function Qc(e,t){return Rs(33,e,void 0,void 0,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0)}function $c(e,t){return Rs(34,e,void 0,void 0,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0)}function el(e,t,n,r){return Rs(35,e,n,void 0,void 0,void 0,void 0,t,void 0,void 0,void 0,r)}var tl=class{constructor(e,t){this.value=e,this.replacement=t}},nl=()=>{let e={p:0,s:0,f:0};return e.p=new Promise((t,n)=>{e.s=t,e.f=n}),e},rl=(e,t)=>{e.s(t),e.p.s=1,e.p.v=t},il=(e,t)=>{e.f(t),e.p.s=2,e.p.v=t},al=nl.toString(),ol=rl.toString(),sl=il.toString(),cl=(()=>{let e=[],t=[],n=!0,r=!1,i=0,a={flush(e,n,r){for(r=0;r<i;r++){let i=t[r];i&&i[n](e)}},up(t,i,a,o){for(i=0,a=e.length;i<a;i++)o=e[i],!n&&i===a-1?t[r?`return`:`throw`](o):t.next(o)},on(e,r=0){let o=n;if(n){for(r=0;r<i&&t[r];r++);r===i&&i++,t[r]=e}return a.up(e),()=>{if(n&&o){for(o=!1,t[r]=void 0;i>0&&!t[i-1];)i--;t.length=i}}}};return{__SEROVAL_STREAM__:!0,on(e){return a.on(e)},next(t){n&&(e.push(t),a.flush(t,`next`))},throw(i){n&&(e.push(i),a.flush(i,`throw`),n=!1,r=!1,t.length=0)},return(i){n&&(e.push(i),a.flush(i,`return`),n=!1,r=!0,t.length=0)}}}).toString(),ll=e=>t=>()=>{let n=0,r={[e](){return r},next(){if(n>t.d)return{done:!0,value:void 0};let e=n++,r=t.v[e];if(e===t.t)throw r;return{done:e===t.d,value:r}}};return r},ul=ll.toString(),dl=(e,t)=>n=>()=>{let r=0,i=-1,a=!1,o=[],s=[],c={finalize(e=0,t=s.length){for(;e<t;e++)s[e].s({done:!0,value:void 0})}};n.on({next(e){let t=s.shift();t&&t.s({done:!1,value:e}),o.push(e)},throw(e){let t=s.shift();t&&t.f(e),c.finalize(),i=o.length,a=!0,o.push(e)},return(e){let t=s.shift();t&&t.s({done:!0,value:e}),c.finalize(),i=o.length,o.push(e)}});let l={[e](){return l},next(){if(i===-1){let e=r++;if(e>=o.length){let e=t();return s.push(e),e.p}return{done:!1,value:o[e]}}if(r>i)return{done:!0,value:void 0};let e=r++,n=o[e];if(e!==i)return{done:!1,value:n};if(a)throw n;return{done:!0,value:n}}};return l},fl=dl.toString(),pl=e=>{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r.buffer},ml=pl.toString(),hl=class{constructor(e,t,n){this.v=e,this.t=t,this.d=n}};function gl(e){return e instanceof hl}function _l(e,t,n){return new hl(e,t,n)}function vl(e){let t=[],n=-1,r=-1,i=e[xs]();for(;;)try{let e=i.next();if(t.push(e.value),e.done){r=t.length-1;break}}catch(e){n=t.length,r=n,t.push(e);break}return _l(t,n,r)}var yl=ll(xs);function bl(e){return yl(e)}var xl={},Sl={},Cl={0:{},1:{},2:{},3:{},4:{},5:{}},nee={0:`[]`,1:al,2:ol,3:sl,4:cl,5:ml},wl=class{constructor(){this.buffer=[],this.listeners=[],this.alive=!0,this.success=!1,this.count=0}flush(e,t){for(let r=0;r<this.count;r++){var n;(n=this.listeners[r])==null||n[t](e)}}replay(e){for(let t=0,n=this.buffer.length;t<n;t++){let r=this.buffer[t];!this.alive&&t===n-1?e[this.success?`return`:`throw`](r):e.next(r)}}on(e){let t=this.alive,n=0;if(t){for(;n<this.count&&this.listeners[n];n++);n===this.count&&this.count++,this.listeners[n]=e}return this.replay(e),()=>{if(this.alive&&t){for(t=!1,this.listeners[n]=void 0;this.count>0&&!this.listeners[this.count-1];)this.count--;this.listeners.length=this.count}}}next(e){this.alive&&(this.buffer.push(e),this.flush(e,`next`))}throw(e){this.alive&&(this.buffer.push(e),this.flush(e,`throw`),this.alive=!1,this.success=!1,this.listeners.length=0)}return(e){this.alive&&(this.buffer.push(e),this.flush(e,`return`),this.alive=!1,this.success=!0,this.listeners.length=0)}};function Tl(e){return e instanceof wl}function El(){return new wl}function Dl(e,t){let n=El(),r=e[vs](),i=!1,a=!1;t?.push(()=>{a||i||(i=!0,Promise.resolve().then(()=>r.return?.call(r)).catch(()=>{}))});async function o(){try{for(;!i;){let e=await r.next();if(i)return;if(e.done){a=!0,n.return(e.value);break}n.next(e.value)}}catch(e){a=!0,i||n.throw(e)}}return o().catch(()=>{}),n}var Ol=dl(vs,nl);function kl(e){return Ol(e)}async function Al(e){try{return[1,await e]}catch(e){return[0,e]}}function jl(e,t){return{plugins:t.plugins,mode:e,marked:new Set,features:127^(t.disabledFeatures||0),refs:t.refs||new Map,depthLimit:t.depthLimit||1e3,compactArrayBufferViews:t.compactArrayBufferViews??!1}}function Ml(e,t){e.marked.add(t)}function Nl(e,t){let n=e.refs.size;return e.refs.set(t,n),n}function Pl(e,t){let n=e.refs.get(t);return n==null?{type:0,value:Nl(e,t)}:(Ml(e,n),{type:1,value:Mc(n)})}function Fl(e,t){let n=Pl(e,t);return n.type===1?n:xc(t)?{type:2,value:Lc(n.value,t)}:n}function Il(e,t){let n=Fl(e,t);if(n.type!==0)return n.value;if(t in Ms)return Ic(n.value,t);throw new sc(t)}function Ll(e,t){let n=Pl(e,Cl[t]);return n.type===1?n.value:Rs(26,n.value,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}function Rl(e){let t=Pl(e,xl);return t.type===1?t.value:Rs(27,t.value,void 0,void 0,void 0,void 0,void 0,void 0,Il(e,xs),void 0,void 0,void 0)}function zl(e){let t=Pl(e,Sl);return t.type===1?t.value:Rs(29,t.value,void 0,void 0,void 0,void 0,void 0,[Ll(e,1),Il(e,vs)],void 0,void 0,void 0,void 0)}function Bl(e,t,n,r){return Rs(n?11:10,e,void 0,void 0,void 0,r,void 0,void 0,void 0,void 0,Oc(t),void 0)}function Vl(e,t,n,r){return Rs(8,t,void 0,void 0,void 0,void 0,{k:n,v:r},void 0,Ll(e,0),void 0,void 0,void 0)}function Hl(e,t,n){return Rs(22,t,n,void 0,void 0,void 0,void 0,void 0,Ll(e,1),void 0,void 0,void 0)}function Ul(e,t){if(!e.compactArrayBufferViews)return t;let n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer,r=t.constructor;return new r(n)}function Wl(e){if(typeof Buffer<`u`)return Buffer.from(e).toString(`base64`);let t=new Uint8Array(e);if(typeof t.toBase64==`function`)return t.toBase64();let n=``;for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}function Gl(e,t,n){return Rs(19,t,Wl(n),void 0,void 0,void 0,void 0,void 0,Ll(e,5),void 0,void 0,void 0)}function Kl(e,t){return{base:jl(e,t),child:void 0}}var ql=class{constructor(e,t){this._p=e,this.depth=t}parse(e){return pu(this._p,this.depth,e)}};async function Jl(e,t,n){let r=[];for(let i=0,a=n.length;i<a;i++)i in n?r[i]=await pu(e,t,n[i]):r[i]=0;return r}async function Yl(e,t,n,r){return zc(n,r,await Jl(e,t,r))}async function Xl(e,t,n){let r=Object.entries(n),i=[],a=[];for(let n=0,o=r.length;n<o;n++)i.push(Zs(r[n][0])),a.push(await pu(e,t,r[n][1]));return xs in n&&(i.push(Il(e.base,xs)),a.push(Jc(Rl(e.base),await pu(e,t,vl(n))))),vs in n&&(i.push(Il(e.base,vs)),a.push(Yc(zl(e.base),await pu(e,t,Dl(n))))),ks in n&&(i.push(Il(e.base,ks)),a.push(Ac(n[ks]))),bs in n&&(i.push(Il(e.base,bs)),a.push(n[bs]?Bs:Vs)),{k:i,v:a}}async function Zl(e,t,n,r,i){return Bl(n,r,i,await Xl(e,t,r))}async function Ql(e,t,n,r){return Bc(n,await pu(e,t,r.valueOf()))}async function $l(e,t,n,r){return r=Ul(e.base,r),Hc(n,r,await pu(e,t,r.buffer))}async function eu(e,t,n,r){return r=Ul(e.base,r),Uc(n,r,await pu(e,t,r.buffer))}async function tu(e,t,n,r){return r=Ul(e.base,r),Wc(n,r,await pu(e,t,r.buffer))}async function nu(e,t,n,r){let i=Dc(r,e.base.features);return Gc(n,r,i?await Xl(e,t,i):void 0)}async function ru(e,t,n,r){let i=Dc(r,e.base.features);return Kc(n,r,i?await Xl(e,t,i):void 0)}async function iu(e,t,n,r){let i=[],a=[];for(let[n,o]of r.entries())i.push(await pu(e,t,n)),a.push(await pu(e,t,o));return Vl(e.base,n,i,a)}async function au(e,t,n,r){let i=[];for(let n of r.keys())i.push(await pu(e,t,n));return qc(n,i)}async function ou(e,t,n,r){let i=e.base.plugins;if(i)for(let a=0,o=i.length;a<o;a++){let o=i[a];if(o.parse.async&&o.test(r))return Rc(n,o.tag,await o.parse.async(r,new ql(e,t),{id:n}))}}async function su(e,t,n,r){let[i,a]=await Al(r);return Rs(12,n,i,void 0,void 0,void 0,void 0,void 0,await pu(e,t,a),void 0,void 0,void 0)}function cu(e,t,n,r,i){let a=[],o=n.on({next:n=>{Ml(this.base,t),pu(this,e,n).then(e=>{a.push(Zc(t,e))},e=>{i(e),o()})},throw:n=>{Ml(this.base,t),pu(this,e,n).then(e=>{a.push(Qc(t,e)),r(a),o()},e=>{i(e),o()})},return:n=>{Ml(this.base,t),pu(this,e,n).then(e=>{a.push($c(t,e)),r(a),o()},e=>{i(e),o()})}})}async function lu(e,t,n,r){return Xc(n,Ll(e.base,4),await new Promise(cu.bind(e,t,n,r)))}async function uu(e,t,n,r){let i=[];for(let n=0,a=r.v.length;n<a;n++)i[n]=await pu(e,t,r.v[n]);return el(n,i,r.t,r.d)}async function du(e,t,n,r){if(Array.isArray(r))return Yl(e,t,n,r);if(Tl(r))return lu(e,t,n,r);if(gl(r))return uu(e,t,n,r);let i=r.constructor;if(i!==void 0&&typeof i!=`function`){let e=Object.getPrototypeOf(r);i=e===null?void 0:e.constructor}if(i===tl)return pu(e,t,r.replacement);let a=await ou(e,t,n,r);if(a)return a;switch(i){case Object:return Zl(e,t,n,r,!1);case void 0:return Zl(e,t,n,r,!0);case Date:return Nc(n,r);case Error:case EvalError:case RangeError:case ReferenceError:case SyntaxError:case TypeError:case URIError:return nu(e,t,n,r);case Number:case Boolean:case String:case BigInt:return Ql(e,t,n,r);case ArrayBuffer:return Gl(e.base,n,r);case Int8Array:case Int16Array:case Int32Array:case Uint8Array:case Uint16Array:case Uint32Array:case Uint8ClampedArray:case Float32Array:case Float64Array:return $l(e,t,n,r);case DataView:return tu(e,t,n,r);case Map:return iu(e,t,n,r);case Set:return au(e,t,n,r)}if(i===Promise||r instanceof Promise)return su(e,t,n,r);let o=e.base.features;if(o&32&&i===RegExp)return Fc(n,r);if(o&16)switch(i){case BigInt64Array:case BigUint64Array:return eu(e,t,n,r)}if(o&1&&typeof AggregateError<`u`&&(i===AggregateError||r instanceof AggregateError))return ru(e,t,n,r);if(o&64&&typeof Temporal<`u`)switch(i){case Temporal.Instant:return Pc(n,0,r);case Temporal.Duration:return Pc(n,1,r);case Temporal.PlainDate:return Pc(n,2,r);case Temporal.PlainDateTime:return Pc(n,3,r);case Temporal.PlainMonthDay:return Pc(n,4,r);case Temporal.PlainTime:return Pc(n,5,r);case Temporal.PlainYearMonth:return Pc(n,6,r);case Temporal.ZonedDateTime:return Pc(n,7,r)}if(r instanceof Error)return nu(e,t,n,r);if(xs in r||vs in r)return Zl(e,t,n,r,!!i);throw new sc(r)}async function fu(e,t,n){let r=Fl(e.base,n);if(r.type!==0)return r.value;let i=await ou(e,t,r.value,n);if(i)return i;throw new sc(n)}async function pu(e,t,n){if(t>=e.base.depthLimit)throw new hc(e.base.depthLimit);switch(typeof n){case`boolean`:return n?Bs:Vs;case`undefined`:return Hs;case`string`:return Ac(n);case`number`:return kc(n);case`bigint`:return jc(n);case`object`:if(n){let r=Fl(e.base,n);return r.type===0?await du(e,t+1,r.value,n):r.value}return Us;case`symbol`:return Il(e.base,n);case`function`:return fu(e,t,n);default:throw new sc(n)}}async function mu(e,t){try{return await pu(e,0,t)}catch(e){throw e instanceof ic?e:new ic(e)}}function hu(e){return e}function gu(e,t){for(let n=0,r=t.length;n<r;n++){let r=t[n];e.has(r)||(e.add(r),r.extends&&gu(e,r.extends))}}function _u(e){if(e){let t=new Set;return gu(t,e),[...t]}}function vu(e){switch(e){case`Int8Array`:return Int8Array;case`Int16Array`:return Int16Array;case`Int32Array`:return Int32Array;case`Uint8Array`:return Uint8Array;case`Uint16Array`:return Uint16Array;case`Uint32Array`:return Uint32Array;case`Uint8ClampedArray`:return Uint8ClampedArray;case`Float32Array`:return Float32Array;case`Float64Array`:return Float64Array;case`BigInt64Array`:return BigInt64Array;case`BigUint64Array`:return BigUint64Array;default:throw new pc(e)}}function yu(e){switch(e){case`constructor`:case`__proto__`:case`prototype`:case`__defineGetter__`:case`__defineSetter__`:case`__lookupGetter__`:case`__lookupSetter__`:return!1;default:return!0}}function bu(e){switch(e){case vs:case bs:case ks:case xs:return!0;default:return!1}}var xu=1e6,Su=512,Cu=1e4,wu=2e4;function Tu(e,t){switch(t){case 3:return Object.freeze(e);case 1:return Object.preventExtensions(e);case 2:return Object.seal(e);default:return e}}var Eu=1e3;function Du(e,t){let n=t.maxBase64Length??xu;if(!Number.isSafeInteger(n)||n<0)throw RangeError(`maxBase64Length must be a non-negative safe integer`);let r=t.refs||new Map;return`types`in r||Object.assign(r,{types:new Map}),{mode:e,plugins:t.plugins,refs:r,features:t.features??127^(t.disabledFeatures||0),depthLimit:t.depthLimit||Eu,maxBase64Length:n}}function Ou(e){return{mode:1,base:Du(1,e),child:void 0,state:{marked:new Set(e.markedRefs)}}}var ku=class{constructor(e,t){this._p=e,this.depth=t}deserialize(e){return _d(this._p,this.depth,e)}};function Au(e,t){if(t<0||!Number.isFinite(t)||!Number.isInteger(t))throw new mc({t:4,i:t});if(e.refs.has(t))throw Error(`Conflicted ref id: `+t)}function ju(e){return!!e&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Mu(e,t,n){return Au(e.base,t),e.state.marked.has(t)&&e.base.refs.set(t,n),n}function Nu(e,t,n){return Au(e.base,t),e.base.refs.set(t,n),n}function Pu(e,t,n){return e.mode===1?Mu(e,t,n):Nu(e,t,n)}function Fu(e,t,n){if(Object.hasOwn(t,n))return t[n];throw new mc(e)}function Iu(e,t){return Pu(e,t.i,wc($s(t.s)))}function Lu(e,t){if(!Array.isArray(t))throw new mc(e)}function Ru(e,t,n){let r=n.a;Lu(n,r);let i=r.length,a=Pu(e,n.i,Array(i));for(let n=0,o;n<i;n++)o=r[n],o&&(a[n]=_d(e,t,o));return Tu(a,n.o),a}function zu(e,t,n){yu(t)?e[t]=n:Object.defineProperty(e,t,{value:n,configurable:!0,enumerable:!0,writable:!0})}function Bu(e,t,n,r,i){if(typeof r==`string`)zu(n,$s(r),_d(e,t,i));else{let a=_d(e,t,r);switch(typeof a){case`string`:zu(n,a,_d(e,t,i));break;case`symbol`:bu(a)&&(n[a]=_d(e,t,i));break;default:throw new mc(r)}}}function Vu(e,t,n){e.base.refs.types.set(t,n)}function Hu(e,t,n,r){if(e.base.refs.types.get(n)!==r)throw new mc(t)}function Uu(e,t,n,r){let i=n.k;if(Lu(n,i),Lu(n,n.v),i.length>0)for(let a=0,o=n.v,s=i.length;a<s;a++)Bu(e,t,r,i[a],o[a]);return r}function Wu(e,t,n){let r=Pu(e,n.i,n.t===10?{}:Object.create(null));return Uu(e,t,n.p,r),Tu(r,n.o),r}function Gu(e,t){return Pu(e,t.i,new Date(t.s))}function Ku(e,t){if(!(e.base.features&64))throw new cc(t);let n;switch(t.c){case 0:n=Temporal.Instant.from(t.s);break;case 1:n=Temporal.Duration.from(t.s);break;case 2:n=Temporal.PlainDate.from(t.s);break;case 3:n=Temporal.PlainDateTime.from(t.s);break;case 4:n=Temporal.PlainMonthDay.from(t.s);break;case 5:n=Temporal.PlainTime.from(t.s);break;case 6:n=Temporal.PlainYearMonth.from(t.s);break;case 7:n=Temporal.ZonedDateTime.from(t.s);break;default:throw new mc(t)}return Pu(e,t.i,n)}function qu(e,t){if(e.base.features&32){let n=$s(t.c);if(n.length>wu)throw new mc(t);return Pu(e,t.i,new RegExp(n,t.m))}throw new cc(t)}function Ju(e,t,n){let r=Pu(e,n.i,new Set);Lu(n,n.a);for(let i=0,a=n.a,o=a.length;i<o;i++)r.add(_d(e,t,a[i]));return r}function Yu(e,t,n){let r=Pu(e,n.i,new Map);Lu(n,n.e.k),Lu(n,n.e.v);for(let i=0,a=n.e.k,o=n.e.v,s=a.length;i<s;i++)r.set(_d(e,t,a[i]),_d(e,t,o[i]));return r}function Xu(e,t){if(typeof t.s!=`string`)throw new mc(t);if(t.s.length>e.base.maxBase64Length)throw RangeError(`ArrayBuffer exceeds maxBase64Length (`+e.base.maxBase64Length+`)`);let n=$s(t.s),r;if(n.length<Su||typeof Buffer>`u`)r=pl(n);else{let e=atob(n);r=new ArrayBuffer(e.length),Buffer.from(r).write(e,`latin1`)}return Pu(e,t.i,r)}function Zu(e,t,n){let r=vu(n.c),i=_d(e,t,n.f);if(!(i instanceof ArrayBuffer))throw new mc(n);let a=n.b??0;if(a<0||a>i.byteLength)throw new mc(n);return Pu(e,n.i,new r(i,a,n.l))}function Qu(e,t,n){let r=_d(e,t,n.f);if(!(r instanceof ArrayBuffer))throw new mc(n);let i=n.b??0;if(i<0||i>r.byteLength)throw new mc(n);return Pu(e,n.i,new DataView(r,i,n.l))}function $u(e,t,n,r){if(n.p){let i=Uu(e,t,n.p,{});Object.defineProperties(r,Object.getOwnPropertyDescriptors(i))}return r}function ed(e,t,n){return $u(e,t,n,Pu(e,n.i,AggregateError([],$s(n.m))))}function td(e,t,n){let r=Fu(n,Ls,n.s);return $u(e,t,n,Pu(e,n.i,new r($s(n.m))))}function nd(e,t,n){let r=nl(),i=Pu(e,n.i,r.p),a=_d(e,t,n.f);if(ju(a))throw new mc(n.f);return n.s?r.s(a):r.f(a),i}function rd(e,t,n){return Pu(e,n.i,Object(_d(e,t,n.f)))}function id(e,t,n){let r=e.base.plugins;if(r){let i=$s(n.c);for(let a=0,o=r.length;a<o;a++){let o=r[a];if(o.tag===i)return Pu(e,n.i,o.deserialize(n.s,new ku(e,t),{id:n.i}))}}throw new lc(n.c)}function ad(e,t){let n=Pu(e,t.i,Pu(e,t.s,nl()).p);return Vu(e,t.s,22),n}function od(e,t,n){let r=e.base.refs.get(n.i);if(r){Hu(e,n,n.i,22);let i=_d(e,t,n.a[1]);if(ju(i))throw new mc(n.a[1]);n.t===23?r.s(i):r.f(i)}else throw new uc(`Promise`)}function sd(e,t,n){_d(e,t,n.a[0]);let r=_d(e,t,n.a[1]);if(!gl(r))throw new mc(n.a[1]);return bl(r)}function cd(e,t,n){_d(e,t,n.a[0]);let r=_d(e,t,n.a[1]);if(!Tl(r))throw new mc(n.a[1]);return kl(r)}function ld(e,t,n){let r=Pu(e,n.i,El());Vu(e,n.i,31);let i=n.a;Lu(n,i);let a=i.length;if(a)for(let n=0;n<a;n++)_d(e,t,i[n]);return r}function ud(e,t,n){let r=e.base.refs.get(n.i);if(r)Hu(e,n,n.i,31),r.next(_d(e,t,n.f));else throw new uc(`Stream`)}function dd(e,t,n){let r=e.base.refs.get(n.i);if(r)Hu(e,n,n.i,31),r.throw(_d(e,t,n.f));else throw new uc(`Stream`)}function fd(e,t,n){let r=e.base.refs.get(n.i);if(r)Hu(e,n,n.i,31),r.return(_d(e,t,n.f));else throw new uc(`Stream`)}function pd(e,t,n){_d(e,t,n.f)}function md(e,t,n){_d(e,t,n.a[1])}function hd(e,t){return Number.isInteger(e)&&e>=-1&&e<t}function gd(e,t,n){Lu(n,n.a);let r=n.a.length;if(!(hd(n.s,r)&&hd(n.l,r)))throw new mc(n);let i=Pu(e,n.i,_l([],n.s,n.l));for(let a=0;a<r;a++)i.v[a]=_d(e,t,n.a[a]);return i}function _d(e,t,n){if(t>e.base.depthLimit)throw new hc(e.base.depthLimit);switch(t+=1,n.t){case 2:return Fu(n,Fs,n.s);case 0:return Number(n.s);case 1:return $s(String(n.s));case 3:if(String(n.s).length>Cu)throw new mc(n);return BigInt(n.s);case 4:return e.base.refs.get(n.i);case 18:return Iu(e,n);case 9:return Ru(e,t,n);case 10:case 11:return Wu(e,t,n);case 5:return Gu(e,n);case 6:return qu(e,n);case 7:return Ju(e,t,n);case 8:return Yu(e,t,n);case 19:return Xu(e,n);case 16:case 15:return Zu(e,t,n);case 20:return Qu(e,t,n);case 14:return ed(e,t,n);case 13:return td(e,t,n);case 12:return nd(e,t,n);case 17:return Fu(n,Ns,n.s);case 21:return rd(e,t,n);case 25:return id(e,t,n);case 22:return ad(e,n);case 23:case 24:return od(e,t,n);case 28:return sd(e,t,n);case 30:return cd(e,t,n);case 31:return ld(e,t,n);case 32:return ud(e,t,n);case 33:return dd(e,t,n);case 34:return fd(e,t,n);case 27:return pd(e,t,n);case 29:return md(e,t,n);case 35:return gd(e,t,n);case 36:return Ku(e,n);default:throw new cc(n)}}function vd(e,t){try{return _d(e,0,t)}catch(e){throw new ac(e)}}var yd=(()=>T).toString(),bd=/=>/.test(yd);function xd(e,t){return bd?(e.length===1?e[0]:`(`+e.join(`,`)+`)`)+`=>`+(t.startsWith(`{`)?`(`+t+`)`:t):`function(`+e.join(`,`)+`){return `+t+`}`}function Sd(e,t){return bd?(e.length===1?e[0]:`(`+e.join(`,`)+`)`)+`=>{`+t+`}`:`function(`+e.join(`,`)+`){`+t+`}`}var Cd=`hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_`,wd=34,Td=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_`,Ed=64;function Dd(e){let t=e%wd,n=Cd[t];for(e=(e-t)/wd;e>0;)t=e%Ed,n+=Td[t],e=(e-t)/Ed;return n}var Od=/^[$A-Z_][0-9A-Z_$]*$/i;function kd(e){let t=e[0];return(t===`$`||t===`_`||t>=`A`&&t<=`Z`||t>=`a`&&t<=`z`)&&Od.test(e)}function Ad(e){switch(e.t){case 0:return e.s+`=`+e.v;case 2:return e.s+`.set(`+e.k+`,`+e.v+`)`;case 1:return e.s+`.add(`+e.v+`)`;case 3:return e.s+`.delete(`+e.k+`)`;case 4:return`Object.defineProperty(`+e.s+`,"__proto__",{value:`+e.k+`,configurable:!0,enumerable:!0,writable:!0})`}}function jd(e){let t=[],n=e[0];for(let r=1,i=e.length,a,o=n;r<i;r++)a=e[r],a.t===0&&a.v===o.v?n={t:0,s:a.s,k:void 0,v:Ad(n)}:a.t===2&&a.s===o.s?n={t:2,s:Ad(n),k:a.k,v:a.v}:a.t===1&&a.s===o.s?n={t:1,s:Ad(n),k:void 0,v:a.v}:a.t===3&&a.s===o.s?n={t:3,s:Ad(n),k:a.k,v:void 0}:(t.push(n),n=a),o=a;return t.push(n),t}function Md(e){if(e.length){let t=``,n=jd(e);for(let e=0,r=n.length;e<r;e++)t+=Ad(n[e])+`,`;return t}}var Nd=`Object.create(null)`,Pd=`new Set`,Fd=`new Map`,Id=`Promise.resolve`,Ld=`Promise.reject`,Rd={3:`Object.freeze`,2:`Object.seal`,1:`Object.preventExtensions`,0:void 0};function zd(e,t){return{mode:e,plugins:t.plugins,features:t.features,marked:new Set(t.markedRefs),stack:[],flags:[],assignments:[]}}function Bd(e){return{mode:2,base:zd(2,e),state:e,child:void 0}}var Vd=class{constructor(e){this._p=e}serialize(e){return Vf(this._p,e)}};function Hd(e,t){let n=e.valid.get(t);n??(n=e.valid.size,e.valid.set(t,n));let r=e.vars[n];return r??(r=Dd(n),e.vars[n]=r),r}function Ud(e){return`$R[`+e+`]`}function Wd(e,t){return e.mode===1?Hd(e.state,t):Ud(t)}function Gd(e,t){e.marked.add(t)}function Kd(e,t){return e.marked.has(t)}function qd(e,t,n){t!==0&&(Gd(e.base,n),e.base.flags.push({type:t,value:Wd(e,n)}))}function Jd(e){let t=``;for(let n=0,r=e.flags,i=r.length;n<i;n++){let e=r[n];t+=Rd[e.type]+`(`+e.value+`),`}return t}function Yd(e){let t=Md(e.assignments),n=Jd(e);return t?n?t+n:t:n}function Xd(e,t,n){e.assignments.push({t:0,s:t,k:void 0,v:n})}function Zd(e,t,n){e.base.assignments.push({t:1,s:Wd(e,t),k:void 0,v:n})}function Qd(e,t,n,r){e.base.assignments.push({t:2,s:Wd(e,t),k:n,v:r})}function $d(e,t,n){e.base.assignments.push({t:3,s:Wd(e,t),k:n,v:void 0})}function ef(e,t,n,r){Xd(e.base,Wd(e,t)+`[`+n+`]`,r)}function tf(e,t,n,r){yu(n)?Xd(e.base,Wd(e,t)+`.`+n,r):e.base.assignments.push({t:4,s:Wd(e,t),k:r,v:void 0})}function nf(e,t,n,r){Xd(e.base,Wd(e,t)+`.v[`+n+`]`,r)}function rf(e,t){return t.t===4&&e.stack.includes(t.i)}function af(e,t,n){return e.mode===1&&!Kd(e.base,t)?n:Wd(e,t)+`=`+n}function of(e){return`__SEROVAL_REFS__.get("`+e.s+`")`}function sf(e,t,n,r){return n?rf(e.base,n)?(Gd(e.base,t),ef(e,t,r,Wd(e,n.i)),``):Vf(e,n):``}function cf(e,t){let n=t.i,r=t.a,i=r.length;if(i>0){e.base.stack.push(n);let a=sf(e,n,r[0],0),o=a===``;for(let t=1,s;t<i;t++)s=sf(e,n,r[t],t),a+=`,`+s,o=s===``;return e.base.stack.pop(),qd(e,t.o,t.i),`[`+a+(o?`,]`:`]`)}return`[]`}function lf(e,t,n,r){if(typeof n==`string`){let i=Number(n),a=i>=0&&i.toString()===n||kd(n);if(rf(e.base,r)){let o=Wd(e,r.i);return Gd(e.base,t.i),a&&i!==i?tf(e,t.i,n,o):ef(e,t.i,a?n:`"`+n+`"`,o),``}return yu(n)?(a?n:`"`+n+`"`)+`:`+Vf(e,r):`["`+n+`"]:`+Vf(e,r)}return`[`+Vf(e,n)+`]:`+Vf(e,r)}function uf(e,t,n){let r=n.k,i=r.length;if(i>0){let a=n.v;e.base.stack.push(t.i);let o=lf(e,t,r[0],a[0]);for(let n=1,s=o;n<i;n++)s=lf(e,t,r[n],a[n]),o+=(s&&o&&`,`)+s;return e.base.stack.pop(),`{`+o+`}`}return`{}`}function df(e,t){return qd(e,t.o,t.i),uf(e,t,t.p)}function ff(e,t,n,r){let i=uf(e,t,n);return i===`{}`?r:`Object.assign(`+r+`,`+i+`)`}function ree(e,t,n,r,i){let a=e.base,o=Vf(e,i),s=Number(r),c=s>=0&&s.toString()===r||kd(r);if(rf(a,i))c&&s!==s?tf(e,t.i,r,o):ef(e,t.i,c?r:`"`+r+`"`,o);else{let i=a.assignments;a.assignments=n,c&&s!==s?tf(e,t.i,r,o):ef(e,t.i,c?r:`"`+r+`"`,o),a.assignments=i}}function iee(e,t,n,r,i){if(typeof r==`string`)ree(e,t,n,r,i);else{let a=e.base,o=a.stack;a.stack=[];let s=Vf(e,i);a.stack=o;let c=a.assignments;a.assignments=n,ef(e,t.i,Vf(e,r),s),a.assignments=c}}function aee(e,t,n){let r=n.k,i=r.length;if(i>0){let a=[],o=n.v;e.base.stack.push(t.i);for(let n=0;n<i;n++)iee(e,t,a,r[n],o[n]);return e.base.stack.pop(),Md(a)}}function pf(e,t,n){if(t.p){let r=e.base;if(r.features&8)n=ff(e,t,t.p,n);else{Gd(r,t.i);let i=aee(e,t,t.p);if(i)return`(`+af(e,t.i,n)+`,`+i+Wd(e,t.i)+`)`}}return n}function oee(e,t){return qd(e,t.o,t.i),pf(e,t,Nd)}function see(e){return`new Date("`+e.s+`")`}var cee={0:`Temporal.Instant`,1:`Temporal.Duration`,2:`Temporal.PlainDate`,3:`Temporal.PlainDateTime`,4:`Temporal.PlainMonthDay`,5:`Temporal.PlainTime`,6:`Temporal.PlainYearMonth`,7:`Temporal.ZonedDateTime`};function lee(e,t){if(e.base.features&64)return cee[t.c]+`.from("`+t.s+`")`;throw new cc(t)}function uee(e,t){if(e.base.features&32)return`/`+$s(t.c)+`/`+t.m;throw new cc(t)}function mf(e,t,n){let r=e.base;return rf(r,n)?(Gd(r,t),Zd(e,t,Wd(e,n.i)),``):Vf(e,n)}function hf(e,t){let n=Pd,r=t.a,i=r.length,a=t.i;if(i>0){e.base.stack.push(a);let t=mf(e,a,r[0]);for(let n=1,o=t;n<i;n++)o=mf(e,a,r[n]),t+=(o&&t&&`,`)+o;e.base.stack.pop(),t&&(n+=`([`+t+`])`)}return n}function gf(e,t,n,r,i){let a=e.base;if(rf(a,n)){let o=Wd(e,n.i);if(Gd(a,t),rf(a,r))return Qd(e,t,o,Wd(e,r.i)),``;if(r.t!==4&&r.i!=null&&Kd(a,r.i)){let n=`(`+Vf(e,r)+`,[`+i+`,`+i+`])`;return Qd(e,t,o,Wd(e,r.i)),$d(e,t,i),n}let s=a.stack;return a.stack=[],Qd(e,t,o,Vf(e,r)),a.stack=s,``}if(rf(a,r)){let o=Wd(e,r.i);if(Gd(a,t),n.t!==4&&n.i!=null&&Kd(a,n.i)){let r=`(`+Vf(e,n)+`,[`+i+`,`+i+`])`;return Qd(e,t,Wd(e,n.i),o),$d(e,t,i),r}let s=a.stack;return a.stack=[],Qd(e,t,Vf(e,n),o),a.stack=s,``}return`[`+Vf(e,n)+`,`+Vf(e,r)+`]`}function _f(e,t){let n=Fd,r=t.e.k,i=r.length,a=t.i,o=t.f,s=Wd(e,o.i),c=e.base;if(i>0){let o=t.e.v;c.stack.push(a);let l=gf(e,a,r[0],o[0],s);for(let t=1,n=l;t<i;t++)n=gf(e,a,r[t],o[t],s),l+=(n&&l&&`,`)+n;c.stack.pop(),l&&(n+=`([`+l+`])`)}return o.t===26&&(Gd(c,o.i),n=`(`+Vf(e,o)+`,`+n+`)`),n}function vf(e,t){return Tf(e,t.f)+`("`+t.s+`")`}function yf(e,t){return`new `+t.c+`(`+Vf(e,t.f)+`,`+t.b+`,`+t.l+`)`}function bf(e,t){return`new DataView(`+Vf(e,t.f)+`,`+t.b+`,`+t.l+`)`}function xf(e,t){let n=t.i;e.base.stack.push(n);let r=pf(e,t,`new AggregateError([],"`+t.m+`")`);return e.base.stack.pop(),r}function Sf(e,t){return pf(e,t,`new `+Is[t.s]+`("`+t.m+`")`)}function Cf(e,t){let n,r=t.f,i=t.i,a=t.s?Id:Ld,o=e.base;if(rf(o,r)){let i=Wd(e,r.i);n=a+(t.s?`().then(`+xd([],i)+`)`:`().catch(`+Sd([],`throw `+i)+`)`)}else{o.stack.push(i);let t=Vf(e,r);o.stack.pop(),n=a+`(`+t+`)`}return n}function wf(e,t){return`Object(`+Vf(e,t.f)+`)`}function Tf(e,t){let n=Vf(e,t);return t.t===4?n:`(`+n+`)`}function Ef(e,t){if(e.mode===1)throw new cc(t);return`(`+af(e,t.s,Tf(e,t.f)+`()`)+`).p`}function Df(e,t){if(e.mode===1)throw new cc(t);return Tf(e,t.a[0])+`(`+Wd(e,t.i)+`,`+Vf(e,t.a[1])+`)`}function Of(e,t){if(e.mode===1)throw new cc(t);return Tf(e,t.a[0])+`(`+Wd(e,t.i)+`,`+Vf(e,t.a[1])+`)`}function kf(e,t){let n=e.base.plugins;if(n)for(let r=0,i=n.length;r<i;r++){let i=n[r];if(i.tag===t.c)return e.child??=new Vd(e),i.serialize(t.s,e.child,{id:t.i})}throw new lc(t.c)}function Af(e,t){let n=``,r=!1;return t.f.t!==4&&(Gd(e.base,t.f.i),n=`(`+Vf(e,t.f)+`,`,r=!0),n+=af(e,t.i,`(`+ul+`)(`+Wd(e,t.f.i)+`)`),r&&(n+=`)`),n}function jf(e,t){return Tf(e,t.a[0])+`(`+Vf(e,t.a[1])+`)`}function Mf(e,t){let n=t.a[0],r=t.a[1],i=e.base,a=``;n.t!==4&&(Gd(i,n.i),a+=`(`+Vf(e,n)),r.t!==4&&(Gd(i,r.i),a+=(a?`,`:`(`)+Vf(e,r)),a&&(a+=`,`);let o=af(e,t.i,`(`+fl+`)(`+Wd(e,r.i)+`,`+Wd(e,n.i)+`)`);return a?a+o+`)`:o}function Nf(e,t){return Tf(e,t.a[0])+`(`+Vf(e,t.a[1])+`)`}function Pf(e,t){let n=af(e,t.i,Tf(e,t.f)+`()`),r=t.a.length;if(r){let i=Vf(e,t.a[0]);for(let n=1;n<r;n++)i+=`,`+Vf(e,t.a[n]);return`(`+n+`,`+i+`,`+Wd(e,t.i)+`)`}return n}function Ff(e,t){return Wd(e,t.i)+`.next(`+Vf(e,t.f)+`)`}function If(e,t){return Wd(e,t.i)+`.throw(`+Vf(e,t.f)+`)`}function Lf(e,t){return Wd(e,t.i)+`.return(`+Vf(e,t.f)+`)`}function Rf(e,t,n,r){let i=e.base;return rf(i,r)?(Gd(i,t),nf(e,t,n,Wd(e,r.i)),``):Vf(e,r)}function zf(e,t){let n=t.a,r=n.length,i=t.i;if(r>0){e.base.stack.push(i);let a=Rf(e,i,0,n[0]);for(let t=1,o=a;t<r;t++)o=Rf(e,i,t,n[t]),a+=(o&&a&&`,`)+o;if(e.base.stack.pop(),a)return`{__SEROVAL_SEQUENCE__:!0,v:[`+a+`],t:`+t.s+`,d:`+t.l+`}`}return`{__SEROVAL_SEQUENCE__:!0,v:[],t:-1,d:0}`}function Bf(e,t){switch(t.t){case 17:return js[t.s];case 18:return of(t);case 9:return cf(e,t);case 10:return df(e,t);case 11:return oee(e,t);case 5:return see(t);case 6:return uee(e,t);case 7:return hf(e,t);case 8:return _f(e,t);case 19:return vf(e,t);case 16:case 15:return yf(e,t);case 20:return bf(e,t);case 14:return xf(e,t);case 13:return Sf(e,t);case 12:return Cf(e,t);case 21:return wf(e,t);case 22:return Ef(e,t);case 25:return kf(e,t);case 26:return nee[t.s];case 35:return zf(e,t);case 36:return lee(e,t);default:throw new cc(t)}}function Vf(e,t){switch(t.t){case 2:return Ps[t.s];case 0:return``+t.s;case 1:return`"`+t.s+`"`;case 3:return t.s+`n`;case 4:return Wd(e,t.i);case 23:return Df(e,t);case 24:return Of(e,t);case 27:return Af(e,t);case 28:return jf(e,t);case 29:return Mf(e,t);case 30:return Nf(e,t);case 31:return Pf(e,t);case 32:return Ff(e,t);case 33:return If(e,t);case 34:return Lf(e,t);default:return af(e,t.i,Bf(e,t))}}function Hf(e,t){let n=Vf(e,t),r=t.i;if(r==null)return n;let i=Yd(e.base),a=Wd(e,r),o=e.state.scopeId,s=o==null?``:`$R`,c=i?`(`+n+`,`+i+a+`)`:n;if(s===``)return t.t===10&&!i?`(`+c+`)`:c;let l=o==null?`()`:`($R["`+Zs(o)+`"])`;return`(`+xd([s],c)+`)`+l}var Uf=class{constructor(e,t){this._p=e,this.depth=t}parse(e){return gp(this._p,this.depth,e)}},Wf=class{constructor(e,t){this._p=e,this.depth=t}parse(e){return gp(this._p,this.depth,e)}parseWithError(e){return Cp(this._p,this.depth,e)}isAlive(){return this._p.state.alive}pushPendingState(){xp(this._p)}popPendingState(){Sp(this._p)}onParse(e){_p(this._p,e)}onError(e){vp(this._p,e)}addCleanup(e){this._p.state.cleanups.push(e)}};function Gf(e){return{alive:!0,pending:0,initial:!0,buffer:[],onParse:e.onParse,onError:e.onError,onDone:e.onDone,cleanups:[]}}function Kf(e){return{type:2,base:jl(2,e),state:Gf(e)}}function qf(e,t,n){let r=[];for(let i=0,a=n.length;i<a;i++)i in n?r[i]=gp(e,t,n[i]):r[i]=0;return r}function Jf(e,t,n,r){return zc(n,r,qf(e,t,r))}function Yf(e,t,n){let r=Object.entries(n),i=[],a=[];for(let n=0,o=r.length;n<o;n++)i.push(Zs(r[n][0])),a.push(gp(e,t,r[n][1]));return xs in n&&(i.push(Il(e.base,xs)),a.push(Jc(Rl(e.base),gp(e,t,vl(n))))),vs in n&&(i.push(Il(e.base,vs)),a.push(Yc(zl(e.base),gp(e,t,e.type===1?El():Dl(n,e.state.cleanups))))),ks in n&&(i.push(Il(e.base,ks)),a.push(Ac(n[ks]))),bs in n&&(i.push(Il(e.base,bs)),a.push(n[bs]?Bs:Vs)),{k:i,v:a}}function Xf(e,t,n,r,i){return Bl(n,r,i,Yf(e,t,r))}function Zf(e,t,n,r){return Bc(n,gp(e,t,r.valueOf()))}function Qf(e,t,n,r){return r=Ul(e.base,r),Hc(n,r,gp(e,t,r.buffer))}function $f(e,t,n,r){return r=Ul(e.base,r),Uc(n,r,gp(e,t,r.buffer))}function ep(e,t,n,r){return r=Ul(e.base,r),Wc(n,r,gp(e,t,r.buffer))}function tp(e,t,n,r){let i=Dc(r,e.base.features);return Gc(n,r,i?Yf(e,t,i):void 0)}function np(e,t,n,r){let i=Dc(r,e.base.features);return Kc(n,r,i?Yf(e,t,i):void 0)}function rp(e,t,n,r){let i=[],a=[];for(let[n,o]of r.entries())i.push(gp(e,t,n)),a.push(gp(e,t,o));return Vl(e.base,n,i,a)}function ip(e,t,n,r){let i=[];for(let n of r.keys())i.push(gp(e,t,n));return qc(n,i)}function ap(e,t,n,r){let i=Xc(n,Ll(e.base,4),[]);return e.type===1||(xp(e),r.on({next:r=>{if(e.state.alive){let i=Cp(e,t,r);i&&_p(e,Zc(n,i))}},throw:r=>{if(e.state.alive){let i=Cp(e,t,r);i&&_p(e,Qc(n,i))}Sp(e)},return:r=>{if(e.state.alive){let i=Cp(e,t,r);i&&_p(e,$c(n,i))}Sp(e)}})),i}function op(e,t,n){if(this.state.alive){let r=Cp(this,t,n);r&&_p(this,Rs(23,e,void 0,void 0,void 0,void 0,void 0,[Ll(this.base,2),r],void 0,void 0,void 0,void 0)),Sp(this)}}function sp(e,t,n){if(this.state.alive){let r=Cp(this,t,n);r&&_p(this,Rs(24,e,void 0,void 0,void 0,void 0,void 0,[Ll(this.base,3),r],void 0,void 0,void 0,void 0))}Sp(this)}function cp(e,t,n,r){let i=Nl(e.base,{});return e.type===2&&(xp(e),r.then(op.bind(e,i,t),sp.bind(e,i,t))),Hl(e.base,n,i)}function lp(e,t,n,r,i){for(let a=0,o=i.length;a<o;a++){let o=i[a];if(o.parse.sync&&o.test(r))return Rc(n,o.tag,o.parse.sync(r,new Uf(e,t),{id:n}))}}function up(e,t,n,r,i){for(let a=0,o=i.length;a<o;a++){let o=i[a];if(o.parse.stream&&o.test(r))return Rc(n,o.tag,o.parse.stream(r,new Wf(e,t),{id:n}))}}function dp(e,t,n,r){let i=e.base.plugins;if(i)return e.type===1?lp(e,t,n,r,i):up(e,t,n,r,i)}function fp(e,t,n,r){let i=[];for(let n=0,a=r.v.length;n<a;n++)i[n]=gp(e,t,r.v[n]);return el(n,i,r.t,r.d)}function pp(e,t,n,r,i){switch(i){case Object:return Xf(e,t,n,r,!1);case void 0:return Xf(e,t,n,r,!0);case Date:return Nc(n,r);case Error:case EvalError:case RangeError:case ReferenceError:case SyntaxError:case TypeError:case URIError:return tp(e,t,n,r);case Number:case Boolean:case String:case BigInt:return Zf(e,t,n,r);case ArrayBuffer:return Gl(e.base,n,r);case Int8Array:case Int16Array:case Int32Array:case Uint8Array:case Uint16Array:case Uint32Array:case Uint8ClampedArray:case Float32Array:case Float64Array:return Qf(e,t,n,r);case DataView:return ep(e,t,n,r);case Map:return rp(e,t,n,r);case Set:return ip(e,t,n,r)}if(i===Promise||r instanceof Promise)return cp(e,t,n,r);let a=e.base.features;if(a&32&&i===RegExp)return Fc(n,r);if(a&16)switch(i){case BigInt64Array:case BigUint64Array:return $f(e,t,n,r)}if(a&1&&typeof AggregateError<`u`&&(i===AggregateError||r instanceof AggregateError))return np(e,t,n,r);if(a&64&&typeof Temporal<`u`)switch(i){case Temporal.Instant:return Pc(n,0,r);case Temporal.Duration:return Pc(n,1,r);case Temporal.PlainDate:return Pc(n,2,r);case Temporal.PlainDateTime:return Pc(n,3,r);case Temporal.PlainMonthDay:return Pc(n,4,r);case Temporal.PlainTime:return Pc(n,5,r);case Temporal.PlainYearMonth:return Pc(n,6,r);case Temporal.ZonedDateTime:return Pc(n,7,r)}if(r instanceof Error)return tp(e,t,n,r);if(xs in r||vs in r)return Xf(e,t,n,r,!!i);throw new sc(r)}function mp(e,t,n,r){if(Array.isArray(r))return Jf(e,t,n,r);if(Tl(r))return ap(e,t,n,r);if(gl(r))return fp(e,t,n,r);let i=r.constructor;if(i!==void 0&&typeof i!=`function`){let e=Object.getPrototypeOf(r);i=e===null?void 0:e.constructor}return i===tl?gp(e,t,r.replacement):dp(e,t,n,r)||pp(e,t,n,r,i)}function hp(e,t,n){let r=Fl(e.base,n);if(r.type!==0)return r.value;let i=dp(e,t,r.value,n);if(i)return i;throw new sc(n)}function gp(e,t,n){if(t>=e.base.depthLimit)throw new hc(e.base.depthLimit);switch(typeof n){case`boolean`:return n?Bs:Vs;case`undefined`:return Hs;case`string`:return Ac(n);case`number`:return kc(n);case`bigint`:return jc(n);case`object`:if(n){let r=Fl(e.base,n);return r.type===0?mp(e,t+1,r.value,n):r.value}return Us;case`symbol`:return Il(e.base,n);case`function`:return hp(e,t,n);default:throw new sc(n)}}function _p(e,t){e.state.initial?e.state.buffer.push(t):bp(e,t,!1)}function vp(e,t){if(e.state.onError)e.state.onError(t);else throw t instanceof ic?t:new ic(t)}function yp(e){e.state.onDone&&e.state.onDone();for(let t=0,n=e.state.cleanups.length;t<n;t++)e.state.cleanups[t]()}function bp(e,t,n){try{e.state.onParse(t,n)}catch(t){vp(e,t)}}function xp(e){e.state.pending++}function Sp(e){--e.state.pending<=0&&yp(e)}function Cp(e,t,n){try{return gp(e,t,n)}catch(t){vp(e,t);return}}function wp(e,t){let n=Cp(e,0,t);n&&(bp(e,n,!0),e.state.initial=!1,Tp(e,e.state),e.state.pending<=0&&Ep(e))}function Tp(e,t){for(let n=0,r=t.buffer.length;n<r;n++)bp(e,t.buffer[n],!1)}function Ep(e){e.state.alive&&(yp(e),e.state.alive=!1)}async function Dp(e,t={}){let n=_u(t.plugins);return await mu(Kl(2,{compactArrayBufferViews:t.compactArrayBufferViews,plugins:n,disabledFeatures:t.disabledFeatures,refs:t.refs}),e)}function Op(e,t){let n=_u(t.plugins),r=Kf({compactArrayBufferViews:t.compactArrayBufferViews,plugins:n,refs:t.refs,disabledFeatures:t.disabledFeatures,onParse(e,i){let a=Bd({plugins:n,features:r.base.features,scopeId:t.scopeId,markedRefs:r.base.marked}),o;try{o=Hf(a,e)}catch(e){t.onError&&t.onError(e);return}t.onSerialize(o,i)},onError:t.onError,onDone:t.onDone});return wp(r,e),Ep.bind(null,r)}function kp(e,t){let n=_u(t.plugins),r=Kf({compactArrayBufferViews:t.compactArrayBufferViews,plugins:n,refs:t.refs,disabledFeatures:t.disabledFeatures,depthLimit:t.depthLimit,onParse:t.onParse,onError:t.onError,onDone:t.onDone});return wp(r,e),Ep.bind(null,r)}function Ap(e,t={}){let n=_u(t.plugins),r=t.disabledFeatures||0,i=e.f??127;return vd(Ou({maxBase64Length:t.maxBase64Length,plugins:n,markedRefs:e.m,features:i&~r,disabledFeatures:r}),e.t)}function jp(e){return hu({tag:`$TSR/t/`+e.key,test:e.test,parse:{sync(t,n){return{v:n.parse(e.toSerializable(t))}},async async(t,n){return{v:await n.parse(e.toSerializable(t))}},stream(t,n){return{v:n.parse(e.toSerializable(t))}}},serialize:void 0,deserialize(t,n){return e.fromSerializable(n.deserialize(t.v))}})}var Mp=class{constructor(e,t){this.stream=e,this.hint=t?.hint??`binary`}};n();function Np(e,t){let n=e[1];e.length=0,n?.(t)}var Pp=u();function Fp(){let e=a(),t=e.routesById[A];C(e,t);let n=(0,Pp.jsxs)(Pp.Fragment,{children:[!1,(0,Pp.jsx)(Ip,{})]});return e.options.InnerWrap?(0,Pp.jsx)(e.options.InnerWrap,{children:n}):n}function Ip(){let e=a(),t=e._rendered,n=e.stores.matches.get(),r=n[0],i=r?.routeId;j(()=>{t[0]===n&&Np(t,!0)},[t,n]);let o=i?(0,Pp.jsx)(E,{routeId:i}):null;return e.options.disableGlobalCatchBoundary?o:(0,Pp.jsx)(y,{getResetKey:()=>r,onCatch:void 0,children:o})}function Lp({router:e,children:t,...n}){i(n)&&e.update({...e.options,...n,context:{...e.options.context,...n.context}});let r=(0,Pp.jsx)(l.Provider,{value:e,children:t});return e.options.Wrap?(0,Pp.jsx)(e.options.Wrap,{children:r}):r}function Rp({router:e,...t}){return(0,Pp.jsx)(Lp,{router:e,...t,children:(0,Pp.jsx)(Fp,{})})}function zp(e){return(0,Pp.jsx)(Rp,{router:e.router})}var Bp=hu({tag:`$TSR/Error`,test(e){return e instanceof Error},parse:{sync(e,t){return{message:t.parse(e.message)}},async async(e,t){return{message:await t.parse(e.message)}},stream(e,t){return{message:t.parse(e.message)}}},serialize(e,t){return`new Error(`+t.serialize(e.message)+`)`},deserialize(e,t){return Error(t.deserialize(e.message))}});function Vp(e){let t=[];for(let n=0;n<e.length;n+=32768)t.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(t.join(``))}function Hp(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var Up=new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});function Wp(e){try{return`t`+Up.decode(e)}catch{return`b`+Vp(e)}}var Gp=new TextEncoder;function Kp(e){let t=e.slice(1);return e[0]===`t`?Gp.encode(t):Hp(t)}function qp(e,t,n){n?.throwIfAborted();let r=El(),i=e.getReader(),a=!0,o=()=>{a=!1,n?.removeEventListener(`abort`,c),i.releaseLock()},s=e=>a?(i.cancel(e).catch(()=>{}),o(),!0):!1,c=()=>{s(n.reason)&&r.throw(n.reason)};return n?.addEventListener(`abort`,c),(async()=>{try{for(;a;){let{done:e,value:n}=await i.read();if(!a)return;if(e){o(),r.return(void 0);return}r.next(t(n))}}catch(e){s(e)&&r.throw(e)}})(),[r,s]}function Jp(e,t){let n,r=!1;return new ReadableStream({start(i){let a=e.on({next(e){if(!r)try{i.enqueue(t(e))}catch(e){r=!0;let t=n;n=void 0,t?.(),i.error(e)}},throw(e){r||(r=!0,n=void 0,i.error(e))},return(){r||(r=!0,n=void 0,i.close())}});r?a():n=a},cancel(){let e=n;n=void 0,e?.()}})}function Yp(e){return hu({tag:`tss/RawStream`,test:e=>e instanceof Mp,parse:{async:async(t,n)=>{let r=await n.parse(t.hint===`text`),[i]=qp(t.stream,t.hint===`text`?Wp:Vp,e);return{text:r,stream:await n.parse(i)}}},serialize:void 0,deserialize:void 0})}var Xp=Yp(),Zp=hu({tag:`tss/RawStream`,test:()=>!1,parse:{},serialize:void 0,deserialize(e,t){return Jp(t.deserialize(e.stream),t.deserialize(e.text)?Kp:Hp)}}),Qp={},$p=e=>new ReadableStream({start(t){e.on({next(e){try{t.enqueue(e)}catch{}},throw(e){t.error(e)},return(){try{t.close()}catch{}}})}}),em=hu({tag:`seroval-plugins/web/ReadableStreamFactory`,test(e){return e===Qp},parse:{sync(){return Qp},async async(){return await Promise.resolve(Qp)},stream(){return Qp}},serialize(){return $p.toString()},deserialize(){return Qp}});async function tm(e,t){try{for(;;){let n=await t.read();if(n.done){e.return(n.value),t.releaseLock();break}e.next(n.value)}}catch(n){t.releaseLock(),e.throw(n)}}function nm(e){e.cancel().catch(()=>{}),e.releaseLock()}function rm(e){let t=El(),n=e.getReader(),r=nm.bind(null,n);return tm(t,n).catch(r),[t,r]}var im=hu({tag:`seroval/plugins/web/ReadableStream`,extends:[em],test(e){return typeof ReadableStream>`u`?!1:e instanceof ReadableStream},parse:{sync(e,t){return{factory:t.parse(Qp),stream:t.parse(El())}},async async(e,t){return{factory:await t.parse(Qp),stream:await t.parse(rm(e)[0])}},stream(e,t){let[n,r]=rm(e);return t.addCleanup(r),{factory:t.parse(Qp),stream:t.parse(n)}}},serialize(e,t){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize(e,t){let n=t.deserialize(e.stream);if(!n||typeof n!=`object`||!Tl(n))throw Error(`Expected a stream source.`);return $p(n)}});function am(e){return[Bp,e?Yp(e):Xp,im]}var om=[Zp,...am()];function sm(e){let t=1;return hu({tag:`tss/RawStream`,test(e){return e instanceof Mp},parse:{stream(n,r){let i=t++;return e(i,n.stream),{streamId:r.parse(i)}}},serialize:void 0,deserialize:void 0})}var cm=`$_TSR`;function lm(e,t){return hu({tag:`$TSR/t/`+e.key,test:e.test,parse:{stream(t,n){return{v:n.parse(e.toSerializable(t))}}},serialize(n,r){return t&&(t.didRun=!0),cm+`.t.get("`+e.key+`")(`+r.serialize(n.v)+`)`},deserialize:void 0})}var um=`self.$_TSR={h(){this.hydrated=!0,this.c()},e(){this.streamEnded=!0,this.c()},c(){this.hydrated&&this.streamEnded&&(delete self.$_TSR,delete self.$R.tsr)},p(e){this.initialized?e():this.buffer.push(e)},buffer:[]}`,dm=new TextEncoder,fm=`</body></html>`,pm=`<\/script>`,mm=fm.indexOf(`y`),hm=pm.indexOf(`p`),gm=dm.encode(fm),_m=dm.encode(pm);function vm(e,t,n,r=0){return dm.encodeInto(t===0?e:e.slice(t),r===0?n:n.subarray(r))}function ym(e,t,n=0,r=!1){let{pattern:i,anchorIndex:a}=e,o=e.matched,s,c=n;for(;c<t.length;){if(o===0){if(a>0&&c<t.length-a){let e=t.indexOf(i[a],c+a);if(e<0){c=t.length-a;continue}c=e-a}else if(c=t.indexOf(i[0],c),c<0)return e.matched=o,s}let n=t[c];if(n===i[o]?o++:o=+(n===i[0]),c++,o===i.length){if(o=0,!r)return e.matched=o,c;s=c}}return e.matched=o,s}function bm(e,t,n=0,r=0){let i=e.indexOf(t[r],n+r);for(;i>=0;){let n=i-r;if(n+t.length>e.length)return-1;let a=0;for(;a<t.length&&e[n+a]===t[a];)a++;if(a===t.length)return n;i=e.indexOf(t[r],i+1)}return-1}function xm(e,t,n=0){candidate:for(let r=Math.min(t.length-1,e.length-n);r>0;r--){let n=e.length-r;for(let i=0;i<r;i++)if(e[n+i]!==t[i])continue candidate;return n}}var Sm=new TextEncoder,Cm=`;`,wm=16384,Tm=16777216,Em=4096,Dm=256,Om=16384,km=65536,Am=km,jm=`data-tsr-stream-part`,Mm=`{let s=document.currentScript,p;while((p=s.previousElementSibling)&&p.hasAttribute('${jm}'))p.remove();s.remove()}`,Nm=Cm+Mm,Pm=`document.currentScript.remove()<\/script>`,Fm=`document.currentScript.remove();/*$tsr-stream-boundary*/`,Im=`;/*$tsr-stream-boundary*/<\/script>`,Lm=Im.lastIndexOf(`*`),Rm=Sm.encode(Im),zm=cm+`.router=`,Bm=cm+`.p(()=>`,Vm=[vc(`tsr`),um],Hm={Waiting:0,Ready:1,Active:2,Done:3,Failed:4};function Um(e){return e.replace(/[&"'<>]/g,e=>`&#${e.charCodeAt(0)};`)}function Wm(e,t){let n=[];for(let r of e){if(!r)continue;let e=n[n.length-1];e?.children&&e.children.length+1+r.length<=wm?e.children+=Cm+r:n.push({tag:`script`,attrs:{nonce:t,[jm]:``},children:r})}let r=n[n.length-1];if(r){let e=r.children;e.length+Nm.length<=wm?r.children=e+Nm:n.push({tag:`script`,attrs:{nonce:t,[jm]:``},children:Mm})}return{before:n,boundary:{tag:`script`,attrs:{nonce:t},children:Fm}}}var Gm=class{constructor(e,t){this.nonce=e,this.queuedSources=[],this.queuedSourceHead=0,this.initialTaken=!1,this.barrierLifted=!1,this.producerDone=!1,this.retainedSources=0,this.regularCodeUnits=0,this.hasOversizedSource=!1,this.segmentIndex=0,this.closingSegmentIndex=0,this.source=``,this.sourceOffset=0,this.outputCapacity=Dm,this.outputState=Hm.Waiting,this.takeInitialHydrationScriptTags=this.takeInitialHydrationScriptTags.bind(this);let n=t??Vm;for(let e of n){if(!this.account(e))break;this.queuedSources.push(e)}}get state(){return this.outputState}get error(){return this.outputError}notify(){try{this.listener?.()}catch(e){console.error(`Hydration script output listener error:`,e)}}refresh(e=!0){let t=this.outputState===Hm.Failed?Hm.Failed:this.active?Hm.Active:typeof this.consumer==`object`&&this.initialTaken&&this.barrierLifted&&!this.queueIsEmpty()?Hm.Ready:this.producerDone&&this.initialTaken&&this.queueIsEmpty()?Hm.Done:Hm.Waiting;this.outputState!==t&&(this.outputState=t,e&&this.notify())}clearTimeoutIfSet(){this.timeout!==void 0&&(clearTimeout(this.timeout),this.timeout=void 0)}queueIsEmpty(){return this.queuedSourceHead===this.queuedSources.length}clearQueue(){this.queuedSources=[],this.queuedSourceHead=0}dropBufferedOutput(){this.clearQueue(),this.active=void 0,this.retainedSources=0,this.regularCodeUnits=0,this.hasOversizedSource=!1,this.segmentIndex=0,this.closingSegmentIndex=0,this.source=``,this.sourceOffset=0,this.outputCapacity=Dm,this.opening=void 0}fail(e){this.consumer!==`cleaned`&&this.outputState!==Hm.Failed&&(this.outputError=e,this.clearTimeoutIfSet(),this.dropBufferedOutput(),this.outputState=Hm.Failed,this.notify())}rejectBacklog(e){return this.fail(Error(`SSR hydration backlog exceeded maximum ${e} count`)),!1}account(e){if(this.retainedSources===Em)return this.rejectBacklog(`source-part`);if(e.length>Tm){if(this.hasOversizedSource)return this.rejectBacklog(`code-unit`);this.hasOversizedSource=!0}else if(this.regularCodeUnits+e.length>Tm)return this.rejectBacklog(`code-unit`);else this.regularCodeUnits+=e.length;return this.retainedSources++,!0}releaseSource(e){this.retainedSources--,e.length>Tm?this.hasOversizedSource=!1:this.regularCodeUnits-=e.length}releaseAccounting(e){for(let t of e)t!==void 0&&this.releaseSource(t)}liftBarrier(){this.consumer!==`cleaned`&&!this.barrierLifted&&(this.barrierLifted=!0,this.refresh())}producerCanWrite(){return this.consumer!==`cleaned`&&this.outputState!==Hm.Failed&&!this.producerDone}pushSource(e){if(!this.producerCanWrite())return!1;if(this.account(e))this.queuedSources.push(e),this.initialTaken&&this.refresh();else return!1;return this.producerCanWrite()}takeQueuedBatch(e){if(this.queuedSourceHead===0&&e===this.queuedSources.length){let e=this.queuedSources;return this.clearQueue(),e}let t=this.queuedSourceHead+e,n=this.queuedSources.slice(this.queuedSourceHead,t);for(let e=this.queuedSourceHead;e<t;e++)this.queuedSources[e]=void 0;return this.queuedSourceHead=t,this.queueIsEmpty()?this.clearQueue():this.queuedSourceHead>=1024&&this.queuedSourceHead>=this.queuedSources.length-this.queuedSourceHead&&(this.queuedSources=this.queuedSources.slice(this.queuedSourceHead),this.queuedSourceHead=0),n}release(e){this.releaseAccounting(e),this.active=void 0,this.source=``,this.sourceOffset=0,this.refresh(!1)}advanceSource(){let e=this.active;if(this.segmentIndex>0&&this.segmentIndex<this.closingSegmentIndex){let t=this.segmentIndex-1>>1;if(this.segmentIndex%2==1){let n=e[t];n!==void 0&&(this.releaseSource(n),e[t]=void 0)}}if(this.segmentIndex++,this.segmentIndex<this.closingSegmentIndex){let t=this.segmentIndex-1>>1;this.source=this.segmentIndex%2==1?e[t]:Cm}else this.segmentIndex===this.closingSegmentIndex?this.source=Pm:this.release(e);this.sourceOffset=0}pullActive(){let e=new Uint8Array(this.outputCapacity),t=0;for(;this.active;)if(this.sourceOffset===this.source.length)this.advanceSource();else if(t===e.length)break;else{let n=vm(this.source,this.sourceOffset,e,t);if(n.read===0)break;this.sourceOffset+=n.read,t+=n.written}if(t===0)throw Error(`SSR router script record produced no output`);return t===e.length?e:t*2<e.length?e.slice(0,t):e.subarray(0,t)}pullReady(){let e=this.opening??=this.nonce?`<script nonce="${Um(this.nonce)}">`:`<script>`,t=e.length+40,n=0;for(let e=this.queuedSourceHead;e<this.queuedSources.length;e++){let r=this.queuedSources[e],i=t+1+r.length;if(n>0&&i>Am||(t=i,n++,t>Am))break}let r=this.takeQueuedBatch(n);if(t<=Om){let t=r.length===1?r[0]:r.join(Cm),n=Sm.encode(e+t+`;document.currentScript.remove()<\/script>`);return this.release(r),n}return this.active=r,this.segmentIndex=0,this.closingSegmentIndex=(r.length<<1)+1,this.source=e,this.sourceOffset=0,this.outputCapacity=Math.max(Dm,Math.min(km,t)),this.outputState=Hm.Active,this.pullActive()}pullChunk(){if(this.outputState!==Hm.Ready&&this.outputState!==Hm.Active)throw Error(`Hydration script output is not ready`);try{return this.outputState===Hm.Ready?this.pullReady():this.pullActive()}catch(e){throw this.fail(e),e}}subscribe(e){if(this.consumer===`cleaned`)return()=>{};if(this.listener)throw Error(`SSR hydration output already has a subscriber`);return this.listener=e,()=>{this.listener===e&&(this.listener=void 0)}}pushSerializedSource(e,t,n){let r=t?zm+e:e;return n&&(r=Bm+r+`)`),this.pushSource(r)}finish(){this.pushSource(`$_TSR.e()`)&&(this.producerDone=!0,this.clearTimeoutIfSet(),this.refresh())}takeInitialHydrationScriptTags(){if(this.consumer===`cleaned`||this.outputState===Hm.Failed||this.initialTaken)return;let e=this.queuedSources,t=Wm(e,this.nonce);return this.initialTaken=!0,this.releaseAccounting(e),e.length=0,this.queuedSourceHead=0,this.refresh(),t}disableHydration(){this.consumer!==`cleaned`&&this.outputState!==Hm.Failed&&((this.initialTaken||this.consumer!==void 0||this.producerDone)&&ee(),this.releaseAccounting(this.queuedSources),this.clearQueue(),this.initialTaken=!0,this.barrierLifted=!0,this.producerDone=!0,this.refresh())}isInitialTaken(){return this.initialTaken}skipInitialTake(){this.consumer!==`cleaned`&&!this.initialTaken&&(this.initialTaken=!0,this.refresh())}claimOutput(){if(this.consumer===`cleaned`)throw Error(`SSR hydration script output is already cleaned up`);if(this.consumer!==void 0)throw Error(`SSR hydration script output already has a consumer`);return this.consumer=this,this.refresh(!1),this}reserveFastPath(e){let t=this.consumer===e;return this.outputState===Hm.Failed||!this.producerDone||!this.initialTaken||!this.queueIsEmpty()||this.active||!t?!1:(this.consumer=`fast-path`,!0)}startSerializationTimeout(e){this.consumer===`cleaned`||this.outputState===Hm.Failed||this.producerDone||this.timeout!==void 0||(this.timeout=setTimeout(()=>{this.timeout=void 0,this.consumer!==`cleaned`&&this.outputState!==Hm.Failed&&!this.producerDone&&(console.error(`Serialization timeout after app render finished`),this.fail(Error(`Serialization timeout after app render finished`)))},e))}cleanup(){this.consumer!==`cleaned`&&(this.consumer=`cleaned`,this.clearTimeoutIfSet(),this.dropBufferedOutput(),this.listener=void 0,this.outputError=void 0,this.producerDone=!0,this.outputState=Hm.Done)}};function Km(e,t){return new Gm(e,t)}var qm=globalThis.Buffer,Jm=qm?e=>qm.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`):Vp,Ym=()=>{},Xm=()=>{},Zm=`((s,u=1)=>new ReadableStream({start(c,f){f=s.on({next(b){const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)},throw(e){s=u=0;c.error(e)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`,Qm=`((s,u=1,e=new TextEncoder)=>new ReadableStream({start(c,f){f=s.on({next(v){const x=v.slice(1);if(v[0]==='t')c.enqueue(e.encode(x));else{const d=atob(x),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}},throw(x){s=u=0;c.error(x)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`;function $m(e,t,n){return hu({tag:e,test(e){return e===t},parse:{stream(){return{}}},serialize(){return n},deserialize:void 0})}var eh=[Bp,hu({tag:`tss/RawStream`,extends:[$m(`tss/RawStreamFactory`,Ym,Zm),$m(`tss/RawStreamFactoryText`,Xm,Qm)],test(e){return e instanceof Mp},parse:{stream(e,t){let n=e.hint===`text`,r=t.parse(n?Xm:Ym),[i,a]=qp(e.stream,n?Wp:Jm);return t.addCleanup(a),{factory:r,stream:t.parse(i)}}},serialize(e,t){return`(`+t.serialize(e.factory)+`)(`+t.serialize(e.stream)+`)`},deserialize:void 0}),im];function th(e){let t={i:gs(e.id),u:e.updatedAt,s:e.status};for(let[n,r]of[[`__beforeLoadContext`,`b`],[`loaderData`,`l`],[`error`,`e`],[`ssr`,`ssr`]])e[n]!==void 0&&(t[r]=e[n]);return e._notFound&&(t.g=!0),t}function nh(e){try{e?.()}catch(e){console.error(`Error disposing SSR serialization:`,e)}}function rh(e,t,n){let r=e.slice();e.length=0;for(let e of r)try{e(n)}catch(e){console.error(t,e)}}var ih=100,ah=new WeakMap;function oh(e){let t=ah.get(e);if(t)return t;let n=h(ih);return ah.set(e,n),n}function sh(e,t){let n=e.inlineCss?.styles,r=t.inlineCssHrefs;if(!n||!r?.length)return;let i=``;for(let e of r)i+=n[e];return i}function ch(e,t){let n=sh(e,t);return n===void 0?void 0:w(n)}function lh(e){let t=``;for(let n=0;n<e.length;n++)t+=(n===0?``:`\0`)+e[n].routeId;return t}function uh(e,t,n){{let t=oh(e).get(n);if(t)return t}let r=dh(e,t);return oh(e).set(n,r),r}function dh(e,t){let n=e.inlineCss?.styles,r={};if(!n){for(let n of t){let t=e.routes[n.routeId];t&&(r[n.routeId]=t)}return{routes:r,hasStrippedRoutes:!1}}let i=[],a=new Set,o=!1;for(let s of t){let t=s.routeId,c=e.routes[t];if(!c)continue;let l=fh(n,c,i,a);l!==c&&(o=!0),r[t]=l}return{routes:r,hasStrippedRoutes:o,...i.length?{inlineCssHrefs:i}:{}}}function fh(e,t,n,r){let i=t.css;if(!i)return t;if(i.length===0){let e={...t};return delete e.css,e}let a;for(let t=0;t<i.length;t++){let o=i[t],s=D(o);e[s]===void 0?a&&a.push(o):(r.has(s)||(r.add(s),n.push(s)),a||=i.slice(0,t))}if(!a)return t;if(a.length>0)return{...t,css:a};let o={...t};return delete o.css,o}function ph(e){return!!e.scripts?.length||!!e.css?.length}function mh(e){return!!e&&(!!e.preloads?.length||ph(e))}function hh(e,t){let n=t?.preloads?.length?[...t.preloads,...e?.preloads??[]]:e?.preloads,r=t?.scripts?.length?[...t.scripts,...e?.scripts??[]]:e?.scripts,i=t?.css?.length?[...t.css,...e?.css??[]]:e?.css;return{...e??{},...n?.length?{preloads:n}:{},...r?.length?{scripts:r}:{},...i?.length?{css:i}:{}}}function gh(e,t,n,r){let i={...e?{scriptFormat:e}:{},...t?{inlineStyle:t}:{},routes:n};return mh(r)?{...i,routes:{...n,[A]:hh(n[A],r)}}:i}function _h({router:e,manifest:t,getRequestAssets:n}){let r;e.ssr={get manifest(){if(!t)return t;let i=n?.(),a=mh(i);if(!a&&!t.inlineCss)return t;let o,s=t.routes;if(t.inlineCss){let n=v(e.stores.matches.get()),i=lh(n);if(r?.cacheKey===i)o=r.inlineCssAsset,s=r.routes;else{let e=uh(t,n,i);o=ch(t,e),e.hasStrippedRoutes&&(s={...t.routes,...e.routes}),r={cacheKey:i,inlineCssAsset:o,routes:s}}}return gh(t.scriptFormat,o,s,a?i:void 0)}};let i=`idle`,a=!1,o=[],s=[],c=!1,l=!1,u,d=Km(e.options.ssr?.nonce),f={hydrationScripts:d,dehydrate:async n=>{i!==`idle`&&ee(),n?.signal?.throwIfAborted(),i=`started`;let r=v(e.stores.matches.get());e.isShell()&&(r=r.slice(0,1));let a=r.map(th),o;if(t){let e=lh(r),i=uh(t,r,e);o=gh(t.scriptFormat,i.inlineCssHrefs?x():void 0,i.routes,n?.requestAssets)}let s={manifest:o,matches:a},f=e.options.dehydrate,p=f?n?.signal?await S(f.call(e.options),n.signal):await f.call(e.options):void 0;if(n?.signal?.throwIfAborted(),c)return;p!==void 0&&(s.dehydratedData=p);let m={didRun:!1},h=e.options.serializationAdapters,g=h?[...h.map(e=>lm(e,m)),...eh]:eh,_=!1,y=!1,b=e=>{if(_||c)return;_=!0;let t=u;u=void 0,e===!0?(l=!0,d.finish()):e&&d.fail(e.error),t&&queueMicrotask(()=>nh(t))},C,w=Op(s,{refs:new Map,plugins:g,onSerialize:(e,t)=>{_||c||(y||=t,d.pushSerializedSource(e,t,m.didRun)||b(!1))},onError:e=>{_||c||(console.error(`Serialization error:`,e),C={error:e},b({error:e}))},scopeId:`tsr`,onDone:()=>{y&&b(!0)}});if(c||_?nh(w):u=w,C)throw C.error},onRenderFinished:e=>{if(!c){if(a)try{e()}catch(e){console.error(`Error in render finished listener:`,e)}else o.push(e)}},onCleanup:e=>{if(c)try{e(l)}catch(e){console.error(`Error in SSR cleanup listener:`,e)}else s.push(e)},setRenderFinished:()=>{c||a||(a=!0,d.liftBarrier(),rh(o,`Error in render finished listener:`,void 0))},disableHydration:()=>{c||i===`disabled`||(i!==`idle`&&ee(),d.disableHydration(),i=`disabled`)},takeInitialHydrationScriptTags:d.takeInitialHydrationScriptTags,cleanup(){if(c)return;c=!0,d.cleanup();let t=u;u=void 0,nh(t),rh(s,`Error in SSR cleanup listener:`,l),o.length=0,e.ssr=void 0,e.serverSsr=void 0}};e.serverSsr=f;for(let t of e.serverSsrLifecycle?.onServerSsrAttach??[])try{t(f)}catch(e){console.error(`SSR attach listener error:`,e)}}function vh(e,t){typeof e==`string`&&(e=e.replace(`\\`,`%5C`));let n=new URL(e,t),r=n.pathname.startsWith(`//`),i=o(r?n.pathname.replace(/^\/+/,`/`):n.pathname),a=new URLSearchParams(n.search),s=i+(a.size>0?`?`:``)+a.toString()+n.hash;return{url:new URL(s,n.origin),handledProtocolRelativeURL:r}}function yh(e){return typeof e!=`object`||!e||!(`response`in e)||!(e.response instanceof Response)||!(`serverSsrCleanup`in e)?!1:e.serverSsrCleanup===`none`||e.serverSsrCleanup===`stream`&&`dispose`in e&&typeof e.dispose==`function`}function bh(e){if(e instanceof Response)return{response:e,serverSsrCleanup:`none`};if(yh(e))return e;throw TypeError(`Expected a Response from the SSR handler`)}function xh(e,t){let n=e.body;n&&n.cancel(t).catch(console.error)}function Sh(e,t){let n=bh(e);n.serverSsrCleanup===`stream`?n.dispose(t):xh(n.response,t)}function Ch(e){return e._serverResult?.type===`render`?e._serverResult.status:200}function wh(e,t){let n=t.body;if(!n)throw Error(`Invariant failed: SSR stream response requires a body`);return{response:t,serverSsrCleanup:`stream`,dispose(t){e.serverSsr?.cleanup(),n.cancel(t).catch(()=>{})}}}function Th(e,t,n){let r=bh(t);if(r.serverSsrCleanup!==`stream`)return n.aborted&&Sh(t,n.reason),r;let i=()=>{Sh(r,n.reason)};if(n.aborted)return i(),r;let a=e?.serverSsr;return a?.hydrationScripts.requestSignal===n?(a.onCleanup(()=>{n.aborted&&i()}),r):(n.addEventListener(`abort`,i,{once:!0}),a&&a.onCleanup(()=>{n.removeEventListener(`abort`,i)}),r)}function Eh(e,t,n){return Sh(e,n),{response:t,serverSsrCleanup:`none`}}function Dh(e,t){let n=bh(e);return Sh(n,t),{response:new Response(null,n.response),serverSsrCleanup:`none`}}function Oh(e){return e}function kh(e){if(Array.isArray(e))return e.flatMap(e=>kh(e));if(typeof e!=`string`)return[];let t=[],n=0,r,i,a,o,s,c=()=>{for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n<e.length},l=()=>(i=e.charAt(n),i!==`=`&&i!==`;`&&i!==`,`);for(;n<e.length;){for(r=n,s=!1;c();)if(i=e.charAt(n),i===`,`){for(a=n,n+=1,c(),o=n;n<e.length&&l();)n+=1;n<e.length&&e.charAt(n)===`=`?(s=!0,n=o,t.push(e.slice(r,a)),r=n):n=a+1}else n+=1;(!s||n>=e.length)&&t.push(e.slice(r))}return t}function Ah(e){return e instanceof Headers?e:Array.isArray(e)||typeof e==`object`?new Headers(e):null}function jh(...e){return e.reduce((e,t)=>{let n=Ah(t);if(!n)return e;for(let[t,r]of n.entries())t===`set-cookie`?kh(r).forEach(t=>e.append(`set-cookie`,t)):e.set(t,r);return e},new Headers)}var Mh=6e4,Nh=256,Ph=65536,Fh={BeforeBoundary:0,Merge:1,HeldClose:2,PassThrough:3};function Ih(e){try{e.releaseLock()}catch{}}function Lh(e,t){let n=e.cancel(t).catch(()=>{});return Ih(e),n}function Rh(e,t,n,r,i,a){try{e===`complete`?n.close():e===`failure`&&n.error(t)}catch{}let o=e!==`complete`;if(o)try{a?.(t)}catch{}let s=o?Lh(r,t):Ih(r);return i.cleanup(),s}function zh(e){return e?.lifetimeMs??(e?.timeoutMs??Mh)*2}function Bh(){let e=Error(`SSR stream transform aborted by router SSR cleanup`);return e.name=`AbortError`,e}function Vh(e,t){if(!e)return;let n=()=>t(e.reason);return e.addEventListener(`abort`,n,{once:!0}),()=>e.removeEventListener(`abort`,n)}function Hh(e,t){let n=setTimeout(e,t);return n.unref?.(),n}function Uh(e,t,n,r){let i=t?.signal,a,o,s=()=>{o?.(),o=void 0,i&&e.hydrationScripts.requestSignal===i&&(e.hydrationScripts.requestSignal=void 0),a!==void 0&&(clearTimeout(a),a=void 0)},c=zh(t);return a=Hh(()=>{if(n())return;let e=Error(`Stream lifetime exceeded`);console.warn(`SSR stream transform exceeded maximum lifetime (${c}ms), forcing cleanup`),r(`failure`,e)},c),o=Vh(i,e=>{r(`failure`,e)}),i&&(e.hydrationScripts.requestSignal=i),e.onCleanup(()=>{n()||r(`failure`,Bh())}),s}function Wh(e,t,n){try{t?.(n)}catch{}e.cleanup()}function Gh(e,t){let n=e.length-t,r=Math.min(Ph,Math.max(Nh,Math.min(e.length,n*3))),i=new Uint8Array(r),{read:a,written:o}=vm(e,t,i);return{bytes:o===i.length?i:i.subarray(0,o),read:a}}function Kh(e,t,n){let r=e.serverSsr;if(!r)throw Error(`Invariant failed: router.serverSsr is required`);let i=r.hydrationScripts,a;try{a=t.getReader()}catch(e){throw Wh(r,n?.onAbort,e),e}try{if(n?.signal?.throwIfAborted(),i.reserveFastPath())return qh(r,a,void 0,n);let e=i.claimOutput();if(e.state===Hm.Failed)throw e.error;return qh(r,a,e,n)}catch(e){throw Lh(a,e),Wh(r,n?.onAbort,e),e}}function qh(e,t,n,r){let i=e.hydrationScripts,a,o=!1,s=!1,c=n?Fh.BeforeBoundary:Fh.PassThrough,l=!1,u,d=!1,f,p,m=0,h,g,_=0,v=r?.rendererSafePoint===`script-close`,y=r?.rendererSafePoint===`record-end`,b,x,S,C,w=()=>{};function E(){return new Promise(e=>{C=e})}function D(){let e=C;C=void 0,e?.()}function O(e){return e.length!==0&&(a.enqueue(e),!0)}function k(){p=void 0,h=void 0,g===void 0&&y&&S===void 0&&(l=!0)}function A(e,t,n=e===p.length){let r=p,i=m===0&&e===r.length?r:r.subarray(m,e);return m=e,t&&(l=!0),n&&k(),O(i)}function j(){let e=g,t=Gh(e,_);_+=t.read,p=t.bytes,m=0,_===e.length&&(g=void 0)}function M(){let e=p;if(!i.isInitialTaken())return A(e.length,!1);let t=ym(b??={pattern:Rm,anchorIndex:Lm,matched:0},e,m);return t===void 0?A(e.length,!1):(c=Fh.Merge,i.liftBarrier(),A(t,!0))}function ee(e,t){return m=e,c=Fh.HeldClose,x&&(x.matched=0),l=!0,m===p.length&&k(),t?O(t):!1}function N(e){let t=p;return ee(e+gm.length,e===m?void 0:t.subarray(m,e))}function P(e){let t=te(p,m,e);return t!==void 0&&A(t,!0)}function te(e,t,r){let i=n.state;if(r===t||i===Hm.Done)return;let a=r===e.length?e:e.subarray(0,r),o=x??={pattern:_m,anchorIndex:hm,matched:0},s=i===Hm.Waiting,c=ym(o,a,t,s);if(c!==void 0)return s&&(o.matched=0),c}function ne(){let e=p,t=S,n=Math.min(e.length-m,gm.length),r=new Uint8Array(t.length+n);r.set(t),r.set(e.subarray(m,m+n),t.length);let i=bm(r,gm,0,mm),a=i<0?xm(r,gm):void 0,o=i>=0?i:a??r.length;if(v){let n=te(r,0,o);if(n!==void 0)return m+=n-t.length,S=void 0,l=!0,m===e.length&&k(),O(r.subarray(0,n))}return i>=0?(S=void 0,ee(m+i+gm.length-t.length,i===0?void 0:r.subarray(0,i))):(S=a===void 0?void 0:r.slice(a),m+=n,O(o===r.length?r:r.subarray(0,o)))}function F(){let e=p;if(S){if(ne())return!0;if(c===Fh.HeldClose)return!1;if(m>=e.length)return k(),!1}let t=h??=bm(e,gm,m,mm);if(t>=0)return v&&P(t)?!0:N(t);let n=xm(e,gm,m),r=n??e.length;return v&&P(r)?!0:(S=n===void 0?void 0:e.slice(n),A(r,!1,!0))}function I(){if(m>=p.length)return k(),!1;if(l=!1,c===Fh.BeforeBoundary)return M();if(c===Fh.Merge)return F();let e=p;return v&&P(e.length)?!0:A(e.length,!1)}function re(n,i){if(!o)return o=!0,u?.(),u=void 0,w(),f=void 0,p=void 0,h=void 0,g=void 0,S=void 0,D(),Rh(n,i,a,t,e,r?.onAbort)}function ie(){d||f||o||(d=!0,t.read().then(e=>{d=!1,o||(e.done?ae(e):f=e,D())},e=>{d=!1,o||le(e)}))}function ae(t){if(t.done){s=!0,l=S===void 0,i.startSerializationTimeout(r?.timeoutMs??Mh),e.setRenderFinished();return}let n=t.value;if(typeof n==`string`){if(n.length===0)return;g=n,_=0,l=!1,j()}else n.byteLength!==0&&(p=n,m=0,l=!1)}async function oe(){if(g!==void 0){j();return}if(f){let e=f;f=void 0,ae(e);return}if(!(c!==Fh.BeforeBoundary&&l&&n.state!==Hm.Done)&&!d){let e=await t.read();if(o)return;ae(e);return}let e=E();ie(),await e}async function se(){try{for(;;){if(p){let e=m===0?p:p.subarray(m);if(p=void 0,O(e))return;continue}if(g!==void 0){j();continue}if(s){re(`complete`);return}if(d){await E();continue}let e=f;if(e)f=void 0;else if(e=await t.read(),o)return;if(e.done||typeof e.value==`string`)ae(e);else if(e.value.byteLength>0){a.enqueue(e.value);return}}}catch(e){le(e)}}async function ce(){let e=n;for(;!o;){let t=e.state;if(t===Hm.Active){a.enqueue(e.pullChunk());return}if(c!==Fh.BeforeBoundary&&l&&t===Hm.Ready){!s&&!p&&g===void 0&&ie(),a.enqueue(e.pullChunk());return}if(c===Fh.Merge&&t===Hm.Done&&S===void 0&&i.reserveFastPath(e))return c=Fh.PassThrough,u?.(),u=void 0,se();if(p){if(I())return}else{if(s){if(c===Fh.BeforeBoundary){i.skipInitialTake(),c=Fh.Merge,l=!0;continue}if(S){let e=S;if(S=void 0,l=!0,O(e))return;continue}if(t===Hm.Waiting){await E();continue}if(c===Fh.HeldClose){a.enqueue(gm.slice()),re(`complete`);return}re(`complete`);return}await oe()}}}function le(e){o||(console.error(`Error processing appStream:`,e),re(`failure`,e))}let ue=new ReadableStream({start(e){a=e},pull(){return c===Fh.PassThrough?se():ce().catch(le)},cancel(e){return re(`cancel`,e)}});return n&&(u=n.subscribe(()=>{n.state===Hm.Failed?re(`failure`,n.error):D()})),w=Uh(e,r,()=>o,re),ue}var Jh=t((e=>{var t=n(),r=d(),i=Symbol.for(`react.transitional.element`),a=Symbol.for(`react.portal`),o=Symbol.for(`react.fragment`),s=Symbol.for(`react.strict_mode`),c=Symbol.for(`react.profiler`),l=Symbol.for(`react.consumer`),u=Symbol.for(`react.context`),f=Symbol.for(`react.forward_ref`),p=Symbol.for(`react.suspense`),m=Symbol.for(`react.suspense_list`),h=Symbol.for(`react.memo`),g=Symbol.for(`react.lazy`),_=Symbol.for(`react.scope`),v=Symbol.for(`react.activity`),y=Symbol.for(`react.legacy_hidden`),b=Symbol.for(`react.memo_cache_sentinel`),x=Symbol.for(`react.view_transition`),S=Symbol.for(`react.recoverable`),C=Symbol.iterator;function w(e){return typeof e!=`object`||!e?null:(e=C&&e[C]||e[`@@iterator`],typeof e==`function`?e:null)}var E=Symbol.for(`react.optimistic_key`),D=Array.isArray;function O(e,t){var n=e.length&3,r=e.length-n,i=t;for(t=0;t<r;){var a=e.charCodeAt(t)&255|(e.charCodeAt(++t)&255)<<8|(e.charCodeAt(++t)&255)<<16|(e.charCodeAt(++t)&255)<<24;++t,a=3432918353*(a&65535)+((3432918353*(a>>>16)&65535)<<16)|0,a=a<<15|a>>>17,a=461845907*(a&65535)+((461845907*(a>>>16)&65535)<<16)|0,i^=a,i=i<<13|i>>>19,i=5*(i&65535)+((5*(i>>>16)&65535)<<16)|0,i=(i&65535)+27492+(((i>>>16)+58964&65535)<<16)}switch(a=0,n){case 3:a^=(e.charCodeAt(t+2)&255)<<16;case 2:a^=(e.charCodeAt(t+1)&255)<<8;case 1:a^=e.charCodeAt(t)&255,a=3432918353*(a&65535)+((3432918353*(a>>>16)&65535)<<16)|0,a=a<<15|a>>>17,i^=461845907*(a&65535)+((461845907*(a>>>16)&65535)<<16)|0}return i^=e.length,i^=i>>>16,i=2246822507*(i&65535)+((2246822507*(i>>>16)&65535)<<16)|0,i^=i>>>13,i=3266489909*(i&65535)+((3266489909*(i>>>16)&65535)<<16)|0,(i^i>>>16)>>>0}function k(e){setTimeout(function(){throw e})}var A=Promise,j=typeof queueMicrotask==`function`?queueMicrotask:function(e){A.resolve(null).then(e).catch(k)},M=null,ee=0;function N(e,t){if(t.byteLength!==0){if(4096<t.byteLength)0<ee&&(e.enqueue(new Uint8Array(M.buffer,0,ee)),M=new Uint8Array(4096),ee=0),e.enqueue(t);else{var n=M.length-ee;n<t.byteLength&&(n===0?e.enqueue(M):(M.set(t.subarray(0,n),ee),e.enqueue(M),t=t.subarray(n)),M=new Uint8Array(4096),ee=0),M.set(t,ee),ee+=t.byteLength}}}function P(e,t){return N(e,t),!0}function te(e){M&&0<ee&&(e.enqueue(new Uint8Array(M.buffer,0,ee)),M=null,ee=0)}var ne=new TextEncoder;function F(e){return ne.encode(e)}function I(e){return ne.encode(e)}function re(e){return e.byteLength}function ie(e,t){typeof e.error==`function`?e.error(t):e.close()}var ae=Object.assign,oe=Object.prototype.hasOwnProperty,se=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$`),ce={},le={};function ue(e){return oe.call(le,e)?!0:oe.call(ce,e)?!1:se.test(e)?le[e]=!0:(ce[e]=!0,!1)}var de=new Set(`animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp`.split(` `)),fe=new Map([[`acceptCharset`,`accept-charset`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`],[`crossOrigin`,`crossorigin`],[`accentHeight`,`accent-height`],[`alignmentBaseline`,`alignment-baseline`],[`arabicForm`,`arabic-form`],[`baselineShift`,`baseline-shift`],[`capHeight`,`cap-height`],[`clipPath`,`clip-path`],[`clipRule`,`clip-rule`],[`colorInterpolation`,`color-interpolation`],[`colorInterpolationFilters`,`color-interpolation-filters`],[`colorProfile`,`color-profile`],[`colorRendering`,`color-rendering`],[`dominantBaseline`,`dominant-baseline`],[`enableBackground`,`enable-background`],[`fillOpacity`,`fill-opacity`],[`fillRule`,`fill-rule`],[`floodColor`,`flood-color`],[`floodOpacity`,`flood-opacity`],[`fontFamily`,`font-family`],[`fontSize`,`font-size`],[`fontSizeAdjust`,`font-size-adjust`],[`fontStretch`,`font-stretch`],[`fontStyle`,`font-style`],[`fontVariant`,`font-variant`],[`fontWeight`,`font-weight`],[`glyphName`,`glyph-name`],[`glyphOrientationHorizontal`,`glyph-orientation-horizontal`],[`glyphOrientationVertical`,`glyph-orientation-vertical`],[`horizAdvX`,`horiz-adv-x`],[`horizOriginX`,`horiz-origin-x`],[`imageRendering`,`image-rendering`],[`letterSpacing`,`letter-spacing`],[`lightingColor`,`lighting-color`],[`markerEnd`,`marker-end`],[`markerMid`,`marker-mid`],[`markerStart`,`marker-start`],[`maskType`,`mask-type`],[`overlinePosition`,`overline-position`],[`overlineThickness`,`overline-thickness`],[`paintOrder`,`paint-order`],[`panose-1`,`panose-1`],[`pointerEvents`,`pointer-events`],[`renderingIntent`,`rendering-intent`],[`shapeRendering`,`shape-rendering`],[`stopColor`,`stop-color`],[`stopOpacity`,`stop-opacity`],[`strikethroughPosition`,`strikethrough-position`],[`strikethroughThickness`,`strikethrough-thickness`],[`strokeDasharray`,`stroke-dasharray`],[`strokeDashoffset`,`stroke-dashoffset`],[`strokeLinecap`,`stroke-linecap`],[`strokeLinejoin`,`stroke-linejoin`],[`strokeMiterlimit`,`stroke-miterlimit`],[`strokeOpacity`,`stroke-opacity`],[`strokeWidth`,`stroke-width`],[`textAnchor`,`text-anchor`],[`textDecoration`,`text-decoration`],[`textRendering`,`text-rendering`],[`transformOrigin`,`transform-origin`],[`underlinePosition`,`underline-position`],[`underlineThickness`,`underline-thickness`],[`unicodeBidi`,`unicode-bidi`],[`unicodeRange`,`unicode-range`],[`unitsPerEm`,`units-per-em`],[`vAlphabetic`,`v-alphabetic`],[`vHanging`,`v-hanging`],[`vIdeographic`,`v-ideographic`],[`vMathematical`,`v-mathematical`],[`vectorEffect`,`vector-effect`],[`vertAdvY`,`vert-adv-y`],[`vertOriginX`,`vert-origin-x`],[`vertOriginY`,`vert-origin-y`],[`wordSpacing`,`word-spacing`],[`writingMode`,`writing-mode`],[`xmlnsXlink`,`xmlns:xlink`],[`xHeight`,`x-height`]]),pe=/["'&<>]/;function L(e){if(typeof e==`boolean`||typeof e==`number`||typeof e==`bigint`)return``+e;e=``+e;var t=pe.exec(e);if(t){var n=``,r,i=0;for(r=t.index;r<e.length;r++){switch(e.charCodeAt(r)){case 34:t=`&quot;`;break;case 38:t=`&amp;`;break;case 39:t=`&#x27;`;break;case 60:t=`&lt;`;break;case 62:t=`&gt;`;break;default:continue}i!==r&&(n+=e.slice(i,r)),i=r+1,n+=t}e=i===r?n:n+e.slice(i,r)}return e}var me=/([A-Z])/g,he=/^ms-/,ge=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function _e(e){return ge.test(``+e)?`javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')`:e}var ve=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ye=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,be={pending:!1,data:null,method:null,action:null},xe=ye.d;ye.d={f:xe.f,r:xe.r,D:Er,C:Dr,L:Or,m:kr,X:jr,S:Ar,M:Mr};var Se=[],Ce=null;I(`"></template>`);var we=I(`<script`),Te=I(`<\/script>`),Ee=I(`<script src="`),De=I(`<script type="module" src="`),Oe=I(` nonce="`),ke=I(` integrity="`),Ae=I(` crossorigin="`),je=I(` async=""><\/script>`),Me=I(`<style`),Ne=/(<\/|<)(s)(cript)/gi;function Pe(e,t,n,r){return``+t+(n===`s`?`\\u0073`:`\\u0053`)+r}var Fe=I(`<script type="importmap">`),Ie=I(`<\/script>`);function Le(e,t,n,r,i,a){n=typeof t==`string`?t:t&&t.script;var o=n===void 0?we:I(`<script nonce="`+L(n)+`"`),s=typeof t==`string`?void 0:t&&t.style,c=s===void 0?Me:I(`<style nonce="`+L(s)+`"`),l=e.idPrefix,u=[],d=e.bootstrapScriptContent,f=e.bootstrapScripts,p=e.bootstrapModules;if(d!==void 0&&(u.push(o),vr(u,e),u.push(mt,F((``+d).replace(Ne,Pe)),Te)),d=[],r!==void 0&&(d.push(n===void 0?Fe:I(`<script type="importmap" nonce="`+L(n)+`">`)),d.push(F((``+JSON.stringify(r)).replace(Ne,Pe))),d.push(Ie)),r=i?{preconnects:``,fontPreloads:``,highImagePreloads:``,remainingCapacity:2+(typeof a==`number`?a:2e3)}:null,i={placeholderPrefix:I(l+`P:`),segmentPrefix:I(l+`S:`),boundaryPrefix:I(l+`B:`),startInlineScript:o,startInlineStyle:c,preamble:ze(),externalRuntimeScript:null,bootstrapChunks:u,importMapChunks:d,onHeaders:i,headers:r,resets:{font:{},dns:{},connect:{default:{},anonymous:{},credentials:{}},image:{},style:{}},charsetChunks:[],viewportChunks:[],hoistableChunks:[],preconnects:new Set,fontPreloads:new Set,highImagePreloads:new Set,styles:new Map,bootstrapScripts:new Set,scripts:new Set,bulkPreloads:new Set,preloads:{images:new Map,stylesheets:new Map,scripts:new Map,moduleScripts:new Map},nonce:{script:n,style:s},hoistableState:null,stylesToHoist:!1},f!==void 0)for(r=0;r<f.length;r++)l=f[r],s=o=void 0,c={rel:`preload`,as:`script`,fetchPriority:`low`,nonce:t},typeof l==`string`?c.href=a=l:(c.href=a=l.src,c.integrity=s=typeof l.integrity==`string`?l.integrity:void 0,c.crossOrigin=o=typeof l==`string`||l.crossOrigin==null?void 0:l.crossOrigin===`use-credentials`?`use-credentials`:``),l=e,d=a,l.scriptResources[d]=null,l.moduleScriptResources[d]=null,l=[],Ct(l,c),i.bootstrapScripts.add(l),u.push(Ee,F(L(a)),rt),n&&u.push(Oe,F(L(n)),rt),typeof s==`string`&&u.push(ke,F(L(s)),rt),typeof o==`string`&&u.push(Ae,F(L(o)),rt),vr(u,e),u.push(je);if(p!==void 0)for(t=0;t<p.length;t++)s=p[t],a=r=void 0,o={rel:`modulepreload`,fetchPriority:`low`,nonce:n},typeof s==`string`?o.href=f=s:(o.href=f=s.src,o.integrity=a=typeof s.integrity==`string`?s.integrity:void 0,o.crossOrigin=r=typeof s==`string`||s.crossOrigin==null?void 0:s.crossOrigin===`use-credentials`?`use-credentials`:``),s=e,c=f,s.scriptResources[c]=null,s.moduleScriptResources[c]=null,s=[],Ct(s,o),i.bootstrapScripts.add(s),u.push(De,F(L(f)),rt),n&&u.push(Oe,F(L(n)),rt),typeof a==`string`&&u.push(ke,F(L(a)),rt),typeof r==`string`&&u.push(Ae,F(L(r)),rt),vr(u,e),u.push(je);return i}function Re(e,t,n,r,i){return{idPrefix:e===void 0?``:e,nextFormID:0,streamingFormat:0,bootstrapScriptContent:n,bootstrapScripts:r,bootstrapModules:i,instructions:0,hasBody:!1,hasHtml:!1,unknownResources:{},dnsResources:{},connectResources:{default:{},anonymous:{},credentials:{}},imageResources:{},styleResources:{},scriptResources:{},moduleUnknownResources:{},moduleScriptResources:{}}}function ze(){return{htmlChunks:null,headChunks:null,bodyChunks:null}}function Be(e,t,n,r){return{insertionMode:e,selectedValue:t,tagScope:n,viewTransition:r}}function Ve(e){return Be(e===`http://www.w3.org/2000/svg`?4:e===`http://www.w3.org/1998/Math/MathML`?5:0,null,0,null)}function He(e,t,n){var r=e.tagScope&-25;switch(t){case`noscript`:return Be(2,null,r|1,null);case`select`:return Be(2,n.value==null?n.defaultValue:n.value,r,null);case`svg`:return Be(4,null,r,null);case`picture`:return Be(2,null,r|2,null);case`math`:return Be(5,null,r,null);case`foreignObject`:return Be(2,null,r,null);case`table`:return Be(6,null,r,null);case`thead`:case`tbody`:case`tfoot`:return Be(7,null,r,null);case`colgroup`:return Be(9,null,r,null);case`tr`:return Be(8,null,r,null);case`head`:if(2>e.insertionMode)return Be(3,null,r,null);break;case`html`:if(e.insertionMode===0)return Be(1,null,r,null)}return 6<=e.insertionMode||2>e.insertionMode?Be(2,null,r,null):e.viewTransition!==null||e.tagScope!==r?Be(e.insertionMode,e.selectedValue,r,null):e}function Ue(e){return e===null?null:{update:e.update,enter:`none`,exit:`none`,share:e.update,parentEnter:`none`,parentExit:`none`,name:e.autoName,autoName:e.autoName,nameIdx:0}}function We(e,t){return t.tagScope&32&&(e.instructions|=128),Be(t.insertionMode,t.selectedValue,t.tagScope|12,Ue(t.viewTransition))}function Ge(e,t){e=Ue(t.viewTransition);var n=t.tagScope|16;return e!==null&&e.share!==`none`&&(n|=64),Be(t.insertionMode,t.selectedValue,n,e)}function Ke(e,t,n){return e=`_`+e.idPrefix+`R_`+t,0<n&&(e+=`H`+n.toString(32)),e+`_`}var qe=I(`<!-- -->`);function Je(e,t,n,r){return t===``?r:(r&&e.push(qe),e.push(F(L(t))),!0)}function Ye(e,t){t=t.viewTransition,t!==null&&(t.name!==`auto`&&(ot(e,`vt-name`,t.nameIdx===0?t.name:t.name+`_`+t.nameIdx),t.nameIdx++),ot(e,`vt-update`,t.update),t.enter!==`none`&&ot(e,`vt-enter`,t.enter),t.exit!==`none`&&ot(e,`vt-exit`,t.exit),t.share!==`none`&&ot(e,`vt-share`,t.share))}var Xe=new Map,Ze=I(` style="`),Qe=I(`:`),$e=I(`;`);function et(e,t){if(typeof t!=`object`)throw Error("The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.");var n=!0,r;for(r in t)if(oe.call(t,r)){var i=t[r];if(i!=null&&typeof i!=`boolean`&&i!==``){if(r.indexOf(`--`)===0){var a=F(L(r));i=F(L((``+i).trim()))}else a=Xe.get(r),a===void 0&&(a=I(L(r.replace(me,`-$1`).toLowerCase().replace(he,`-ms-`))),Xe.set(r,a)),i=typeof i==`number`?i===0||de.has(r)?F(``+i):F(i+`px`):F(L((``+i).trim()));n?(n=!1,e.push(Ze,a,Qe,i)):e.push($e,a,Qe,i)}}n||e.push(rt)}var tt=I(` `),nt=I(`="`),rt=I(`"`),it=I(`=""`);function at(e,t,n){n&&typeof n!=`function`&&typeof n!=`symbol`&&e.push(tt,F(t),it)}function ot(e,t,n){typeof n!=`function`&&typeof n!=`symbol`&&typeof n!=`boolean`&&e.push(tt,F(t),nt,F(L(n)),rt)}var st=I(L(`javascript:throw new Error('React form unexpectedly submitted.')`)),ct=I(`<input type="hidden"`);function lt(e,t){this.push(ct),ut(e),ot(this,`name`,t),ot(this,`value`,e),this.push(ht)}function ut(e){if(typeof e!=`string`)throw Error(`File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration.`)}function dt(e,t){if(typeof t.$$FORM_ACTION==`function`){var n=e.nextFormID++;e=e.idPrefix+n;try{var r=t.$$FORM_ACTION(e);return r&&r.data?.forEach(ut),r}catch(e){if(typeof e==`object`&&e&&typeof e.then==`function`)throw e}}return null}function ft(e,t,n,r,i,a,o,s){var c=null;if(typeof r==`function`){var l=dt(t,r);l===null?(e.push(tt,F(`formAction`),nt,st,rt),o=a=i=r=s=null,bt(t,n)):(s=l.name,r=l.action||``,i=l.encType,a=l.method,o=l.target,c=l.data)}return s!=null&&pt(e,`name`,s),r!=null&&pt(e,`formAction`,r),i!=null&&pt(e,`formEncType`,i),a!=null&&pt(e,`formMethod`,a),o!=null&&pt(e,`formTarget`,o),c}function pt(e,t,n){switch(t){case`className`:ot(e,`class`,n);break;case`tabIndex`:ot(e,`tabindex`,n);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:ot(e,t,n);break;case`style`:et(e,n);break;case`src`:case`href`:if(n===``)break;case`action`:case`formAction`:if(n==null||typeof n==`function`||typeof n==`symbol`||typeof n==`boolean`)break;n=_e(``+n),e.push(tt,F(t),nt,F(L(n)),rt);break;case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`ref`:break;case`autoFocus`:case`multiple`:case`muted`:at(e,t.toLowerCase(),n);break;case`xlinkHref`:if(typeof n==`function`||typeof n==`symbol`||typeof n==`boolean`)break;n=_e(``+n),e.push(tt,F(`xlink:href`),nt,F(L(n)),rt);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:typeof n!=`function`&&typeof n!=`symbol`&&e.push(tt,F(t),nt,F(L(n)),rt);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`credentialless`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:n&&typeof n!=`function`&&typeof n!=`symbol`&&e.push(tt,F(t),it);break;case`capture`:case`download`:!0===n?e.push(tt,F(t),it):!1!==n&&typeof n!=`function`&&typeof n!=`symbol`&&e.push(tt,F(t),nt,F(L(n)),rt);break;case`cols`:case`rows`:case`size`:case`span`:typeof n!=`function`&&typeof n!=`symbol`&&!isNaN(n)&&1<=n&&e.push(tt,F(t),nt,F(L(n)),rt);break;case`rowSpan`:case`start`:typeof n==`function`||typeof n==`symbol`||isNaN(n)||e.push(tt,F(t),nt,F(L(n)),rt);break;case`xlinkActuate`:ot(e,`xlink:actuate`,n);break;case`xlinkArcrole`:ot(e,`xlink:arcrole`,n);break;case`xlinkRole`:ot(e,`xlink:role`,n);break;case`xlinkShow`:ot(e,`xlink:show`,n);break;case`xlinkTitle`:ot(e,`xlink:title`,n);break;case`xlinkType`:ot(e,`xlink:type`,n);break;case`xmlBase`:ot(e,`xml:base`,n);break;case`xmlLang`:ot(e,`xml:lang`,n);break;case`xmlSpace`:ot(e,`xml:space`,n);break;default:if((!(2<t.length)||t[0]!==`o`&&t[0]!==`O`||t[1]!==`n`&&t[1]!==`N`)&&(t=fe.get(t)||t,ue(t))){switch(typeof n){case`function`:case`symbol`:return;case`boolean`:var r=t.toLowerCase().slice(0,5);if(r!==`data-`&&r!==`aria-`)return}e.push(tt,F(t),nt,F(L(n)),rt)}}}var mt=I(`>`),ht=I(`/>`);function gt(e,t,n){if(t!=null){if(n!=null)throw Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");if(typeof t!=`object`||!(`__html`in t))throw Error("`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information.");t=t.__html,t!=null&&e.push(F(``+t))}}function _t(e){var n=``;return t.Children.forEach(e,function(e){e!=null&&(n+=e)}),n}var vt=I(` selected=""`),yt=I(`addEventListener("submit",function(a){if(!a.defaultPrevented){var b=a.target,d=a.submitter,c=b.action,e=d;if(d){var f=d.getAttribute("formAction");null!=f&&(c=f,e=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===c&&(a.preventDefault(),a=new FormData(b,e),c=b.ownerDocument||b,(c.$$reactFormReplay=c.$$reactFormReplay||[]).push(b,d,a))}});`);function bt(e,t){if(!(e.instructions&16)){e.instructions|=16;var n=t.preamble,r=t.bootstrapChunks;(n.htmlChunks||n.headChunks)&&r.length===0?(r.push(t.startInlineScript),vr(r,e),r.push(mt,yt,Te)):r.unshift(t.startInlineScript,mt,yt,Te)}}var xt=I(`<!--F!-->`),St=I(`<!--F-->`);function Ct(e,t){for(var n in e.push(Lt(`link`)),t)if(oe.call(t,n)){var r=t[n];if(r!=null)switch(n){case`children`:case`dangerouslySetInnerHTML`:throw Error("link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:pt(e,n,r)}}return e.push(ht),null}var wt=/(<\/|<)(s)(tyle)/gi;function Tt(e,t,n,r){return``+t+(n===`s`?`\\73 `:`\\53 `)+r}function Et(e,t,n,r){for(var i in e.push(Lt(n)),t)if(oe.call(t,i)){var a=t[i];if(a!=null)switch(i){case`children`:case`dangerouslySetInnerHTML`:throw Error(n+" is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`.");default:pt(e,i,a)}}return Ye(e,r),e.push(ht),null}function Dt(e,t){e.push(Lt(`title`));var n=null,r=null,i;for(i in t)if(oe.call(t,i)){var a=t[i];if(a!=null)switch(i){case`children`:n=a;break;case`dangerouslySetInnerHTML`:r=a;break;default:pt(e,i,a)}}return e.push(mt),t=Array.isArray(n)?2>n.length?n[0]:null:n,typeof t!=`function`&&typeof t!=`symbol`&&t!=null&&e.push(F(L(``+t))),gt(e,r,n),e.push(Vt(`title`)),null}var Ot=I(`<!--head-->`),kt=I(`<!--body-->`),At=I(`<!--html-->`);function jt(e,t){e.push(Lt(`script`));var n=null,r=null,i;for(i in t)if(oe.call(t,i)){var a=t[i];if(a!=null)switch(i){case`children`:n=a;break;case`dangerouslySetInnerHTML`:r=a;break;default:pt(e,i,a)}}return e.push(mt),gt(e,r,n),typeof n==`string`&&e.push(F((``+n).replace(Ne,Pe))),e.push(Vt(`script`)),null}function Mt(e,t,n,r){e.push(Lt(n));var i=n=null,a;for(a in t)if(oe.call(t,a)){var o=t[a];if(o!=null)switch(a){case`children`:n=o;break;case`dangerouslySetInnerHTML`:i=o;break;default:pt(e,a,o)}}return Ye(e,r),e.push(mt),gt(e,i,n),n}function Nt(e,t,n,r){e.push(Lt(n));var i=n=null,a;for(a in t)if(oe.call(t,a)){var o=t[a];if(o!=null)switch(a){case`children`:n=o;break;case`dangerouslySetInnerHTML`:i=o;break;default:pt(e,a,o)}}return Ye(e,r),e.push(mt),gt(e,i,n),typeof n==`string`?(e.push(F(L(n))),null):n}var Pt=I(`
4
4
  `),Ft=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,It=new Map;function Lt(e){var t=It.get(e);if(t===void 0){if(!Ft.test(e))throw Error(`Invalid tag: `+e);t=I(`<`+e),It.set(e,t)}return t}var Rt=I(`<!DOCTYPE html>`);function zt(e,t,n,r,i,a,o,s,c){switch(t){case`div`:case`span`:case`svg`:case`path`:break;case`a`:e.push(Lt(`a`));var l=null,u=null,d;for(d in n)if(oe.call(n,d)){var f=n[d];if(f!=null)switch(d){case`children`:l=f;break;case`dangerouslySetInnerHTML`:u=f;break;case`href`:f===``?ot(e,`href`,``):pt(e,d,f);break;default:pt(e,d,f)}}if(Ye(e,s),e.push(mt),gt(e,u,l),typeof l==`string`){e.push(F(L(l)));var p=null}else p=l;return p;case`g`:case`p`:case`li`:break;case`select`:e.push(Lt(`select`));var m=null,h=null,g;for(g in n)if(oe.call(n,g)){var _=n[g];if(_!=null)switch(g){case`children`:m=_;break;case`dangerouslySetInnerHTML`:h=_;break;case`defaultValue`:case`value`:break;default:pt(e,g,_)}}return Ye(e,s),e.push(mt),gt(e,h,m),m;case`option`:var v=s.selectedValue;e.push(Lt(`option`));var y=null,b=null,x=null,S=null,C;for(C in n)if(oe.call(n,C)){var w=n[C];if(w!=null)switch(C){case`children`:y=w;break;case`selected`:x=w;break;case`dangerouslySetInnerHTML`:S=w;break;case`value`:b=w;default:pt(e,C,w)}}if(v!=null){var E=b===null?_t(y):``+b;if(D(v)){for(var O=0;O<v.length;O++)if(``+v[O]===E){e.push(vt);break}}else``+v===E&&e.push(vt)}else x&&e.push(vt);return e.push(mt),gt(e,S,y),y;case`textarea`:e.push(Lt(`textarea`));var k=null,A=null,j=null,M;for(M in n)if(oe.call(n,M)){var ee=n[M];if(ee!=null)switch(M){case`children`:j=ee;break;case`value`:k=ee;break;case`defaultValue`:A=ee;break;case`dangerouslySetInnerHTML`:throw Error("`dangerouslySetInnerHTML` does not make sense on <textarea>.");default:pt(e,M,ee)}}if(k===null&&A!==null&&(k=A),Ye(e,s),e.push(mt),j!=null){if(k!=null)throw Error("If you supply `defaultValue` on a <textarea>, do not pass children.");if(D(j)){if(1<j.length)throw Error(`<textarea> can only have at most one child.`);k=``+j[0]}k=``+j}return typeof k==`string`&&k[0]===`
@@ -72,7 +72,7 @@ z=0;z<F.length;z++){var G=F[z],H=G.getAttribute("vt-name"),I=m.get(H);I&&(h(G,"v
72
72
  M&&"none"!==M&&!l.includes(p)&&h(p,"vt-update");p=p.nextElementSibling}while((b=b.parentNode)&&1===b.nodeType&&"none"!==b.getAttribute("vt-update"));u.push.apply(u,K.querySelectorAll('img[src]:not([loading="lazy"])'))}}}if(C){var A=document.__reactViewTransition=document.startViewTransition({update:function(){B(g);for(var a=[document.documentElement.clientHeight,document.fonts.ready],c={},e=0;e<u.length;c={g:c.g},e++)if(c.g=u[e],!c.g.complete){var q=c.g.getBoundingClientRect();0<q.bottom&&0<q.right&&
73
73
  q.top<window.innerHeight&&q.left<window.innerWidth&&(q=new Promise(function(w){return function(r){w.g.addEventListener("load",r);w.g.addEventListener("error",r)}}(c)),a.push(q))}return Promise.race([Promise.all(a),new Promise(function(w){var r=performance.now();setTimeout(w,2300>r&&2E3<r?2300-r:500)})])},types:[]});A.ready.finally(function(){for(var a=l.length-3;0<=a;a-=3){var c=l[a],e=c.style;e.viewTransitionName=l[a+1];e.viewTransitionClass=l[a+1];""===c.getAttribute("style")&&c.removeAttribute("style")}});
74
74
  A.finished.finally(function(){document.__reactViewTransition===A&&(document.__reactViewTransition=null)});$RB=[];return}}catch(a){}B(g)}.bind(null,$RV);`)),t.push(`$RC("`)),r=i.toString(16),t.push(e.boundaryPrefix),t.push(r),t.push(`","`),t.push(e.segmentPrefix),t.push(r),a?(t.push(`",`),gt(t,n)):t.push(`"`),n=t.push(`)<\/script>`),Xe(t,e)&&n}function qr(e,t,n,r){if(r.status===2)return!0;var a=n.contentState,o=r.id;if(o===-1){if((r.id=n.rootSegmentID)===-1)throw Error(i(392));return B(e,t,r,a)}return o===n.rootSegmentID?B(e,t,r,a):(B(e,t,r,a),n=e.resumableState,e=e.renderState,t.push(e.startInlineScript),t.push(`>`),n.instructions&1?t.push(`$RS("`):(n.instructions|=1,t.push(`$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("`)),t.push(e.segmentPrefix),o=o.toString(16),t.push(o),t.push(`","`),t.push(e.placeholderPrefix),t.push(o),t=t.push(`")<\/script>`),t)}var Jr=!1;function Yr(e,t){try{if(!(0<e.pendingRootTasks)){var n,r=e.completedRootSegment;if(r!==null){if(r.status===5)return;var i=e.completedPreambleSegments;if(i===null)return;Wr=e.byteSize;var a=e.resumableState,o=e.renderState,s=o.preamble,c=s.htmlChunks,l=s.headChunks,u;if(c){for(u=0;u<c.length;u++)t.push(c[u]);if(l)for(u=0;u<l.length;u++)t.push(l[u]);else{var d=Ge(`head`);t.push(d),t.push(`>`)}}else if(l)for(u=0;u<l.length;u++)t.push(l[u]);var f=o.charsetChunks;for(u=0;u<f.length;u++)t.push(f[u]);f.length=0,o.preconnects.forEach(lt,t),o.preconnects.clear();var p=o.viewportChunks;for(u=0;u<p.length;u++)t.push(p[u]);p.length=0,o.fontPreloads.forEach(lt,t),o.fontPreloads.clear(),o.highImagePreloads.forEach(lt,t),o.highImagePreloads.clear(),fe=o,o.styles.forEach(ft,t),fe=null;var m=o.importMapChunks;for(u=0;u<m.length;u++)t.push(m[u]);m.length=0,o.bootstrapScripts.forEach(lt,t),o.scripts.forEach(lt,t),o.scripts.clear(),o.bulkPreloads.forEach(lt,t),o.bulkPreloads.clear(),a.instructions|=32;var h=o.hoistableChunks;for(u=0;u<h.length;u++)t.push(h[u]);for(a=h.length=0;a<i.length;a++){var g=i[a];for(o=0;o<g.length;o++)Gr(e,t,g[o],null)}var _=e.renderState.preamble,v=_.headChunks;if(_.htmlChunks||v){var y=Je(`head`);t.push(y)}var b=_.bodyChunks;if(b)for(i=0;i<b.length;i++)t.push(b[i]);Gr(e,t,r,null),e.completedRootSegment=null;var x=e.renderState;if(e.allPendingTasks!==0||e.clientRenderedBoundaries.length!==0||e.completedBoundaries.length!==0||e.trackedPostpones!==null&&(e.trackedPostpones.rootNodes.length!==0||e.trackedPostpones.rootSlots!==null)){var S=e.resumableState;if(!(S.instructions&64)){if(S.instructions|=64,t.push(x.startInlineScript),!(S.instructions&32)){S.instructions|=32;var C=`_`+S.idPrefix+`R_`;t.push(` id="`);var w=I(C);t.push(w),t.push(`"`)}t.push(`>`),t.push(`requestAnimationFrame(function(){$RT=performance.now()});`),t.push(`<\/script>`)}}Xe(t,x)}var E=e.renderState;r=0;var D=E.viewportChunks;for(r=0;r<D.length;r++)t.push(D[r]);D.length=0,E.preconnects.forEach(lt,t),E.preconnects.clear(),E.fontPreloads.forEach(lt,t),E.fontPreloads.clear(),E.highImagePreloads.forEach(lt,t),E.highImagePreloads.clear(),E.styles.forEach(mt,t),E.scripts.forEach(lt,t),E.scripts.clear(),E.bulkPreloads.forEach(lt,t),E.bulkPreloads.clear();var O=E.hoistableChunks;for(r=0;r<O.length;r++)t.push(O[r]);O.length=0;var k=e.clientRenderedBoundaries;for(n=0;n<k.length;n++){var A=k[n];E=t;var j=e.resumableState,M=e.renderState,ee=A.rootSegmentID,N=A.errorDigest;E.push(M.startInlineScript),E.push(`>`),j.instructions&4?E.push(`$RX("`):(j.instructions|=4,E.push(`$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,null!=c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("`)),E.push(M.boundaryPrefix);var P=ee.toString(16);if(E.push(P),E.push(`"`),N!=null){if(E.push(`,`),N==null)E.push(`null`);else{var te=tt(N);E.push(te)}}var ne=E.push(`)<\/script>`);if(!ne){e.destination=null,n++,k.splice(0,n);return}}k.splice(0,n);var F=e.completedBoundaries;for(n=0;n<F.length;n++)if(!Kr(e,t,F[n])){e.destination=null,n++,F.splice(0,n);return}F.splice(0,n),Jr=!0;var re=e.partialBoundaries;for(n=0;n<re.length;n++){var ie=re[n];a:{k=e,A=t,Wr=ie.byteSize;var ae=ie.completedSegments;for(ne=0;ne<ae.length;ne++)if(!qr(k,A,ie,ae[ne])){ne++,ae.splice(0,ne);var oe=!1;break a}ae.splice(0,ne);var se=ie.row;se!==null&&se.together&&ie.pendingTasks===1&&(se.pendingTasks===1?pr(k,se,se.hoistables):se.pendingTasks--),oe=ct(A,ie.contentState,k.renderState)}if(!oe){e.destination=null,n++,re.splice(0,n);return}}re.splice(0,n),Jr=!1;var ce=e.completedBoundaries;for(n=0;n<ce.length;n++)if(!Kr(e,t,ce[n])){e.destination=null,n++,ce.splice(0,n);return}ce.splice(0,n)}}finally{Jr=!1,n=e.postponedState,n!==null&&(n.nextSegmentId=e.nextSegmentId),e.allPendingTasks===0&&e.clientRenderedBoundaries.length===0&&e.completedBoundaries.length===0&&(e.flushScheduled=!1,n=e.resumableState,n.hasBody&&(re=Je(`body`),t.push(re)),n.hasHtml&&(n=Je(`html`),t.push(n)),$r(e),e.status=13,t.push(null),e.destination=null)}}function Xr(e){if(!1===e.flushScheduled&&e.pingedTasks.length===0&&e.destination!==null){e.flushScheduled=!0;var t=e.destination;t?Yr(e,t):e.flushScheduled=!1}}function Zr(e,t){if(e.status===12)e.status=13,e=e.fatalError,Tn(e)&&(e=En(e)),t.destroy(e);else if(e.status!==13&&e.destination===null){e.destination=t;try{Yr(e,t)}catch(t){ur(e,t,{}),dr(e,t)}}}function Qr(e,t){try{if(0<t.size){var n=e.fatalError;t.forEach(function(t){return Nr(t,e,n)}),t.clear()}e.destination!==null&&Yr(e,e.destination)}catch(t){ur(e,t,{}),dr(e,t)}}function $r(e){e=e.renderLifetimeController,e!==null&&e.abort(`The render ended.`)}function ei(e,t){if(!(e.aborted||e.status!==11&&e.status!==10)){$r(e);var n=typeof t==`object`&&!!t&&t.$$typeof===C;e.aborted=!0,t=n?wn(t):t===void 0?Error(i(432)):typeof t==`object`&&t&&typeof t.then==`function`?Error(i(530)):t,e.fatalError=t,t=e.abortableTasks,t.forEach(function(t){return Mr(t,e)}),Qr(e,t)}}function ti(e,t,n){if(t===null)n.rootNodes.push(e);else{var r=n.workingMap,i=r.get(t);i===void 0&&(i=[t[1],t[2],[],null],r.set(t,i),ti(i,t[0],n)),i[2].push(e)}}function ni(){}function ri(e,t,n,r){var a=!1,o=null,s=``,c=!1;if(t=me(t?t.identifierPrefix:void 0),e=tr(e,t,Ft(t,n),he(0,null,0,null),1/0,ni,void 0,void 0,function(){c=!0},void 0,void 0,void 0),e.flushScheduled=e.destination!==null,zr(e),e.status===10&&(e.status=11),e.trackedPostpones===null&&Pr(e,e.pendingRootTasks===0),ei(e,r),Zr(e,{push:function(e){return e!==null&&(s+=e),!0},destroy:function(e){a=!0,o=e}}),a&&o!==r)throw o;if(!c)throw Error(i(426));return s}e.renderToStaticMarkup=function(e,t){return ri(e,t,!0,`The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server`)},e.renderToString=function(e,t){return ri(e,t,!1,`The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server`)},e.version=`19.3.0`})),Xh=t((e=>{var t=Jh(),n=Yh();e.version=t.version,e.renderToReadableStream=t.renderToReadableStream,e.renderToString=n.renderToString,e.renderToStaticMarkup=n.renderToStaticMarkup,e.resume=t.resume})),Zh=` daum[ /]| deusu/|(?:^|[^g])news(?!sapphire)|(?<! channel/|google/)google(?!(?:wv|app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!cam)scan|(?<!lib)http|24x7|;\\s\\w+;$|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\b\\w+/1\\.0;|\\bbw/|\\bdlc\\b|\\bort/|\\bperl\\b|\\btime/|\\||^[<\\(;]|^[\\w \\.\\-\\(?:\\):%]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[\\w\\-]+/[\\w]+$|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^\\w+/\\d\\.\\d\\s\\([\\w@]+\\)$|^active|^ad muncher|^amaya|^apache/|^avsdevicesdk/|^azure|^biglotron|^blackbox exporter|^bot|^clamav[ /]|^claude-code/|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^email|^exodusmovement|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^igetter/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d\\s[\\w\\.-]+$|^mozilla/\\d\\.\\d\\s\\((?:compatible;)?(?:\\s?[\\w\\d-.]+\\/\\d+\\.\\d+)?\\)$|^navermailapp|^netsurf|^offline|^openai/|^owler|^php|^postman|^ps_daily/|^python|^rank|^read|^reed|^remove\\.bg/|^rest|^rss|^snapchat|^sora |^space bison|^stape/|^svn|^swcd |^taringa|^thumbor/|^track|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|abuse|advisor|agent\\b|analyzer|archive|ask jeeves/teoma|attracta|audit|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|collapsify\\b|convertify|cookiehubverify/|crawl|cursor/|cypress/|dareboost|datanyze|dejaclick|detect|discovery|dmbrowser|download|exaleadcloudview|feed|firephp|foregenix|functionize|grab|hardenize\\b|headless|hotjar|httrack|hubspot marketing grader|ibisbrowser|infrawatch|insight|inspect|iplabel|java(?!;)|library|linkcheck|linktiger|mail\\.ru/|manager|manus-user/|marketgoo/|measure|monitor\\b|neustar wpm|node\\b|nutch|offbyone|openvas|optimize|pageburst|pagespeed|parser|phantomjs|pingdom|playwright|powermarks|preview|productfinder|prospectingstudio|proxy|ptst[ /]\\d|radar|readable/|retriever|rexx;|rigor|rss\\b|scrape|securityheaders|selenium|server|silktide|sindup/|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|testlocally|tools|torrent|transcoder|url|validator|virtuoso|wappalyzer|watchtowr|webglance|webkit2png|whatcms/|xtate/`,Qh=/bot|crawl|http|lighthouse|scan|search|spider/i,$h;function eg(){if($h instanceof RegExp)return $h;try{$h=new RegExp(Zh,`i`)}catch{$h=Qh}return $h}var tg=e=>typeof e==`string`&&e!==``;function ng(e){return tg(e)&&eg().test(e)}var rg=ng,ig=s(Xh(),1),ag=async({request:e,router:t,responseHeaders:n,children:r})=>{let i=e.signal;if(i.aborted)throw t.serverSsr?.cleanup(),i.reason;let a=!1,o=rg(e.headers.get(`User-Agent`)),s=e=>(t,n)=>{!a&&!i.aborted&&console.error(`Error in ${e}:`,t,n)};try{if(typeof ig.renderToReadableStream==`function`){let e=await ig.renderToReadableStream(r,{signal:i,nonce:t.options.ssr?.nonce,progressiveChunkSize:1/0,onError:s(`renderToReadableStream`)}),c=o?new AbortController:void 0,l=Kh(t,e,{rendererSafePoint:`script-close`,signal:i,onAbort:e=>{a=!0,c?.abort(e)}});return c&&await S(e.allReady,c.signal),wh(t,new Response(l,{status:Ch(t),headers:n}))}if(typeof ig.default.renderToPipeableStream==`function`){let e=new Wo,c,l,u=new Promise(e=>{l=e}),d=new AbortController,f=e=>{if(!a){a=!0,d.abort(e);try{c?.abort(e)}catch{}}};try{c=ig.default.renderToPipeableStream(r,{nonce:t.options.ssr?.nonce,progressiveChunkSize:1/0,...o?{onAllReady:l}:{onShellReady:l},onError:s(`renderToPipeableStream`),onShellError:e=>d.abort(e)});let a=Kh(t,Go.toWeb(e),{rendererSafePoint:`script-close`,signal:i,onAbort:f});return await S(u,d.signal),c.pipe(e),wh(t,new Response(a,{status:Ch(t),headers:n}))}catch(e){throw f(e),e}}throw Error(`No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.`)}catch(e){throw t.serverSsr?.cleanup(),e}},og=Oh(({request:e,router:t,responseHeaders:n})=>ag({request:e,router:t,responseHeaders:n,children:(0,Pp.jsx)(zp,{router:t})})),sg=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})(),cg=URL,lg=Response;function ug(e){return decodeURI(e.includes(`%25`)?e.replace(/%25/g,`%2525`):e)}var dg=`h3.internal.event.`,fg=Symbol.for(`${dg}res`),pg=Symbol.for(`${dg}res.headers`),mg=Symbol.for(`${dg}res.err.headers`),hg=class{app;req;url;context;static __is_event__=!0;constructor(e,t,n){this.context=t||e.context||new sg,this.req=e,this.app=n;let r=e._url,i=r&&r instanceof URL?r:new cg(e.url);i.pathname.includes(`%`)&&(i.pathname=ug(i.pathname)),this.url=i}get res(){return this[fg]||=new gg}get runtime(){return this.req.runtime}waitUntil(e){this.req.waitUntil?.(e)}toString(){return`[${this.req.method}] ${this.req.url}`}toJSON(){return this.toString()}get node(){return this.req.runtime?.node}get headers(){return this.req.headers}get path(){return this.url.pathname+this.url.search}get method(){return this.req.method}},gg=class{status;statusText;get headers(){return this[pg]||=new Headers}get errHeaders(){return this[mg]||=new Headers}},_g=/[^\u0009\u0020-\u007E]/g;function vg(e=``){return e.replace(_g,``)}function yg(e,t=200){return!e||(typeof e==`string`&&(e=+e),e<100||e>599)?t:e}var bg=class e extends Error{get name(){return`HTTPError`}status;statusText;headers;cause;data;body;unhandled;static isError(e){return e instanceof Error&&e?.name===`HTTPError`}static status(t,n,r){return new e({...r,statusText:n,status:t})}constructor(e,t){let n,r;typeof e==`string`?(n=e,r=t):r=e;let i=yg(r?.status||r?.statusCode||r?.cause?.status||r?.cause?.statusCode,500),a=vg(r?.statusText||r?.statusMessage||r?.cause?.statusText||r?.cause?.statusMessage),o=n||r?.message||r?.cause?.message||r?.statusText||r?.statusMessage||[`HTTPError`,i,a].filter(Boolean).join(` `);super(o,{cause:r}),this.cause=r,this.status=i,this.statusText=a||void 0;let s=r?.headers||r?.cause?.headers;this.headers=s?new Headers(s):void 0,this.unhandled=r?.unhandled??r?.cause?.unhandled??void 0,this.data=r?.data,this.body=r?.body}get statusCode(){return this.status}get statusMessage(){return this.statusText}toJSON(){let e=this.unhandled;return{status:this.status,statusText:this.statusText,unhandled:e,message:e?`HTTPError`:this.message,data:e?void 0:this.data,...e?void 0:this.body}}};function xg(e,t){if(e==null)return!0;if(t!==`object`)return t===`boolean`||t===`number`||t===`string`;if(typeof e.toJSON==`function`||Array.isArray(e))return!0;if(typeof e.pipe==`function`||typeof e.pipeTo==`function`)return!1;if(e instanceof sg)return!0;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}var Sg=Symbol.for(`h3.notFound`),Cg=Symbol.for(`h3.handled`);function wg(e,t,n={}){if(typeof e?.then==`function`)return(e.catch?.(e=>e)||Promise.resolve(e)).then(e=>wg(e,t,n));let r=Eg(e,t,n);if(typeof r?.then==`function`)return wg(r,t,n);let{onResponse:i}=n;return i?Promise.resolve(i(r,t)).then(()=>r):r}var Tg=class{#e;#t;body;constructor(e,t){this.body=e,this.#t=t}get status(){return this.#t?.status||200}get statusText(){return this.#t?.statusText||`OK`}get headers(){return this.#e||=new Headers(this.#t?.headers)}};function Eg(e,t,n,r){if(e===Cg)return new lg(null);if(e===Sg&&(e=new bg({status:404,message:`Cannot find any route matching [${t.req.method}] ${t.url}`})),e&&e instanceof Error){let i=bg.isError(e),a=i?e:new bg(e);i||(a.unhandled=!0,e?.stack&&(a.stack=e.stack)),a.unhandled&&!n.silent&&console.error(a);let{onError:o}=n,s=t[fg]?.[mg];return o&&!r?Promise.resolve(o(a,t)).catch(e=>e).then(r=>Eg(r??e,t,n,!0)):Pg(a,n.debug,s)}let i=t[fg],a=i?.[pg];if(t[fg]=void 0,!(e instanceof Response)){let r=Mg(e,t,n),o=r.status||i?.status;return new lg(Ng(t.req.method,o)?null:r.body,{status:o,statusText:r.statusText||i?.statusText,headers:r.headers&&a?Dg(r.headers,a):r.headers||a})}if(!a||r||!e.ok)return e;try{return Dg(e.headers,a,e.headers),e}catch{return new lg(Ng(t.req.method,e.status)?null:e.body,{status:e.status,statusText:e.statusText,headers:Dg(e.headers,a)})}}function Dg(e,t,n=new Headers(e)){for(let[e,r]of t)e===`set-cookie`?n.append(e,r):n.set(e,r);return n}var Og=e=>(...t)=>{throw Error(`Headers are frozen (${e} ${t.join(`, `)})`)},kg=class extends Headers{set=Og(`set`);append=Og(`append`);delete=Og(`delete`)},Ag=new kg({"content-length":`0`}),jg=new kg({"content-type":`application/json;charset=UTF-8`});function Mg(e,t,n){if(e==null)return{body:``,headers:Ag};let r=typeof e;if(r===`string`)return{body:e};if(e instanceof Uint8Array)return t.res.headers.set(`content-length`,e.byteLength.toString()),{body:e};if(e instanceof Tg||e?.constructor?.name===`HTTPResponse`)return e;if(xg(e,r))return{body:JSON.stringify(e,void 0,n.debug?2:void 0),headers:jg};if(r===`bigint`)return{body:e.toString(),headers:jg};if(e instanceof Blob){let t=new Headers({"content-type":e.type,"content-length":e.size.toString()}),n=e.name;return n&&(n=encodeURIComponent(n),t.set(`content-disposition`,`filename="${n}"; filename*=UTF-8''${n}`)),{body:e.stream(),headers:t}}return r===`symbol`?{body:e.toString()}:r===`function`?{body:`${e.name}()`}:{body:e}}function Ng(e,t){return e===`HEAD`||t===100||t===101||t===102||t===204||t===205||t===304}function Pg(e,t,n){let r=e.headers?Dg(jg,e.headers):new Headers(jg);return n&&(r=Dg(r,n)),new lg(JSON.stringify({...e.toJSON(),stack:t&&e.stack?e.stack.split(`
75
- `).map(e=>e.trim()):void 0},void 0,t?2:void 0),{status:e.status,statusText:e.statusText,headers:r})}var Fg=Symbol.for(`tanstack-start:event-storage`),Ig=globalThis;Ig[Fg]||(Ig[Fg]=new Ko);var Lg=Ig[Fg];function Rg(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function zg(e){let t=e;if(typeof t.getSetCookie==`function`)return t.getSetCookie();let n=e.get(`set-cookie`);return n?[n]:[]}function Bg(e,t){if(e.ok)return;let n=zg(t.res.headers);if(n.length===0)return;let r=zg(e.headers);e.headers.delete(`set-cookie`);for(let t of r)e.headers.append(`set-cookie`,t);for(let t of n)e.headers.append(`set-cookie`,t)}function Vg(e,t){let n=Ug(e);return Bg(n,t),n}function Hg(e,t){return Rg(e)?Promise.resolve(e).then(e=>Vg(e,t),e=>Vg(Wg(e),t)):Vg(e,t)}function Ug(e){return e instanceof Response?e:new Response(`Internal Server Error`,{status:500})}function Wg(e){if(e instanceof Response)return e;if(e instanceof Error)throw e;return new Response(`Internal Server Error`,{status:500})}function Gg(e){return(t,n)=>{let r;try{r=new hg(t)}catch(e){if(e instanceof URIError)return new Response(null,{status:400,statusText:`Bad Request`});throw e}let i;try{i=Lg.run({h3Event:r},()=>e(t,n))}catch(e){i=Wg(e)}return wg(Hg(i,r),r)}}function Kg(){let e=Lg.getStore();if(!e)throw Error(`No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`);return e.h3Event}function qg(){return Kg().res}var Jg={TSS_SHELL:`X-TSS_SHELL`};async function Yg(e){let{tsrStartManifest:t}=await import(`./assets/_tanstack-start-manifest_v-BIobT_5u.js`),n=t(),r=n.routes;r[A];let i={};for(let e in r){let t=r[e],n={};t.preloads&&t.preloads.length>0&&(n.preloads=t.preloads),t.scripts&&t.scripts.length>0&&(n.scripts=t.scripts),t.css?.length&&(n.css=t.css),(n.preloads||n.scripts||n.css)&&(i[e]=n)}return{...n.scriptFormat?{scriptFormat:n.scriptFormat}:{},...n.inlineCss?{inlineCss:n.inlineCss}:{},routes:i}}var Xg={};async function Zg(e,t){let n=Xg[e];if(!n)throw Error(`Server function info not found for `+e);let r=n.module??=await n.importer();if(!r)throw Error(`Server function module not resolved for `+e);let i=r[n.functionName];if(!i)throw Error(`Server function module export not resolved for serverFn ID: `+e);return i}var Qg=`__TSS_CONTEXT`,$g=Symbol.for(`TSS_SERVER_FUNCTION`),e_=`x-tss-serialized`,t_=`x-tss-raw`,n_=`application/x-tss-framed`,r_=16777216,i_=1024,a_=`${n_}; v=1`,o_=()=>ie().startOptions;function s_(e){return[...(o_()?.serializationAdapters)?.map(jp)??[],...e]}var c_=new TextEncoder,l_=new Uint8Array,u_=4096;function d_(e,t,n){if(n.byteLength>16777216)throw RangeError(`Frame payload exceeds ${r_} bytes`);let r=new Uint8Array(9+n.length);return r[0]=e,r[1]=t>>>24&255,r[2]=t>>>16&255,r[3]=t>>>8&255,r[4]=t&255,r[5]=n.length>>>24&255,r[6]=n.length>>>16&255,r[7]=n.length>>>8&255,r[8]=n.length&255,r.set(n,9),r}function f_(e){let t=e instanceof Error?e.message:String(e??`Unknown error`),n=t.length>u_?`${t.slice(0,u_)}…`:t;return c_.encode(n)}function p_(e,t={}){let n,r=!1,i=0,a,o,s=new Set,c=new Set,l=()=>m(t.signal?.reason),u=()=>{let e=a;a=void 0,e?.()},d=(e,t)=>{e.cancel(t).catch(()=>{})},f=(e,t)=>{e.cancel(t).catch(()=>{})},p=e=>{if(r)return!1;r=[e],t.signal?.removeEventListener(`abort`,l),u();for(let t of s)d(t,e);for(let t of c)f(t,e);return c.clear(),!0},m=e=>{if(p(e))try{n.error(e)}catch{}},h=async()=>{for(;!r&&(n.desiredSize??0)<=0;)await new Promise(e=>{a=e});return!r},g=(e,t,i)=>{if(r)return!1;if(!o&&(n.desiredSize??0)>0)return n.enqueue(d_(e,t,i)),!0;let a=async()=>await h()?(n.enqueue(d_(e,t,i)),!0):!1,s=o?o.then(a):a(),c=()=>{o===l&&(o=void 0)},l=s.then(c,c);return o=l,s},_=()=>{if(i===0&&p())try{n.close()}catch{}},v=e=>{i++,e().then(()=>{i--,_()},e=>{i--,m(e)})};async function y(e,t){let n=t.getReader();s.add(n);try{for(;!r;){let{done:t,value:i}=await n.read();if(r)return;if(t){let t=g(2,e,l_);t!==!0&&await t;return}if(!(i instanceof Uint8Array))throw TypeError(`RawStream chunks must be Uint8Array`);let a=0;do{let t=g(1,e,i.byteLength<=16777216?i:i.subarray(a,a+r_));if(t!==!0&&(t===!1||!await t))return;a+=r_}while(a<i.byteLength)}}catch(t){if(!r){let n=g(3,e,f_(t));n!==!0&&await n}}finally{s.delete(n),n.releaseLock()}}async function b(){let t=e.getReader();s.add(t);try{for(;!r;){let{done:e,value:n}=await t.read();if(r){if(!e)for(let e of n.rawStreams)f(e.stream,r[0]);return}if(e)return;for(let e of n.rawStreams)c.add(e.stream);let i=g(0,0,n.json);if(i!==!0&&(i===!1||!await i))return;for(let e of n.rawStreams)c.delete(e.stream),v(y.bind(void 0,e.id,e.stream))}}catch(e){r||m(e)}finally{s.delete(t),t.releaseLock()}}return new ReadableStream({start(r){n=r,t.signal?.aborted?(f(e,t.signal.reason),m(t.signal.reason)):(t.signal?.addEventListener(`abort`,l,{once:!0}),v(b))},pull(){u()},cancel(e){p(e)&&t.onCancel?.(e)}})}function m_(e){return e!==`__proto__`&&e!==`constructor`&&e!==`prototype`}function h_(e,t){let n=Object.create(null);if(e)for(let t of Object.keys(e))m_(t)&&(n[t]=e[t]);if(t&&typeof t==`object`)for(let e of Object.keys(t))m_(e)&&(n[e]=t[e]);return n}function g_(e){if(!e)return Object.create(null);let t=Object.create(null);for(let n of Object.keys(e))m_(n)&&(t[n]=e[n]);return t}function __(e,t=100){let n=new Set,r=[],i=(e,a)=>{if(a>t)throw Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);e.forEach(e=>{e.options.middleware&&i(e.options.middleware,a+1),n.has(e)||(n.add(e),r.push(e))})};return i(e,0),r}var v_=(e,t)=>{let n={type:`request`,...t||e},r=e=>v_({},Object.assign(n,{validator:e,inputValidator:e}));return{options:n,middleware:e=>v_({},Object.assign(n,{middleware:e})),validator:r,inputValidator:r,client:e=>v_({},Object.assign(n,{client:e})),server:e=>v_({},Object.assign(n,{server:e}))}},y_=(e={})=>v_().server(async t=>{let n=t;return e.filter&&!await e.filter(n)||await b_(e,n)?t.next():T_(e,n)});async function b_(e,t){let n=await x_(e,t);return n===!0||n===void 0&&e.allowRequestsWithoutOriginCheck===!0}async function x_(e,t){let n=t.request.headers.get(`Sec-Fetch-Site`);if(n!==null)return S_(e.secFetchSite??`same-origin`,n,t);let r=t.request.headers.get(`Origin`);if(r!==null)return e.origin?S_(e.origin,r,t):r===new URL(t.request.url).origin;let i=t.request.headers.get(`Referer`);if(i!==null&&e.referer!==!1){if(typeof e.referer==`function`)return e.referer(i,t);if(e.origin){let n=C_(i);return n!==void 0&&S_(e.origin,n,t)}return w_(i,new URL(t.request.url).origin)}}async function S_(e,t,n){return typeof e==`function`?e(t,n):Array.isArray(e)?e.includes(t):t===e}function C_(e){try{return new URL(e).origin}catch{return}}function w_(e,t){if(e===t)return!0;if(!e.startsWith(t))return!1;if(e.length===t.length)return!0;let n=e.charCodeAt(t.length);return n===47||n===63||n===35}async function T_(e,t){return typeof e.failureResponse==`function`?e.failureResponse(t):e.failureResponse?.clone()??new Response(`Forbidden`,{status:403})}var E_=void 0,D_=[`multipart/form-data`,`application/x-www-form-urlencoded`],O_=1e6,k_=1024,A_=33554432,j_=new TextEncoder;function M_(e){return j_.encode(JSON.stringify(e))}function N_(e,t,n){return t>=k_||n+e.byteLength>A_}function P_(e){try{e()}catch{}}function F_(e,t){e.cancel(t).catch(()=>{})}var I_=async({request:e,context:t,serverFnId:n})=>{let r=e.method.toUpperCase(),i=new URL(e.url),a=await Zg(n,{origin:`client`});if(a.method&&r!==a.method)return new Response(`expected ${a.method} method. Got ${r}`,{status:405,headers:{Allow:a.method}});let o=e.headers.get(`x-tsr-serverFn`)===`true`;E_??=s_(om);let s=e.headers.get(`Content-Type`);try{let n;if(D_.some(e=>s&&s.includes(e))){r===`GET`&&ee();let i=await e.formData(),o=i.get(Qg);i.delete(Qg);let s={context:t,data:i,method:r};if(typeof o==`string`)try{let e=Ap(JSON.parse(o),{plugins:E_});typeof e==`object`&&e&&(s.context=h_(e,t))}catch{}n=await a(s)}else if(r===`GET`){let e=i.searchParams.get(`payload`);if(e&&e.length>O_)throw Error(`Payload too large`);let o=e?Ap(JSON.parse(e),{plugins:E_}):void 0;n=await a({data:o?.data,context:h_(o?.context,t),method:r})}else{let i=s?.includes(`application/json`)?Ap(await e.json(),{plugins:E_}):void 0;n=await a({data:i?.data,context:h_(i?.context,t),method:r})}let c=n.error===void 0?n.result:n.error;return m(n)&&(n=R_(n)),!o&&(c instanceof Response||typeof c!=`object`||!c)?c:c instanceof Response?(M(c)||c.headers.set(t_,`true`),c):L_(n,e.signal,E_)}catch(e){if(e instanceof Response)return e;if(m(e))return R_(e);console.error(`Server Fn Error!`,e);let t=JSON.stringify(await Dp(e,{refs:new Map,plugins:E_})),n=qg(),r={"Content-Type":`application/json`,[e_]:`true`};try{return new Response(t,{status:n.status??500,statusText:n.statusText,headers:r})}catch{return new Response(t,{status:500,statusText:``,headers:r})}}};function L_(e,t,n){let r=qg(),i=[],a=0,o=[],s=!1,c=!1,l,u,d=(e,t)=>{if(l)return;c||=t;let n=M_(e);N_(n,i.length,a)?l=[Error(`Server function serialization exceeded its pending output limit`)]:(i.push(n),a+=n.byteLength)},f=()=>{c&&(s=!0)},p=e=>{l??=[e]},m=kp(e,{refs:new Map,plugins:[sm((e,t)=>{if(l)F_(t,l[0]);else if(e>1024){let e=Error(`Too many raw streams in framed response (max ${i_})`);F_(t,e),p(e)}else o.push({id:e,stream:t})}),...n],onParse(e,t){d(e,t)},onDone(){f()},onError:e=>{p(e)}});if(l){P_(m);for(let e of o)F_(e.stream,l[0]);throw l[0]}if(s||(u=m),s&&o.length===0&&i.length===1)return new Response(i[0],{status:r.status,statusText:r.statusText,headers:{"Content-Type":`application/json`,[e_]:`true`}});if(s&&i.length===1){let e=i[0];if(e.byteLength>16777216){let e=Error(`Server function serialization exceeded its pending output limit`);for(let t of o)F_(t.stream,e);throw e}let n=o.splice(0);return i.length=0,w(new ReadableStream({start(t){t.enqueue({json:e,rawStreams:n}),t.close()},cancel(e){for(let t of n)F_(t.stream,e)}}),{signal:t})}let{readable:h,writable:g}=new TransformStream,_=g.getWriter(),v=new AbortController,y=0,b=new Set,x=e=>{if(l)return;l=[e];let t=u;u=void 0;for(let t of o.splice(0))F_(t.stream,e);for(let t of b)for(let n of t.rawStreams)F_(n.stream,e);b.clear(),v.abort(e),_.abort(e).catch(()=>{}),t&&P_(t)},S=(e,t)=>{if(l){for(let e of t)F_(e.stream,l[0]);return!1}if(e.byteLength>16777216||N_(e,b.size,y)){let e=Error(`Server function serialization exceeded its pending output limit`);for(let n of t)F_(n.stream,e);return p(e),!1}y+=e.byteLength;let n={json:e,rawStreams:t};return b.add(n),_.write(n).then(()=>{b.delete(n),y-=e.byteLength},r=>{let i=b.delete(n);if(y-=e.byteLength,i)for(let e of t)F_(e.stream,r)}),!0};d=e=>{l||S(M_(e),o.splice(0))},f=()=>{l||(u=void 0,_.close().catch(()=>{}))},p=e=>{x(e)};let C=o.splice(0);for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!S(i[e],t?C:[])){if(!t)for(let e of C)F_(e.stream,l[0]);throw i.length=0,l[0]}}return i.length=0,s&&f(),_.closed.catch(e=>{x(e)}),w(h,{signal:AbortSignal.any([v.signal,t]),onCancel:x});function w(e,t){let n=p_(e,t);try{return new Response(n,{status:r.status,statusText:r.statusText,headers:{"Content-Type":a_,[e_]:`true`}})}catch(e){throw F_(n,e),e}}}function R_(e){let{headers:t,...n}=e,r=new Response(JSON.stringify(n),{status:404,headers:t});return r.headers.set(`Content-Type`,`application/json`),r}var z_=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,B_=new Set([`fetch`,`font`,`image`,`script`,`style`,`track`]);function V_(e,t){return t===void 0?e:z_.test(t)?`${e}=${t}`:`${e}=${JSON.stringify(t)}`}function H_(e){let t=[`<${e.href}>`,V_(`rel`,e.rel)];return e.as&&t.push(V_(`as`,e.as)),e.crossOrigin!==void 0&&t.push(V_(`crossorigin`,e.crossOrigin||void 0)),e.type&&t.push(V_(`type`,e.type)),e.integrity&&t.push(V_(`integrity`,e.integrity)),e.referrerPolicy&&t.push(V_(`referrerpolicy`,e.referrerPolicy)),e.fetchPriority&&t.push(V_(`fetchpriority`,e.fetchPriority)),t.join(`; `)}function U_(e,t,n){let r=e?.[t]??(n?e?.[n]:void 0);return typeof r==`string`?r:void 0}function W_(e){let t=U_(e,`as`);return t&&B_.has(t)?t:void 0}function G_(e,t){let n=U_(t,`crossOrigin`,`crossorigin`),r=U_(t,`type`),i=U_(t,`integrity`),a=U_(t,`referrerPolicy`,`referrerpolicy`),o=U_(t,`fetchPriority`,`fetchpriority`);n!==void 0&&(e.crossOrigin=n),r&&(e.type=r),i&&(e.integrity=i),a&&(e.referrerPolicy=a),o&&(e.fetchPriority=o)}function K_(e){let t=U_(e,`href`),n=U_(e,`rel`);if(!t||!n)return;let r=n.split(/\s+/),i,a;if(r.includes(`modulepreload`))i=`modulepreload`,a=`script`;else if(r.includes(`stylesheet`))i=`preload`,a=`style`;else if(r.includes(`preload`)){if(a=W_(e),!a)return;i=`preload`}else r.includes(`preconnect`)?(i=`preconnect`,a=void 0):r.includes(`dns-prefetch`)&&(i=`dns-prefetch`,a=void 0);if(!i)return;let o={href:t,rel:i};return a&&(o.as=a),G_(o,e),o}function q_(e,t){let n=[];for(let r of t){let t=e.routes[r.id];if(t){for(let r of t.preloads??[]){let t=b(e,r),i={href:t.href,rel:t.rel,as:`script`};t.crossOrigin!==void 0&&(i.crossOrigin=t.crossOrigin),n.push(i)}for(let r of t.css??[]){let t=D(r);if(e.inlineCss?.styles[t]!==void 0)continue;let i=_(r),a={href:t,rel:`preload`,as:`style`};i.crossOrigin!==void 0&&(a.crossOrigin=i.crossOrigin),n.push(a)}}}return n}function J_(e){let t=[];for(let n of e){let e=n.links;if(Array.isArray(e))for(let n of e){let e=K_(n);e&&t.push(e)}}return t}function Y_(e){let t=[],n=[];for(let r of e.hints){let i=H_(r);e.sentLinks.has(i)||(e.sentLinks.add(i),e.sentHints.push(r),t.push(r),n.push(i))}if(t.length||e.phase===`dynamic`)return{phase:e.phase,hints:t,links:n,allHints:e.sentHints.slice(),allLinks:Array.from(e.sentLinks)}}function X_(e){for(let t of e.hints){let n=H_(t);e.sentLinks.has(n)||(e.sentLinks.add(n),e.entries.push({phase:e.phase,hint:t,link:n}))}}function Z_(e){if(!e.filter)return e.entries.map(e=>e.link);try{let t=[];for(let n of e.entries)e.filter(n)&&t.push(n.link);return t}catch(e){return console.error(`Error filtering response Link headers:`,e),[]}}function Q_(e,t,n){try{let r=n(t);r&&Promise.resolve(r).catch(t=>{console.error(`Error sending ${e} early hints:`,t)})}catch(t){console.error(`Error sending ${e} early hints:`,t)}}function $_(e){if(typeof e==`object`)return e.filter}function ev(e){for(let t of Z_(e))e.responseHeaders.append(`Link`,t)}function tv(e){for(let t=0;t<e.event.hints.length;t++)e.entries.push({phase:e.phase,hint:e.event.hints[t],link:e.event.links[t]})}function nv(e){let t=e.onEarlyHints?Y_({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,sentHints:e.sentHints}):void 0;t&&Q_(e.phase,t,e.onEarlyHints),e.responseLinkHeaderEntries&&(t?tv({phase:e.phase,event:t,entries:e.responseLinkHeaderEntries}):X_({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,entries:e.responseLinkHeaderEntries}))}function rv(e){if(!e?.onEarlyHints&&!e?.responseLinkHeader)return;let t=new Set,n=e.onEarlyHints?[]:void 0,r=e.responseLinkHeader?[]:void 0,i=$_(e.responseLinkHeader);return{collectStatic:({manifest:i,matchedRoutes:a})=>{a?.length&&nv({phase:`static`,hints:q_(i,a),sentLinks:t,sentHints:n,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:r})},collectDynamic:i=>{nv({phase:`dynamic`,hints:J_(i),sentLinks:t,sentHints:n,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:r})},appendResponseHeaders:e=>{r?.length&&ev({responseHeaders:e,entries:r,filter:i})}}}function iv(e){return typeof e==`string`?{href:e}:e}function av(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\a `).replace(/\r/g,`\\d `).replace(/\f/g,`\\c `)}async function ov(e){let{strings:t,urls:n}=e.template;if(t.length!==n.length+1)throw Error(`TanStack Start inlineCss template for ${e.stylesheetHref} is invalid`);let r=t[0];for(let i=0;i<n.length;i++){let a=iv(await e.transformFn({kind:`css-url`,url:n[i],stylesheetHref:e.stylesheetHref}));r+=av(a.href)+t[i+1]}return r}async function sv(e,t){let n={},r=await Promise.all(Object.entries(e.styles).map(async([n,r])=>{let i=e.templates?.[n];return[n,i?await ov({stylesheetHref:n,template:i,transformFn:t}):r]}));for(let[e,t]of r)n[e]=t;return{styles:n,...e.templates?{templates:e.templates}:{}}}function cv(e,t){if(e)return typeof e==`string`?e:e[t]}function lv(e){return`prefix`in e}function uv(e){if(typeof e==`string`){let t=e;return{type:`transform`,transformFn:({url:e})=>({href:`${t}${e}`}),cache:!0}}if(typeof e==`function`)return{type:`transform`,transformFn:e,cache:!0};if(lv(e)){let{prefix:t,crossOrigin:n}=e;return{type:`transform`,transformFn:({url:e,kind:r})=>{let i=`${t}${e}`;if(r===`css-url`)return{href:i};let a=cv(n,r);return a?{href:i,crossOrigin:a}:{href:i}},cache:!0}}return`createTransform`in e&&e.createTransform?{type:`createTransform`,createTransform:e.createTransform,cache:e.cache!==!1}:{type:`transform`,transformFn:typeof e.transform==`string`?(({url:t})=>({href:`${e.transform}${t}`})):e.transform,cache:e.cache!==!1}}function dv(e,t){if(typeof e==`string`)return t.crossOrigin?t:t.href;let n={...e,href:t.href};return t.crossOrigin?n.crossOrigin=t.crossOrigin:delete n.crossOrigin,n}async function fv(e,t,n){let r=structuredClone(e),i=n?.inlineCss!==!1,a=new Map,o=e=>{let n=a.get(e);if(n)return n;let r=Promise.resolve(t({url:e,kind:`script`})).then(iv);return a.set(e,r),r};i?r.inlineCss&&=await sv(r.inlineCss,t):delete r.inlineCss;for(let e of Object.values(r.routes))if(e.preloads?.length&&(e.preloads=await Promise.all(e.preloads.map(async e=>{let t=await o(g(e).href);return dv(e,{href:t.href,crossOrigin:t.crossOrigin})}))),e.css?.length&&!r.inlineCss&&(e.css=await Promise.all(e.css.map(async e=>{let n=iv(await t({url:_(e).href,kind:`stylesheet`}));return dv(e,{href:n.href,crossOrigin:n.crossOrigin})}))),e.scripts?.length)for(let t of e.scripts){let e=t.attrs?.src;if(typeof e!=`string`)continue;let n=await o(e);t.attrs={...t.attrs,src:n.href},n.crossOrigin?t.attrs.crossOrigin=n.crossOrigin:delete t.attrs.crossOrigin}return r}function pv(e,t){return{...e.scriptFormat?{scriptFormat:e.scriptFormat}:{},...t?.inlineCss!==!1&&e.inlineCss?{inlineCss:structuredClone(e.inlineCss)}:{},routes:{...e.routes}}}function mv(e){if(typeof e!=`function`)return e??!0}async function hv(e){return e.requestInlineCss===void 0?typeof e.handlerInlineCss==`function`?await e.handlerInlineCss({request:e.request}):e.handlerInlineCss??!0:e.requestInlineCss}function gv(e){let t;return()=>(t||=e().catch(e=>{throw t=void 0,e}),t)}function _v(e,t){let n=e===void 0?void 0:uv(e),r=!n||n.cache,i=!!e&&typeof e==`object`&&`warmup`in e&&e.warmup===!0,a,o=()=>{a=void 0};return{cache:r,warmup:i,clearCachedCreateTransform:o,getTransformFn:async e=>{if(n)return n.type===`createTransform`?!r||!t.cacheCreateTransform?n.createTransform(e):(a||=Promise.resolve(n.createTransform(e)).catch(e=>{throw o(),e}),a):n.transformFn}}}function vv(e){let t=new Map,n=_v(e.transformAssets,{cacheCreateTransform:e.cacheCreateTransform}),r=mv(e.inlineCss),i=async t=>{let r=await n.getTransformFn({warmup:!1,request:t.request}),i=await hv({request:t.request,handlerInlineCss:e.inlineCss,requestInlineCss:t.requestInlineCss});return{getBaseManifest:t.getBaseManifest,transformFn:r,cache:n.cache,inlineCss:i}},a=async(e,t)=>Cv({...await i(e),finalManifestCache:t});return{warmup:({getBaseManifest:e})=>wv({enabled:n.warmup,handlerDefaultInlineCss:r,cache:n.cache,finalManifestCache:t,getBaseManifest:e,getTransformFn:()=>n.getTransformFn({warmup:!0}),onError:n.clearCachedCreateTransform}),resolveCached:e=>a(e,t),resolveUncached:e=>a(e,void 0)}}function yv(e){return e?`inline-css`:`linked-css`}function bv(e,t,n){let r=n.catch(n=>{throw e.get(t)===r&&e.delete(t),n});return e.set(t,r),r}function xv(e,t,n){return e.get(t)||bv(e,t,Promise.resolve().then(n))}async function Sv(e){return e.transformFn?await fv(e.base,e.transformFn,{inlineCss:e.inlineCss}):pv(e.base,{inlineCss:e.inlineCss})}async function Cv(e){let t=async()=>Sv({base:await e.getBaseManifest(),transformFn:e.transformFn,inlineCss:e.inlineCss});return e.finalManifestCache&&(!e.transformFn||e.cache)?xv(e.finalManifestCache,yv(e.inlineCss),t):t()}function wv(e){if(!e.enabled||e.handlerDefaultInlineCss===void 0||!e.cache)return;let t=e.handlerDefaultInlineCss,n=xv(e.finalManifestCache,yv(t),async()=>{let[n,r]=await Promise.all([e.getBaseManifest(),e.getTransformFn()]);return Sv({base:n,transformFn:r,inlineCss:t})});return e.onError&&n.catch(e.onError),n}var Tv=_s({key:`$TSS/serverfn`,test:e=>typeof e!=`function`||!($g in e)?!1:!!e[$g],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>async(t,n)=>{let r=await Zg(e,{origin:`client`}),i=await r({data:t?.data,context:t?.context,method:r.method??`GET`},n);if(i.error!==void 0)throw i.error;return i.result}});function Ev(e){return jh({"Content-Type":`text/html; charset=utf-8`},...v(e.router.stores.matches.get()).map(e=>e.headers))}var Dv,Ov=y_({filter:e=>e.handlerType===`serverFn`}),kv=gv(()=>Yg()),Av=()=>kv(),jv=rv;async function Mv(){let[e,t,n]=await Promise.all([import(`./assets/router-uhTdTHZE.js`),import(`./assets/start-C63VetBp.js`),import(`./assets/empty-plugin-adapters-BaGcmrjC.js`)]);return{routerEntry:e,startEntry:t,pluginAdapters:n}}function Nv(){return Dv||=Mv(),Dv}var Pv=`/`,Fv=`/_serverFn/`,Iv=process.env.TSS_PRERENDERING===`true`,Lv=process.env.TSS_SHELL===`true`,Rv=`Internal Server Error`,zv=`Internal Server Error`;function Bv(){throw Error(Rv)}function Vv(){throw Error(zv)}function Hv(e){return yh(e)||e instanceof Response?e:e?.response}var Uv=new WeakMap;function Wv(e,t){let n=Hv(e);(yh(n)||n instanceof Response)&&Sh(n,t)}function Gv(e){return e instanceof Response&&e.body!==null}function Kv(e,t){return Gv(t)&&(t.body===e.response.body||Uv.get(t)===e.response)}function qv(e,t){let{response:n,sourceBody:r,streamResponse:i}=e;i?.dispose(t),(!i||n.body!==r)&&n.body.cancel(t).catch(()=>{})}function Jv(e){let{response:t,sourceBody:n,streamResponse:r}=e;return r?r.response===t&&t.body===n?r:t.body===n?{...r,response:t}:{...r,response:t,dispose(t){qv(e,t)}}:t}function Yv(e){return t=>Wv(t,e.reason)}async function Xv(e,t,n,r,i){let a=-1,o,s=!1,c=Yv(r),l=e=>{let t=yh(e)?e:void 0,r=t?.serverSsrCleanup===`stream`?t:void 0,i=t?t.response:e,a=o;s?i!==n.response&&Wv(e,`late middleware response`):(a&&a.response===i?a.streamResponse??=r:a&&Kv(a,i)?(a.response=i,a.streamResponse??=r):(a&&qv(a,`middleware response replaced`),o=Gv(i)?{response:i,sourceBody:i.body,streamResponse:r}:void 0),n.response=i)},u=()=>{n.response!==o?.response&&l(n.response)},d;function p(e){let t=m(e);return d=t,t}async function m(o){if(r.throwIfAborted(),o){o.context&&(n.context=h_(n.context,o.context));for(let e of Object.keys(o))e===`response`?l(o.response):e!==`context`&&(n[e]=o[e])}a++;let s=a===e.length,m=a<e.length?e[a]:s?t:void 0,h=s&&i?i:p;if(!m)return n;let g;try{let e=m({...n,next:h});if(d&&e===d){if(d=void 0,await e,r.aborted)throw r.reason;return n}f(e)?g=await S(e,r,c,c):(g=e,r.throwIfAborted())}catch(e){if(u(),r.aborted)throw g!==void 0&&c(g),e!==r.reason&&c(e),r.reason;if(e instanceof Response)return l(e),n;throw e}if(s&&i&&!g&&Bv(),u(),g&&g!==n){let e=Hv(g);e!==void 0&&e!==n.response&&l(e),e!==g&&g.context&&g.context!==n.context&&(n.context=h_(n.context,g.context))}return n}try{await m();let e=n.response;if(e||Bv(),u(),r.aborted)throw r.reason;return s=!0,o?Jv(o):e}catch(e){throw s=!0,o&&qv(o,r.aborted?r.reason:e),e}}function Zv(e){let t=typeof e==`function`?{}:e,n=typeof e==`function`?e:e.handler,r=vv({...t,cacheCreateTransform:!0}),i=r.resolveCached;return r.warmup({getBaseManifest:()=>Av(void 0)}),Gg(async(e,t)=>{let r=e.signal,a,o,s=!1;try{r.throwIfAborted();let{url:c,handledProtocolRelativeURL:l}=vh(e.url),u=c.pathname+c.search+c.hash,d=c.origin;if(l)return Response.redirect(c,308);let p=await S(Nv(),r),m=!!Fv&&c.pathname.startsWith(Fv),h=p.startEntry.startInstance,g;if(h){let e=h.getOptions();g=f(e)?await S(e,r):e,r.throwIfAborted()}else g={};let{hasPluginAdapters:_,pluginSerializationAdapters:y}=p.pluginAdapters,b=[...g.serializationAdapters||[],..._?y:[],Tv],x={...g,requestMiddleware:h?g.requestMiddleware:m?[Ov]:void 0,serializationAdapters:b},C=x.requestMiddleware?__(x.requestMiddleware):[],w=new Set(C),E=()=>(o??=(async()=>{r.throwIfAborted();let t=await S(p.routerEntry.getRouter(),r),n=Lv;Iv&&!n&&(n=e.headers.get(Jg.TSS_SHELL)===`true`);let i=O(u);return t.update({history:i,isShell:n,isPrerendering:Iv,origin:t.options.origin??d,defaultSsr:x.defaultSsr,serializationAdapters:[...x.serializationAdapters,...t.options.serializationAdapters||[]],basepath:Pv}),a=t,t})(),o),D=m?`serverFn`:`router`,k={getRouter:E,startOptions:x,request:e,executedRequestMiddlewares:w,handlerType:D},A;if(m){let n=c.pathname.slice(Fv.length).split(`/`)[0];if(!n)throw Error(`Invalid server action param for serverFnId`);A=({context:r})=>F({...k,contextAfterGlobalMiddlewares:r},()=>I_({request:e,context:t?.context,serverFnId:n}))}else{let a=async(a,o)=>{if(!/(^|,)\s*(\*\/\*|text\/html)/.test(e.headers.get(`Accept`)||`*/*`))return bh(Response.json({error:`Only HTML requests are supported here`},{status:406}));let s=await S(i({request:e,requestInlineCss:t?.inlineCss,getBaseManifest:()=>Av(o)}),r),c=jv({onEarlyHints:t?.onEarlyHints,responseLinkHeader:t?.responseLinkHeader});c?.collectStatic({manifest:s,matchedRoutes:o});let l=await E();if(_h({router:l,manifest:s,getRequestAssets:()=>ie({throwIfNotFound:!1})?.requestAssets}),l.options.additionalContext={serverContext:a},await l.load({_signal:r}),r.throwIfAborted(),l._serverResult?.type===`redirect`)return bh(l._serverResult.redirect);c?.collectDynamic(v(l.stores.matches.get()));let u=ie({throwIfNotFound:!1});await l.serverSsr.dehydrate({requestAssets:u?.requestAssets,signal:r}),r.throwIfAborted();let d=Ev({router:l});c?.appendResponseHeaders(d),r.throwIfAborted();let f=Yv(r);return bh(await S(n({request:e,router:l,responseHeaders:d}),r,f,f))};A=({context:t})=>F({...k,contextAfterGlobalMiddlewares:t},()=>ty({getRouter:E,request:e,url:c,executeRouter:a,context:t,executedRequestMiddlewares:w}))}let j=await Xv(C.map(e=>e.options.server),A,{request:e,pathname:c.pathname,handlerType:D,context:g_(t?.context)},r),M;try{M=await $v(j,E,r,m&&e.headers.get(`x-tsr-serverFn`)===`true`),e.method===`HEAD`&&(M=Dh(M,`HEAD body stripped`))}catch(e){throw Wv(j,r.aborted?r.reason:e),e}return Th(a,M,r),r.throwIfAborted(),s=M.serverSsrCleanup===`stream`,M.response}finally{a?.serverSsr&&!s&&a.serverSsr.cleanup()}})}var Qv=new Set;async function $v(e,t,n,r){n.throwIfAborted();let i=bh(e),a=i.response;if(!M(a))return i;let o=a.options,s=a.headers.get(`Location`)||o.href;if(!s&&o.to&&typeof o.to==`string`&&!o.to.startsWith(`/`))throw Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(o)}`);if(!s&&[`params`,`search`,`hash`].some(e=>typeof o[e]==`function`))throw Error(`Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(o).filter(e=>typeof o[e]==`function`).map(e=>`"${e}"`).join(`, `)}`);if(n.throwIfAborted(),s&&!p(s,Qv))o.href=s,a.headers.set(`Location`,s);else{let e=await t();n.throwIfAborted(),e.resolveRedirect(a)}if(r){let e={...o};delete e.headers;let t=new Headers(a.headers);return t.set(`content-type`,`application/json`),Eh(i,Response.json({...e,isSerializedRedirect:!0},{headers:t}),`redirect response replaced`)}return i}function ey(e,t){return t.some(e=>e.options.params?.parse??e.options.parseParams)?n=>{let r=Object.assign(Object.create(null),n.params);for(let e of t){let t=e.options.params?.parse??e.options.parseParams;t&&Object.assign(r,t(r))}return e({...n,params:r})}:e}async function ty({getRouter:e,request:t,url:n,executeRouter:r,context:i,executedRequestMiddlewares:a}){let o=await e(),s=k(o.rewrite,n).pathname,[c,l,u]=o.getMatchedRoutes(s),d=u&&l[`**`]===void 0,f=[],p=e=>r(e.context,c),m;for(let e of c){let t=e.options.server?.middleware;if(t){let e=__(t);for(let t of e)a.has(t)||f.push(t.options.server)}}let h=u?.options.server;if(h?.handlers&&d){let e=typeof h.handlers==`function`?h.handlers({createHandlers:e=>e}):h.handlers,n=t.method.toUpperCase(),r=n===`HEAD`?e.HEAD??e.GET??e.ANY:e[n]??e.ANY;if(r){let e=!!u.options.component;if(typeof r!=`function`&&r.middleware?.length){let e=__(r.middleware);for(let t of e)f.push(t.options.server)}let t=typeof r==`function`?r:r.handler;if(t){let n=ey(t,c);e?f.push(n):(p=n,m=Vv)}}}return bh(await Xv(f,p,{request:t,context:i,params:l,pathname:s,handlerType:`router`},t.signal,m))}var ny=[`__VOID_`,`__PROJECT_`],ry=[`ISR_CACHE`];function iy(e){return e.__VOID_ISR_DEPLOYMENT_ID!=null}var ay=Symbol.for(`void.envContext.v1`),oy=globalThis;oy[ay]??=new Ko;var sy=oy[ay],cy;typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`&&import(`cloudflare:workers`).then(e=>{cy=ly(e.env)??void 0}).catch(()=>{});function ly(e){return typeof e!=`object`||!e||`then`in e&&typeof e.then==`function`?null:e}function uy(){return ly(globalThis.__env__)}function dy(){return sy.getStore()??uy()??cy??(()=>{throw Error(`env: Cloudflare env is unavailable. Use void runtime bindings inside Nuxt/SvelteKit/Analog server request handlers or Worker handlers.`)})()}var fy=Symbol.for(`void.runtimeRequestScope.v1`),py=globalThis;py[fy]??=new Ko;var my=py[fy];function hy(e,t,n){let r=my.getStore();if(!r){if(n)return n();throw Error(`env: Request-scoped resource is unavailable outside a runtime handler.`)}if(r.resources.has(e))return r.resources.get(e);let i=t();return r.resources.set(e,i),i}function gy(e,t){let n=ly(e);if(!n)return t();if(my.getStore())return sy.run(n,t);let r={resources:new Map};return sy.run(n,()=>my.run(r,t))}function _y(e,t){return ny.some(t=>e.startsWith(t))?!0:iy(t)&&ry.includes(e)}function vy(e){return new Proxy(e,{get(e,t,n){if(!(typeof t==`string`&&_y(t,e)))return Reflect.get(e,t,n)},has(e,t){return typeof t==`string`&&_y(t,e)?!1:Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e).filter(t=>typeof t!=`string`||!_y(t,e))},getOwnPropertyDescriptor(e,t){if(!(typeof t==`string`&&_y(t,e)))return Reflect.getOwnPropertyDescriptor(e,t)}})}function yy(){return vy(dy())}function by(e){let t=dy();if(!_y(e,t))return t[e]}var xy=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},Sy=Symbol(),Cy=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),wy=1e4,Ty=e=>`headers`in e,Ey=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Ty(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Dy(e,{all:n,dot:r}):{}};async function Dy(e,t){if(!Ty(e)&&e.bodyCache.formData)return Oy(await e.bodyCache.formData,t);let n=Ty(e)?e.headers:e.raw.headers,r=Cy(await e.arrayBuffer(),n.get(`Content-Type`)||``);Ty(e)||(e.bodyCache.formData=r);let i=await r;return i?Oy(i,t):{}}function Oy(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?ky(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(Ay(n,e,t,r),delete n[e])}),n}var ky=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},Ay=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,34);a.length>33&&jy(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=wy&&jy(),i[e]=Object.create(null)),i=i[e])})},jy=()=>{throw Error(`Nesting limit exceeded`)},My=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&se(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=se(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return P(this.url,e)}queries(e){return re(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return Ey(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let r in t)return t[r].then(t=>{r===`json`&&(t=JSON.stringify(t));let i=r===`formData`?void 0:n.headers.get(`content-type`);return new Response(t,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Sy](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Ny={Stringify:1,BeforeStream:2,Stream:3},Py=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Fy=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Fy(e,t,!1,r,i))).then(()=>i[0]));return n?Py(await o,a):o},dee=`text/plain; charset=UTF-8`,Iy=(e,t)=>({"Content-Type":e,...t}),Ly=(e,t)=>new Response(e,t),fee=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new My(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=Ly(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=Ly(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=Ly(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return Ly(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,Iy(dee,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,Iy(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,Iy(`text/html; charset=UTF-8`,n));return typeof e==`object`?Fy(e,Ny.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Ly(),this.#c(this))},Ry=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},pee=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],zy=`Can not add a route since the matcher is already built.`,By=class extends Error{},Vy=`__COMPOSED_HANDLER`,mee=e=>e.text(`404 Not Found`,404),Hy=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},hee=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...pee,`all`].forEach(e=>{this[e]=(t,...n)=>{let r=e.toUpperCase();return typeof t==`string`?this.#e=t:this.#r(r,this.#e,t),n.forEach(e=>{this.#r(r,this.#e,e)}),this}}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat()){let e=t.toUpperCase();for(let t of n)this.#r(e,this.#e,t)}}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??N:oe}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=mee;errorHandler=Hy;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Hy?r=e.handler:(r=async(n,r)=>(await Ry([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Vy]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=de(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=de(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,de(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){t=de(this._basePath,t);let i={basePath:r===void 0?this._basePath:de(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new fee(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=Ry(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${de(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Uy=()=>Object.create(null),Wy=[];function gee(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Wy];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var Gy=`[^/]+`,Ky=`(?:|/.*)`,qy=Symbol(),Jy=new Set(`.\\+*[^]$()`);function Yy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Xy=class e{#e;#t;#n=Uy();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,Gy]:null:s===`/*`?[``,``,Ky]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Jy.has(n)))throw qy;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw qy}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw qy;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw qy;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Yy).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Jy.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Zy=class{#e={varIndex:0};#t=new Xy;#n=0;paths=Uy();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Qy=Uy();function $y(e){return Qy[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Ky:e===`*`?`.*`:`/:${Gy}`)}$`)}function eb(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if($y(n).test(t))return[...e[n]]}var tb=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Uy()},this.#t={ALL:Uy()},this.#n={ALL:new Zy}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===qy?new By(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(zy);if(!r[e]){this.#n[e]=new Zy;for(let t of[r,i]){t[e]=Uy();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=$y(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=eb(r[e],t)||eb(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=I(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=eb(r[t],e)||eb(r.ALL,e)||[]),i[t][e].push([n,e])}match=gee;buildAllMatchers(){let e=Uy();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Qy=Uy(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Uy(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];o?a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),Uy())]):i[t]=[n.map(([e])=>[e,Uy()]),Wy]}return[o,s.map(e=>a[e]),i]}},nb=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(zy);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof By)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},rb=Uy(),ib=0,ab=class e{#e=[];#t=Uy();#n=[];#r;#i=rb;insert(t,n,r){let i=this,a=ne(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=le(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),c=Array.isArray(r),l=c?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,c&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++ib}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=Uy(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=rb;let r=[this],i=te(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===rb?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},ob=class{name=`TrieRouter`;#e=new ab;add(e,t,n){for(let r of I(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},sb=class extends hee{constructor(e={}){super(e),this.router=e.router??new nb({routers:[new tb,new ob]})}},cb=(...e)=>async function(t,n){let r=!1,i=()=>(r=!0,n()),a,o;for(let n of e)try{let e=await n(t,i);if(e===!0&&!t.finalized)await i();else if(e===!1){a=Error(`No successful middleware found`);continue}else e&&e!==!0&&(o=e);a=void 0;break}catch(e){if(a=e,r)break}if(a)throw a;return o},lb=(...e)=>async function(t,n){let r=t.req.routeIndex;await Ry(e.map(e=>[[async(t,n)=>{t.req.routeIndex=r;let i=await e(t,n);if(i===!1)throw Error(`Unmet condition`);return i}]]))(t,n)},ub=(e,...t)=>{let n,r=(Array.isArray(e)?e:[e]).map(e=>{if(typeof e==`string`)n||=new ob,n.add(`ALL`,e,!0);else return e}).filter(Boolean);n&&r.unshift(e=>!!n?.match(`ALL`,e.req.path)?.[0]?.[0]?.[0]);let i=cb(e=>r.some(t=>t(e)),lb(...t));return async function(e,t){await i(e,t)}},db=[`same-origin`,`same-site`,`none`,`cross-site`],fb=e=>db.includes(e),pb=/^(GET|HEAD|OPTIONS)$/,mb=/^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i,hb=e=>{let t=(e=>e?typeof e==`string`?t=>t===e:typeof e==`function`?e:t=>e.includes(t):(e,t)=>e===new URL(t.req.url).origin)(e?.origin),n=async(e,n)=>e!==void 0&&await t(e,n),r=(e=>e?typeof e==`string`?t=>t===e:typeof e==`function`?e:t=>e.includes(t):e=>e===`same-origin`)(e?.secFetchSite),i=async(e,t)=>e===void 0||!fb(e)?!1:await r(e,t);return async function(e,t){if(!pb.test(e.req.method)&&mb.test(e.req.header(`content-type`)||`text/plain`)&&!await i(e.req.header(`sec-fetch-site`),e)&&!await n(e.req.header(`origin`),e))throw new xy(403,{res:new Response(`Forbidden`,{status:403})});await t()}},gb={crossOriginEmbedderPolicy:[`Cross-Origin-Embedder-Policy`,`require-corp`],crossOriginResourcePolicy:[`Cross-Origin-Resource-Policy`,`same-origin`],crossOriginOpenerPolicy:[`Cross-Origin-Opener-Policy`,`same-origin`],originAgentCluster:[`Origin-Agent-Cluster`,`?1`],referrerPolicy:[`Referrer-Policy`,`no-referrer`],strictTransportSecurity:[`Strict-Transport-Security`,`max-age=15552000; includeSubDomains`],xContentTypeOptions:[`X-Content-Type-Options`,`nosniff`],xDnsPrefetchControl:[`X-DNS-Prefetch-Control`,`off`],xDownloadOptions:[`X-Download-Options`,`noopen`],xFrameOptions:[`X-Frame-Options`,`SAMEORIGIN`],xPermittedCrossDomainPolicies:[`X-Permitted-Cross-Domain-Policies`,`none`],xXssProtection:[`X-XSS-Protection`,`0`]},_ee={crossOriginEmbedderPolicy:!1,crossOriginResourcePolicy:!0,crossOriginOpenerPolicy:!0,originAgentCluster:!0,referrerPolicy:!0,strictTransportSecurity:!0,xContentTypeOptions:!0,xDnsPrefetchControl:!0,xDownloadOptions:!0,xFrameOptions:!0,xPermittedCrossDomainPolicies:!0,xXssProtection:!0,removePoweredBy:!0,permissionsPolicy:{}},_b=e=>{let t={..._ee,...e},n=vb(t),r=[];if(t.contentSecurityPolicy){let[e,i]=yb(t.contentSecurityPolicy,`Content-Security-Policy`);e&&r.push(e),n.push([`Content-Security-Policy`,i])}if(t.contentSecurityPolicyReportOnly){let[e,i]=yb(t.contentSecurityPolicyReportOnly,`Content-Security-Policy-Report-Only`);e&&r.push(e),n.push([`Content-Security-Policy-Report-Only`,i])}return t.permissionsPolicy&&Object.keys(t.permissionsPolicy).length>0&&n.push([`Permissions-Policy`,bb(t.permissionsPolicy)]),t.reportingEndpoints&&n.push([`Reporting-Endpoints`,Sb(t.reportingEndpoints)]),t.reportTo&&n.push([`Report-To`,Cb(t.reportTo)]),async function(e,i){let a=r.length===0?n:r.reduce((t,n)=>n(e,t),n);await i(),wb(e,a),t?.removePoweredBy&&e.res.headers.delete(`X-Powered-By`)}};function vb(e){return Object.entries(gb).filter(([t])=>e[t]).map(([t,n])=>{let r=e[t];return typeof r==`string`?[n[0],r]:n})}function yb(e,t){let n=[],r=[];for(let[t,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];e.forEach((e,i)=>{if(typeof e==`function`){let a=i*2+2+r.length;n.push((n,r)=>{r[a]=e(n,t)})}}),r.push(t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(e,t)=>t?`-`+e.toLowerCase():e.toLowerCase()),...e.flatMap(e=>[` `,e]),`; `)}return r.pop(),n.length===0?[void 0,r.join(``)]:[(e,r)=>r.map(r=>{if(r[0]===t){let t=r[1].slice();return n.forEach(n=>{n(e,t)}),[r[0],t.join(``)]}return r}),r]}function bb(e){return Object.entries(e).map(([e,t])=>{let n=xb(e);return typeof t==`boolean`?`${n}=${t?`*`:`()`}`:Array.isArray(t)?t.length===0?`${n}=()`:t.length===1&&t[0]===`*`?`${n}=*`:t.length===1&&t[0]===`none`?`${n}=()`:`${n}=(${t.map(e=>[`self`,`src`].includes(e)?e:`"${e}"`).join(` `)})`:``}).filter(Boolean).join(`, `)}function xb(e){return e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).toLowerCase()}function Sb(e=[]){return e.map(e=>`${e.name}="${e.url}"`).join(`, `)}function Cb(e=[]){return e.map(e=>JSON.stringify(e)).join(`, `)}function wb(e,t){t.forEach(([t,n])=>{e.res.headers.set(t,n)})}var Tb=e=>async function(t,n){if(e?.alwaysRedirect&&(t.req.method===`GET`||t.req.method===`HEAD`)&&t.req.path!==`/`&&t.req.path.at(-1)===`/`){let e=new URL(t.req.url);return e.pathname=e.pathname.substring(0,e.pathname.length-1),t.redirect(e.toString(),301)}if(await n(),!e?.alwaysRedirect&&t.res.status===404&&(t.req.method===`GET`||t.req.method===`HEAD`)&&t.req.path!==`/`&&t.req.path.at(-1)===`/`){let e=new URL(t.req.url);e.pathname=e.pathname.substring(0,e.pathname.length-1),t.res=t.redirect(e.toString(),301)}};function Eb(e,t,n){let r=ve(e,t,n);if(r.type!==`event`)throw new We({name:t,type:`event`});return r}function Db(e){return ye(e)}function Ob(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function kb(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(e=>typeof e==`string`):t.every(e=>Number.isSafeInteger(e)):!1}function Ab(e){if(typeof e!=`function`)throw Error(`function expected`);return!0}function jb(e,t){if(typeof t!=`string`)throw Error(`${e}: string expected`);return!0}function Mb(e){if(!Number.isSafeInteger(e))throw Error(`invalid integer: ${e}`)}function Nb(e){if(!Array.isArray(e))throw Error(`array expected`)}function Pb(e,t){if(!kb(!0,t))throw Error(`${e}: array of strings expected`)}function Fb(e,t){if(!kb(!1,t))throw Error(`${e}: array of numbers expected`)}function Ib(...e){let t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function Lb(e){let t=typeof e==`string`?e.split(``):e,n=t.length;Pb(`alphabet`,t);let r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(Nb(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(Nb(t),t.map(t=>{jb(`alphabet.decode`,t);let n=r.get(t);if(n===void 0)throw Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function Rb(e=``){return jb(`join`,e),{encode:t=>(Pb(`join.decode`,t),t.join(e)),decode:t=>(jb(`join.decode`,t),t.split(e))}}function zb(e,t=`=`){return Mb(e),jb(`padding`,t),{encode(n){for(Pb(`padding.encode`,n);n.length*e%8;)n.push(t);return n},decode(n){Pb(`padding.decode`,n);let r=n.length;if(r*e%8)throw Error(`padding: invalid, string should have whole number of bytes`);for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8==0)throw Error(`padding: invalid, string has too much padding`);return n.slice(0,r)}}}function Bb(e){return Ab(e),{encode:e=>e,decode:t=>e(t)}}function Vb(e,t,n){if(t<2)throw Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Nb(e),!e.length)return[];let r=0,i=[],a=Array.from(e,e=>{if(Mb(e),e<0||e>=t)throw Error(`invalid integer: ${e}`);return e}),o=a.length;for(;;){let e=0,s=!0;for(let i=r;i<o;i++){let o=a[i],c=t*e,l=c+o;if(!Number.isSafeInteger(l)||c/t!==e||l-o!==c)throw Error(`convertRadix: carry overflow`);let u=l/n;e=l%n;let d=Math.floor(u);if(a[i]=d,!Number.isSafeInteger(d)||d*n+e!==l)throw Error(`convertRadix: carry overflow`);if(s)d?s=!1:r=i;else continue}if(i.push(e),s)break}for(let t=0;t<e.length-1&&e[t]===0;t++)i.push(0);return i.reverse()}var Hb=(e,t)=>t===0?e:Hb(t,e%t),Ub=(e,t)=>e+(t-Hb(e,t)),Wb=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Gb(e,t,n,r){if(Nb(e),t<=0||t>32)throw Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw Error(`convertRadix2: wrong to=${n}`);if(Ub(t,n)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Ub(t,n)}`);let i=0,a=0,o=Wb[t],s=Wb[n]-1,c=[];for(let r of e){if(Mb(r),r>=o)throw Error(`convertRadix2: invalid data word=${r} from=${t}`);if(i=i<<t|r,a+t>32)throw Error(`convertRadix2: carry overflow pos=${a} from=${t}`);for(a+=t;a>=n;a-=n)c.push((i>>a-n&s)>>>0);let e=Wb[a];if(e===void 0)throw Error(`invalid carry`);i&=e-1}if(i=i<<n-a&s,!r&&a>=t)throw Error(`Excess padding`);if(!r&&i>0)throw Error(`Non-zero padding: ${i}`);return r&&a>0&&c.push(i>>>0),c}function Kb(e){return Mb(e),{encode:t=>{if(!Ob(t))throw Error(`radix.encode input should be Uint8Array`);return Vb(Array.from(t),256,e)},decode:t=>(Fb(`radix.decode`,t),Uint8Array.from(Vb(t,e,256)))}}function qb(e,t=!1){if(Mb(e),e<=0||e>32)throw Error(`radix2: bits should be in (0..32]`);if(Ub(8,e)>32||Ub(e,8)>32)throw Error(`radix2: carry overflow`);return{encode:n=>{if(!Ob(n))throw Error(`radix2.encode input should be Uint8Array`);return Gb(Array.from(n),8,e,!t)},decode:n=>(Fb(`radix2.decode`,n),Uint8Array.from(Gb(n,e,8,t)))}}function Jb(e){return Ab(e),function(...t){try{return e.apply(null,t)}catch{}}}Ib(qb(4),Lb(`0123456789ABCDEF`),Rb(``));var Yb=Ib(qb(5),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`),zb(5),Rb(``));Ib(qb(5),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHIJKLMNOPQRSTUV`),zb(5),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHIJKLMNOPQRSTUV`),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHJKMNPQRSTVWXYZ`),Rb(``),Bb(e=>e.toUpperCase().replace(/O/g,`0`).replace(/[IL]/g,`1`)));var Xb=typeof Uint8Array.from([]).toBase64==`function`&&typeof Uint8Array.fromBase64==`function`;Xb||Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`),zb(6),Rb(``)),Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`),Rb(``)),Xb||Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`),zb(6),Rb(``)),Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`),Rb(``));var Zb=(e=>Ib(Kb(58),Lb(e),Rb(``)))(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`),Qb=Ib(Lb(`qpzry9x8gf2tvdw0s3jn54khce6mua7l`),Rb(``)),$b=[996825010,642813549,513874426,1027748829,705979059];function ex(e){let t=e>>25,n=(e&33554431)<<5;for(let e=0;e<$b.length;e++)(t>>e&1)==1&&(n^=$b[e]);return n}function tx(e,t,n=1){let r=e.length,i=1;for(let t=0;t<r;t++){let n=e.charCodeAt(t);if(n<33||n>126)throw Error(`Invalid prefix (${e})`);i=ex(i)^n>>5}i=ex(i);for(let t=0;t<r;t++)i=ex(i)^e.charCodeAt(t)&31;for(let e of t)i=ex(i)^e;for(let e=0;e<6;e++)i=ex(i);return i^=n,Qb.encode(Gb([i%Wb[30]],30,5,!1))}function nx(e){let t=e===`bech32`?1:734539939,n=qb(5),r=n.decode,i=n.encode,a=Jb(r);function o(e,n,r=90){jb(`bech32.encode prefix`,e),Ob(n)&&(n=Array.from(n)),Fb(`bech32.encode`,n);let i=e.length;if(i===0)throw TypeError(`Invalid prefix length ${i}`);let a=i+7+n.length;if(r!==!1&&a>r)throw TypeError(`Length ${a} exceeds limit ${r}`);let o=e.toLowerCase(),s=tx(o,n,t);return`${o}1${Qb.encode(n)}${s}`}function s(e,n=90){jb(`bech32.decode input`,e);let r=e.length;if(r<8||n!==!1&&r>n)throw TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);let i=e.toLowerCase();if(e!==i&&e!==e.toUpperCase())throw Error(`String must be lowercase or uppercase`);let a=i.lastIndexOf(`1`);if(a===0||a===-1)throw Error(`Letter "1" must be present between prefix and data only`);let o=i.slice(0,a),s=i.slice(a+1);if(s.length<6)throw Error(`Data must be at least 6 characters long`);let c=Qb.decode(s).slice(0,-6),l=tx(o,c,t);if(!s.endsWith(l))throw Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:o,words:c}}let c=Jb(s);function l(e){let{prefix:t,words:n}=s(e,!1);return{prefix:t,words:n,bytes:r(n)}}function u(e,t){return o(e,i(t))}return{encode:o,decode:s,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:a,toWords:i}}nx(`bech32`),nx(`bech32m`),typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`||Ib(qb(4),Lb(`0123456789abcdef`),Rb(``),Bb(e=>{if(typeof e!=`string`||e.length%2!=0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));var rx=BigInt(0),ix=BigInt(1);function ax(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function ox(e,t,n=``){let r=Ct(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function sx(e){let t=e.toString(16);return t.length&1?`0`+t:t}function cx(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?rx:BigInt(`0x`+e)}function lx(e){return cx(St(e))}function ux(e){return Et(e),cx(St(Uint8Array.from(e).reverse()))}function dx(e,t){return wt(e.toString(16).padStart(t*2,`0`))}function fx(e,t){return dx(e,t).reverse()}function px(e,t,n){let r;if(typeof t==`string`)try{r=wt(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(Ct(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}var mx=e=>typeof e==`bigint`&&rx<=e;function hx(e,t,n){return mx(e)&&mx(t)&&mx(n)&&t<=e&&e<n}function gx(e,t,n,r){if(!hx(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function _x(e){let t=0;for(;e>rx;e>>=ix,t+=1);return t}var vx=e=>(ix<<BigInt(e))-ix;function yx(e,t,n){if(typeof e!=`number`||e<2)throw Error(`hashLen must be a number`);if(typeof t!=`number`||t<2)throw Error(`qByteLen must be a number`);if(typeof n!=`function`)throw Error(`hmacFn must be a function`);let r=e=>new Uint8Array(e),i=e=>Uint8Array.of(e),a=r(e),o=r(e),s=0,c=()=>{a.fill(1),o.fill(0),s=0},l=(...e)=>n(o,a,...e),u=(e=r(0))=>{o=l(i(0),e),a=l(),e.length!==0&&(o=l(i(1),e),a=l())},d=()=>{if(s++>=1e3)throw Error(`drbg: tried 1000 values`);let e=0,n=[];for(;e<t;){a=l();let t=a.slice();n.push(t),e+=a.length}return bt(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function bx(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function xx(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var Sx=BigInt(0),Cx=BigInt(1),wx=BigInt(2),Tx=BigInt(3),Ex=BigInt(4),Dx=BigInt(5),Ox=BigInt(7),kx=BigInt(8),Ax=BigInt(9),jx=BigInt(16);function Mx(e,t){let n=e%t;return n>=Sx?n:t+n}function Nx(e,t){if(e===Sx)throw Error(`invert: expected non-zero number`);if(t<=Sx)throw Error(`invert: expected positive modulus, got `+t);let n=Mx(e,t),r=t,i=Sx,a=Cx,o=Cx,s=Sx;for(;n!==Sx;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==Cx)throw Error(`invert: does not exist`);return Mx(i,t)}function Px(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Fx(e,t){let n=(e.ORDER+Cx)/Ex,r=e.pow(t,n);return Px(e,r,t),r}function Ix(e,t){let n=(e.ORDER-Dx)/kx,r=e.mul(t,wx),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,wx),i),s=e.mul(a,e.sub(o,e.ONE));return Px(e,s,t),s}function Lx(e){let t=Kx(e),n=Rx(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Ox)/jx;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Px(e,p,t),p}}function Rx(e){if(e<Tx)throw Error(`sqrt is not defined for small field`);let t=e-Cx,n=0;for(;t%wx===Sx;)t/=wx,n++;let r=wx,i=Kx(e);for(;Wx(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Fx;let a=i.pow(r,t),o=(t+Cx)/wx;return function(e,r){if(e.is0(r))return r;if(Wx(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=Cx<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function zx(e){return e%Ex===Tx?Fx:e%kx===Dx?Ix:e%jx===Ax?Lx(e):Rx(e)}var Bx=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Vx(e){return bx(e,Bx.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Hx(e,t,n){if(n<Sx)throw Error(`invalid exponent, negatives unsupported`);if(n===Sx)return e.ONE;if(n===Cx)return t;let r=e.ONE,i=t;for(;n>Sx;)n&Cx&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Cx;return r}function Ux(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function Wx(e,t){let n=(e.ORDER-Cx)/wx,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function Gx(e,t){t!==void 0&&yt(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Kx(e,t,n=!1,r={}){if(e<=Sx)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=Gx(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:vx(c),ZERO:Sx,ONE:Cx,allowedLengths:s,create:t=>Mx(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return Sx<=t&&t<e},is0:e=>e===Sx,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Cx)===Cx,neg:t=>Mx(-t,e),eql:(e,t)=>e===t,sqr:t=>Mx(t*t,e),add:(t,n)=>Mx(t+n,e),sub:(t,n)=>Mx(t-n,e),mul:(t,n)=>Mx(t*n,e),pow:(e,t)=>Hx(d,e,t),div:(t,n)=>Mx(t*Nx(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Nx(t,e),sqrt:a||(t=>(u||=zx(e),u(d,t))),toBytes:e=>n?fx(e,l):dx(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?ux(t):lx(t);if(o&&(i=Mx(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>Ux(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function qx(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function Jx(e){let t=qx(e);return t+Math.ceil(t/2)}function Yx(e,t,n=!1){let r=e.length,i=qx(t),a=Jx(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=Mx(n?ux(e):lx(e),t-Cx)+Cx;return n?fx(o,i):dx(o,i)}var Xx=BigInt(0),Zx=BigInt(1);function Qx(e,t){let n=t.negate();return e?n:t}function $x(e,t){let n=Ux(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function eS(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function tS(e,t){eS(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:vx(e),maxNumber:i,shiftBy:BigInt(e)}}function nS(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=Zx);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function rS(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function iS(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var aS=new WeakMap,oS=new WeakMap;function sS(e){return oS.get(e)||1}function cS(e){if(e!==Xx)throw Error(`invalid wNAF`)}var lS=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Xx;)t&Zx&&(n=n.add(r)),r=r.double(),t>>=Zx;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=tS(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=tS(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=nS(n,e,a);n=o,c?i=i.add(Qx(u,t[d])):r=r.add(Qx(l,t[s]))}return cS(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=tS(e,this.bits);for(let e=0;e<i.windows&&n!==Xx;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=nS(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return cS(n),r}getPrecomputes(e,t,n){let r=aS.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),aS.set(t,r))),r}cached(e,t,n){let r=sS(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=sS(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){eS(t,this.bits),oS.set(e,t),aS.delete(e)}hasCache(e){return sS(e)!==1}};function uS(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>Xx||r>Xx;)n&Zx&&(a=a.add(i)),r&Zx&&(o=o.add(i)),i=i.double(),n>>=Zx,r>>=Zx;return{p1:a,p2:o}}function dS(e,t,n,r){rS(n,e),iS(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=_x(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=vx(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function fS(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Vx(t),t}return Kx(e,{isLE:n})}function pS(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>Xx))throw Error(`CURVE.${e} must be positive bigint`)}let i=fS(t.p,n.Fp,r),a=fS(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var mS=(e,t)=>(e+(e>=0?t:-t)/xS)/t;function hS(e,t,n){let[[r,i],[a,o]]=t,s=mS(o*e,n),c=mS(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<yS,f=u<yS;d&&(l=-l),f&&(u=-u);let p=vx(Math.ceil(_x(n)/2))+bS;if(l<yS||l>=p||u<yS||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function gS(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function _S(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return ax(n.lowS,`lowS`),ax(n.prehash,`prehash`),n.format!==void 0&&gS(n.format),n}var vS={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=vS;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length&1)throw new n(`tlv.encode: unpadded data`);let r=t.length/2,i=sx(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?sx(i.length/2|128):``;return sx(e)+a+i+t},decode(e,t){let{Err:n}=vS,r=0;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length<2||t[r++]!==e)throw new n(`tlv.decode: wrong tlv`);let i=t[r++],a=!!(i&128),o=0;if(!a)o=i;else{let e=i&127;if(!e)throw new n(`tlv.decode(long): indefinite length not supported`);if(e>4)throw new n(`tlv.decode(long): byte length is too big`);let a=t.subarray(r,r+e);if(a.length!==e)throw new n(`tlv.decode: length bytes not complete`);if(a[0]===0)throw new n(`tlv.decode(long): zero leftmost byte`);for(let e of a)o=o<<8|e;if(r+=e,o<128)throw new n(`tlv.decode(long): not minimal encoding`)}let s=t.subarray(r,r+o);if(s.length!==o)throw new n(`tlv.decode: wrong value length`);return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){let{Err:t}=vS;if(e<yS)throw new t(`integer: negative integers are not allowed`);let n=sx(e);if(Number.parseInt(n[0],16)&8&&(n=`00`+n),n.length&1)throw new t(`unexpected DER parsing assertion: unpadded hex`);return n},decode(e){let{Err:t}=vS;if(e[0]&128)throw new t(`invalid signature integer: negative`);if(e[0]===0&&!(e[1]&128))throw new t(`invalid signature integer: unnecessary leading zero`);return lx(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=vS,i=px(`signature`,e),{v:a,l:o}=r.decode(48,i);if(o.length)throw new t(`invalid signature: left bytes after parsing`);let{v:s,l:c}=r.decode(2,a),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t(`invalid signature: left bytes after parsing`);return{r:n.decode(s),s:n.decode(l)}},hexFromSig(e){let{_tlv:t,_int:n}=vS,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},yS=BigInt(0),bS=BigInt(1),xS=BigInt(2),SS=BigInt(3),CS=BigInt(4);function wS(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=px(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function TS(e,t={}){let n=pS(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;bx(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=DS(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);if(ax(n,`isCompressed`),n){u();let e=!r.isOdd(a);return bt(ES(e),o)}return bt(Uint8Array.of(4),o,r.toBytes(a))}function f(e){ox(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,SS),CS),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof E))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return hS(e,c.basises,i.ORDER)}let S=xx((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),C=xx(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function w(e,t,n,i,a){return n=new E(r.mul(n.X,e),n.Y,n.Z),t=Qx(i,t),n=Qx(a,n),t.add(n)}class E{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof E)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?E.ZERO:new E(t,n,r.ONE)}static fromBytes(e){let t=E.fromAffine(m(ox(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return E.fromBytes(px(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return O.createCache(this,e),t||this.multiply(SS),this}assertValidity(){C(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new E(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,SS),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new E(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,SS),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new E(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(E.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>O.cached(this,e,e=>$x(E,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=w(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return $x(E,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===yS||r.is0())return E.ZERO;if(e===bS)return r;if(O.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=uS(E,r,i,o);return w(n.beta,s,c,t,a)}return O.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return S(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===bS?!0:e?e(E,this):O.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===bS?this:e?e(E,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return ax(e,`isCompressed`),this.assertValidity(),p(E,this,e)}toHex(e=!0){return St(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return $x(E,e)}static msm(e,t){return dS(E,i,e,t)}static fromPrivateKey(e){return E.BASE.multiply(wS(i,e))}}E.BASE=new E(a.Gx,a.Gy,r.ONE),E.ZERO=new E(r.ZERO,r.ONE,r.ZERO),E.Fp=r,E.Fn=i;let D=i.BITS,O=new lS(E,t.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function ES(e){return Uint8Array.of(e?2:3)}function DS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function OS(e,t={}){let{Fn:n}=e,r=t.randomBytes||Tt,i=Object.assign(DS(e.Fp,n),{seed:Jx(n.ORDER)});function a(e){try{return!!wS(n,e)}catch{return!1}}function o(t,n){let{publicKey:r,publicKeyUncompressed:a}=i;try{let i=t.length;return n===!0&&i!==r||n===!1&&i!==a?!1:!!e.fromBytes(t)}catch{return!1}}function s(e=r(i.seed)){return Yx(ox(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(wS(n,t)).toBytes(r)}function l(e){let t=s(e);return{secretKey:t,publicKey:c(t)}}function u(t){if(typeof t==`bigint`)return!1;if(t instanceof e)return!0;let{secretKey:r,publicKey:a,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===a)return;let s=px(`key`,t).length;return s===a||s===o}function d(t,r,i=!0){if(u(t)===!0)throw Error(`first arg must be private key`);if(u(r)===!1)throw Error(`second arg must be public key`);let a=wS(n,t);return e.fromHex(r).multiply(a).toBytes(i)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:a,isValidPublicKey:o,randomSecretKey:s,isValidPrivateKey:a,randomPrivateKey:s,normPrivateKeyToScalar:e=>wS(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function kS(e,t,n={}){xt(t),bx(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||Tt,i=n.hmac||((e,...n)=>Ot(t,e,bt(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=OS(e,n),m={prehash:!1,lowS:typeof n.lowS==`boolean`&&n.lowS,format:void 0,extraEntropy:!1},h=`compact`;function g(e){return e>s>>bS}function _(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function v(e,t){gS(t);let n=p.signature;return ox(e,t===`compact`?n:t===`recovered`?n+1:void 0,`${t} signature`)}class y{constructor(e,t,n){this.r=_(`r`,e),this.s=_(`s`,t),n!=null&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=h){v(e,t);let n;if(t===`der`){let{r:t,s:n}=vS.toSig(ox(e));return new y(t,n)}t===`recovered`&&(n=e[0],t=`compact`,e=e.subarray(1));let r=o.BYTES,i=e.subarray(0,r),a=e.subarray(r,r*2);return new y(o.fromBytes(i),o.fromBytes(a),n)}static fromHex(e,t){return this.fromBytes(wt(e),t)}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(t){let n=a.ORDER,{r,s:i,recovery:c}=this;if(c==null||![0,1,2,3].includes(c))throw Error(`recovery id invalid`);if(s*xS<n&&c>1)throw Error(`recovery id is ambiguous for h>1 curve`);let l=c===2||c===3?r+s:r;if(!a.isValid(l))throw Error(`recovery id 2 or 3 invalid`);let u=a.toBytes(l),d=e.fromBytes(bt(ES(!(c&1)),u)),f=o.inv(l),p=x(px(`msgHash`,t)),m=o.create(-p*f),h=o.create(i*f),g=e.BASE.multiplyUnsafe(m).add(d.multiplyUnsafe(h));if(g.is0())throw Error(`point at infinify`);return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=h){if(gS(e),e===`der`)return wt(vS.hexFromSig(this));let t=o.toBytes(this.r),n=o.toBytes(this.s);if(e===`recovered`){if(this.recovery==null)throw Error(`recovery bit must be present`);return bt(Uint8Array.of(this.recovery),t,n)}return bt(t,n)}toHex(e){return St(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(px(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(px(`sig`,e),`der`)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes(`der`)}toDERHex(){return St(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return St(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=lx(e),n=e.length*8-c;return n>0?t>>BigInt(n):t},x=n.bits2int_modN||function(e){return o.create(b(e))},S=vx(c);function C(e){return gx(`num < 2^`+c,e,yS,S),o.toBytes(e)}function w(e,n){return ox(e,void 0,`message`),n?ox(t(e),void 0,`prehashed message`):e}function E(t,n,i){if([`recovered`,`canonical`].some(e=>e in i))throw Error(`sign() legacy options not supported`);let{lowS:a,prehash:s,extraEntropy:c}=_S(i,m);t=w(t,s);let l=x(t),u=wS(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(px(`extraEntropy`,e))}let f=bt(...d),h=l;function _(t){let n=b(t);if(!o.isValidNot0(n))return;let r=o.inv(n),i=e.BASE.multiply(n).toAffine(),s=o.create(i.x);if(s===yS)return;let c=o.create(r*o.create(h+s*u));if(c===yS)return;let l=(i.x===s?0:2)|Number(i.y&bS),d=c;return a&&g(c)&&(d=o.neg(c),l^=1),new y(s,d,l)}return{seed:f,k2sig:_}}function D(e,n,r={}){e=px(`message`,e);let{seed:a,k2sig:s}=E(e,n,r);return yx(t.outputLen,o.BYTES,i)(a,s)}function O(e){let t,n=typeof e==`string`||Ct(e),r=!n&&typeof e==`object`&&!!e&&typeof e.r==`bigint`&&typeof e.s==`bigint`;if(!n&&!r)throw Error(`invalid signature, expected Uint8Array, hex string or Signature instance`);if(r)t=new y(e.r,e.s);else if(n){try{t=y.fromBytes(px(`sig`,e),`der`)}catch(e){if(!(e instanceof vS.Err))throw e}if(!t)try{t=y.fromBytes(px(`sig`,e),`compact`)}catch{return!1}}return t||!1}function k(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=_S(i,m);if(r=px(`publicKey`,r),n=w(px(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?O(t):y.fromBytes(px(`sig`,t),c);if(l===!1)return!1;try{let t=e.fromBytes(r);if(a&&l.hasHighS())return!1;let{r:i,s}=l,c=x(n),u=o.inv(s),d=o.create(c*u),f=o.create(i*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(f));return!p.is0()&&o.create(p.x)===i}catch{return!1}}function A(e,t,n={}){let{prehash:r}=_S(n,m);return t=w(t,r),y.fromBytes(e,`recovered`).recoverPublicKey(t).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p,Point:e,sign:D,verify:k,recoverPublicKey:A,Signature:y,hash:t})}function AS(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Kx(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function jS(e){let{CURVE:t,curveOpts:n}=AS(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function MS(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Gx(n.Fn.ORDER,n.Fn.BITS))})}function NS(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=jS(e);return MS(e,kS(TS(t,n),r,i))}function PS(e,t){let n=t=>NS({...e,hash:t});return{...n(t),create:n}}var FS=class extends Error{constructor(e){let{cause:t,code:n,message:r,data:i,stack:a}=e;super(r,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.BaseError`}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t,this.code=n,this.data=i,this.stack=a??``}};Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Missing or invalid parameters.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidInputError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Requested resource not found.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ResourceNotFoundError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Requested resource not available.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ResourceUnavailableError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});var IS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Transaction creation failed.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.TransactionRejectedError`})}};Object.defineProperty(IS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Method is not implemented.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.MethodNotSupportedError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});var LS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Rate limit exceeded.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.LimitExceededError`})}};Object.defineProperty(LS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`JSON-RPC version not supported.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.VersionNotSupportedError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Input is not a valid JSON-RPC request.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidRequestError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Method does not exist.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.MethodNotFoundError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});var RS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Invalid method parameters.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidParamsError`})}};Object.defineProperty(RS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});var zS=class e extends FS{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??`Internal JSON-RPC error.`,stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InternalError`})}};Object.defineProperty(zS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Failed to parse JSON-RPC response.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ParseError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});var BS=`<redacted>`,VS=`VOID_ENV_UNMASK`;function HS(e,t,n={}){return n.unmask||typeof e!=`string`||e.length===0?t:t.split(e).join(BS)}var US=null;function WS(){if(US!==null)return US;try{US=globalThis.process?.env?.[VS]===`1`}catch{US=!1}return US&&console.error(`[void/env] ${VS}=1 is set — env validation errors will include raw values. Unset it before sharing logs.`),US}var GS=Symbol.for(`void.env.registry`),KS=globalThis,qS=KS[GS]??={schema:null,hasDefineEnvBeenCalled:!1,bootValidation:null},JS=new WeakMap,YS=[];function XS(e){let t=JS.get(e);return t||(t=new Map,JS.set(e,t),YS.push(t)),t}function ZS(){return Object.fromEntries(Object.entries({BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!0,TSS_DEV_SERVER:`false`,TSS_DEV_SSR_STYLES_BASEPATH:`/`,TSS_DEV_SSR_STYLES_ENABLED:`true`,TSS_DISABLE_CSRF_MIDDLEWARE_WARNING:`false`,TSS_INLINE_CSS_ENABLED:`false`,TSS_ROUTER_BASEPATH:``,TSS_SERVER_FN_BASE:`/_serverFn/`}).filter(([e])=>e.startsWith(`VITE_`)))}var QS=class extends Error{key;issues;constructor(e,t){super(`Invalid env "${e}": ${t.map(e=>e.message).join(`, `)}`),this.name=`EnvValidationError`,this.key=e,this.issues=t}};function $S(e){let t=dy();if(_y(e,t))return;let n=yy(),r=ZS(),i=Object.hasOwn(r,e)?r[e]:n[e];if(!qS.schema)return i;let a=qS.schema[e];if(!a)return i;let o=XS(t);if(o.has(e))return o.get(e);let s=a[`~standard`].validate(i);if(s instanceof Promise)throw Error(`env: Async validator for '${e}' cannot be resolved synchronously. Proxy property access is synchronous, so async Standard Schema validators must be pre-resolved by calling \`_validateEnvOnce(env)\` at worker boot (Void splices this into the generated entry) or by awaiting \`validateAllEnv(env)\` before the first \`env.${e}\` read. Once pre-validated, the resolved value is cached and served synchronously here.`);if(s.issues){let t=WS();throw new QS(e,s.issues.map(e=>({...e,message:HS(i,e.message,{unmask:t})})))}return o.set(e,s.value),s.value}var U=new Proxy({},{get(e,t){if(typeof t!=`symbol`)return $S(t)},has(e,t){return typeof t==`symbol`?!1:Object.hasOwn(ZS(),t)||Reflect.has(yy(),t)},ownKeys(){return[...new Set([...Reflect.ownKeys(yy()),...Object.keys(ZS())])]},getOwnPropertyDescriptor(e,t){if(typeof t!=`symbol`)return{enumerable:!0,configurable:!0,value:$S(String(t))}}});function eC(e={}){let t=e.challenge??ut(32);return{challenge:t,options:Bt(Ut({...e,challenge:t}))}}function tC(e,t){let n=Vt(e);return Wt({...t,metadata:n.metadata,publicKey:Mt(t.publicKey),signature:n.signature})}function nC(e){try{let{authData:t}=Jt(Ft(e.attestationObject));return t.length<53?void 0:rC(t.subarray(37,53))}catch{return}}function rC(e){let t=dt(e).slice(2);return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20,32)].join(`-`)}function iC(e={}){let t=e.challenge??ut(32);return{challenge:t,options:Rt(Gt({...e,challenge:t}))}}function aC(e,t){let n=Un(e),r=Ht({...t,credential:n});return{...zt(r),aaguid:nC(e)}}function oC(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var sC;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(sC=`jose/v6.2.12`);var cC=Symbol();async function lC(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new ba:e});if(i.status!==200)throw new Mi(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new Mi(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var uC=Symbol();function dC(e,t){return Number.isFinite(e)&&Date.now()<e+t}function fC(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function pC(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=fC(r.cooldownDuration,3e4,`cooldownDuration`),s=fC(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);sC&&!c.has(`User-Agent`)&&c.set(`User-Agent`,sC),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[cC],u=r[uC],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;dC(e,s)&&Fi(t)&&(d=e,h=wi(t))}let g=async()=>{if(f&&oC()&&(f=void 0),!f){let e=++p,t=f=lC(n,c,AbortSignal.timeout(a),l).then(t=>{let n=wi(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!dC(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof fi&&!dC(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>dC(d,o),enumerable:!0},fresh:{get:()=>dC(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}var mC={N:16384,r:16,p:1,dkLen:64};function hC(e,t){return new Promise((n,r)=>{eee(e.normalize(`NFKC`),t,mC.dkLen,{N:mC.N,r:mC.r,p:mC.p,maxmem:128*mC.N*mC.r*2},(e,t)=>{e?r(e):n(t)})})}async function gC(e){let t=Jo(16).toString(`hex`);return`${t}:${(await hC(e,t)).toString(`hex`)}`}async function _C(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await hC(t,n)).toString(`hex`)===r}var vC=gC,yC=async({hash:e,password:t})=>_C(e,t),bC=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],xC=new Set(bC);async function SC({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let b=ci(t.clientId);if(!b)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,b),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await oa(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))xC.has(e)||y.searchParams.set(e,t);return y}var CC=Wn(R(),R()).refine(e=>!Object.keys(e).some(e=>xC.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${bC.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional();function wC(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function TC(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function EC(e,t){t&&e.set(`client_id`,t)}function DC(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function OC(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function kC({body:e,options:t,clientId:n,requireClientSecret:r}){r&&DC(`client_secret_post`,t),t.clientSecret&&(OC(`client_secret_post`,n),EC(e,n),e.set(`client_secret`,t.clientSecret))}function AC({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);DC(`client_secret_basic`,t),OC(`client_secret_basic`,n),e.authorization=Pr(n,t.clientSecret)}function jC(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function MC({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){jC(e);let s=ci(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);TC(`private_key_jwt`,n,e),EC(e,s);return}let c=a??wC(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),jC(e);else if(c.method===`private_key_jwt`){if(TC(c.method,n,e),OC(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await ii({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});EC(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(TC(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);OC(c.method,s),EC(e,s)}else c.method===`client_secret_basic`?AC({headers:t,options:n,clientId:s,body:e}):kC({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}var NC=new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function PC({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=IC({refreshToken:e,options:t,extraParams:a,resource:o});return await MC({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function FC(e,t){if(t)for(let[n,r]of Object.entries(t))NC.has(n)||e.set(n,r)}function IC({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&FC(i,n),{body:i,headers:a}}async function LC({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await PC({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await Or(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:ui(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date(new Date().getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date(new Date().getTime()+l.refresh_token_expires_in*1e3)),d}async function RC({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=zC({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await MC({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function zC({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function BC({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await RC({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await Or(i,{method:`POST`,body:d,headers:f});if(m)throw m;return Mr(p)}var VC=30,HC=[`iss`,`sub`,`aud`,`exp`,`iat`];function UC(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:HC,clockTolerance:VC}}async function WC(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function GC(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await WC(t):!1}async function vee(e,t,n){if(![t.audience].flat().some(Boolean))throw Error(`ID token audience is not configured`);let r=await ra(e,t.jwks,UC(t));if(n&&!await GC(r.payload.nonce,n,t.nonceComparison))throw Error(`ID token nonce does not match`);if(t.verifyClaims&&!t.verifyClaims(r.payload))throw Error(`ID token claims were rejected`);return r}function KC(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function qC(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;return a?`verify`in a?await a.verify(t,n,r):t.split(`.`).length===3?(await vee(t,a,n),!0):a.allowOpaqueToken===!0:!1}catch{return!1}}var JC=/[\u0000-\u001f\u007f-\u009f]/,YC=`https://better-auth.invalid`,XC=/%2[fF]|%5[cC]/,ZC=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},QC=e=>{if(JC.test(e))return null;let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=r.search(/[?#]/),o=ZC(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},$C=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||JC.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(XC.test(n))return!1;try{return new URL(e,YC).origin===YC}catch{return!1}},ew=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&$C(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return vr(t)(xa(e)||e);let n=pi(e);return n?vr(t)(n):!1}let r=Aa(e);if(r===`http:`||r===`https:`||!r)return t===xa(e);let i=QC(e),a=QC(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function tw(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function nw(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function rw(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=Ii(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}var iw=tw(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),aw=Qr(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await sw(e),rw(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw V.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?V.from(`FORBIDDEN`,B.INVALID_ORIGIN):n===`callbackURL`?V.from(`FORBIDDEN`,B.INVALID_CALLBACK_URL):n===`redirectURL`?V.from(`FORBIDDEN`,B.INVALID_REDIRECT_URL):n===`errorCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_NEW_USER_CALLBACK_URL):V.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),ow=e=>Qr(async t=>{if(!t.request||rw(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?V.from(`FORBIDDEN`,B.INVALID_ORIGIN):n===`callbackURL`?V.from(`FORBIDDEN`,B.INVALID_CALLBACK_URL):n===`redirectURL`?V.from(`FORBIDDEN`,B.INVALID_REDIRECT_URL):n===`errorCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_NEW_USER_CALLBACK_URL):V.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function sw(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`),i=r||n.get(`referer`)||``,a=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(nw(e)){e.context.options.advanced?.disableOriginCheck===!0&&iw();return}if(rw(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?Ni(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?xa(o):void 0)??i;if(!s||s===`null`)throw V.from(`FORBIDDEN`,B.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!c.some(e=>ew(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${c}`),V.from(`FORBIDDEN`,B.INVALID_ORIGIN)}var cw=Qr(async e=>{e.request&&await lw(e)});async function lw(e){let t=e.request;if(!t||e.context.skipCSRFCheck||nw(e))return;let n=t.headers;if(n.has(`cookie`))return await sw(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),V.from(`FORBIDDEN`,B.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await sw(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await sw(e,!0)}var uw=new Map,dw=1e5;function fw(){let e=Date.now();for(let[t,n]of uw)e>=n.expiresAt&&uw.delete(t);if(uw.size<=dw)return;let t=uw.size-dw,n=0;for(let e of uw.keys())if(uw.delete(e),++n>=t)break}function pw(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:hw(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function mw(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"Content-Type":`application/json`,"X-Retry-After":e.toString()}})}function hw(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function gw(e){let t=`rateLimit`,n=e.adapter,r=Math.max(..._w(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return r&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:hw(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function _w(e){let t=[e.rateLimit.window,...Cw().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function vw(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new H(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){fw();let r=Date.now(),i=uw.get(e),a=pw(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&uw.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return gw(e)}var yw=!1,bw=`no-trusted-ip`;async function xw(e,t){let n=new URL(t.baseURL).pathname,r=Ii(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=ia(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!yw&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),yw=!0);let s=Ti(o??bw,r),c=Cw().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?vr(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function Sw(e,t){if(!t.rateLimit.enabled)return;let n=await xw(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=vw(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return mw(l??i)}function Cw(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}var ww=`better-auth.session-cache+jwt`,Tw=`better-auth:session-cache`;function Ew(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function Dw(e){let t=ja(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}function Ow(e){if(!e?.method)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function kw(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;Ow(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new V(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new V(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}var Aw=async e=>{let t=await ca(`SHA-256`).digest(new TextEncoder().encode(e));return Ia.encode(new Uint8Array(t),{padding:!1})};async function jw(e,t){return!t||t===`plain`?e:t===`hashed`?Aw(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function Mw(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}function Nw(e,t){let n=qa(t.options),r=t.hooks;async function i(t,i,a){let o=br(),s=t;for(let{source:e,hooks:t}of r){let r=t[i]?.create?.before;if(r){let t=await n(`db create.before ${i}`,{[Qa]:`create.before`,[no]:i,[to]:e},()=>r(s,o));if(t===!1)return null;typeof t==`object`&&`data`in t&&(s={...s,...t.data})}}let c=null;(!a||a.executeMainFn)&&(c=await(await gi(e)).create({model:i,data:s,forceAllowId:!0})),a?.fn&&(c=await a.fn(c??s));for(let{source:e,hooks:t}of r){let r=t[i]?.create?.after;r&&await ta(async()=>{await n(`db create.after ${i}`,{[Qa]:`create.after`,[no]:i,[to]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=br(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db update.before ${a}`,{[Qa]:`update.before`,[no]:a,[to]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await gi(e)).update({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await ta(async()=>{await n(`db update.after ${a}`,{[Qa]:`update.after`,[no]:a,[to]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=br(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db updateMany.before ${a}`,{[Qa]:`updateMany.before`,[no]:a,[to]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await gi(e)).updateMany({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await ta(async()=>{await n(`db updateMany.after ${a}`,{[Qa]:`updateMany.after`,[no]:a,[to]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=br(),s=null;try{s=(await(await gi(e)).findMany({model:i,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":e},()=>r(s,o))===!1)return null}let c=a?await a.fn(t):null,l=(!a||a.executeMainFn)&&s?await(await gi(e)).delete({model:i,where:t}):c;if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${i}`,{[Qa]:`delete.after`,[no]:i,[to]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=br(),s=[];try{s=await(await gi(e)).findMany({model:i,where:t})}catch{}for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":t},()=>r(e,o))===!1)return null}let c=a?await a.fn(t):null,l=!a||a.executeMainFn?await(await gi(e)).deleteMany({model:i,where:t}):c;for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${i}`,{[Qa]:`delete.after`,[no]:i,[to]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=br(),c=r.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),l=o??null;if(c.length){if(!l)try{l=(await(await gi(e)).findMany({model:t,where:i,limit:1}))[0]||null}catch{}if(l){for(let{source:e,fn:r}of c)if(await n(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>r(l,s))===!1)return null}}let u=await a();if(!u)return null;for(let{source:e,hooks:i}of r){let r=i[t]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${t}`,{[Qa]:`delete.after`,[no]:t,[to]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function Pw(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}var Fw=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=new Map,o=r.session?.expiresIn||604800,s=!!i&&r.session?.storeSessionInDatabase===!0&&r.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:u,deleteWithHooks:d,deleteManyWithHooks:f,consumeOneWithHooks:p}=Nw(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await gi(e)).updateMany({model:`session`,where:n,update:{expiresAt:new Date}})},executeMainFn:!1})};async function h(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=($a(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=$a(r);if(!a)return;let o=Pw(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function g(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&$a(t)||[]}async function _(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await g(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;c?await i.set(r,JSON.stringify(s),Pw(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await ta(()=>_(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function y(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>Si(e,async()=>{let e=await c({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new V(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await c({...n,userId:e.id,createdAt:new Date,updatedAt:new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};Ow(e);let r;try{r=Sr()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new V(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await kw(r,{user:i,source:e})}return await c(i,`user`,void 0)},createAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(s)return(await(await gi(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:new Date,operator:`gt`}]})).map(e=>li(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=$a(e)||[],a=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(li(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await gi(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await gi(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await gi(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await g(e);(!i||r.session?.storeSessionInDatabase)&&await f([{field:`userId`,value:e}],`session`,void 0),await f([{field:`userId`,value:e}],`account`,void 0),await d([{field:`id`,value:e}],`user`,void 0)!==null&&await v(e,t)},createSession:async(a,l,u,d,f)=>{let p=await(async()=>{let e=br();return e?.headers||e?.request?.headers})(),m=r.session?.storeSessionInDatabase,h=f?.deferSecondaryStorageWrites===!0&&s,{id:g,..._}=u||{},v;if(i&&!m){let e=t.generateId({model:`session`});v=e===!1?Xa():e}let y=Nr(r),b={...v?{id:v}:{},ipAddress:p&&ia(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:ri(l?86400:o,`sec`),userId:a,token:Xa(32),createdAt:new Date,updatedAt:new Date,...y,...d?_:{}},x=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=$a(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==b.token));let s=[...r,{token:b.token,expiresAt:b.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=Pw(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await gi(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=Pw(b.expiresAt,o);return u>0&&await i.set(b.token,JSON.stringify({session:t,user:l}),u),t};return await c(b,`session`,i?{fn:async e=>h?(await ta(async()=>{await x(e)},{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}),e):x(e),executeMainFn:m}:void 0)},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=$a(e);return n?{session:li(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:ur(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await gi(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:li(t.options,s),user:ur(t.options,o)}:null},findSessions:async(t,n)=>{let r=[...new Set(t)],a=new Map,o=[];if(i)for(let e of r){let t=await i.get(e);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=new Date)continue;let o={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};a.set(e,o)}catch{continue}else o.push(e)}let c=i?o:r;if(c.length>0&&(!i||s)){let t=await(await gi(e)).findMany({model:`session`,limit:c.length,where:[{field:`token`,value:c,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]],join:{user:!0}});for(let{user:e,...n}of t)e&&a.set(n.token,{session:n,user:e})}return r.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,n)=>await l(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=$a(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=li(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=Pw(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&$a(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),Pw(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=$a(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=$a(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),Pw(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e}]);return}}await d([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await f([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await d([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await g(e);if(i){if(!r.session?.storeSessionInDatabase){await v(e,n);return}if(t.options.session?.preserveSessionInDatabase){await m([{field:`userId`,value:e}])!==null&&await v(e,n);return}}await f([{field:`userId`,value:e}],`session`,void 0)!==null&&await v(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e,operator:`in`}]);return}}await f([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({providerId:t,accountId:n})=>{let r=await(await gi(e)).findMany({model:`account`,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}],limit:2,join:{user:!0}});if(r.length>1)throw new H(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let i=r[0];if(!i)return null;let{user:a,...o}=i;return a?{kind:`owned`,user:a,account:o}:{kind:`orphaned`,account:o}},findUserByEmail:async(t,n)=>{let r=await(await gi(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await gi(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await ta(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await ta(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await u({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await gi(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await gi(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`accountId`,value:t}]}),findAccountByKey:async({providerId:t,accountId:n})=>{let r=await(await gi(e)).findMany({model:`account`,limit:2,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}]});if(r.length>1)throw new H(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return r[0]??null},findAccountByUserId:async t=>await(await gi(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=Mw(e.identifier,r.verification?.storeIdentifier),n=await jw(e.identifier,t);return await c({createdAt:new Date,updatedAt:new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=Pw(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=Mw(t,r.verification?.storeIdentifier),a=await jw(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=$a(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=$a(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await gi(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await f([{field:`expiresAt`,value:new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await jw(e,Mw(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await d([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=Mw(t,r.verification?.storeIdentifier),a=await jw(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?$a(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>y(`verification:${t}`,()=>Si(e,async()=>{let n=await gi(e),r=[{field:`identifier`,value:t}],i=await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:2}),a=i[0]??null;return a?p(`verification`,[{field:`id`,value:a.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:a.id}]});return e?(i.length>1&&await n.deleteMany({model:`verification`,where:r}),e):null},a):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt<new Date?null:c},reserveVerificationValue:async t=>{let n=ro(new Uint8Array(await ca(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=Mw(t.identifier,r.verification?.storeIdentifier),o=await jw(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new H(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=Pw(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await jw(e,Mw(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=$a(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=Pw(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await l(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:h}};async function Iw(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=ti(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=Jr(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=Fw(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function Lw(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function Rw(e,t){let n=[];if(yi(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||_i(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=Ni(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=Za.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function zw(e){if(Da(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has(`host`)||t.has(`x-forwarded-host`))return t}function Bw(e){return e.advanced?.trustedProxyHeaders??!1}async function Vw(e,t,n){let r=e.options.baseURL,i=Xr(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new H(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:xa(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?Da(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await Rw(o,c),a.trustedProviders=await Uw(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=kr(a.options),a.createAuthCookie=zr(a.options)),a}async function Hw(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function Uw(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function Ww(e){return e}async function Gw(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new H(`OAUTH_ACCOUNT_SUBJECT_INVALID`);return{providerId:e.id,accountId:o}}async function Kw(e,t,n){try{return await Gw(e,t,n)}catch{throw V.from(`UNAUTHORIZED`,B.FAILED_TO_GET_USER_INFO)}}var qw={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`},Jw=`https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`;function Yw(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=Yi(t,i);throw e.redirect(a)}function Xw(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${Jw}`}function Zw(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function Qw(e,t){return e&&(t.options.account?.encryptOAuthTokens&&Zw(e)?ma({key:t.secretConfig,data:e}):e)}function $w(e,t){return t.options.account?.encryptOAuthTokens&&e?Zi({key:t.secretConfig,data:e}):e}function eT(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function tT(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function nT(e,t,n,r=3600,i){return await ea({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function rT(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),V.from(`BAD_REQUEST`,B.VERIFICATION_EMAIL_NOT_ENABLED);let n=await nT(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}var iT=wa(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:z({email:rr().meta({description:`The email to send the verification email to`}),callbackURL:R().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),V.from(`BAD_REQUEST`,B.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await Zr(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await nT(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await rT(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw V.from(`BAD_REQUEST`,B.EMAIL_MISMATCH);if(n?.user.emailVerified)throw V.from(`BAD_REQUEST`,B.EMAIL_ALREADY_VERIFIED);return await rT(e,n.user),e.json({status:!0})}),aT=wa(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:z({token:R().meta({description:`The token to verify the email`}),callbackURL:R().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[ow(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){if(e.query.callbackURL){let n=new URLSearchParams({error:t.code}),r=Yi(e.query.callbackURL,n);throw e.redirect(r)}throw V.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await ra(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof vi?t(B.TOKEN_EXPIRED):t(B.INVALID_TOKEN)}let i=z({email:rr(),updateTo:R().optional(),requestType:R().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(B.USER_NOT_FOUND);if(i.updateTo){let n=await Zr(e);if(n&&n.user.email!==i.email)return t(B.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await nT(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},tT(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await Kr(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:ur(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await nT(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},tT(e.request))),await Kr(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:ur(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await Zr(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);await Kr(e,{session:t,user:{...a.user,emailVerified:!0}})}else await Kr(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function oT(e,t){return{linked:!1,error:{code:e,message:t}}}async function sT(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await kw(e,{user:{...n,id:t.userId,email:n.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:r.providerId,profile:i}}})}catch(e){if(!Hr(e)||!e.body?.code)throw e;return oT(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(r.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),oT(qw.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return oT(qw.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return oT(qw.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=oi(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(o.id,i)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...r,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return oT(qw.UNABLE_TO_LINK_ACCOUNT);return await uT(e,t.userId,n),{linked:!0}}async function cT(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
75
+ `).map(e=>e.trim()):void 0},void 0,t?2:void 0),{status:e.status,statusText:e.statusText,headers:r})}var Fg=Symbol.for(`tanstack-start:event-storage`),Ig=globalThis;Ig[Fg]||(Ig[Fg]=new Ko);var Lg=Ig[Fg];function Rg(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&typeof e.then==`function`}function zg(e){let t=e;if(typeof t.getSetCookie==`function`)return t.getSetCookie();let n=e.get(`set-cookie`);return n?[n]:[]}function Bg(e,t){if(e.ok)return;let n=zg(t.res.headers);if(n.length===0)return;let r=zg(e.headers);e.headers.delete(`set-cookie`);for(let t of r)e.headers.append(`set-cookie`,t);for(let t of n)e.headers.append(`set-cookie`,t)}function Vg(e,t){let n=Ug(e);return Bg(n,t),n}function Hg(e,t){return Rg(e)?Promise.resolve(e).then(e=>Vg(e,t),e=>Vg(Wg(e),t)):Vg(e,t)}function Ug(e){return e instanceof Response?e:new Response(`Internal Server Error`,{status:500})}function Wg(e){if(e instanceof Response)return e;if(e instanceof Error)throw e;return new Response(`Internal Server Error`,{status:500})}function Gg(e){return(t,n)=>{let r;try{r=new hg(t)}catch(e){if(e instanceof URIError)return new Response(null,{status:400,statusText:`Bad Request`});throw e}let i;try{i=Lg.run({h3Event:r},()=>e(t,n))}catch(e){i=Wg(e)}return wg(Hg(i,r),r)}}function Kg(){let e=Lg.getStore();if(!e)throw Error(`No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`);return e.h3Event}function qg(){return Kg().res}var Jg={TSS_SHELL:`X-TSS_SHELL`};async function Yg(e){let{tsrStartManifest:t}=await import(`./assets/_tanstack-start-manifest_v-DQjMcFpU.js`),n=t(),r=n.routes;r[A];let i={};for(let e in r){let t=r[e],n={};t.preloads&&t.preloads.length>0&&(n.preloads=t.preloads),t.scripts&&t.scripts.length>0&&(n.scripts=t.scripts),t.css?.length&&(n.css=t.css),(n.preloads||n.scripts||n.css)&&(i[e]=n)}return{...n.scriptFormat?{scriptFormat:n.scriptFormat}:{},...n.inlineCss?{inlineCss:n.inlineCss}:{},routes:i}}var Xg={};async function Zg(e,t){let n=Xg[e];if(!n)throw Error(`Server function info not found for `+e);let r=n.module??=await n.importer();if(!r)throw Error(`Server function module not resolved for `+e);let i=r[n.functionName];if(!i)throw Error(`Server function module export not resolved for serverFn ID: `+e);return i}var Qg=`__TSS_CONTEXT`,$g=Symbol.for(`TSS_SERVER_FUNCTION`),e_=`x-tss-serialized`,t_=`x-tss-raw`,n_=`application/x-tss-framed`,r_=16777216,i_=1024,a_=`${n_}; v=1`,o_=()=>ie().startOptions;function s_(e){return[...(o_()?.serializationAdapters)?.map(jp)??[],...e]}var c_=new TextEncoder,l_=new Uint8Array,u_=4096;function d_(e,t,n){if(n.byteLength>16777216)throw RangeError(`Frame payload exceeds ${r_} bytes`);let r=new Uint8Array(9+n.length);return r[0]=e,r[1]=t>>>24&255,r[2]=t>>>16&255,r[3]=t>>>8&255,r[4]=t&255,r[5]=n.length>>>24&255,r[6]=n.length>>>16&255,r[7]=n.length>>>8&255,r[8]=n.length&255,r.set(n,9),r}function f_(e){let t=e instanceof Error?e.message:String(e??`Unknown error`),n=t.length>u_?`${t.slice(0,u_)}…`:t;return c_.encode(n)}function p_(e,t={}){let n,r=!1,i=0,a,o,s=new Set,c=new Set,l=()=>m(t.signal?.reason),u=()=>{let e=a;a=void 0,e?.()},d=(e,t)=>{e.cancel(t).catch(()=>{})},f=(e,t)=>{e.cancel(t).catch(()=>{})},p=e=>{if(r)return!1;r=[e],t.signal?.removeEventListener(`abort`,l),u();for(let t of s)d(t,e);for(let t of c)f(t,e);return c.clear(),!0},m=e=>{if(p(e))try{n.error(e)}catch{}},h=async()=>{for(;!r&&(n.desiredSize??0)<=0;)await new Promise(e=>{a=e});return!r},g=(e,t,i)=>{if(r)return!1;if(!o&&(n.desiredSize??0)>0)return n.enqueue(d_(e,t,i)),!0;let a=async()=>await h()?(n.enqueue(d_(e,t,i)),!0):!1,s=o?o.then(a):a(),c=()=>{o===l&&(o=void 0)},l=s.then(c,c);return o=l,s},_=()=>{if(i===0&&p())try{n.close()}catch{}},v=e=>{i++,e().then(()=>{i--,_()},e=>{i--,m(e)})};async function y(e,t){let n=t.getReader();s.add(n);try{for(;!r;){let{done:t,value:i}=await n.read();if(r)return;if(t){let t=g(2,e,l_);t!==!0&&await t;return}if(!(i instanceof Uint8Array))throw TypeError(`RawStream chunks must be Uint8Array`);let a=0;do{let t=g(1,e,i.byteLength<=16777216?i:i.subarray(a,a+r_));if(t!==!0&&(t===!1||!await t))return;a+=r_}while(a<i.byteLength)}}catch(t){if(!r){let n=g(3,e,f_(t));n!==!0&&await n}}finally{s.delete(n),n.releaseLock()}}async function b(){let t=e.getReader();s.add(t);try{for(;!r;){let{done:e,value:n}=await t.read();if(r){if(!e)for(let e of n.rawStreams)f(e.stream,r[0]);return}if(e)return;for(let e of n.rawStreams)c.add(e.stream);let i=g(0,0,n.json);if(i!==!0&&(i===!1||!await i))return;for(let e of n.rawStreams)c.delete(e.stream),v(y.bind(void 0,e.id,e.stream))}}catch(e){r||m(e)}finally{s.delete(t),t.releaseLock()}}return new ReadableStream({start(r){n=r,t.signal?.aborted?(f(e,t.signal.reason),m(t.signal.reason)):(t.signal?.addEventListener(`abort`,l,{once:!0}),v(b))},pull(){u()},cancel(e){p(e)&&t.onCancel?.(e)}})}function m_(e){return e!==`__proto__`&&e!==`constructor`&&e!==`prototype`}function h_(e,t){let n=Object.create(null);if(e)for(let t of Object.keys(e))m_(t)&&(n[t]=e[t]);if(t&&typeof t==`object`)for(let e of Object.keys(t))m_(e)&&(n[e]=t[e]);return n}function g_(e){if(!e)return Object.create(null);let t=Object.create(null);for(let n of Object.keys(e))m_(n)&&(t[n]=e[n]);return t}function __(e,t=100){let n=new Set,r=[],i=(e,a)=>{if(a>t)throw Error(`Middleware nesting depth exceeded maximum of ${t}. Check for circular references.`);e.forEach(e=>{e.options.middleware&&i(e.options.middleware,a+1),n.has(e)||(n.add(e),r.push(e))})};return i(e,0),r}var v_=(e,t)=>{let n={type:`request`,...t||e},r=e=>v_({},Object.assign(n,{validator:e,inputValidator:e}));return{options:n,middleware:e=>v_({},Object.assign(n,{middleware:e})),validator:r,inputValidator:r,client:e=>v_({},Object.assign(n,{client:e})),server:e=>v_({},Object.assign(n,{server:e}))}},y_=(e={})=>v_().server(async t=>{let n=t;return e.filter&&!await e.filter(n)||await b_(e,n)?t.next():T_(e,n)});async function b_(e,t){let n=await x_(e,t);return n===!0||n===void 0&&e.allowRequestsWithoutOriginCheck===!0}async function x_(e,t){let n=t.request.headers.get(`Sec-Fetch-Site`);if(n!==null)return S_(e.secFetchSite??`same-origin`,n,t);let r=t.request.headers.get(`Origin`);if(r!==null)return e.origin?S_(e.origin,r,t):r===new URL(t.request.url).origin;let i=t.request.headers.get(`Referer`);if(i!==null&&e.referer!==!1){if(typeof e.referer==`function`)return e.referer(i,t);if(e.origin){let n=C_(i);return n!==void 0&&S_(e.origin,n,t)}return w_(i,new URL(t.request.url).origin)}}async function S_(e,t,n){return typeof e==`function`?e(t,n):Array.isArray(e)?e.includes(t):t===e}function C_(e){try{return new URL(e).origin}catch{return}}function w_(e,t){if(e===t)return!0;if(!e.startsWith(t))return!1;if(e.length===t.length)return!0;let n=e.charCodeAt(t.length);return n===47||n===63||n===35}async function T_(e,t){return typeof e.failureResponse==`function`?e.failureResponse(t):e.failureResponse?.clone()??new Response(`Forbidden`,{status:403})}var E_=void 0,D_=[`multipart/form-data`,`application/x-www-form-urlencoded`],O_=1e6,k_=1024,A_=33554432,j_=new TextEncoder;function M_(e){return j_.encode(JSON.stringify(e))}function N_(e,t,n){return t>=k_||n+e.byteLength>A_}function P_(e){try{e()}catch{}}function F_(e,t){e.cancel(t).catch(()=>{})}var I_=async({request:e,context:t,serverFnId:n})=>{let r=e.method.toUpperCase(),i=new URL(e.url),a=await Zg(n,{origin:`client`});if(a.method&&r!==a.method)return new Response(`expected ${a.method} method. Got ${r}`,{status:405,headers:{Allow:a.method}});let o=e.headers.get(`x-tsr-serverFn`)===`true`;E_??=s_(om);let s=e.headers.get(`Content-Type`);try{let n;if(D_.some(e=>s&&s.includes(e))){r===`GET`&&ee();let i=await e.formData(),o=i.get(Qg);i.delete(Qg);let s={context:t,data:i,method:r};if(typeof o==`string`)try{let e=Ap(JSON.parse(o),{plugins:E_});typeof e==`object`&&e&&(s.context=h_(e,t))}catch{}n=await a(s)}else if(r===`GET`){let e=i.searchParams.get(`payload`);if(e&&e.length>O_)throw Error(`Payload too large`);let o=e?Ap(JSON.parse(e),{plugins:E_}):void 0;n=await a({data:o?.data,context:h_(o?.context,t),method:r})}else{let i=s?.includes(`application/json`)?Ap(await e.json(),{plugins:E_}):void 0;n=await a({data:i?.data,context:h_(i?.context,t),method:r})}let c=n.error===void 0?n.result:n.error;return m(n)&&(n=R_(n)),!o&&(c instanceof Response||typeof c!=`object`||!c)?c:c instanceof Response?(M(c)||c.headers.set(t_,`true`),c):L_(n,e.signal,E_)}catch(e){if(e instanceof Response)return e;if(m(e))return R_(e);console.error(`Server Fn Error!`,e);let t=JSON.stringify(await Dp(e,{refs:new Map,plugins:E_})),n=qg(),r={"Content-Type":`application/json`,[e_]:`true`};try{return new Response(t,{status:n.status??500,statusText:n.statusText,headers:r})}catch{return new Response(t,{status:500,statusText:``,headers:r})}}};function L_(e,t,n){let r=qg(),i=[],a=0,o=[],s=!1,c=!1,l,u,d=(e,t)=>{if(l)return;c||=t;let n=M_(e);N_(n,i.length,a)?l=[Error(`Server function serialization exceeded its pending output limit`)]:(i.push(n),a+=n.byteLength)},f=()=>{c&&(s=!0)},p=e=>{l??=[e]},m=kp(e,{refs:new Map,plugins:[sm((e,t)=>{if(l)F_(t,l[0]);else if(e>1024){let e=Error(`Too many raw streams in framed response (max ${i_})`);F_(t,e),p(e)}else o.push({id:e,stream:t})}),...n],onParse(e,t){d(e,t)},onDone(){f()},onError:e=>{p(e)}});if(l){P_(m);for(let e of o)F_(e.stream,l[0]);throw l[0]}if(s||(u=m),s&&o.length===0&&i.length===1)return new Response(i[0],{status:r.status,statusText:r.statusText,headers:{"Content-Type":`application/json`,[e_]:`true`}});if(s&&i.length===1){let e=i[0];if(e.byteLength>16777216){let e=Error(`Server function serialization exceeded its pending output limit`);for(let t of o)F_(t.stream,e);throw e}let n=o.splice(0);return i.length=0,w(new ReadableStream({start(t){t.enqueue({json:e,rawStreams:n}),t.close()},cancel(e){for(let t of n)F_(t.stream,e)}}),{signal:t})}let{readable:h,writable:g}=new TransformStream,_=g.getWriter(),v=new AbortController,y=0,b=new Set,x=e=>{if(l)return;l=[e];let t=u;u=void 0;for(let t of o.splice(0))F_(t.stream,e);for(let t of b)for(let n of t.rawStreams)F_(n.stream,e);b.clear(),v.abort(e),_.abort(e).catch(()=>{}),t&&P_(t)},S=(e,t)=>{if(l){for(let e of t)F_(e.stream,l[0]);return!1}if(e.byteLength>16777216||N_(e,b.size,y)){let e=Error(`Server function serialization exceeded its pending output limit`);for(let n of t)F_(n.stream,e);return p(e),!1}y+=e.byteLength;let n={json:e,rawStreams:t};return b.add(n),_.write(n).then(()=>{b.delete(n),y-=e.byteLength},r=>{let i=b.delete(n);if(y-=e.byteLength,i)for(let e of t)F_(e.stream,r)}),!0};d=e=>{l||S(M_(e),o.splice(0))},f=()=>{l||(u=void 0,_.close().catch(()=>{}))},p=e=>{x(e)};let C=o.splice(0);for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!S(i[e],t?C:[])){if(!t)for(let e of C)F_(e.stream,l[0]);throw i.length=0,l[0]}}return i.length=0,s&&f(),_.closed.catch(e=>{x(e)}),w(h,{signal:AbortSignal.any([v.signal,t]),onCancel:x});function w(e,t){let n=p_(e,t);try{return new Response(n,{status:r.status,statusText:r.statusText,headers:{"Content-Type":a_,[e_]:`true`}})}catch(e){throw F_(n,e),e}}}function R_(e){let{headers:t,...n}=e,r=new Response(JSON.stringify(n),{status:404,headers:t});return r.headers.set(`Content-Type`,`application/json`),r}var z_=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,B_=new Set([`fetch`,`font`,`image`,`script`,`style`,`track`]);function V_(e,t){return t===void 0?e:z_.test(t)?`${e}=${t}`:`${e}=${JSON.stringify(t)}`}function H_(e){let t=[`<${e.href}>`,V_(`rel`,e.rel)];return e.as&&t.push(V_(`as`,e.as)),e.crossOrigin!==void 0&&t.push(V_(`crossorigin`,e.crossOrigin||void 0)),e.type&&t.push(V_(`type`,e.type)),e.integrity&&t.push(V_(`integrity`,e.integrity)),e.referrerPolicy&&t.push(V_(`referrerpolicy`,e.referrerPolicy)),e.fetchPriority&&t.push(V_(`fetchpriority`,e.fetchPriority)),t.join(`; `)}function U_(e,t,n){let r=e?.[t]??(n?e?.[n]:void 0);return typeof r==`string`?r:void 0}function W_(e){let t=U_(e,`as`);return t&&B_.has(t)?t:void 0}function G_(e,t){let n=U_(t,`crossOrigin`,`crossorigin`),r=U_(t,`type`),i=U_(t,`integrity`),a=U_(t,`referrerPolicy`,`referrerpolicy`),o=U_(t,`fetchPriority`,`fetchpriority`);n!==void 0&&(e.crossOrigin=n),r&&(e.type=r),i&&(e.integrity=i),a&&(e.referrerPolicy=a),o&&(e.fetchPriority=o)}function K_(e){let t=U_(e,`href`),n=U_(e,`rel`);if(!t||!n)return;let r=n.split(/\s+/),i,a;if(r.includes(`modulepreload`))i=`modulepreload`,a=`script`;else if(r.includes(`stylesheet`))i=`preload`,a=`style`;else if(r.includes(`preload`)){if(a=W_(e),!a)return;i=`preload`}else r.includes(`preconnect`)?(i=`preconnect`,a=void 0):r.includes(`dns-prefetch`)&&(i=`dns-prefetch`,a=void 0);if(!i)return;let o={href:t,rel:i};return a&&(o.as=a),G_(o,e),o}function q_(e,t){let n=[];for(let r of t){let t=e.routes[r.id];if(t){for(let r of t.preloads??[]){let t=b(e,r),i={href:t.href,rel:t.rel,as:`script`};t.crossOrigin!==void 0&&(i.crossOrigin=t.crossOrigin),n.push(i)}for(let r of t.css??[]){let t=D(r);if(e.inlineCss?.styles[t]!==void 0)continue;let i=_(r),a={href:t,rel:`preload`,as:`style`};i.crossOrigin!==void 0&&(a.crossOrigin=i.crossOrigin),n.push(a)}}}return n}function J_(e){let t=[];for(let n of e){let e=n.links;if(Array.isArray(e))for(let n of e){let e=K_(n);e&&t.push(e)}}return t}function Y_(e){let t=[],n=[];for(let r of e.hints){let i=H_(r);e.sentLinks.has(i)||(e.sentLinks.add(i),e.sentHints.push(r),t.push(r),n.push(i))}if(t.length||e.phase===`dynamic`)return{phase:e.phase,hints:t,links:n,allHints:e.sentHints.slice(),allLinks:Array.from(e.sentLinks)}}function X_(e){for(let t of e.hints){let n=H_(t);e.sentLinks.has(n)||(e.sentLinks.add(n),e.entries.push({phase:e.phase,hint:t,link:n}))}}function Z_(e){if(!e.filter)return e.entries.map(e=>e.link);try{let t=[];for(let n of e.entries)e.filter(n)&&t.push(n.link);return t}catch(e){return console.error(`Error filtering response Link headers:`,e),[]}}function Q_(e,t,n){try{let r=n(t);r&&Promise.resolve(r).catch(t=>{console.error(`Error sending ${e} early hints:`,t)})}catch(t){console.error(`Error sending ${e} early hints:`,t)}}function $_(e){if(typeof e==`object`)return e.filter}function ev(e){for(let t of Z_(e))e.responseHeaders.append(`Link`,t)}function tv(e){for(let t=0;t<e.event.hints.length;t++)e.entries.push({phase:e.phase,hint:e.event.hints[t],link:e.event.links[t]})}function nv(e){let t=e.onEarlyHints?Y_({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,sentHints:e.sentHints}):void 0;t&&Q_(e.phase,t,e.onEarlyHints),e.responseLinkHeaderEntries&&(t?tv({phase:e.phase,event:t,entries:e.responseLinkHeaderEntries}):X_({phase:e.phase,hints:e.hints,sentLinks:e.sentLinks,entries:e.responseLinkHeaderEntries}))}function rv(e){if(!e?.onEarlyHints&&!e?.responseLinkHeader)return;let t=new Set,n=e.onEarlyHints?[]:void 0,r=e.responseLinkHeader?[]:void 0,i=$_(e.responseLinkHeader);return{collectStatic:({manifest:i,matchedRoutes:a})=>{a?.length&&nv({phase:`static`,hints:q_(i,a),sentLinks:t,sentHints:n,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:r})},collectDynamic:i=>{nv({phase:`dynamic`,hints:J_(i),sentLinks:t,sentHints:n,onEarlyHints:e.onEarlyHints,responseLinkHeaderEntries:r})},appendResponseHeaders:e=>{r?.length&&ev({responseHeaders:e,entries:r,filter:i})}}}function iv(e){return typeof e==`string`?{href:e}:e}function av(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\a `).replace(/\r/g,`\\d `).replace(/\f/g,`\\c `)}async function ov(e){let{strings:t,urls:n}=e.template;if(t.length!==n.length+1)throw Error(`TanStack Start inlineCss template for ${e.stylesheetHref} is invalid`);let r=t[0];for(let i=0;i<n.length;i++){let a=iv(await e.transformFn({kind:`css-url`,url:n[i],stylesheetHref:e.stylesheetHref}));r+=av(a.href)+t[i+1]}return r}async function sv(e,t){let n={},r=await Promise.all(Object.entries(e.styles).map(async([n,r])=>{let i=e.templates?.[n];return[n,i?await ov({stylesheetHref:n,template:i,transformFn:t}):r]}));for(let[e,t]of r)n[e]=t;return{styles:n,...e.templates?{templates:e.templates}:{}}}function cv(e,t){if(e)return typeof e==`string`?e:e[t]}function lv(e){return`prefix`in e}function uv(e){if(typeof e==`string`){let t=e;return{type:`transform`,transformFn:({url:e})=>({href:`${t}${e}`}),cache:!0}}if(typeof e==`function`)return{type:`transform`,transformFn:e,cache:!0};if(lv(e)){let{prefix:t,crossOrigin:n}=e;return{type:`transform`,transformFn:({url:e,kind:r})=>{let i=`${t}${e}`;if(r===`css-url`)return{href:i};let a=cv(n,r);return a?{href:i,crossOrigin:a}:{href:i}},cache:!0}}return`createTransform`in e&&e.createTransform?{type:`createTransform`,createTransform:e.createTransform,cache:e.cache!==!1}:{type:`transform`,transformFn:typeof e.transform==`string`?(({url:t})=>({href:`${e.transform}${t}`})):e.transform,cache:e.cache!==!1}}function dv(e,t){if(typeof e==`string`)return t.crossOrigin?t:t.href;let n={...e,href:t.href};return t.crossOrigin?n.crossOrigin=t.crossOrigin:delete n.crossOrigin,n}async function fv(e,t,n){let r=structuredClone(e),i=n?.inlineCss!==!1,a=new Map,o=e=>{let n=a.get(e);if(n)return n;let r=Promise.resolve(t({url:e,kind:`script`})).then(iv);return a.set(e,r),r};i?r.inlineCss&&=await sv(r.inlineCss,t):delete r.inlineCss;for(let e of Object.values(r.routes))if(e.preloads?.length&&(e.preloads=await Promise.all(e.preloads.map(async e=>{let t=await o(g(e).href);return dv(e,{href:t.href,crossOrigin:t.crossOrigin})}))),e.css?.length&&!r.inlineCss&&(e.css=await Promise.all(e.css.map(async e=>{let n=iv(await t({url:_(e).href,kind:`stylesheet`}));return dv(e,{href:n.href,crossOrigin:n.crossOrigin})}))),e.scripts?.length)for(let t of e.scripts){let e=t.attrs?.src;if(typeof e!=`string`)continue;let n=await o(e);t.attrs={...t.attrs,src:n.href},n.crossOrigin?t.attrs.crossOrigin=n.crossOrigin:delete t.attrs.crossOrigin}return r}function pv(e,t){return{...e.scriptFormat?{scriptFormat:e.scriptFormat}:{},...t?.inlineCss!==!1&&e.inlineCss?{inlineCss:structuredClone(e.inlineCss)}:{},routes:{...e.routes}}}function mv(e){if(typeof e!=`function`)return e??!0}async function hv(e){return e.requestInlineCss===void 0?typeof e.handlerInlineCss==`function`?await e.handlerInlineCss({request:e.request}):e.handlerInlineCss??!0:e.requestInlineCss}function gv(e){let t;return()=>(t||=e().catch(e=>{throw t=void 0,e}),t)}function _v(e,t){let n=e===void 0?void 0:uv(e),r=!n||n.cache,i=!!e&&typeof e==`object`&&`warmup`in e&&e.warmup===!0,a,o=()=>{a=void 0};return{cache:r,warmup:i,clearCachedCreateTransform:o,getTransformFn:async e=>{if(n)return n.type===`createTransform`?!r||!t.cacheCreateTransform?n.createTransform(e):(a||=Promise.resolve(n.createTransform(e)).catch(e=>{throw o(),e}),a):n.transformFn}}}function vv(e){let t=new Map,n=_v(e.transformAssets,{cacheCreateTransform:e.cacheCreateTransform}),r=mv(e.inlineCss),i=async t=>{let r=await n.getTransformFn({warmup:!1,request:t.request}),i=await hv({request:t.request,handlerInlineCss:e.inlineCss,requestInlineCss:t.requestInlineCss});return{getBaseManifest:t.getBaseManifest,transformFn:r,cache:n.cache,inlineCss:i}},a=async(e,t)=>Cv({...await i(e),finalManifestCache:t});return{warmup:({getBaseManifest:e})=>wv({enabled:n.warmup,handlerDefaultInlineCss:r,cache:n.cache,finalManifestCache:t,getBaseManifest:e,getTransformFn:()=>n.getTransformFn({warmup:!0}),onError:n.clearCachedCreateTransform}),resolveCached:e=>a(e,t),resolveUncached:e=>a(e,void 0)}}function yv(e){return e?`inline-css`:`linked-css`}function bv(e,t,n){let r=n.catch(n=>{throw e.get(t)===r&&e.delete(t),n});return e.set(t,r),r}function xv(e,t,n){return e.get(t)||bv(e,t,Promise.resolve().then(n))}async function Sv(e){return e.transformFn?await fv(e.base,e.transformFn,{inlineCss:e.inlineCss}):pv(e.base,{inlineCss:e.inlineCss})}async function Cv(e){let t=async()=>Sv({base:await e.getBaseManifest(),transformFn:e.transformFn,inlineCss:e.inlineCss});return e.finalManifestCache&&(!e.transformFn||e.cache)?xv(e.finalManifestCache,yv(e.inlineCss),t):t()}function wv(e){if(!e.enabled||e.handlerDefaultInlineCss===void 0||!e.cache)return;let t=e.handlerDefaultInlineCss,n=xv(e.finalManifestCache,yv(t),async()=>{let[n,r]=await Promise.all([e.getBaseManifest(),e.getTransformFn()]);return Sv({base:n,transformFn:r,inlineCss:t})});return e.onError&&n.catch(e.onError),n}var Tv=_s({key:`$TSS/serverfn`,test:e=>typeof e!=`function`||!($g in e)?!1:!!e[$g],toSerializable:({serverFnMeta:e})=>({functionId:e.id}),fromSerializable:({functionId:e})=>async(t,n)=>{let r=await Zg(e,{origin:`client`}),i=await r({data:t?.data,context:t?.context,method:r.method??`GET`},n);if(i.error!==void 0)throw i.error;return i.result}});function Ev(e){return jh({"Content-Type":`text/html; charset=utf-8`},...v(e.router.stores.matches.get()).map(e=>e.headers))}var Dv,Ov=y_({filter:e=>e.handlerType===`serverFn`}),kv=gv(()=>Yg()),Av=()=>kv(),jv=rv;async function Mv(){let[e,t,n]=await Promise.all([import(`./assets/router-nrTsbXpb.js`),import(`./assets/start-C63VetBp.js`),import(`./assets/empty-plugin-adapters-BaGcmrjC.js`)]);return{routerEntry:e,startEntry:t,pluginAdapters:n}}function Nv(){return Dv||=Mv(),Dv}var Pv=`/`,Fv=`/_serverFn/`,Iv=process.env.TSS_PRERENDERING===`true`,Lv=process.env.TSS_SHELL===`true`,Rv=`Internal Server Error`,zv=`Internal Server Error`;function Bv(){throw Error(Rv)}function Vv(){throw Error(zv)}function Hv(e){return yh(e)||e instanceof Response?e:e?.response}var Uv=new WeakMap;function Wv(e,t){let n=Hv(e);(yh(n)||n instanceof Response)&&Sh(n,t)}function Gv(e){return e instanceof Response&&e.body!==null}function Kv(e,t){return Gv(t)&&(t.body===e.response.body||Uv.get(t)===e.response)}function qv(e,t){let{response:n,sourceBody:r,streamResponse:i}=e;i?.dispose(t),(!i||n.body!==r)&&n.body.cancel(t).catch(()=>{})}function Jv(e){let{response:t,sourceBody:n,streamResponse:r}=e;return r?r.response===t&&t.body===n?r:t.body===n?{...r,response:t}:{...r,response:t,dispose(t){qv(e,t)}}:t}function Yv(e){return t=>Wv(t,e.reason)}async function Xv(e,t,n,r,i){let a=-1,o,s=!1,c=Yv(r),l=e=>{let t=yh(e)?e:void 0,r=t?.serverSsrCleanup===`stream`?t:void 0,i=t?t.response:e,a=o;s?i!==n.response&&Wv(e,`late middleware response`):(a&&a.response===i?a.streamResponse??=r:a&&Kv(a,i)?(a.response=i,a.streamResponse??=r):(a&&qv(a,`middleware response replaced`),o=Gv(i)?{response:i,sourceBody:i.body,streamResponse:r}:void 0),n.response=i)},u=()=>{n.response!==o?.response&&l(n.response)},d;function p(e){let t=m(e);return d=t,t}async function m(o){if(r.throwIfAborted(),o){o.context&&(n.context=h_(n.context,o.context));for(let e of Object.keys(o))e===`response`?l(o.response):e!==`context`&&(n[e]=o[e])}a++;let s=a===e.length,m=a<e.length?e[a]:s?t:void 0,h=s&&i?i:p;if(!m)return n;let g;try{let e=m({...n,next:h});if(d&&e===d){if(d=void 0,await e,r.aborted)throw r.reason;return n}f(e)?g=await S(e,r,c,c):(g=e,r.throwIfAborted())}catch(e){if(u(),r.aborted)throw g!==void 0&&c(g),e!==r.reason&&c(e),r.reason;if(e instanceof Response)return l(e),n;throw e}if(s&&i&&!g&&Bv(),u(),g&&g!==n){let e=Hv(g);e!==void 0&&e!==n.response&&l(e),e!==g&&g.context&&g.context!==n.context&&(n.context=h_(n.context,g.context))}return n}try{await m();let e=n.response;if(e||Bv(),u(),r.aborted)throw r.reason;return s=!0,o?Jv(o):e}catch(e){throw s=!0,o&&qv(o,r.aborted?r.reason:e),e}}function Zv(e){let t=typeof e==`function`?{}:e,n=typeof e==`function`?e:e.handler,r=vv({...t,cacheCreateTransform:!0}),i=r.resolveCached;return r.warmup({getBaseManifest:()=>Av(void 0)}),Gg(async(e,t)=>{let r=e.signal,a,o,s=!1;try{r.throwIfAborted();let{url:c,handledProtocolRelativeURL:l}=vh(e.url),u=c.pathname+c.search+c.hash,d=c.origin;if(l)return Response.redirect(c,308);let p=await S(Nv(),r),m=!!Fv&&c.pathname.startsWith(Fv),h=p.startEntry.startInstance,g;if(h){let e=h.getOptions();g=f(e)?await S(e,r):e,r.throwIfAborted()}else g={};let{hasPluginAdapters:_,pluginSerializationAdapters:y}=p.pluginAdapters,b=[...g.serializationAdapters||[],..._?y:[],Tv],x={...g,requestMiddleware:h?g.requestMiddleware:m?[Ov]:void 0,serializationAdapters:b},C=x.requestMiddleware?__(x.requestMiddleware):[],w=new Set(C),E=()=>(o??=(async()=>{r.throwIfAborted();let t=await S(p.routerEntry.getRouter(),r),n=Lv;Iv&&!n&&(n=e.headers.get(Jg.TSS_SHELL)===`true`);let i=O(u);return t.update({history:i,isShell:n,isPrerendering:Iv,origin:t.options.origin??d,defaultSsr:x.defaultSsr,serializationAdapters:[...x.serializationAdapters,...t.options.serializationAdapters||[]],basepath:Pv}),a=t,t})(),o),D=m?`serverFn`:`router`,k={getRouter:E,startOptions:x,request:e,executedRequestMiddlewares:w,handlerType:D},A;if(m){let n=c.pathname.slice(Fv.length).split(`/`)[0];if(!n)throw Error(`Invalid server action param for serverFnId`);A=({context:r})=>F({...k,contextAfterGlobalMiddlewares:r},()=>I_({request:e,context:t?.context,serverFnId:n}))}else{let a=async(a,o)=>{if(!/(^|,)\s*(\*\/\*|text\/html)/.test(e.headers.get(`Accept`)||`*/*`))return bh(Response.json({error:`Only HTML requests are supported here`},{status:406}));let s=await S(i({request:e,requestInlineCss:t?.inlineCss,getBaseManifest:()=>Av(o)}),r),c=jv({onEarlyHints:t?.onEarlyHints,responseLinkHeader:t?.responseLinkHeader});c?.collectStatic({manifest:s,matchedRoutes:o});let l=await E();if(_h({router:l,manifest:s,getRequestAssets:()=>ie({throwIfNotFound:!1})?.requestAssets}),l.options.additionalContext={serverContext:a},await l.load({_signal:r}),r.throwIfAborted(),l._serverResult?.type===`redirect`)return bh(l._serverResult.redirect);c?.collectDynamic(v(l.stores.matches.get()));let u=ie({throwIfNotFound:!1});await l.serverSsr.dehydrate({requestAssets:u?.requestAssets,signal:r}),r.throwIfAborted();let d=Ev({router:l});c?.appendResponseHeaders(d),r.throwIfAborted();let f=Yv(r);return bh(await S(n({request:e,router:l,responseHeaders:d}),r,f,f))};A=({context:t})=>F({...k,contextAfterGlobalMiddlewares:t},()=>ty({getRouter:E,request:e,url:c,executeRouter:a,context:t,executedRequestMiddlewares:w}))}let j=await Xv(C.map(e=>e.options.server),A,{request:e,pathname:c.pathname,handlerType:D,context:g_(t?.context)},r),M;try{M=await $v(j,E,r,m&&e.headers.get(`x-tsr-serverFn`)===`true`),e.method===`HEAD`&&(M=Dh(M,`HEAD body stripped`))}catch(e){throw Wv(j,r.aborted?r.reason:e),e}return Th(a,M,r),r.throwIfAborted(),s=M.serverSsrCleanup===`stream`,M.response}finally{a?.serverSsr&&!s&&a.serverSsr.cleanup()}})}var Qv=new Set;async function $v(e,t,n,r){n.throwIfAborted();let i=bh(e),a=i.response;if(!M(a))return i;let o=a.options,s=a.headers.get(`Location`)||o.href;if(!s&&o.to&&typeof o.to==`string`&&!o.to.startsWith(`/`))throw Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(o)}`);if(!s&&[`params`,`search`,`hash`].some(e=>typeof o[e]==`function`))throw Error(`Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(o).filter(e=>typeof o[e]==`function`).map(e=>`"${e}"`).join(`, `)}`);if(n.throwIfAborted(),s&&!p(s,Qv))o.href=s,a.headers.set(`Location`,s);else{let e=await t();n.throwIfAborted(),e.resolveRedirect(a)}if(r){let e={...o};delete e.headers;let t=new Headers(a.headers);return t.set(`content-type`,`application/json`),Eh(i,Response.json({...e,isSerializedRedirect:!0},{headers:t}),`redirect response replaced`)}return i}function ey(e,t){return t.some(e=>e.options.params?.parse??e.options.parseParams)?n=>{let r=Object.assign(Object.create(null),n.params);for(let e of t){let t=e.options.params?.parse??e.options.parseParams;t&&Object.assign(r,t(r))}return e({...n,params:r})}:e}async function ty({getRouter:e,request:t,url:n,executeRouter:r,context:i,executedRequestMiddlewares:a}){let o=await e(),s=k(o.rewrite,n).pathname,[c,l,u]=o.getMatchedRoutes(s),d=u&&l[`**`]===void 0,f=[],p=e=>r(e.context,c),m;for(let e of c){let t=e.options.server?.middleware;if(t){let e=__(t);for(let t of e)a.has(t)||f.push(t.options.server)}}let h=u?.options.server;if(h?.handlers&&d){let e=typeof h.handlers==`function`?h.handlers({createHandlers:e=>e}):h.handlers,n=t.method.toUpperCase(),r=n===`HEAD`?e.HEAD??e.GET??e.ANY:e[n]??e.ANY;if(r){let e=!!u.options.component;if(typeof r!=`function`&&r.middleware?.length){let e=__(r.middleware);for(let t of e)f.push(t.options.server)}let t=typeof r==`function`?r:r.handler;if(t){let n=ey(t,c);e?f.push(n):(p=n,m=Vv)}}}return bh(await Xv(f,p,{request:t,context:i,params:l,pathname:s,handlerType:`router`},t.signal,m))}var ny=[`__VOID_`,`__PROJECT_`],ry=[`ISR_CACHE`];function iy(e){return e.__VOID_ISR_DEPLOYMENT_ID!=null}var ay=Symbol.for(`void.envContext.v1`),oy=globalThis;oy[ay]??=new Ko;var sy=oy[ay],cy;typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`&&import(`cloudflare:workers`).then(e=>{cy=ly(e.env)??void 0}).catch(()=>{});function ly(e){return typeof e!=`object`||!e||`then`in e&&typeof e.then==`function`?null:e}function uy(){return ly(globalThis.__env__)}function dy(){return sy.getStore()??uy()??cy??(()=>{throw Error(`env: Cloudflare env is unavailable. Use void runtime bindings inside Nuxt/SvelteKit/Analog server request handlers or Worker handlers.`)})()}var fy=Symbol.for(`void.runtimeRequestScope.v1`),py=globalThis;py[fy]??=new Ko;var my=py[fy];function hy(e,t,n){let r=my.getStore();if(!r){if(n)return n();throw Error(`env: Request-scoped resource is unavailable outside a runtime handler.`)}if(r.resources.has(e))return r.resources.get(e);let i=t();return r.resources.set(e,i),i}function gy(e,t){let n=ly(e);if(!n)return t();if(my.getStore())return sy.run(n,t);let r={resources:new Map};return sy.run(n,()=>my.run(r,t))}function _y(e,t){return ny.some(t=>e.startsWith(t))?!0:iy(t)&&ry.includes(e)}function vy(e){return new Proxy(e,{get(e,t,n){if(!(typeof t==`string`&&_y(t,e)))return Reflect.get(e,t,n)},has(e,t){return typeof t==`string`&&_y(t,e)?!1:Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e).filter(t=>typeof t!=`string`||!_y(t,e))},getOwnPropertyDescriptor(e,t){if(!(typeof t==`string`&&_y(t,e)))return Reflect.getOwnPropertyDescriptor(e,t)}})}function yy(){return vy(dy())}function by(e){let t=dy();if(!_y(e,t))return t[e]}var xy=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}},Sy=Symbol(),Cy=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),wy=1e4,Ty=e=>`headers`in e,Ey=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Ty(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Dy(e,{all:n,dot:r}):{}};async function Dy(e,t){if(!Ty(e)&&e.bodyCache.formData)return Oy(await e.bodyCache.formData,t);let n=Ty(e)?e.headers:e.raw.headers,r=Cy(await e.arrayBuffer(),n.get(`Content-Type`)||``);Ty(e)||(e.bodyCache.formData=r);let i=await r;return i?Oy(i,t):{}}function Oy(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?ky(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(Ay(n,e,t,r),delete n[e])}),n}var ky=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},Ay=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,34);a.length>33&&jy(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=wy&&jy(),i[e]=Object.create(null)),i=i[e])})},jy=()=>{throw Error(`Nesting limit exceeded`)},My=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&se(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=se(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return P(this.url,e)}queries(e){return re(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return Ey(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let r in t)return t[r].then(t=>{r===`json`&&(t=JSON.stringify(t));let i=r===`formData`?void 0:n.headers.get(`content-type`);return new Response(t,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Sy](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Ny={Stringify:1,BeforeStream:2,Stream:3},Py=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Fy=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Fy(e,t,!1,r,i))).then(()=>i[0]));return n?Py(await o,a):o},dee=`text/plain; charset=UTF-8`,Iy=(e,t)=>({"Content-Type":e,...t}),Ly=(e,t)=>new Response(e,t),fee=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new My(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=Ly(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=Ly(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=Ly(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return Ly(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,Iy(dee,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,Iy(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,Iy(`text/html; charset=UTF-8`,n));return typeof e==`object`?Fy(e,Ny.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Ly(),this.#c(this))},Ry=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},pee=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],zy=`Can not add a route since the matcher is already built.`,By=class extends Error{},Vy=`__COMPOSED_HANDLER`,mee=e=>e.text(`404 Not Found`,404),Hy=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},hee=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...pee,`all`].forEach(e=>{this[e]=(t,...n)=>{let r=e.toUpperCase();return typeof t==`string`?this.#e=t:this.#r(r,this.#e,t),n.forEach(e=>{this.#r(r,this.#e,e)}),this}}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat()){let e=t.toUpperCase();for(let t of n)this.#r(e,this.#e,t)}}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??N:oe}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=mee;errorHandler=Hy;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Hy?r=e.handler:(r=async(n,r)=>(await Ry([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Vy]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=de(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=de(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,de(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){t=de(this._basePath,t);let i={basePath:r===void 0?this._basePath:de(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new fee(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=Ry(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${de(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Uy=()=>Object.create(null),Wy=[];function gee(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Wy];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var Gy=`[^/]+`,Ky=`(?:|/.*)`,qy=Symbol(),Jy=new Set(`.\\+*[^]$()`);function Yy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Xy=class e{#e;#t;#n=Uy();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,Gy]:null:s===`/*`?[``,``,Ky]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Jy.has(n)))throw qy;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw qy}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw qy;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw qy;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Yy).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Jy.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Zy=class{#e={varIndex:0};#t=new Xy;#n=0;paths=Uy();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Qy=Uy();function $y(e){return Qy[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Ky:e===`*`?`.*`:`/:${Gy}`)}$`)}function eb(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if($y(n).test(t))return[...e[n]]}var tb=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Uy()},this.#t={ALL:Uy()},this.#n={ALL:new Zy}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===qy?new By(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(zy);if(!r[e]){this.#n[e]=new Zy;for(let t of[r,i]){t[e]=Uy();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=$y(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=eb(r[e],t)||eb(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=I(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=eb(r[t],e)||eb(r.ALL,e)||[]),i[t][e].push([n,e])}match=gee;buildAllMatchers(){let e=Uy();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Qy=Uy(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Uy(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];o?a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),Uy())]):i[t]=[n.map(([e])=>[e,Uy()]),Wy]}return[o,s.map(e=>a[e]),i]}},nb=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(zy);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof By)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},rb=Uy(),ib=0,ab=class e{#e=[];#t=Uy();#n=[];#r;#i=rb;insert(t,n,r){let i=this,a=ne(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=le(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),c=Array.isArray(r),l=c?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,c&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++ib}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=Uy(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=rb;let r=[this],i=te(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===rb?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},ob=class{name=`TrieRouter`;#e=new ab;add(e,t,n){for(let r of I(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},sb=class extends hee{constructor(e={}){super(e),this.router=e.router??new nb({routers:[new tb,new ob]})}},cb=(...e)=>async function(t,n){let r=!1,i=()=>(r=!0,n()),a,o;for(let n of e)try{let e=await n(t,i);if(e===!0&&!t.finalized)await i();else if(e===!1){a=Error(`No successful middleware found`);continue}else e&&e!==!0&&(o=e);a=void 0;break}catch(e){if(a=e,r)break}if(a)throw a;return o},lb=(...e)=>async function(t,n){let r=t.req.routeIndex;await Ry(e.map(e=>[[async(t,n)=>{t.req.routeIndex=r;let i=await e(t,n);if(i===!1)throw Error(`Unmet condition`);return i}]]))(t,n)},ub=(e,...t)=>{let n,r=(Array.isArray(e)?e:[e]).map(e=>{if(typeof e==`string`)n||=new ob,n.add(`ALL`,e,!0);else return e}).filter(Boolean);n&&r.unshift(e=>!!n?.match(`ALL`,e.req.path)?.[0]?.[0]?.[0]);let i=cb(e=>r.some(t=>t(e)),lb(...t));return async function(e,t){await i(e,t)}},db=[`same-origin`,`same-site`,`none`,`cross-site`],fb=e=>db.includes(e),pb=/^(GET|HEAD|OPTIONS)$/,mb=/^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i,hb=e=>{let t=(e=>e?typeof e==`string`?t=>t===e:typeof e==`function`?e:t=>e.includes(t):(e,t)=>e===new URL(t.req.url).origin)(e?.origin),n=async(e,n)=>e!==void 0&&await t(e,n),r=(e=>e?typeof e==`string`?t=>t===e:typeof e==`function`?e:t=>e.includes(t):e=>e===`same-origin`)(e?.secFetchSite),i=async(e,t)=>e===void 0||!fb(e)?!1:await r(e,t);return async function(e,t){if(!pb.test(e.req.method)&&mb.test(e.req.header(`content-type`)||`text/plain`)&&!await i(e.req.header(`sec-fetch-site`),e)&&!await n(e.req.header(`origin`),e))throw new xy(403,{res:new Response(`Forbidden`,{status:403})});await t()}},gb={crossOriginEmbedderPolicy:[`Cross-Origin-Embedder-Policy`,`require-corp`],crossOriginResourcePolicy:[`Cross-Origin-Resource-Policy`,`same-origin`],crossOriginOpenerPolicy:[`Cross-Origin-Opener-Policy`,`same-origin`],originAgentCluster:[`Origin-Agent-Cluster`,`?1`],referrerPolicy:[`Referrer-Policy`,`no-referrer`],strictTransportSecurity:[`Strict-Transport-Security`,`max-age=15552000; includeSubDomains`],xContentTypeOptions:[`X-Content-Type-Options`,`nosniff`],xDnsPrefetchControl:[`X-DNS-Prefetch-Control`,`off`],xDownloadOptions:[`X-Download-Options`,`noopen`],xFrameOptions:[`X-Frame-Options`,`SAMEORIGIN`],xPermittedCrossDomainPolicies:[`X-Permitted-Cross-Domain-Policies`,`none`],xXssProtection:[`X-XSS-Protection`,`0`]},_ee={crossOriginEmbedderPolicy:!1,crossOriginResourcePolicy:!0,crossOriginOpenerPolicy:!0,originAgentCluster:!0,referrerPolicy:!0,strictTransportSecurity:!0,xContentTypeOptions:!0,xDnsPrefetchControl:!0,xDownloadOptions:!0,xFrameOptions:!0,xPermittedCrossDomainPolicies:!0,xXssProtection:!0,removePoweredBy:!0,permissionsPolicy:{}},_b=e=>{let t={..._ee,...e},n=vb(t),r=[];if(t.contentSecurityPolicy){let[e,i]=yb(t.contentSecurityPolicy,`Content-Security-Policy`);e&&r.push(e),n.push([`Content-Security-Policy`,i])}if(t.contentSecurityPolicyReportOnly){let[e,i]=yb(t.contentSecurityPolicyReportOnly,`Content-Security-Policy-Report-Only`);e&&r.push(e),n.push([`Content-Security-Policy-Report-Only`,i])}return t.permissionsPolicy&&Object.keys(t.permissionsPolicy).length>0&&n.push([`Permissions-Policy`,bb(t.permissionsPolicy)]),t.reportingEndpoints&&n.push([`Reporting-Endpoints`,Sb(t.reportingEndpoints)]),t.reportTo&&n.push([`Report-To`,Cb(t.reportTo)]),async function(e,i){let a=r.length===0?n:r.reduce((t,n)=>n(e,t),n);await i(),wb(e,a),t?.removePoweredBy&&e.res.headers.delete(`X-Powered-By`)}};function vb(e){return Object.entries(gb).filter(([t])=>e[t]).map(([t,n])=>{let r=e[t];return typeof r==`string`?[n[0],r]:n})}function yb(e,t){let n=[],r=[];for(let[t,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];e.forEach((e,i)=>{if(typeof e==`function`){let a=i*2+2+r.length;n.push((n,r)=>{r[a]=e(n,t)})}}),r.push(t.replace(/[A-Z]+(?![a-z])|[A-Z]/g,(e,t)=>t?`-`+e.toLowerCase():e.toLowerCase()),...e.flatMap(e=>[` `,e]),`; `)}return r.pop(),n.length===0?[void 0,r.join(``)]:[(e,r)=>r.map(r=>{if(r[0]===t){let t=r[1].slice();return n.forEach(n=>{n(e,t)}),[r[0],t.join(``)]}return r}),r]}function bb(e){return Object.entries(e).map(([e,t])=>{let n=xb(e);return typeof t==`boolean`?`${n}=${t?`*`:`()`}`:Array.isArray(t)?t.length===0?`${n}=()`:t.length===1&&t[0]===`*`?`${n}=*`:t.length===1&&t[0]===`none`?`${n}=()`:`${n}=(${t.map(e=>[`self`,`src`].includes(e)?e:`"${e}"`).join(` `)})`:``}).filter(Boolean).join(`, `)}function xb(e){return e.replace(/([a-z\d])([A-Z])/g,`$1-$2`).toLowerCase()}function Sb(e=[]){return e.map(e=>`${e.name}="${e.url}"`).join(`, `)}function Cb(e=[]){return e.map(e=>JSON.stringify(e)).join(`, `)}function wb(e,t){t.forEach(([t,n])=>{e.res.headers.set(t,n)})}var Tb=e=>async function(t,n){if(e?.alwaysRedirect&&(t.req.method===`GET`||t.req.method===`HEAD`)&&t.req.path!==`/`&&t.req.path.at(-1)===`/`){let e=new URL(t.req.url);return e.pathname=e.pathname.substring(0,e.pathname.length-1),t.redirect(e.toString(),301)}if(await n(),!e?.alwaysRedirect&&t.res.status===404&&(t.req.method===`GET`||t.req.method===`HEAD`)&&t.req.path!==`/`&&t.req.path.at(-1)===`/`){let e=new URL(t.req.url);e.pathname=e.pathname.substring(0,e.pathname.length-1),t.res=t.redirect(e.toString(),301)}};function Eb(e,t,n){let r=ve(e,t,n);if(r.type!==`event`)throw new We({name:t,type:`event`});return r}function Db(e){return ye(e)}function Ob(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`}function kb(e,t){return Array.isArray(t)?t.length===0?!0:e?t.every(e=>typeof e==`string`):t.every(e=>Number.isSafeInteger(e)):!1}function Ab(e){if(typeof e!=`function`)throw Error(`function expected`);return!0}function jb(e,t){if(typeof t!=`string`)throw Error(`${e}: string expected`);return!0}function Mb(e){if(!Number.isSafeInteger(e))throw Error(`invalid integer: ${e}`)}function Nb(e){if(!Array.isArray(e))throw Error(`array expected`)}function Pb(e,t){if(!kb(!0,t))throw Error(`${e}: array of strings expected`)}function Fb(e,t){if(!kb(!1,t))throw Error(`${e}: array of numbers expected`)}function Ib(...e){let t=e=>e,n=(e,t)=>n=>e(t(n));return{encode:e.map(e=>e.encode).reduceRight(n,t),decode:e.map(e=>e.decode).reduce(n,t)}}function Lb(e){let t=typeof e==`string`?e.split(``):e,n=t.length;Pb(`alphabet`,t);let r=new Map(t.map((e,t)=>[e,t]));return{encode:r=>(Nb(r),r.map(r=>{if(!Number.isSafeInteger(r)||r<0||r>=n)throw Error(`alphabet.encode: digit index outside alphabet "${r}". Allowed: ${e}`);return t[r]})),decode:t=>(Nb(t),t.map(t=>{jb(`alphabet.decode`,t);let n=r.get(t);if(n===void 0)throw Error(`Unknown letter: "${t}". Allowed: ${e}`);return n}))}}function Rb(e=``){return jb(`join`,e),{encode:t=>(Pb(`join.decode`,t),t.join(e)),decode:t=>(jb(`join.decode`,t),t.split(e))}}function zb(e,t=`=`){return Mb(e),jb(`padding`,t),{encode(n){for(Pb(`padding.encode`,n);n.length*e%8;)n.push(t);return n},decode(n){Pb(`padding.decode`,n);let r=n.length;if(r*e%8)throw Error(`padding: invalid, string should have whole number of bytes`);for(;r>0&&n[r-1]===t;r--)if((r-1)*e%8==0)throw Error(`padding: invalid, string has too much padding`);return n.slice(0,r)}}}function Bb(e){return Ab(e),{encode:e=>e,decode:t=>e(t)}}function Vb(e,t,n){if(t<2)throw Error(`convertRadix: invalid from=${t}, base cannot be less than 2`);if(n<2)throw Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Nb(e),!e.length)return[];let r=0,i=[],a=Array.from(e,e=>{if(Mb(e),e<0||e>=t)throw Error(`invalid integer: ${e}`);return e}),o=a.length;for(;;){let e=0,s=!0;for(let i=r;i<o;i++){let o=a[i],c=t*e,l=c+o;if(!Number.isSafeInteger(l)||c/t!==e||l-o!==c)throw Error(`convertRadix: carry overflow`);let u=l/n;e=l%n;let d=Math.floor(u);if(a[i]=d,!Number.isSafeInteger(d)||d*n+e!==l)throw Error(`convertRadix: carry overflow`);if(s)d?s=!1:r=i;else continue}if(i.push(e),s)break}for(let t=0;t<e.length-1&&e[t]===0;t++)i.push(0);return i.reverse()}var Hb=(e,t)=>t===0?e:Hb(t,e%t),Ub=(e,t)=>e+(t-Hb(e,t)),Wb=(()=>{let e=[];for(let t=0;t<40;t++)e.push(2**t);return e})();function Gb(e,t,n,r){if(Nb(e),t<=0||t>32)throw Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw Error(`convertRadix2: wrong to=${n}`);if(Ub(t,n)>32)throw Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${Ub(t,n)}`);let i=0,a=0,o=Wb[t],s=Wb[n]-1,c=[];for(let r of e){if(Mb(r),r>=o)throw Error(`convertRadix2: invalid data word=${r} from=${t}`);if(i=i<<t|r,a+t>32)throw Error(`convertRadix2: carry overflow pos=${a} from=${t}`);for(a+=t;a>=n;a-=n)c.push((i>>a-n&s)>>>0);let e=Wb[a];if(e===void 0)throw Error(`invalid carry`);i&=e-1}if(i=i<<n-a&s,!r&&a>=t)throw Error(`Excess padding`);if(!r&&i>0)throw Error(`Non-zero padding: ${i}`);return r&&a>0&&c.push(i>>>0),c}function Kb(e){return Mb(e),{encode:t=>{if(!Ob(t))throw Error(`radix.encode input should be Uint8Array`);return Vb(Array.from(t),256,e)},decode:t=>(Fb(`radix.decode`,t),Uint8Array.from(Vb(t,e,256)))}}function qb(e,t=!1){if(Mb(e),e<=0||e>32)throw Error(`radix2: bits should be in (0..32]`);if(Ub(8,e)>32||Ub(e,8)>32)throw Error(`radix2: carry overflow`);return{encode:n=>{if(!Ob(n))throw Error(`radix2.encode input should be Uint8Array`);return Gb(Array.from(n),8,e,!t)},decode:n=>(Fb(`radix2.decode`,n),Uint8Array.from(Gb(n,e,8,t)))}}function Jb(e){return Ab(e),function(...t){try{return e.apply(null,t)}catch{}}}Ib(qb(4),Lb(`0123456789ABCDEF`),Rb(``));var Yb=Ib(qb(5),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`),zb(5),Rb(``));Ib(qb(5),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZ234567`),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHIJKLMNOPQRSTUV`),zb(5),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHIJKLMNOPQRSTUV`),Rb(``)),Ib(qb(5),Lb(`0123456789ABCDEFGHJKMNPQRSTVWXYZ`),Rb(``),Bb(e=>e.toUpperCase().replace(/O/g,`0`).replace(/[IL]/g,`1`)));var Xb=typeof Uint8Array.from([]).toBase64==`function`&&typeof Uint8Array.fromBase64==`function`;Xb||Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`),zb(6),Rb(``)),Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`),Rb(``)),Xb||Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`),zb(6),Rb(``)),Ib(qb(6),Lb(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`),Rb(``));var Zb=(e=>Ib(Kb(58),Lb(e),Rb(``)))(`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`),Qb=Ib(Lb(`qpzry9x8gf2tvdw0s3jn54khce6mua7l`),Rb(``)),$b=[996825010,642813549,513874426,1027748829,705979059];function ex(e){let t=e>>25,n=(e&33554431)<<5;for(let e=0;e<$b.length;e++)(t>>e&1)==1&&(n^=$b[e]);return n}function tx(e,t,n=1){let r=e.length,i=1;for(let t=0;t<r;t++){let n=e.charCodeAt(t);if(n<33||n>126)throw Error(`Invalid prefix (${e})`);i=ex(i)^n>>5}i=ex(i);for(let t=0;t<r;t++)i=ex(i)^e.charCodeAt(t)&31;for(let e of t)i=ex(i)^e;for(let e=0;e<6;e++)i=ex(i);return i^=n,Qb.encode(Gb([i%Wb[30]],30,5,!1))}function nx(e){let t=e===`bech32`?1:734539939,n=qb(5),r=n.decode,i=n.encode,a=Jb(r);function o(e,n,r=90){jb(`bech32.encode prefix`,e),Ob(n)&&(n=Array.from(n)),Fb(`bech32.encode`,n);let i=e.length;if(i===0)throw TypeError(`Invalid prefix length ${i}`);let a=i+7+n.length;if(r!==!1&&a>r)throw TypeError(`Length ${a} exceeds limit ${r}`);let o=e.toLowerCase(),s=tx(o,n,t);return`${o}1${Qb.encode(n)}${s}`}function s(e,n=90){jb(`bech32.decode input`,e);let r=e.length;if(r<8||n!==!1&&r>n)throw TypeError(`invalid string length: ${r} (${e}). Expected (8..${n})`);let i=e.toLowerCase();if(e!==i&&e!==e.toUpperCase())throw Error(`String must be lowercase or uppercase`);let a=i.lastIndexOf(`1`);if(a===0||a===-1)throw Error(`Letter "1" must be present between prefix and data only`);let o=i.slice(0,a),s=i.slice(a+1);if(s.length<6)throw Error(`Data must be at least 6 characters long`);let c=Qb.decode(s).slice(0,-6),l=tx(o,c,t);if(!s.endsWith(l))throw Error(`Invalid checksum in ${e}: expected "${l}"`);return{prefix:o,words:c}}let c=Jb(s);function l(e){let{prefix:t,words:n}=s(e,!1);return{prefix:t,words:n,bytes:r(n)}}function u(e,t){return o(e,i(t))}return{encode:o,decode:s,encodeFromBytes:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:a,toWords:i}}nx(`bech32`),nx(`bech32m`),typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`||Ib(qb(4),Lb(`0123456789abcdef`),Rb(``),Bb(e=>{if(typeof e!=`string`||e.length%2!=0)throw TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));var rx=BigInt(0),ix=BigInt(1);function ax(e,t=``){if(typeof e!=`boolean`){let n=t&&`"${t}"`;throw Error(n+`expected boolean, got type=`+typeof e)}return e}function ox(e,t,n=``){let r=Ct(e),i=e?.length,a=t!==void 0;if(!r||a&&i!==t){let o=n&&`"${n}" `,s=a?` of length ${t}`:``,c=r?`length=${i}`:`type=${typeof e}`;throw Error(o+`expected Uint8Array`+s+`, got `+c)}return e}function sx(e){let t=e.toString(16);return t.length&1?`0`+t:t}function cx(e){if(typeof e!=`string`)throw Error(`hex string expected, got `+typeof e);return e===``?rx:BigInt(`0x`+e)}function lx(e){return cx(St(e))}function ux(e){return Et(e),cx(St(Uint8Array.from(e).reverse()))}function dx(e,t){return wt(e.toString(16).padStart(t*2,`0`))}function fx(e,t){return dx(e,t).reverse()}function px(e,t,n){let r;if(typeof t==`string`)try{r=wt(t)}catch(t){throw Error(e+` must be hex string or Uint8Array, cause: `+t)}else if(Ct(t))r=Uint8Array.from(t);else throw Error(e+` must be hex string or Uint8Array`);let i=r.length;if(typeof n==`number`&&i!==n)throw Error(e+` of length `+n+` expected, got `+i);return r}var mx=e=>typeof e==`bigint`&&rx<=e;function hx(e,t,n){return mx(e)&&mx(t)&&mx(n)&&t<=e&&e<n}function gx(e,t,n,r){if(!hx(t,n,r))throw Error(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function _x(e){let t=0;for(;e>rx;e>>=ix,t+=1);return t}var vx=e=>(ix<<BigInt(e))-ix;function yx(e,t,n){if(typeof e!=`number`||e<2)throw Error(`hashLen must be a number`);if(typeof t!=`number`||t<2)throw Error(`qByteLen must be a number`);if(typeof n!=`function`)throw Error(`hmacFn must be a function`);let r=e=>new Uint8Array(e),i=e=>Uint8Array.of(e),a=r(e),o=r(e),s=0,c=()=>{a.fill(1),o.fill(0),s=0},l=(...e)=>n(o,a,...e),u=(e=r(0))=>{o=l(i(0),e),a=l(),e.length!==0&&(o=l(i(1),e),a=l())},d=()=>{if(s++>=1e3)throw Error(`drbg: tried 1000 values`);let e=0,n=[];for(;e<t;){a=l();let t=a.slice();n.push(t),e+=a.length}return bt(...n)};return(e,t)=>{c(),u(e);let n;for(;!(n=t(d()));)u();return c(),n}}function bx(e,t,n={}){if(!e||typeof e!=`object`)throw Error(`expected valid options object`);function r(t,n,r){let i=e[t];if(r&&i===void 0)return;let a=typeof i;if(a!==n||i===null)throw Error(`param "${t}" is invalid: expected ${n}, got ${a}`)}Object.entries(t).forEach(([e,t])=>r(e,t,!1)),Object.entries(n).forEach(([e,t])=>r(e,t,!0))}function xx(e){let t=new WeakMap;return(n,...r)=>{let i=t.get(n);if(i!==void 0)return i;let a=e(n,...r);return t.set(n,a),a}}var Sx=BigInt(0),Cx=BigInt(1),wx=BigInt(2),Tx=BigInt(3),Ex=BigInt(4),Dx=BigInt(5),Ox=BigInt(7),kx=BigInt(8),Ax=BigInt(9),jx=BigInt(16);function Mx(e,t){let n=e%t;return n>=Sx?n:t+n}function Nx(e,t){if(e===Sx)throw Error(`invert: expected non-zero number`);if(t<=Sx)throw Error(`invert: expected positive modulus, got `+t);let n=Mx(e,t),r=t,i=Sx,a=Cx,o=Cx,s=Sx;for(;n!==Sx;){let e=r/n,t=r%n,c=i-o*e,l=a-s*e;r=n,n=t,i=o,a=s,o=c,s=l}if(r!==Cx)throw Error(`invert: does not exist`);return Mx(i,t)}function Px(e,t,n){if(!e.eql(e.sqr(t),n))throw Error(`Cannot find square root`)}function Fx(e,t){let n=(e.ORDER+Cx)/Ex,r=e.pow(t,n);return Px(e,r,t),r}function Ix(e,t){let n=(e.ORDER-Dx)/kx,r=e.mul(t,wx),i=e.pow(r,n),a=e.mul(t,i),o=e.mul(e.mul(a,wx),i),s=e.mul(a,e.sub(o,e.ONE));return Px(e,s,t),s}function Lx(e){let t=Kx(e),n=Rx(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+Ox)/jx;return(e,t)=>{let n=e.pow(t,o),s=e.mul(n,r),c=e.mul(n,i),l=e.mul(n,a),u=e.eql(e.sqr(s),t),d=e.eql(e.sqr(c),t);n=e.cmov(n,s,u),s=e.cmov(l,c,d);let f=e.eql(e.sqr(s),t),p=e.cmov(n,s,f);return Px(e,p,t),p}}function Rx(e){if(e<Tx)throw Error(`sqrt is not defined for small field`);let t=e-Cx,n=0;for(;t%wx===Sx;)t/=wx,n++;let r=wx,i=Kx(e);for(;Wx(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Fx;let a=i.pow(r,t),o=(t+Cx)/wx;return function(e,r){if(e.is0(r))return r;if(Wx(e,r)!==1)throw Error(`Cannot find square root`);let i=n,s=e.mul(e.ONE,a),c=e.pow(r,t),l=e.pow(r,o);for(;!e.eql(c,e.ONE);){if(e.is0(c))return e.ZERO;let t=1,n=e.sqr(c);for(;!e.eql(n,e.ONE);)if(t++,n=e.sqr(n),t===i)throw Error(`Cannot find square root`);let r=Cx<<BigInt(i-t-1),a=e.pow(s,r);i=t,s=e.sqr(a),c=e.mul(c,s),l=e.mul(l,a)}return l}}function zx(e){return e%Ex===Tx?Fx:e%kx===Dx?Ix:e%jx===Ax?Lx(e):Rx(e)}var Bx=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function Vx(e){return bx(e,Bx.reduce((e,t)=>(e[t]=`function`,e),{ORDER:`bigint`,MASK:`bigint`,BYTES:`number`,BITS:`number`})),e}function Hx(e,t,n){if(n<Sx)throw Error(`invalid exponent, negatives unsupported`);if(n===Sx)return e.ONE;if(n===Cx)return t;let r=e.ONE,i=t;for(;n>Sx;)n&Cx&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Cx;return r}function Ux(e,t,n=!1){let r=Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((t,n,i)=>e.is0(n)?t:(r[i]=t,e.mul(t,n)),e.ONE),a=e.inv(i);return t.reduceRight((t,n,i)=>e.is0(n)?t:(r[i]=e.mul(t,r[i]),e.mul(t,n)),a),r}function Wx(e,t){let n=(e.ORDER-Cx)/wx,r=e.pow(t,n),i=e.eql(r,e.ONE),a=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!a&&!o)throw Error(`invalid Legendre symbol result`);return i?1:a?0:-1}function Gx(e,t){t!==void 0&&yt(t);let n=t===void 0?e.toString(2).length:t;return{nBitLength:n,nByteLength:Math.ceil(n/8)}}function Kx(e,t,n=!1,r={}){if(e<=Sx)throw Error(`invalid field: expected ORDER > 0, got `+e);let i,a,o=!1,s;if(typeof t==`object`&&t){if(r.sqrt||n)throw Error(`cannot specify opts in two arguments`);let e=t;e.BITS&&(i=e.BITS),e.sqrt&&(a=e.sqrt),typeof e.isLE==`boolean`&&(n=e.isLE),typeof e.modFromBytes==`boolean`&&(o=e.modFromBytes),s=e.allowedLengths}else typeof t==`number`&&(i=t),r.sqrt&&(a=r.sqrt);let{nBitLength:c,nByteLength:l}=Gx(e,i);if(l>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);let u,d=Object.freeze({ORDER:e,isLE:n,BITS:c,BYTES:l,MASK:vx(c),ZERO:Sx,ONE:Cx,allowedLengths:s,create:t=>Mx(t,e),isValid:t=>{if(typeof t!=`bigint`)throw Error(`invalid field element: expected bigint, got `+typeof t);return Sx<=t&&t<e},is0:e=>e===Sx,isValidNot0:e=>!d.is0(e)&&d.isValid(e),isOdd:e=>(e&Cx)===Cx,neg:t=>Mx(-t,e),eql:(e,t)=>e===t,sqr:t=>Mx(t*t,e),add:(t,n)=>Mx(t+n,e),sub:(t,n)=>Mx(t-n,e),mul:(t,n)=>Mx(t*n,e),pow:(e,t)=>Hx(d,e,t),div:(t,n)=>Mx(t*Nx(n,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>Nx(t,e),sqrt:a||(t=>(u||=zx(e),u(d,t))),toBytes:e=>n?fx(e,l):dx(e,l),fromBytes:(t,r=!0)=>{if(s){if(!s.includes(t.length)||t.length>l)throw Error(`Field.fromBytes: expected `+s+` bytes, got `+t.length);let e=new Uint8Array(l);e.set(t,n?0:e.length-t.length),t=e}if(t.length!==l)throw Error(`Field.fromBytes: expected `+l+` bytes, got `+t.length);let i=n?ux(t):lx(t);if(o&&(i=Mx(i,e)),!r&&!d.isValid(i))throw Error(`invalid field element: outside of range 0..ORDER`);return i},invertBatch:e=>Ux(d,e),cmov:(e,t,n)=>n?t:e});return Object.freeze(d)}function qx(e){if(typeof e!=`bigint`)throw Error(`field order must be bigint`);let t=e.toString(2).length;return Math.ceil(t/8)}function Jx(e){let t=qx(e);return t+Math.ceil(t/2)}function Yx(e,t,n=!1){let r=e.length,i=qx(t),a=Jx(t);if(r<16||r<a||r>1024)throw Error(`expected `+a+`-1024 bytes of input, got `+r);let o=Mx(n?ux(e):lx(e),t-Cx)+Cx;return n?fx(o,i):dx(o,i)}var Xx=BigInt(0),Zx=BigInt(1);function Qx(e,t){let n=t.negate();return e?n:t}function $x(e,t){let n=Ux(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function eS(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw Error(`invalid window size, expected [1..`+t+`], got W=`+e)}function tS(e,t){eS(e,t);let n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e;return{windows:n,windowSize:r,mask:vx(e),maxNumber:i,shiftBy:BigInt(e)}}function nS(e,t,n){let{windowSize:r,mask:i,maxNumber:a,shiftBy:o}=n,s=Number(e&i),c=e>>o;s>r&&(s-=a,c+=Zx);let l=t*r,u=l+Math.abs(s)-1,d=s===0,f=s<0,p=t%2!=0;return{nextN:c,offset:u,isZero:d,isNeg:f,isNegF:p,offsetF:l}}function rS(e,t){if(!Array.isArray(e))throw Error(`array expected`);e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function iS(e,t){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,n)=>{if(!t.isValid(e))throw Error(`invalid scalar at index `+n)})}var aS=new WeakMap,oS=new WeakMap;function sS(e){return oS.get(e)||1}function cS(e){if(e!==Xx)throw Error(`invalid wNAF`)}var lS=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let r=e;for(;t>Xx;)t&Zx&&(n=n.add(r)),r=r.double(),t>>=Zx;return n}precomputeWindow(e,t){let{windows:n,windowSize:r}=tS(t,this.bits),i=[],a=e,o=a;for(let e=0;e<n;e++){o=a,i.push(o);for(let e=1;e<r;e++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,n){if(!this.Fn.isValid(n))throw Error(`invalid scalar`);let r=this.ZERO,i=this.BASE,a=tS(e,this.bits);for(let e=0;e<a.windows;e++){let{nextN:o,offset:s,isZero:c,isNeg:l,isNegF:u,offsetF:d}=nS(n,e,a);n=o,c?i=i.add(Qx(u,t[d])):r=r.add(Qx(l,t[s]))}return cS(n),{p:r,f:i}}wNAFUnsafe(e,t,n,r=this.ZERO){let i=tS(e,this.bits);for(let e=0;e<i.windows&&n!==Xx;e++){let{nextN:a,offset:o,isZero:s,isNeg:c}=nS(n,e,i);if(n=a,!s){let e=t[o];r=r.add(c?e.negate():e)}}return cS(n),r}getPrecomputes(e,t,n){let r=aS.get(t);return r||(r=this.precomputeWindow(t,e),e!==1&&(typeof n==`function`&&(r=n(r)),aS.set(t,r))),r}cached(e,t,n){let r=sS(e);return this.wNAF(r,this.getPrecomputes(r,e,n),t)}unsafe(e,t,n,r){let i=sS(e);return i===1?this._unsafeLadder(e,t,r):this.wNAFUnsafe(i,this.getPrecomputes(i,e,n),t,r)}createCache(e,t){eS(t,this.bits),oS.set(e,t),aS.delete(e)}hasCache(e){return sS(e)!==1}};function uS(e,t,n,r){let i=t,a=e.ZERO,o=e.ZERO;for(;n>Xx||r>Xx;)n&Zx&&(a=a.add(i)),r&Zx&&(o=o.add(i)),i=i.double(),n>>=Zx,r>>=Zx;return{p1:a,p2:o}}function dS(e,t,n,r){rS(n,e),iS(r,t);let i=n.length,a=r.length;if(i!==a)throw Error(`arrays of points and scalars must have equal length`);let o=e.ZERO,s=_x(BigInt(i)),c=1;s>12?c=s-3:s>4?c=s-2:s>0&&(c=2);let l=vx(c),u=Array(Number(l)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c,f=o;for(let e=d;e>=0;e-=c){u.fill(o);for(let t=0;t<a;t++){let i=r[t],a=Number(i>>BigInt(e)&l);u[a]=u[a].add(n[t])}let t=o;for(let e=u.length-1,n=o;e>0;e--)n=n.add(u[e]),t=t.add(n);if(f=f.add(t),e!==0)for(let e=0;e<c;e++)f=f.double()}return f}function fS(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return Vx(t),t}return Kx(e,{isLE:n})}function pS(e,t,n={},r){if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(typeof n==`bigint`&&n>Xx))throw Error(`CURVE.${e} must be positive bigint`)}let i=fS(t.p,n.Fp,r),a=fS(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}var mS=(e,t)=>(e+(e>=0?t:-t)/xS)/t;function hS(e,t,n){let[[r,i],[a,o]]=t,s=mS(o*e,n),c=mS(-i*e,n),l=e-s*r-c*a,u=-s*i-c*o,d=l<yS,f=u<yS;d&&(l=-l),f&&(u=-u);let p=vx(Math.ceil(_x(n)/2))+bS;if(l<yS||l>=p||u<yS||u>=p)throw Error(`splitScalar (endomorphism): failed, k=`+e);return{k1neg:d,k1:l,k2neg:f,k2:u}}function gS(e){if(![`compact`,`recovered`,`der`].includes(e))throw Error(`Signature format must be "compact", "recovered", or "der"`);return e}function _S(e,t){let n={};for(let r of Object.keys(t))n[r]=e[r]===void 0?t[r]:e[r];return ax(n.lowS,`lowS`),ax(n.prehash,`prehash`),n.format!==void 0&&gS(n.format),n}var vS={Err:class extends Error{constructor(e=``){super(e)}},_tlv:{encode:(e,t)=>{let{Err:n}=vS;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length&1)throw new n(`tlv.encode: unpadded data`);let r=t.length/2,i=sx(r);if(i.length/2&128)throw new n(`tlv.encode: long form length too big`);let a=r>127?sx(i.length/2|128):``;return sx(e)+a+i+t},decode(e,t){let{Err:n}=vS,r=0;if(e<0||e>256)throw new n(`tlv.encode: wrong tag`);if(t.length<2||t[r++]!==e)throw new n(`tlv.decode: wrong tlv`);let i=t[r++],a=!!(i&128),o=0;if(!a)o=i;else{let e=i&127;if(!e)throw new n(`tlv.decode(long): indefinite length not supported`);if(e>4)throw new n(`tlv.decode(long): byte length is too big`);let a=t.subarray(r,r+e);if(a.length!==e)throw new n(`tlv.decode: length bytes not complete`);if(a[0]===0)throw new n(`tlv.decode(long): zero leftmost byte`);for(let e of a)o=o<<8|e;if(r+=e,o<128)throw new n(`tlv.decode(long): not minimal encoding`)}let s=t.subarray(r,r+o);if(s.length!==o)throw new n(`tlv.decode: wrong value length`);return{v:s,l:t.subarray(r+o)}}},_int:{encode(e){let{Err:t}=vS;if(e<yS)throw new t(`integer: negative integers are not allowed`);let n=sx(e);if(Number.parseInt(n[0],16)&8&&(n=`00`+n),n.length&1)throw new t(`unexpected DER parsing assertion: unpadded hex`);return n},decode(e){let{Err:t}=vS;if(e[0]&128)throw new t(`invalid signature integer: negative`);if(e[0]===0&&!(e[1]&128))throw new t(`invalid signature integer: unnecessary leading zero`);return lx(e)}},toSig(e){let{Err:t,_int:n,_tlv:r}=vS,i=px(`signature`,e),{v:a,l:o}=r.decode(48,i);if(o.length)throw new t(`invalid signature: left bytes after parsing`);let{v:s,l:c}=r.decode(2,a),{v:l,l:u}=r.decode(2,c);if(u.length)throw new t(`invalid signature: left bytes after parsing`);return{r:n.decode(s),s:n.decode(l)}},hexFromSig(e){let{_tlv:t,_int:n}=vS,r=t.encode(2,n.encode(e.r))+t.encode(2,n.encode(e.s));return t.encode(48,r)}},yS=BigInt(0),bS=BigInt(1),xS=BigInt(2),SS=BigInt(3),CS=BigInt(4);function wS(e,t){let{BYTES:n}=e,r;if(typeof t==`bigint`)r=t;else{let i=px(`private key`,t);try{r=e.fromBytes(i)}catch{throw Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw Error(`invalid private key: out of range [1..N-1]`);return r}function TS(e,t={}){let n=pS(`weierstrass`,e,t),{Fp:r,Fn:i}=n,a=n.CURVE,{h:o,n:s}=a;bx(t,{},{allowInfinityPoint:`boolean`,clearCofactor:`function`,isTorsionFree:`function`,fromBytes:`function`,toBytes:`function`,endo:`object`,wrapPrivateKey:`boolean`});let{endo:c}=t;if(c&&(!r.is0(a.a)||typeof c.beta!=`bigint`||!Array.isArray(c.basises)))throw Error(`invalid endo: expected "beta": bigint and "basises": array`);let l=DS(r,i);function u(){if(!r.isOdd)throw Error(`compression is not supported: Field does not have .isOdd()`)}function d(e,t,n){let{x:i,y:a}=t.toAffine(),o=r.toBytes(i);if(ax(n,`isCompressed`),n){u();let e=!r.isOdd(a);return bt(ES(e),o)}return bt(Uint8Array.of(4),o,r.toBytes(a))}function f(e){ox(e,void 0,`Point`);let{publicKey:t,publicKeyUncompressed:n}=l,i=e.length,a=e[0],o=e.subarray(1);if(i===t&&(a===2||a===3)){let e=r.fromBytes(o);if(!r.isValid(e))throw Error(`bad point: is not on curve, wrong x`);let t=h(e),n;try{n=r.sqrt(t)}catch(e){let t=e instanceof Error?`: `+e.message:``;throw Error(`bad point: is not on curve, sqrt error`+t)}u();let i=r.isOdd(n);return(a&1)==1!==i&&(n=r.neg(n)),{x:e,y:n}}if(i===n&&a===4){let e=r.BYTES,t=r.fromBytes(o.subarray(0,e)),n=r.fromBytes(o.subarray(e,e*2));if(!g(t,n))throw Error(`bad point: is not on curve`);return{x:t,y:n}}throw Error(`bad point: got length ${i}, expected compressed=${t} or uncompressed=${n}`)}let p=t.toBytes||d,m=t.fromBytes||f;function h(e){let t=r.sqr(e),n=r.mul(t,e);return r.add(r.add(n,r.mul(e,a.a)),a.b)}function g(e,t){let n=r.sqr(t),i=h(e);return r.eql(n,i)}if(!g(a.Gx,a.Gy))throw Error(`bad curve params: generator point`);let _=r.mul(r.pow(a.a,SS),CS),v=r.mul(r.sqr(a.b),BigInt(27));if(r.is0(r.add(_,v)))throw Error(`bad curve params: a or b`);function y(e,t,n=!1){if(!r.isValid(t)||n&&r.is0(t))throw Error(`bad point coordinate ${e}`);return t}function b(e){if(!(e instanceof E))throw Error(`ProjectivePoint expected`)}function x(e){if(!c||!c.basises)throw Error(`no endo`);return hS(e,c.basises,i.ORDER)}let S=xx((e,t)=>{let{X:n,Y:i,Z:a}=e;if(r.eql(a,r.ONE))return{x:n,y:i};let o=e.is0();t??=o?r.ONE:r.inv(a);let s=r.mul(n,t),c=r.mul(i,t),l=r.mul(a,t);if(o)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw Error(`invZ was invalid`);return{x:s,y:c}}),C=xx(e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.Y))return;throw Error(`bad point: ZERO`)}let{x:n,y:i}=e.toAffine();if(!r.isValid(n)||!r.isValid(i))throw Error(`bad point: x or y not field elements`);if(!g(n,i))throw Error(`bad point: equation left != right`);if(!e.isTorsionFree())throw Error(`bad point: not in prime-order subgroup`);return!0});function w(e,t,n,i,a){return n=new E(r.mul(n.X,e),n.Y,n.Z),t=Qx(i,t),n=Qx(a,n),t.add(n)}class E{constructor(e,t,n){this.X=y(`x`,e),this.Y=y(`y`,t,!0),this.Z=y(`z`,n),Object.freeze(this)}static CURVE(){return a}static fromAffine(e){let{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw Error(`invalid affine point`);if(e instanceof E)throw Error(`projective point not allowed`);return r.is0(t)&&r.is0(n)?E.ZERO:new E(t,n,r.ONE)}static fromBytes(e){let t=E.fromAffine(m(ox(e,void 0,`point`)));return t.assertValidity(),t}static fromHex(e){return E.fromBytes(px(`pointHex`,e))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=8,t=!0){return O.createCache(this,e),t||this.multiply(SS),this}assertValidity(){C(this)}hasEvenY(){let{y:e}=this.toAffine();if(!r.isOdd)throw Error(`Field doesn't support isOdd`);return!r.isOdd(e)}equals(e){b(e);let{X:t,Y:n,Z:i}=this,{X:a,Y:o,Z:s}=e,c=r.eql(r.mul(t,s),r.mul(a,i)),l=r.eql(r.mul(n,s),r.mul(o,i));return c&&l}negate(){return new E(this.X,r.neg(this.Y),this.Z)}double(){let{a:e,b:t}=a,n=r.mul(t,SS),{X:i,Y:o,Z:s}=this,c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(i,i),f=r.mul(o,o),p=r.mul(s,s),m=r.mul(i,o);return m=r.add(m,m),u=r.mul(i,s),u=r.add(u,u),c=r.mul(e,u),l=r.mul(n,p),l=r.add(c,l),c=r.sub(f,l),l=r.add(f,l),l=r.mul(c,l),c=r.mul(m,c),u=r.mul(n,u),p=r.mul(e,p),m=r.sub(d,p),m=r.mul(e,m),m=r.add(m,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,p),d=r.mul(d,m),l=r.add(l,d),p=r.mul(o,s),p=r.add(p,p),d=r.mul(p,m),c=r.sub(c,d),u=r.mul(p,f),u=r.add(u,u),u=r.add(u,u),new E(c,l,u)}add(e){b(e);let{X:t,Y:n,Z:i}=this,{X:o,Y:s,Z:c}=e,l=r.ZERO,u=r.ZERO,d=r.ZERO,f=a.a,p=r.mul(a.b,SS),m=r.mul(t,o),h=r.mul(n,s),g=r.mul(i,c),_=r.add(t,n),v=r.add(o,s);_=r.mul(_,v),v=r.add(m,h),_=r.sub(_,v),v=r.add(t,i);let y=r.add(o,c);return v=r.mul(v,y),y=r.add(m,g),v=r.sub(v,y),y=r.add(n,i),l=r.add(s,c),y=r.mul(y,l),l=r.add(h,g),y=r.sub(y,l),d=r.mul(f,v),l=r.mul(p,g),d=r.add(l,d),l=r.sub(h,d),d=r.add(h,d),u=r.mul(l,d),h=r.add(m,m),h=r.add(h,m),g=r.mul(f,g),v=r.mul(p,v),h=r.add(h,g),g=r.sub(m,g),g=r.mul(f,g),v=r.add(v,g),m=r.mul(h,v),u=r.add(u,m),m=r.mul(y,v),l=r.mul(_,l),l=r.sub(l,m),m=r.mul(_,h),d=r.mul(y,d),d=r.add(d,m),new E(l,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(E.ZERO)}multiply(e){let{endo:n}=t;if(!i.isValidNot0(e))throw Error(`invalid scalar: out of range`);let r,a,o=e=>O.cached(this,e,e=>$x(E,e));if(n){let{k1neg:t,k1:i,k2neg:s,k2:c}=x(e),{p:l,f:u}=o(i),{p:d,f}=o(c);a=u.add(f),r=w(n.beta,l,d,t,s)}else{let{p:t,f:n}=o(e);r=t,a=n}return $x(E,[r,a])[0]}multiplyUnsafe(e){let{endo:n}=t,r=this;if(!i.isValid(e))throw Error(`invalid scalar: out of range`);if(e===yS||r.is0())return E.ZERO;if(e===bS)return r;if(O.hasCache(this))return this.multiply(e);if(n){let{k1neg:t,k1:i,k2neg:a,k2:o}=x(e),{p1:s,p2:c}=uS(E,r,i,o);return w(n.beta,s,c,t,a)}return O.unsafe(r,e)}multiplyAndAddUnsafe(e,t,n){let r=this.multiplyUnsafe(t).add(e.multiplyUnsafe(n));return r.is0()?void 0:r}toAffine(e){return S(this,e)}isTorsionFree(){let{isTorsionFree:e}=t;return o===bS?!0:e?e(E,this):O.unsafe(this,s).is0()}clearCofactor(){let{clearCofactor:e}=t;return o===bS?this:e?e(E,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(e=!0){return ax(e,`isCompressed`),this.assertValidity(),p(E,this,e)}toHex(e=!0){return St(this.toBytes(e))}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(e=!0){return this.toBytes(e)}_setWindowSize(e){this.precompute(e)}static normalizeZ(e){return $x(E,e)}static msm(e,t){return dS(E,i,e,t)}static fromPrivateKey(e){return E.BASE.multiply(wS(i,e))}}E.BASE=new E(a.Gx,a.Gy,r.ONE),E.ZERO=new E(r.ZERO,r.ONE,r.ZERO),E.Fp=r,E.Fn=i;let D=i.BITS,O=new lS(E,t.endo?Math.ceil(D/2):D);return E.BASE.precompute(8),E}function ES(e){return Uint8Array.of(e?2:3)}function DS(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function OS(e,t={}){let{Fn:n}=e,r=t.randomBytes||Tt,i=Object.assign(DS(e.Fp,n),{seed:Jx(n.ORDER)});function a(e){try{return!!wS(n,e)}catch{return!1}}function o(t,n){let{publicKey:r,publicKeyUncompressed:a}=i;try{let i=t.length;return n===!0&&i!==r||n===!1&&i!==a?!1:!!e.fromBytes(t)}catch{return!1}}function s(e=r(i.seed)){return Yx(ox(e,i.seed,`seed`),n.ORDER)}function c(t,r=!0){return e.BASE.multiply(wS(n,t)).toBytes(r)}function l(e){let t=s(e);return{secretKey:t,publicKey:c(t)}}function u(t){if(typeof t==`bigint`)return!1;if(t instanceof e)return!0;let{secretKey:r,publicKey:a,publicKeyUncompressed:o}=i;if(n.allowedLengths||r===a)return;let s=px(`key`,t).length;return s===a||s===o}function d(t,r,i=!0){if(u(t)===!0)throw Error(`first arg must be private key`);if(u(r)===!1)throw Error(`second arg must be public key`);let a=wS(n,t);return e.fromHex(r).multiply(a).toBytes(i)}return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:l,Point:e,utils:{isValidSecretKey:a,isValidPublicKey:o,randomSecretKey:s,isValidPrivateKey:a,randomPrivateKey:s,normPrivateKeyToScalar:e=>wS(n,e),precompute(t=8,n=e.BASE){return n.precompute(t,!1)}},lengths:i})}function kS(e,t,n={}){xt(t),bx(n,{},{hmac:`function`,lowS:`boolean`,randomBytes:`function`,bits2int:`function`,bits2int_modN:`function`});let r=n.randomBytes||Tt,i=n.hmac||((e,...n)=>Ot(t,e,bt(...n))),{Fp:a,Fn:o}=e,{ORDER:s,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p}=OS(e,n),m={prehash:!1,lowS:typeof n.lowS==`boolean`&&n.lowS,format:void 0,extraEntropy:!1},h=`compact`;function g(e){return e>s>>bS}function _(e,t){if(!o.isValidNot0(t))throw Error(`invalid signature ${e}: out of range 1..Point.Fn.ORDER`);return t}function v(e,t){gS(t);let n=p.signature;return ox(e,t===`compact`?n:t===`recovered`?n+1:void 0,`${t} signature`)}class y{constructor(e,t,n){this.r=_(`r`,e),this.s=_(`s`,t),n!=null&&(this.recovery=n),Object.freeze(this)}static fromBytes(e,t=h){v(e,t);let n;if(t===`der`){let{r:t,s:n}=vS.toSig(ox(e));return new y(t,n)}t===`recovered`&&(n=e[0],t=`compact`,e=e.subarray(1));let r=o.BYTES,i=e.subarray(0,r),a=e.subarray(r,r*2);return new y(o.fromBytes(i),o.fromBytes(a),n)}static fromHex(e,t){return this.fromBytes(wt(e),t)}addRecoveryBit(e){return new y(this.r,this.s,e)}recoverPublicKey(t){let n=a.ORDER,{r,s:i,recovery:c}=this;if(c==null||![0,1,2,3].includes(c))throw Error(`recovery id invalid`);if(s*xS<n&&c>1)throw Error(`recovery id is ambiguous for h>1 curve`);let l=c===2||c===3?r+s:r;if(!a.isValid(l))throw Error(`recovery id 2 or 3 invalid`);let u=a.toBytes(l),d=e.fromBytes(bt(ES(!(c&1)),u)),f=o.inv(l),p=x(px(`msgHash`,t)),m=o.create(-p*f),h=o.create(i*f),g=e.BASE.multiplyUnsafe(m).add(d.multiplyUnsafe(h));if(g.is0())throw Error(`point at infinify`);return g.assertValidity(),g}hasHighS(){return g(this.s)}toBytes(e=h){if(gS(e),e===`der`)return wt(vS.hexFromSig(this));let t=o.toBytes(this.r),n=o.toBytes(this.s);if(e===`recovered`){if(this.recovery==null)throw Error(`recovery bit must be present`);return bt(Uint8Array.of(this.recovery),t,n)}return bt(t,n)}toHex(e){return St(this.toBytes(e))}assertValidity(){}static fromCompact(e){return y.fromBytes(px(`sig`,e),`compact`)}static fromDER(e){return y.fromBytes(px(`sig`,e),`der`)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes(`der`)}toDERHex(){return St(this.toBytes(`der`))}toCompactRawBytes(){return this.toBytes(`compact`)}toCompactHex(){return St(this.toBytes(`compact`))}}let b=n.bits2int||function(e){if(e.length>8192)throw Error(`input is too large`);let t=lx(e),n=e.length*8-c;return n>0?t>>BigInt(n):t},x=n.bits2int_modN||function(e){return o.create(b(e))},S=vx(c);function C(e){return gx(`num < 2^`+c,e,yS,S),o.toBytes(e)}function w(e,n){return ox(e,void 0,`message`),n?ox(t(e),void 0,`prehashed message`):e}function E(t,n,i){if([`recovered`,`canonical`].some(e=>e in i))throw Error(`sign() legacy options not supported`);let{lowS:a,prehash:s,extraEntropy:c}=_S(i,m);t=w(t,s);let l=x(t),u=wS(o,n),d=[C(u),C(l)];if(c!=null&&c!==!1){let e=c===!0?r(p.secretKey):c;d.push(px(`extraEntropy`,e))}let f=bt(...d),h=l;function _(t){let n=b(t);if(!o.isValidNot0(n))return;let r=o.inv(n),i=e.BASE.multiply(n).toAffine(),s=o.create(i.x);if(s===yS)return;let c=o.create(r*o.create(h+s*u));if(c===yS)return;let l=(i.x===s?0:2)|Number(i.y&bS),d=c;return a&&g(c)&&(d=o.neg(c),l^=1),new y(s,d,l)}return{seed:f,k2sig:_}}function D(e,n,r={}){e=px(`message`,e);let{seed:a,k2sig:s}=E(e,n,r);return yx(t.outputLen,o.BYTES,i)(a,s)}function O(e){let t,n=typeof e==`string`||Ct(e),r=!n&&typeof e==`object`&&!!e&&typeof e.r==`bigint`&&typeof e.s==`bigint`;if(!n&&!r)throw Error(`invalid signature, expected Uint8Array, hex string or Signature instance`);if(r)t=new y(e.r,e.s);else if(n){try{t=y.fromBytes(px(`sig`,e),`der`)}catch(e){if(!(e instanceof vS.Err))throw e}if(!t)try{t=y.fromBytes(px(`sig`,e),`compact`)}catch{return!1}}return t||!1}function k(t,n,r,i={}){let{lowS:a,prehash:s,format:c}=_S(i,m);if(r=px(`publicKey`,r),n=w(px(`message`,n),s),`strict`in i)throw Error(`options.strict was renamed to lowS`);let l=c===void 0?O(t):y.fromBytes(px(`sig`,t),c);if(l===!1)return!1;try{let t=e.fromBytes(r);if(a&&l.hasHighS())return!1;let{r:i,s}=l,c=x(n),u=o.inv(s),d=o.create(c*u),f=o.create(i*u),p=e.BASE.multiplyUnsafe(d).add(t.multiplyUnsafe(f));return!p.is0()&&o.create(p.x)===i}catch{return!1}}function A(e,t,n={}){let{prehash:r}=_S(n,m);return t=w(t,r),y.fromBytes(e,`recovered`).recoverPublicKey(t).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:f,lengths:p,Point:e,sign:D,verify:k,recoverPublicKey:A,Signature:y,hash:t})}function AS(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(e=>Math.ceil(e/2)))):void 0;return{CURVE:t,curveOpts:{Fp:n,Fn:Kx(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes}}}function jS(e){let{CURVE:t,curveOpts:n}=AS(e),r={hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:n,hash:e.hash,ecdsaOpts:r}}function MS(e,t){let n=t.Point;return Object.assign({},t,{ProjectivePoint:n,CURVE:Object.assign({},e,Gx(n.Fn.ORDER,n.Fn.BITS))})}function NS(e){let{CURVE:t,curveOpts:n,hash:r,ecdsaOpts:i}=jS(e);return MS(e,kS(TS(t,n),r,i))}function PS(e,t){let n=t=>NS({...e,hash:t});return{...n(t),create:n}}var FS=class extends Error{constructor(e){let{cause:t,code:n,message:r,data:i,stack:a}=e;super(r,{cause:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.BaseError`}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cause=t,this.code=n,this.data=i,this.stack=a??``}};Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Missing or invalid parameters.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidInputError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32e3}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Requested resource not found.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ResourceNotFoundError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32001}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Requested resource not available.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ResourceUnavailableError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32002});var IS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Transaction creation failed.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.TransactionRejectedError`})}};Object.defineProperty(IS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32003}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Method is not implemented.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.MethodNotSupportedError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32004});var LS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Rate limit exceeded.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.LimitExceededError`})}};Object.defineProperty(LS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32005}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`JSON-RPC version not supported.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.VersionNotSupportedError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32006}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Input is not a valid JSON-RPC request.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidRequestError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32600}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Method does not exist.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.MethodNotFoundError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32601});var RS=class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Invalid method parameters.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InvalidParamsError`})}};Object.defineProperty(RS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32602});var zS=class e extends FS{constructor(t={}){super({cause:t.cause,code:e.code,data:t.data,message:t.message??`Internal JSON-RPC error.`,stack:t.stack}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.InternalError`})}};Object.defineProperty(zS,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32603}),Object.defineProperty(class e extends FS{constructor(t={}){super({code:e.code,data:t.data,message:t.message??`Failed to parse JSON-RPC response.`}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:`RpcResponse.ParseError`})}},"code",{enumerable:!0,configurable:!0,writable:!0,value:-32700});var BS=`<redacted>`,VS=`VOID_ENV_UNMASK`;function HS(e,t,n={}){return n.unmask||typeof e!=`string`||e.length===0?t:t.split(e).join(BS)}var US=null;function WS(){if(US!==null)return US;try{US=globalThis.process?.env?.[VS]===`1`}catch{US=!1}return US&&console.error(`[void/env] ${VS}=1 is set — env validation errors will include raw values. Unset it before sharing logs.`),US}var GS=Symbol.for(`void.env.registry`),KS=globalThis,qS=KS[GS]??={schema:null,hasDefineEnvBeenCalled:!1,bootValidation:null},JS=new WeakMap,YS=[];function XS(e){let t=JS.get(e);return t||(t=new Map,JS.set(e,t),YS.push(t)),t}function ZS(){return Object.fromEntries(Object.entries({BASE_URL:`/`,DEV:!1,MODE:`production`,PROD:!0,SSR:!0,TSS_DEV_SERVER:`false`,TSS_DEV_SSR_STYLES_BASEPATH:`/`,TSS_DEV_SSR_STYLES_ENABLED:`true`,TSS_DISABLE_CSRF_MIDDLEWARE_WARNING:`false`,TSS_INLINE_CSS_ENABLED:`false`,TSS_ROUTER_BASEPATH:``,TSS_SERVER_FN_BASE:`/_serverFn/`}).filter(([e])=>e.startsWith(`VITE_`)))}var QS=class extends Error{key;issues;constructor(e,t){super(`Invalid env "${e}": ${t.map(e=>e.message).join(`, `)}`),this.name=`EnvValidationError`,this.key=e,this.issues=t}};function $S(e){let t=dy();if(_y(e,t))return;let n=yy(),r=ZS(),i=Object.hasOwn(r,e)?r[e]:n[e];if(!qS.schema)return i;let a=qS.schema[e];if(!a)return i;let o=XS(t);if(o.has(e))return o.get(e);let s=a[`~standard`].validate(i);if(s instanceof Promise)throw Error(`env: Async validator for '${e}' cannot be resolved synchronously. Proxy property access is synchronous, so async Standard Schema validators must be pre-resolved by calling \`_validateEnvOnce(env)\` at worker boot (Void splices this into the generated entry) or by awaiting \`validateAllEnv(env)\` before the first \`env.${e}\` read. Once pre-validated, the resolved value is cached and served synchronously here.`);if(s.issues){let t=WS();throw new QS(e,s.issues.map(e=>({...e,message:HS(i,e.message,{unmask:t})})))}return o.set(e,s.value),s.value}var U=new Proxy({},{get(e,t){if(typeof t!=`symbol`)return $S(t)},has(e,t){return typeof t==`symbol`?!1:Object.hasOwn(ZS(),t)||Reflect.has(yy(),t)},ownKeys(){return[...new Set([...Reflect.ownKeys(yy()),...Object.keys(ZS())])]},getOwnPropertyDescriptor(e,t){if(typeof t!=`symbol`)return{enumerable:!0,configurable:!0,value:$S(String(t))}}});function eC(e={}){let t=e.challenge??ut(32);return{challenge:t,options:Bt(Ut({...e,challenge:t}))}}function tC(e,t){let n=Vt(e);return Wt({...t,metadata:n.metadata,publicKey:Mt(t.publicKey),signature:n.signature})}function nC(e){try{let{authData:t}=Jt(Ft(e.attestationObject));return t.length<53?void 0:rC(t.subarray(37,53))}catch{return}}function rC(e){let t=dt(e).slice(2);return[t.slice(0,8),t.slice(8,12),t.slice(12,16),t.slice(16,20),t.slice(20,32)].join(`-`)}function iC(e={}){let t=e.challenge??ut(32);return{challenge:t,options:Rt(Gt({...e,challenge:t}))}}function aC(e,t){let n=Un(e),r=Ht({...t,credential:n});return{...zt(r),aaguid:nC(e)}}function oC(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}var sC;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(sC=`jose/v6.2.12`);var cC=Symbol();async function lC(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new ba:e});if(i.status!==200)throw new Mi(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new Mi(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}var uC=Symbol();function dC(e,t){return Number.isFinite(e)&&Date.now()<e+t}function fC(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function pC(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=fC(r.cooldownDuration,3e4,`cooldownDuration`),s=fC(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);sC&&!c.has(`User-Agent`)&&c.set(`User-Agent`,sC),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[cC],u=r[uC],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;dC(e,s)&&Fi(t)&&(d=e,h=wi(t))}let g=async()=>{if(f&&oC()&&(f=void 0),!f){let e=++p,t=f=lC(n,c,AbortSignal.timeout(a),l).then(t=>{let n=wi(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!dC(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof fi&&!dC(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>dC(d,o),enumerable:!0},fresh:{get:()=>dC(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}var mC={N:16384,r:16,p:1,dkLen:64};function hC(e,t){return new Promise((n,r)=>{eee(e.normalize(`NFKC`),t,mC.dkLen,{N:mC.N,r:mC.r,p:mC.p,maxmem:128*mC.N*mC.r*2},(e,t)=>{e?r(e):n(t)})})}async function gC(e){let t=Jo(16).toString(`hex`);return`${t}:${(await hC(e,t)).toString(`hex`)}`}async function _C(e,t){let[n,r]=e.split(`:`);if(!n||!r)throw Error(`Invalid password hash`);return(await hC(t,n)).toString(`hex`)===r}var vC=gC,yC=async({hash:e,password:t})=>_C(e,t),bC=[`state`,`client_id`,`redirect_uri`,`response_type`,`code_challenge`,`code_challenge_method`,`nonce`,`scope`],xC=new Set(bC);async function SC({id:e,options:t,authorizationEndpoint:n,state:r,codeVerifier:i,scopes:a,claims:o,redirectURI:s,duration:c,prompt:l,accessType:u,responseType:d,display:f,loginHint:p,nonce:m,hd:h,responseMode:g,additionalParams:_,scopeJoiner:v}){t=typeof t==`function`?await t():t;let y=new URL(t.authorizationEndpoint||n);y.searchParams.set(`response_type`,d||`code`);let b=ci(t.clientId);if(!b)throw Error(`OAuth provider requires clientId`);if(y.searchParams.set(`client_id`,b),y.searchParams.set(`state`,r),a?.length&&y.searchParams.set(`scope`,a.join(v||` `)),y.searchParams.set(`redirect_uri`,t.redirectURI||s),c&&y.searchParams.set(`duration`,c),f&&y.searchParams.set(`display`,f),p&&y.searchParams.set(`login_hint`,p),m&&y.searchParams.set(`nonce`,m),l&&y.searchParams.set(`prompt`,l),h&&y.searchParams.set(`hd`,h),u&&y.searchParams.set(`access_type`,u),g&&y.searchParams.set(`response_mode`,g),i){let e=await oa(i);y.searchParams.set(`code_challenge_method`,`S256`),y.searchParams.set(`code_challenge`,e)}if(o){let e=o.reduce((e,t)=>(e[t]=null,e),{});y.searchParams.set(`claims`,JSON.stringify({id_token:{email:null,email_verified:null,...e}}))}if(_)for(let[e,t]of Object.entries(_))xC.has(e)||y.searchParams.set(e,t);return y}var CC=Wn(R(),R()).refine(e=>!Object.keys(e).some(e=>xC.has(e)),{message:`additionalParams cannot include reserved OAuth parameters: ${bC.join(`, `)}`}).meta({description:`Extra query parameters to append to the provider authorization URL (e.g. Cognito identity_provider, Google hd).`}).optional();function wC(e,t){return t===`basic`?{method:`client_secret_basic`}:e.clientSecret?{method:`client_secret_post`}:{method:`none`}}function TC(e,t,n){if(t.clientSecret||n.has(`client_secret`))throw Error(`${e} token endpoint authentication cannot be combined with clientSecret`)}function EC(e,t){t&&e.set(`client_id`,t)}function DC(e,t){if(!t.clientSecret)throw Error(`${e} token endpoint authentication requires clientSecret`)}function OC(e,t){if(!t)throw Error(`${e} token endpoint authentication requires clientId`)}function kC({body:e,options:t,clientId:n,requireClientSecret:r}){r&&DC(`client_secret_post`,t),t.clientSecret&&(OC(`client_secret_post`,n),EC(e,n),e.set(`client_secret`,t.clientSecret))}function AC({headers:e,options:t,clientId:n,body:r}){if(r.has(`client_secret`))throw Error(`client_secret_basic token endpoint authentication cannot be combined with client_secret body parameters`);DC(`client_secret_basic`,t),OC(`client_secret_basic`,n),e.authorization=Pr(n,t.clientSecret)}function jC(e){if(e.has(`client_assertion`)!==e.has(`client_assertion_type`))throw Error(`client_assertion and client_assertion_type must both be provided`)}async function MC({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i,tokenEndpointAuth:a,authentication:o}){jC(e);let s=ci(n.clientId);if(e.has(`client_assertion`)){if(a)throw Error(`client_assertion body parameters cannot be combined with tokenEndpointAuth`);TC(`private_key_jwt`,n,e),EC(e,s);return}let c=a??wC(n,o);if(c.method===`custom`)await c.customizeRequest({body:e,headers:t,options:n,tokenEndpoint:r,grantType:i}),jC(e);else if(c.method===`private_key_jwt`){if(TC(c.method,n,e),OC(c.method,s),!r)throw Error(`private_key_jwt token endpoint authentication requires tokenEndpoint`);let t=await ii({getClientAssertion:c.getClientAssertion,context:{clientId:s,tokenEndpoint:r,grantType:i}});EC(e,s);for(let[n,r]of Object.entries(t))e.set(n,r)}else if(c.method===`none`){if(TC(c.method,n,e),i===`client_credentials`)throw Error(`none token endpoint authentication cannot be used with client_credentials grant`);OC(c.method,s),EC(e,s)}else c.method===`client_secret_basic`?AC({headers:t,options:n,clientId:s,body:e}):kC({body:e,options:n,clientId:s,requireClientSecret:a?.method===`client_secret_post`})}var NC=new Set([`grant_type`,`refresh_token`,`__proto__`,`constructor`,`prototype`]);async function PC({refreshToken:e,options:t,authentication:n,tokenEndpointAuth:r,tokenEndpoint:i,extraParams:a,resource:o}){t=typeof t==`function`?await t():t;let s=IC({refreshToken:e,options:t,extraParams:a,resource:o});return await MC({body:s.body,headers:s.headers,options:t,tokenEndpoint:i??``,grantType:`refresh_token`,tokenEndpointAuth:r,authentication:n}),s}function FC(e,t){if(t)for(let[n,r]of Object.entries(t))NC.has(n)||e.set(n,r)}function IC({refreshToken:e,options:t,extraParams:n,resource:r}){let i=new URLSearchParams,a={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`};if(i.set(`grant_type`,`refresh_token`),i.set(`refresh_token`,e),r){if(typeof r==`string`)i.append(`resource`,r);else for(let e of r)i.append(`resource`,e)}return n&&FC(i,n),{body:i,headers:a}}async function LC({refreshToken:e,options:t,tokenEndpoint:n,authentication:r,tokenEndpointAuth:i,extraParams:a,resource:o}){let{body:s,headers:c}=await PC({refreshToken:e,options:t,authentication:r,tokenEndpointAuth:i,tokenEndpoint:n,extraParams:a,resource:o}),{data:l,error:u}=await Or(n,{method:`POST`,body:s,headers:c});if(u)throw u;let d={accessToken:l.access_token,refreshToken:l.refresh_token,tokenType:l.token_type,scopes:ui(l.scope),idToken:l.id_token};return l.expires_in&&(d.accessTokenExpiresAt=new Date(new Date().getTime()+l.expires_in*1e3)),l.refresh_token_expires_in&&(d.refreshTokenExpiresAt=new Date(new Date().getTime()+l.refresh_token_expires_in*1e3)),d}async function RC({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:i,tokenEndpointAuth:a,tokenEndpoint:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){r=typeof r==`function`?await r():r;let d=zC({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:s,headers:c,additionalParams:l,resource:u});return await MC({body:d.body,headers:d.headers,options:r,tokenEndpoint:o??``,grantType:`authorization_code`,tokenEndpointAuth:a,authentication:i}),d}function zC({code:e,codeVerifier:t,redirectURI:n,options:r,deviceId:i,headers:a,additionalParams:o={},resource:s}){let c=new URLSearchParams,l={"content-type":`application/x-www-form-urlencoded`,accept:`application/json`,...a};if(c.set(`grant_type`,`authorization_code`),c.set(`code`,e),t&&c.set(`code_verifier`,t),r.clientKey&&c.set(`client_key`,r.clientKey),i&&c.set(`device_id`,i),c.set(`redirect_uri`,r.redirectURI||n),s){if(typeof s==`string`)c.append(`resource`,s);else for(let e of s)c.append(`resource`,e)}for(let[e,t]of Object.entries(o))c.has(e)||c.append(e,t);return{body:c,headers:l}}async function BC({code:e,codeVerifier:t,redirectURI:n,options:r,tokenEndpoint:i,authentication:a,tokenEndpointAuth:o,deviceId:s,headers:c,additionalParams:l={},resource:u}){let{body:d,headers:f}=await RC({code:e,codeVerifier:t,redirectURI:n,options:r,authentication:a,tokenEndpointAuth:o,tokenEndpoint:i,deviceId:s,headers:c,additionalParams:l,resource:u}),{data:p,error:m}=await Or(i,{method:`POST`,body:d,headers:f});if(m)throw m;return Mr(p)}var VC=30,HC=[`iss`,`sub`,`aud`,`exp`,`iat`];function UC(e){return{issuer:e.issuer,audience:e.audience,algorithms:e.algorithms,maxTokenAge:e.maxTokenAge,requiredClaims:HC,clockTolerance:VC}}async function WC(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function GC(e,t,n=`exact`){return typeof e==`string`?e===t||n===`exact-or-sha256`&&e===await WC(t):!1}async function vee(e,t,n){if(![t.audience].flat().some(Boolean))throw Error(`ID token audience is not configured`);let r=await ra(e,t.jwks,UC(t));if(n&&!await GC(r.payload.nonce,n,t.nonceComparison))throw Error(`ID token nonce does not match`);if(t.verifyClaims&&!t.verifyClaims(r.payload))throw Error(`ID token claims were rejected`);return r}function KC(e){let t=e.options??{};return!t.disableIdTokenSignIn&&!!(e.idToken||t.verifyIdToken)}async function qC(e,t,n,r){let i=e.options??{};if(i.disableIdTokenSignIn)return!1;try{if(i.verifyIdToken)return await i.verifyIdToken(t,n,r);let a=e.idToken;return a?`verify`in a?await a.verify(t,n,r):t.split(`.`).length===3?(await vee(t,a,n),!0):a.allowOpaqueToken===!0:!1}catch{return!1}}var JC=/[\u0000-\u001f\u007f-\u009f]/,YC=`https://better-auth.invalid`,XC=/%2[fF]|%5[cC]/,ZC=e=>{let t=e;try{t=decodeURIComponent(e)}catch{}let n=[];for(let e of t.split(`/`))e===`..`?n.pop():e!==`.`&&e!==``&&n.push(e);return n.length>0?`/${n.join(`/`)}`:``},QC=e=>{if(JC.test(e))return null;let t=e.indexOf(`:`);if(t<=0)return null;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1),i=``;if(r.startsWith(`//`)){r=r.slice(2);let e=r.search(/[/?#]/);e===-1?(i=r,r=``):(i=r.slice(0,e),r=r.slice(e))}let a=r.search(/[?#]/),o=ZC(a===-1?r:r.slice(0,a));return{scheme:n,authority:i.toLowerCase(),path:o}},$C=e=>{if(!e.startsWith(`/`)||e.startsWith(`//`)||e.includes(`\\`)||JC.test(e))return!1;let t=e.search(/[?#]/),n=t===-1?e:e.slice(0,t);if(XC.test(n))return!1;try{return new URL(e,YC).origin===YC}catch{return!1}},ew=(e,t,n)=>{if(e.startsWith(`/`))return n?.allowRelativePaths===!0&&$C(e);if(t.includes(`*`)||t.includes(`?`)){if(t.includes(`://`))return vr(t)(xa(e)||e);let n=pi(e);return n?vr(t)(n):!1}let r=Aa(e);if(r===`http:`||r===`https:`||!r)return t===xa(e);let i=QC(e),a=QC(t);return!i||!a||i.scheme!==a.scheme||a.authority&&i.authority!==a.authority?!1:!a.path||i.path===a.path||i.path.startsWith(`${a.path}/`)};function tw(e,t,n){let r=!1;return function(...i){return r||=((n?.warn??console.warn)(`[Deprecation] ${t}`),!0),e.apply(this,i)}}function nw(e){return e.context.skipOriginCheck===!0&&e.context.options.advanced?.disableCSRFCheck===void 0}function rw(e){let t=e.context.skipOriginCheck;if(t===!0)return!0;if(Array.isArray(t)&&e.request)try{let n=new URL(e.context.baseURL).pathname,r=Ii(e.request.url,n);return t.some(e=>{let t=e.replace(/\/+$/,``);return r===t||r.startsWith(`${t}/`)})}catch{}return!1}var iw=tw(function(){},`disableOriginCheck: true currently also disables CSRF checks. In a future version, disableOriginCheck will ONLY disable URL validation. To keep CSRF disabled, add disableCSRFCheck: true to your config.`),aw=Qr(async e=>{if(e.request?.method===`GET`||e.request?.method===`OPTIONS`||e.request?.method===`HEAD`||!e.request||(await sw(e),rw(e)))return;let{body:t,query:n}=e,r=t?.callbackURL||n?.callbackURL,i=t?.redirectTo,a=t?.errorCallbackURL,o=t?.newUserCallbackURL,s=(t,n)=>{if(t){if(typeof t!=`string`)throw V.fromStatus(`BAD_REQUEST`,{message:`Invalid ${n}: expected a string`});if(!e.context.isTrustedOrigin(t,{allowRelativePaths:n!==`origin`}))throw e.context.logger.error(`Invalid ${n}: ${t}`),e.context.logger.info(`If it's a valid URL, please add ${t} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${e.context.trustedOrigins}`),n===`origin`?V.from(`FORBIDDEN`,B.INVALID_ORIGIN):n===`callbackURL`?V.from(`FORBIDDEN`,B.INVALID_CALLBACK_URL):n===`redirectURL`?V.from(`FORBIDDEN`,B.INVALID_REDIRECT_URL):n===`errorCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_NEW_USER_CALLBACK_URL):V.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})}};r&&s(r,`callbackURL`),i&&s(i,`redirectURL`),a&&s(a,`errorCallbackURL`),o&&s(o,`newUserCallbackURL`)}),ow=e=>Qr(async t=>{if(!t.request||rw(t))return;let n=e(t),r=(e,n)=>{if(e&&!t.context.isTrustedOrigin(e,{allowRelativePaths:n!==`origin`}))throw t.context.logger.error(`Invalid ${n}: ${e}`),t.context.logger.info(`If it's a valid URL, please add ${e} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${t.context.trustedOrigins}`),n===`origin`?V.from(`FORBIDDEN`,B.INVALID_ORIGIN):n===`callbackURL`?V.from(`FORBIDDEN`,B.INVALID_CALLBACK_URL):n===`redirectURL`?V.from(`FORBIDDEN`,B.INVALID_REDIRECT_URL):n===`errorCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_ERROR_CALLBACK_URL):n===`newUserCallbackURL`?V.from(`FORBIDDEN`,B.INVALID_NEW_USER_CALLBACK_URL):V.fromStatus(`FORBIDDEN`,{message:`Invalid ${n}`})},i=Array.isArray(n)?n:[n];for(let e of i)r(e,`callbackURL`)});async function sw(e,t=!1){let n=e.request?.headers;if(!n||!e.request)return;let r=n.get(`origin`),i=r||n.get(`referer`)||``,a=n.has(`cookie`);if(e.context.skipCSRFCheck)return;if(nw(e)){e.context.options.advanced?.disableOriginCheck===!0&&iw();return}if(rw(e)||!(t||a))return;let o=r===`null`&&n.get(`sec-fetch-site`)===`same-origin`?Ni(void 0,e.context.options.basePath,e.request,!1,e.context.options.advanced?.trustedProxyHeaders):void 0,s=(o?xa(o):void 0)??i;if(!s||s===`null`)throw V.from(`FORBIDDEN`,B.MISSING_OR_NULL_ORIGIN);let c=Array.isArray(e.context.options.trustedOrigins)?e.context.trustedOrigins:[...e.context.trustedOrigins,...(await e.context.options.trustedOrigins?.(e.request))?.filter(e=>!!e)||[]];if(!c.some(e=>ew(s,e)))throw e.context.logger.error(`Invalid origin: ${s}`),e.context.logger.info(`If it's a valid URL, please add ${s} to trustedOrigins in your auth config\n`,`Current list of trustedOrigins: ${c}`),V.from(`FORBIDDEN`,B.INVALID_ORIGIN)}var cw=Qr(async e=>{e.request&&await lw(e)});async function lw(e){let t=e.request;if(!t||e.context.skipCSRFCheck||nw(e))return;let n=t.headers;if(n.has(`cookie`))return await sw(e);let r=n.get(`Sec-Fetch-Site`),i=n.get(`Sec-Fetch-Mode`),a=n.get(`Sec-Fetch-Dest`);if(r&&r.trim()||i&&i.trim()||a&&a.trim()){if(r===`cross-site`&&i===`navigate`)throw e.context.logger.error(`Blocked cross-site navigation login attempt (CSRF protection)`,{secFetchSite:r,secFetchMode:i,secFetchDest:a}),V.from(`FORBIDDEN`,B.CROSS_SITE_NAVIGATION_LOGIN_BLOCKED);return await sw(e,!0)}if(n.get(`origin`)||n.get(`referer`))return await sw(e,!0)}var uw=new Map,dw=1e5;function fw(){let e=Date.now();for(let[t,n]of uw)e>=n.expiresAt&&uw.delete(t);if(uw.size<=dw)return;let t=uw.size-dw,n=0;for(let e of uw.keys())if(uw.delete(e),++n>=t)break}function pw(e,t,n){let r=t.window*1e3;return e?n-e.lastRequest>=r?{next:{...e,count:1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:e.count>=t.max?{next:e,update:!0,allowed:!1,retryAfter:hw(e.lastRequest,t.window)}:{next:{...e,count:e.count+1,lastRequest:n},update:!0,allowed:!0,retryAfter:null}:{next:{key:``,count:1,lastRequest:n},update:!1,allowed:!0,retryAfter:null}}function mw(e){return new Response(JSON.stringify({message:`Too many requests. Please try again later.`}),{status:429,statusText:`Too Many Requests`,headers:{"Content-Type":`application/json`,"X-Retry-After":e.toString()}})}function hw(e,t){let n=Date.now(),r=t*1e3;return Math.ceil((e+r-n)/1e3)}function gw(e){let t=`rateLimit`,n=e.adapter,r=Math.max(..._w(e)),i=async e=>{let r=(await n.findMany({model:t,where:[{field:`key`,value:e}]}))[0];return r&&(r.lastRequest=Number(r.lastRequest)),r},a=async(e,s)=>{s.window>r&&(r=s.window);let c=s.window*1e3,l=await i(e),u=Date.now();if(!l)try{return await n.create({model:t,data:{key:e,count:1,lastRequest:u}}),{allowed:!0,retryAfter:null}}catch(t){if(!await i(e))throw t;return a(e,s)}if(u-l.lastRequest>=c)return await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`lte`,value:l.lastRequest}],increment:{},set:{count:1,lastRequest:u}})?(await o(u),{allowed:!0,retryAfter:null}):a(e,s);let d=u-c;if(await n.incrementOne({model:t,where:[{field:`key`,value:e},{field:`lastRequest`,operator:`gt`,value:d},{field:`count`,operator:`lt`,value:s.max}],increment:{count:1},set:{lastRequest:u}}))return{allowed:!0,retryAfter:null};let f=await i(e);return!f||u-f.lastRequest>=c?a(e,s):{allowed:!1,retryAfter:hw(f.lastRequest,s.window)}},o=async i=>{let a=i-r*1e3;await e.runInBackgroundOrAwait(n.deleteMany({model:t,where:[{field:`lastRequest`,operator:`lt`,value:a}]}).then(()=>void 0).catch(t=>e.logger.error(`Error pruning rate limit rows`,t)))};return{consume:a}}function _w(e){let t=[e.rateLimit.window,...Cw().map(e=>e.window)];for(let n of e.options.plugins||[])n.rateLimit&&t.push(...n.rateLimit.map(e=>e.window));if(e.rateLimit.customRules)for(let n of Object.values(e.rateLimit.customRules))n&&typeof n!=`function`&&t.push(n.window);let n=t.filter(e=>Number.isFinite(e)&&e>0);return n.length>0?n:[e.rateLimit.window]}function vw(e,t){if(e.options.rateLimit?.customStorage)return e.options.rateLimit.customStorage;let n=e.rateLimit.storage;if(n===`secondary-storage`){let t=t=>t??e.options.rateLimit?.window??10,n=e.options.secondaryStorage?.increment;if(!n)throw new H(`Secondary-storage rate limiting requires SecondaryStorage.increment.`);return{consume:async(e,r)=>await n(e,t(r.window))<=r.max?{allowed:!0,retryAfter:null}:{allowed:!1,retryAfter:r.window}}}if(n===`memory`){let t=t=>t??e.options.rateLimit?.window??10;return{async consume(e,n){fw();let r=Date.now(),i=uw.get(e),a=pw(i&&r<i.expiresAt?i.data:void 0,n,r);return a.allowed&&uw.set(e,{data:{...a.next,key:e},expiresAt:r+t(n.window)*1e3}),{allowed:a.allowed,retryAfter:a.retryAfter}}}}return gw(e)}var yw=!1,bw=`no-trusted-ip`;async function xw(e,t){let n=new URL(t.baseURL).pathname,r=Ii(e.url,n),i=t.rateLimit.window,a=t.rateLimit.max,o=ia(e,t.options);if(!o&&t.options.advanced?.ipAddress?.disableIpTracking)return null;!o&&!yw&&(t.logger.warn("Rate limiting could not determine a client IP and is falling back to a single shared per-path bucket. Ensure your runtime forwards a trusted client IP header, then set `advanced.ipAddress.ipAddressHeaders` or `advanced.ipAddress.trustedProxies` so the address can be resolved."),yw=!0);let s=Ti(o??bw,r),c=Cw().find(e=>e.pathMatcher(r));c&&(i=c.window,a=c.max);for(let e of t.options.plugins||[])if(e.rateLimit){let t=e.rateLimit.find(e=>e.pathMatcher(r));if(t){i=t.window,a=t.max;break}}if(t.rateLimit.customRules){let n=Object.keys(t.rateLimit.customRules).find(e=>e.includes(`*`)?vr(e)(r):e===r);if(n){let r=t.rateLimit.customRules[n],o=typeof r==`function`?await r(e,{window:i,max:a}):r;if(o&&(i=o.window,a=o.max),o===!1)return null}}return{key:s,currentWindow:i,currentMax:a}}async function Sw(e,t){if(!t.rateLimit.enabled)return;let n=await xw(e,t);if(!n)return;let{key:r,currentWindow:i,currentMax:a}=n,o=vw(t,{window:i}),s={window:i,max:a},{allowed:c,retryAfter:l}=await o.consume(r,s);if(!c)return mw(l??i)}function Cw(){return[{pathMatcher(e){return e.startsWith(`/sign-in`)||e.startsWith(`/sign-up`)||e.startsWith(`/change-password`)||e.startsWith(`/change-email`)},window:10,max:3},{pathMatcher(e){return e===`/request-password-reset`||e===`/send-verification-email`||e.startsWith(`/forget-password`)||e===`/email-otp/send-verification-otp`||e===`/email-otp/request-password-reset`},window:60,max:3}]}var ww=`better-auth.session-cache+jwt`,Tw=`better-auth:session-cache`;function Ew(e){let t={clockTolerance:15,audience:e?.audience??`better-auth:session-cache`};return e?.issuer&&(t.issuer=e.issuer),t}function Dw(e){let t=ja(e);return!t||typeof e.iss!=`string`||!e.iss||e.sub!==t.user.id||e.sid!==t.session.token?null:{...e,...t}}function Ow(e){if(!e?.method)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`User validation source is required`});if(e.method===`oauth`&&!e.oauth?.providerId)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`OAuth user validation source requires oauth.providerId`});if((e.method===`sso-oidc`||e.method===`sso-saml`)&&!e.sso?.providerId)throw new V(`FORBIDDEN`,{code:`validation_source_missing`,message:`SSO user validation source requires sso.providerId`})}async function kw(e,t){let n=e.context.options.user?.validateUserInfo;if(!n)return;Ow(t.source);let r;try{r=await n(t,e)}catch(t){throw e.context.logger.error(`validateUserInfo callback threw`,t),new V(`FORBIDDEN`,{code:`validation_failed`,message:`User validation failed`})}if(r?.error)throw new V(`FORBIDDEN`,{code:r.error,message:r.errorDescription||r.error})}var Aw=async e=>{let t=await ca(`SHA-256`).digest(new TextEncoder().encode(e));return Ia.encode(new Uint8Array(t),{padding:!1})};async function jw(e,t){return!t||t===`plain`?e:t===`hashed`?Aw(e):typeof t==`object`&&`hash`in t?t.hash(e):e}function Mw(e,t){if(t){if(typeof t==`object`&&`default`in t){if(t.overrides){for(let[n,r]of Object.entries(t.overrides))if(e.startsWith(n))return r}return t.default}return t}}function Nw(e,t){let n=qa(t.options),r=t.hooks;async function i(t,i,a){let o=br(),s=t;for(let{source:e,hooks:t}of r){let r=t[i]?.create?.before;if(r){let t=await n(`db create.before ${i}`,{[Qa]:`create.before`,[no]:i,[to]:e},()=>r(s,o));if(t===!1)return null;typeof t==`object`&&`data`in t&&(s={...s,...t.data})}}let c=null;(!a||a.executeMainFn)&&(c=await(await gi(e)).create({model:i,data:s,forceAllowId:!0})),a?.fn&&(c=await a.fn(c??s));for(let{source:e,hooks:t}of r){let r=t[i]?.create?.after;r&&await ta(async()=>{await n(`db create.after ${i}`,{[Qa]:`create.after`,[no]:i,[to]:e},()=>r(c,o))})}return c}async function a(t,i,a,o){let s=br(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db update.before ${a}`,{[Qa]:`update.before`,[no]:a,[to]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await gi(e)).update({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await ta(async()=>{await n(`db update.after ${a}`,{[Qa]:`update.after`,[no]:a,[to]:e},()=>r(u,s))})}return u}async function o(t,i,a,o){let s=br(),c=t;for(let{source:e,hooks:i}of r){let r=i[a]?.update?.before;if(r){let i=await n(`db updateMany.before ${a}`,{[Qa]:`updateMany.before`,[no]:a,[to]:e},()=>r(t,s));if(i===!1)return null;typeof i==`object`&&`data`in i&&(c={...c,...i.data})}}let l=o?await o.fn(c):null,u=!o||o.executeMainFn?await(await gi(e)).updateMany({model:a,update:c,where:i}):l;for(let{source:e,hooks:t}of r){let r=t[a]?.update?.after;r&&await ta(async()=>{await n(`db updateMany.after ${a}`,{[Qa]:`updateMany.after`,[no]:a,[to]:e},()=>r(u,s))})}return u}async function s(t,i,a){let o=br(),s=null;try{s=(await(await gi(e)).findMany({model:i,where:t,limit:1}))[0]||null}catch{}if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":e},()=>r(s,o))===!1)return null}let c=a?await a.fn(t):null,l=(!a||a.executeMainFn)&&s?await(await gi(e)).delete({model:i,where:t}):c;if(s)for(let{source:e,hooks:t}of r){let r=t[i]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${i}`,{[Qa]:`delete.after`,[no]:i,[to]:e},()=>r(s,o))})}return l}async function c(t,i,a){let o=br(),s=[];try{s=await(await gi(e)).findMany({model:i,where:t})}catch{}for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.before;if(r&&await n(`db delete.before ${i}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":i,"better_auth.context":t},()=>r(e,o))===!1)return null}let c=a?await a.fn(t):null,l=!a||a.executeMainFn?await(await gi(e)).deleteMany({model:i,where:t}):c;for(let e of s)for(let{source:t,hooks:a}of r){let r=a[i]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${i}`,{[Qa]:`delete.after`,[no]:i,[to]:t},()=>r(e,o))})}return l}async function l(t,i,a,o){let s=br(),c=r.flatMap(({source:e,hooks:n})=>{let r=n[t]?.delete?.before;return r?[{source:e,fn:r}]:[]}),l=o??null;if(c.length){if(!l)try{l=(await(await gi(e)).findMany({model:t,where:i,limit:1}))[0]||null}catch{}if(l){for(let{source:e,fn:r}of c)if(await n(`db delete.before ${t}`,{"better_auth.hook.type":`delete.before`,"db.collection.name":t,"better_auth.context":e},()=>r(l,s))===!1)return null}}let u=await a();if(!u)return null;for(let{source:e,hooks:i}of r){let r=i[t]?.delete?.after;r&&await ta(async()=>{await n(`db delete.after ${t}`,{[Qa]:`delete.after`,[no]:t,[to]:e},()=>r(u,s))})}return u}return{createWithHooks:i,updateWithHooks:a,updateManyWithHooks:o,deleteWithHooks:s,deleteManyWithHooks:c,consumeOneWithHooks:l}}function Pw(e,t=Date.now()){let n=typeof e==`number`?e:e.getTime();return Math.max(Math.floor((n-t)/1e3),0)}var Fw=(e,t)=>{let n=t.logger,r=t.options,i=r.secondaryStorage,a=new Map,o=r.session?.expiresIn||604800,s=!!i&&r.session?.storeSessionInDatabase===!0&&r.session?.preserveSessionInDatabase!==!0,{createWithHooks:c,updateWithHooks:l,updateManyWithHooks:u,deleteWithHooks:d,deleteManyWithHooks:f,consumeOneWithHooks:p}=Nw(e,t),m=t=>{let n=[...t,{field:`expiresAt`,value:new Date,operator:`gt`}];return f(n,`session`,{fn:async()=>{await(await gi(e)).updateMany({model:`session`,where:n,update:{expiresAt:new Date}})},executeMainFn:!1})};async function h(e){if(!i)return;let t=await i.get(`active-sessions-${e.id}`);if(!t)return;let n=Date.now(),r=($a(t)||[]).filter(e=>e.expiresAt>n);await Promise.all(r.map(async({token:t})=>{let r=await i.get(t);if(!r)return;let a=$a(r);if(!a)return;let o=Pw(a.session.expiresAt,n);await i.set(t,JSON.stringify({session:a.session,user:e}),Math.floor(o))}))}async function g(e){if(!i)return[];let t=await i.get(`active-sessions-${e}`);return t&&$a(t)||[]}async function _(e,t){if(!i)return;let n=new Set(t.map(e=>e.token));for(let{token:e}of t)await i.delete(e);let r=`active-sessions-${e}`,a=await g(e),o=Date.now(),s=a.filter(e=>e.expiresAt>o&&!n.has(e.token));s.sort((e,t)=>e.expiresAt-t.expiresAt);let c=s.at(-1)?.expiresAt;c?await i.set(r,JSON.stringify(s),Pw(c,o)):await i.delete(r)}async function v(e,t){if(!i)return;let r=t??await g(e);await ta(()=>_(e,r),{onError(e){n.error(`Failed to delete committed user sessions from secondary storage`,e)}})}async function y(e,t){let n=a.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),o=n.catch(()=>{}).then(()=>i);a.set(e,o),await n.catch(()=>{});try{return await t()}finally{r(),a.get(e)===o&&a.delete(e)}}return{createOAuthUser:async(t,n)=>Si(e,async()=>{let e=await c({createdAt:new Date,updatedAt:new Date,...t,email:t.email?.toLowerCase()},`user`,void 0);if(!e)throw new V(`BAD_REQUEST`,{message:`Failed to create user`});return{user:e,account:await c({...n,userId:e.id,createdAt:new Date,updatedAt:new Date},`account`,void 0)}}),createUser:async(e,t)=>{let i={createdAt:new Date,updatedAt:new Date,...e,email:e.email?.toLowerCase()};if(r.user?.validateUserInfo){let e={...t,action:`create-user`};Ow(e);let r;try{r=Sr()}catch(e){throw n.error(`Unable to run validateUserInfo: missing endpoint context`,e),new V(`FORBIDDEN`,{code:`validation_context_missing`,message:`User validation requires an endpoint context`})}await kw(r,{user:i,source:e})}return await c(i,`user`,void 0)},createAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),listSessions:async(n,r)=>{if(s)return(await(await gi(e)).findMany({model:`session`,where:[{field:`userId`,value:n},{field:`expiresAt`,value:new Date,operator:`gt`}]})).map(e=>li(t.options,e));if(i){let e=await i.get(`active-sessions-${n}`);if(!e)return[];let r=$a(e)||[],a=Date.now(),o=new Set,s=[];for(let{token:e,expiresAt:n}of r){if(n<=a||o.has(e))continue;o.add(e);let r=await i.get(e);if(r)try{let e=typeof r==`string`?JSON.parse(r):r;if(!e?.session)continue;s.push(li(t.options,{...e.session,expiresAt:new Date(e.session.expiresAt)}))}catch{continue}}return s}return await(await gi(e)).findMany({model:`session`,where:[{field:`userId`,value:n},...r?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]]})},listUsers:async(t,n,r,i)=>await(await gi(e)).findMany({model:`user`,limit:t,offset:n,sortBy:r,where:i}),countTotalUsers:async t=>{let n=await(await gi(e)).count({model:`user`,where:t});return typeof n==`string`?parseInt(n):n},deleteUser:async e=>{let t=await g(e);(!i||r.session?.storeSessionInDatabase)&&await f([{field:`userId`,value:e}],`session`,void 0),await f([{field:`userId`,value:e}],`account`,void 0),await d([{field:`id`,value:e}],`user`,void 0)!==null&&await v(e,t)},createSession:async(a,l,u,d,f)=>{let p=await(async()=>{let e=br();return e?.headers||e?.request?.headers})(),m=r.session?.storeSessionInDatabase,h=f?.deferSecondaryStorageWrites===!0&&s,{id:g,..._}=u||{},v;if(i&&!m){let e=t.generateId({model:`session`});v=e===!1?Xa():e}let y=Nr(r),b={...v?{id:v}:{},ipAddress:p&&ia(p,r)||``,userAgent:p?.get(`user-agent`)||``,..._,expiresAt:ri(l?86400:o,`sec`),userId:a,token:Xa(32),createdAt:new Date,updatedAt:new Date,...y,...d?_:{}},x=async t=>{if(!i)return t;let n=await i.get(`active-sessions-${a}`),r=[],o=Date.now();n&&(r=$a(n)||[],r=r.filter(e=>e.expiresAt>o&&e.token!==b.token));let s=[...r,{token:b.token,expiresAt:b.expiresAt.getTime()}].sort((e,t)=>e.expiresAt-t.expiresAt),c=Pw(s.at(-1)?.expiresAt??b.expiresAt.getTime(),o);c>0&&await i.set(`active-sessions-${a}`,JSON.stringify(s),c);let l=await(await gi(e)).findOne({model:`user`,where:[{field:`id`,value:a}]}),u=Pw(b.expiresAt,o);return u>0&&await i.set(b.token,JSON.stringify({session:t,user:l}),u),t};return await c(b,`session`,i?{fn:async e=>h?(await ta(async()=>{await x(e)},{onError(e){n.error(`Failed to mirror committed session to secondary storage`,e)}}),e):x(e),executeMainFn:m}:void 0)},findSession:async n=>{if(i){let e=await i.get(n);if(!e&&(!r.session?.storeSessionInDatabase||t.options.session?.preserveSessionInDatabase))return null;if(e){let n=$a(e);return n?{session:li(t.options,{...n.session,expiresAt:new Date(n.session.expiresAt),createdAt:new Date(n.session.createdAt),updatedAt:new Date(n.session.updatedAt)}),user:ur(t.options,{...n.user,createdAt:new Date(n.user.createdAt),updatedAt:new Date(n.user.updatedAt)})}:null}}let a=await(await gi(e)).findOne({model:`session`,where:[{value:n,field:`token`}],join:{user:!0}});if(!a)return null;let{user:o,...s}=a;return o?{session:li(t.options,s),user:ur(t.options,o)}:null},findSessions:async(t,n)=>{let r=[...new Set(t)],a=new Map,o=[];if(i)for(let e of r){let t=await i.get(e);if(t)try{let r=typeof t==`string`?JSON.parse(t):t;if(!r)continue;let i=new Date(r.session.expiresAt);if(n?.onlyActiveSessions&&i<=new Date)continue;let o={session:{...r.session,expiresAt:new Date(r.session.expiresAt)},user:{...r.user,createdAt:new Date(r.user.createdAt),updatedAt:new Date(r.user.updatedAt)}};a.set(e,o)}catch{continue}else o.push(e)}let c=i?o:r;if(c.length>0&&(!i||s)){let t=await(await gi(e)).findMany({model:`session`,limit:c.length,where:[{field:`token`,value:c,operator:`in`},...n?.onlyActiveSessions?[{field:`expiresAt`,value:new Date,operator:`gt`}]:[]],join:{user:!0}});for(let{user:e,...n}of t)e&&a.set(n.token,{session:n,user:e})}return r.flatMap(e=>{let t=a.get(e);return t?[t]:[]})},updateSession:async(e,n)=>await l(n,[{field:`token`,value:e}],`session`,i?{async fn(n){let r=await i.get(e);if(!r)return null;let a=$a(r);if(!a)return null;let o={...a.session,...n,expiresAt:new Date(n.expiresAt??a.session.expiresAt),createdAt:new Date(a.session.createdAt),updatedAt:new Date(n.updatedAt??a.session.updatedAt)},s=li(t.options,o),c=Date.now(),l=new Date(s.expiresAt).getTime(),u=Pw(l,c);if(u>0){await i.set(e,JSON.stringify({session:s,user:a.user}),u);let t=`active-sessions-${s.userId}`,n=await i.get(t),r=(n&&$a(n)||[]).filter(t=>t.token!==e&&t.expiresAt>c).concat([{token:e,expiresAt:l}]).sort((e,t)=>e.expiresAt-t.expiresAt),o=r.at(-1)?.expiresAt;o&&o>c?await i.set(t,JSON.stringify(r),Pw(o,c)):await i.delete(t)}return s},executeMainFn:r.session?.storeSessionInDatabase}:void 0),deleteSession:async e=>{if(i){let a=await i.get(e);if(a){let{session:t}=$a(a)??{};if(!t){n.error(`Session not found in secondary storage`);return}let r=t.userId,o=await i.get(`active-sessions-${r}`);if(o){let t=$a(o)||[],n=Date.now(),a=t.filter(t=>t.expiresAt>n&&t.token!==e),s=a.sort((e,t)=>e.expiresAt-t.expiresAt).at(-1)?.expiresAt;a.length>0&&s&&s>Date.now()?await i.set(`active-sessions-${r}`,JSON.stringify(a),Pw(s,n)):await i.delete(`active-sessions-${r}`)}else n.error(`Active sessions list not found in secondary storage`)}if(await i.delete(e),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e}]);return}}await d([{field:`token`,value:e}],`session`,void 0)},deleteAccounts:async e=>{await f([{field:`userId`,value:e}],`account`,void 0)},deleteAccount:async e=>{await d([{field:`id`,value:e}],`account`,void 0)},deleteUserSessions:async e=>{let n=await g(e);if(i){if(!r.session?.storeSessionInDatabase){await v(e,n);return}if(t.options.session?.preserveSessionInDatabase){await m([{field:`userId`,value:e}])!==null&&await v(e,n);return}}await f([{field:`userId`,value:e}],`session`,void 0)!==null&&await v(e,n)},deleteSessions:async e=>{if(i){if(await Promise.all(e.map(e=>i.delete(e))),!r.session?.storeSessionInDatabase)return;if(t.options.session?.preserveSessionInDatabase){await m([{field:`token`,value:e,operator:`in`}]);return}}await f([{field:`token`,value:e,operator:`in`}],`session`,void 0)},findAccountOwnerByKey:async({providerId:t,accountId:n})=>{let r=await(await gi(e)).findMany({model:`account`,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}],limit:2,join:{user:!0}});if(r.length>1)throw new H(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);let i=r[0];if(!i)return null;let{user:a,...o}=i;return a?{kind:`owned`,user:a,account:o}:{kind:`orphaned`,account:o}},findUserByEmail:async(t,n)=>{let r=await(await gi(e)).findOne({model:`user`,where:[{value:t.toLowerCase(),field:`email`}],join:{...n?.includeAccounts?{account:!0}:{}}});if(!r)return null;let{account:i,...a}=r;return{user:a,accounts:i??[]}},findUserById:async t=>t?await(await gi(e)).findOne({model:`user`,where:[{field:`id`,value:t}]}):null,linkAccount:async e=>await c({createdAt:new Date,updatedAt:new Date,...e},`account`,void 0),updateUser:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`id`,value:e}],`user`,void 0);return await ta(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updateUserByEmail:async(e,t)=>{let r=await l({...t,...t.email?{email:t.email.toLowerCase()}:{}},[{field:`email`,value:e.toLowerCase()}],`user`,void 0);return await ta(()=>h(r),{onError(e){n.error(`Failed to refresh committed user sessions in secondary storage`,e)}}),r},updatePassword:async(e,t)=>{await u({password:t},[{field:`userId`,value:e},{field:`providerId`,value:`credential`},{field:`accountId`,value:e}],`account`,void 0)},findAccounts:async t=>await(await gi(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),findCredentialAccount:async t=>(await gi(e)).findOne({model:`account`,where:[{field:`userId`,value:t},{field:`providerId`,value:`credential`},{field:`accountId`,value:t}]}),findAccountByKey:async({providerId:t,accountId:n})=>{let r=await(await gi(e)).findMany({model:`account`,limit:2,where:[{field:`providerId`,value:t},{field:`accountId`,value:n}]});if(r.length>1)throw new H(`Multiple accounts match the same accountId for provider ${JSON.stringify(t)}. Resolve duplicate account identities before continuing.`);return r[0]??null},findAccountByUserId:async t=>await(await gi(e)).findMany({model:`account`,where:[{field:`userId`,value:t}]}),updateAccount:async(e,t)=>await l(t,[{field:`id`,value:e}],`account`,void 0),createVerificationValue:async e=>{let t=Mw(e.identifier,r.verification?.storeIdentifier),n=await jw(e.identifier,t);return await c({createdAt:new Date,updatedAt:new Date,...e,identifier:n},`verification`,i?{async fn(e){let t=Pw(e.expiresAt);return t>0&&await i.set(`verification:${n}`,JSON.stringify(e),t),e},executeMainFn:r.verification?.storeInDatabase}:void 0)},findVerificationValue:async t=>{let n=Mw(t,r.verification?.storeIdentifier),a=await jw(t,n);if(i){let e=await i.get(`verification:${a}`);if(e){let t=$a(e);if(t)return t}if(n&&n!==`plain`){let e=await i.get(`verification:${t}`);if(e){let t=$a(e);if(t)return t}}if(!r.verification?.storeInDatabase)return null}let o=await gi(e);async function s(e){return o.findMany({model:`verification`,where:[{field:`identifier`,value:e}],sortBy:{field:`createdAt`,direction:`desc`},limit:1})}let c=await s(a);return!c.length&&n&&n!==`plain`&&(c=await s(t)),r.verification?.disableCleanup||await f([{field:`expiresAt`,value:new Date,operator:`lt`}],`verification`,void 0),c[0]||null},deleteVerificationByIdentifier:async e=>{let t=await jw(e,Mw(e,r.verification?.storeIdentifier));i&&await i.delete(`verification:${t}`),(!i||r.verification?.storeInDatabase)&&await d([{field:`identifier`,value:t}],`verification`,void 0)},consumeVerificationValue:async t=>{let n=Mw(t,r.verification?.storeIdentifier),a=await jw(t,n),o=n&&n!==`plain`?[a,t]:[a],s=e=>{if(!e)return null;let t=typeof e==`string`?$a(e):typeof e==`object`?e:null;if(!t)return null;let n=new Date(t.expiresAt);return Number.isFinite(n.getTime())?{...t,expiresAt:n}:null},c=null;if(i&&!r.verification?.storeInDatabase){let e=async e=>s(await i.getAndDelete(e));for(let t of o){let n=await e(`verification:${t}`);if(n){await Promise.all(o.filter(e=>e!==t).map(e=>i.delete(`verification:${e}`))),c=n;break}}}else{let t=async t=>y(`verification:${t}`,()=>Si(e,async()=>{let n=await gi(e),r=[{field:`identifier`,value:t}],i=await n.findMany({model:`verification`,where:r,sortBy:{field:`createdAt`,direction:`desc`},limit:2}),a=i[0]??null;return a?p(`verification`,[{field:`id`,value:a.id}],async()=>{let e=await n.consumeOne({model:`verification`,where:[{field:`id`,value:a.id}]});return e?(i.length>1&&await n.deleteMany({model:`verification`,where:r}),e):null},a):null}));for(let e of o)if(c=await t(e),c)break;c&&i&&await Promise.all(o.map(e=>i.delete(`verification:${e}`)))}return!c||c.expiresAt<new Date?null:c},reserveVerificationValue:async t=>{let n=ro(new Uint8Array(await ca(`SHA-256`).digest(new TextEncoder().encode(`reserve:`+t.identifier))),r),a=Mw(t.identifier,r.verification?.storeIdentifier),o=await jw(t.identifier,a);if(i&&!r.verification?.storeInDatabase)throw new H(`reserveVerificationValue requires database-backed verification storage. Set verification.storeInDatabase to true for flows that reserve verification values.`);try{await e.create({model:`verification`,data:{id:n,identifier:o,value:t.value,expiresAt:t.expiresAt,createdAt:new Date,updatedAt:new Date},forceAllowId:!0})}catch(t){if(await e.findOne({model:`verification`,where:[{field:`id`,value:n}]}))return!1;throw t}if(i){let e=Pw(t.expiresAt);e>0&&await i.set(`verification:${o}`,JSON.stringify({id:n,identifier:o,value:t.value,expiresAt:t.expiresAt}),e)}return!0},updateVerificationByIdentifier:async(e,t)=>{let n=await jw(e,Mw(e,r.verification?.storeIdentifier));if(i){let e=await i.get(`verification:${n}`);if(e){let a=$a(e);if(a){let e={...a,...t},o=e.expiresAt??a.expiresAt,s=Pw(o instanceof Date?o:new Date(o));if(s>0&&await i.set(`verification:${n}`,JSON.stringify(e),s),!r.verification?.storeInDatabase)return e}}}return!i||r.verification?.storeInDatabase?await l(t,[{field:`identifier`,value:n}],`verification`,void 0):t},refreshUserSessions:h}};async function Iw(e){let t=e.options,n=t.plugins||[],r=[],i=[];for(let a of n)if(a.init){let n=a.init(e),o;if(o=ti(n)?await n:n,typeof o==`object`){if(o.options){let{databaseHooks:e,trustedOrigins:n,...s}=o.options;e&&i.push({source:`plugin:${a.id}`,hooks:e}),n&&r.push(n),t=Jr(t,s)}o.context&&Object.assign(e,o.context)}}if(r.length>0){let e=[...t.trustedOrigins?[t.trustedOrigins]:[],...r],n=e.filter(Array.isArray).flat(),i=e.filter(e=>typeof e==`function`);i.length>0?t.trustedOrigins=async e=>{let t=await Promise.all(i.map(t=>t(e)));return[...n,...t.flat()].filter(e=>typeof e==`string`&&e!==``)}:t.trustedOrigins=n}t.databaseHooks&&i.push({source:`user`,hooks:t.databaseHooks}),e.internalAdapter=Fw(e.adapter,{options:t,logger:e.logger,hooks:i,generateId:e.generateId}),e.options=t}function Lw(e){return e.advanced?.crossSubDomainCookies?.enabled,[]}async function Rw(e,t){let n=[];if(yi(e.baseURL)){let t=e.baseURL.allowedHosts,r=e.baseURL.protocol;for(let e of t)e.includes(`://`)?n.push(e):((!r||r===`https`||r===`auto`)&&n.push(`https://${e}`),(r===`http`||r===`auto`||_i(e))&&n.push(`http://${e}`));if(e.baseURL.fallback)try{n.push(new URL(e.baseURL.fallback).origin)}catch{}}else{let r=Ni(typeof e.baseURL==`string`?e.baseURL:void 0,e.basePath,t);r&&n.push(new URL(r).origin)}if(e.trustedOrigins&&(Array.isArray(e.trustedOrigins)&&n.push(...e.trustedOrigins),typeof e.trustedOrigins==`function`)){let r=await e.trustedOrigins(t);n.push(...r)}let r=Za.BETTER_AUTH_TRUSTED_ORIGINS;return r&&n.push(...r.split(`,`)),n.filter(e=>!!e)}function zw(e){if(Da(e?.request))return e.request;if(!e?.headers)return;let t=e.headers instanceof Headers?e.headers:new Headers(e.headers);if(t.has(`host`)||t.has(`x-forwarded-host`))return t}function Bw(e){return e.advanced?.trustedProxyHeaders??!1}async function Vw(e,t,n){let r=e.options.baseURL,i=Xr(r,e.options.basePath||`/api/auth`,t,void 0,n);if(!i)throw new H(`Could not resolve base URL from request. Check your allowedHosts config.`);let a=Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e));a.baseURL=i,a.options={...e.options,baseURL:xa(i)||void 0};let o={...a.options,baseURL:r},s=typeof e.options.trustedOrigins==`function`||typeof e.options.account?.accountLinking?.trustedProviders==`function`,c;return c=s?Da(t)?t:t?new Request(i,{headers:t}):void 0:void 0,a.trustedOrigins=await Rw(o,c),a.trustedProviders=await Uw(a.options,c),e.options.advanced?.crossSubDomainCookies?.enabled&&(a.authCookies=kr(a.options),a.createAuthCookie=zr(a.options)),a}async function Hw(e,t){if(e)for(let n of e){let e=typeof n==`function`?await n():n;if(e[t.field??`id`]===t.value)return e}}async function Uw(e,t){let n=e.account?.accountLinking?.trustedProviders;return n?Array.isArray(n)?n.filter(e=>!!e):(await n(t)??[]).filter(e=>!!e):[]}function Ww(e){return e}async function Gw(e,t,n){let r={tokens:t,profile:n},i=e.accountSubject,a=await i(r),o=String(a);if(typeof a==`number`&&!Number.isFinite(a)||o.trim().length===0||o===`undefined`||o===`null`)throw new H(`OAUTH_ACCOUNT_SUBJECT_INVALID`);return{providerId:e.id,accountId:o}}async function Kw(e,t,n){try{return await Gw(e,t,n)}catch{throw V.from(`UNAUTHORIZED`,B.FAILED_TO_GET_USER_INFO)}}var qw={NO_CODE:`no_code`,PROVIDER_NOT_FOUND:`oauth_provider_not_found`,ISSUER_MISSING:`issuer_missing`,ISSUER_MISMATCH:`issuer_mismatch`,INVALID_CODE:`invalid_code`,NONCE_BINDING_MISSING:`nonce_binding_missing`,UNABLE_TO_GET_USER_INFO:`unable_to_get_user_info`,NO_CALLBACK_URL:`no_callback_url`,UNABLE_TO_LINK_ACCOUNT:`unable_to_link_account`,EMAIL_DOES_NOT_MATCH:`email_does_not_match`,ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER:`account_already_linked_to_different_user`,EMAIL_NOT_FOUND:`email_not_found`,EMAIL_NOT_VERIFIED:`email_not_verified`},Jw=`https://www.better-auth.com/docs/concepts/oauth#handling-providers-without-email`;function Yw(e,t,n,r){let i=new URLSearchParams({error:n});r&&i.set(`error_description`,r);let a=Yi(t,i);throw e.redirect(a)}function Xw(e,t){return`${t?.source===`generic`?`Generic OAuth provider "${e}"`:`Provider "${e}"`} did not return an email${t?.source===`id_token`?` in the id token`:``}. Either request the provider's email scope, or create a placeholder via \`mapProfileToUser\`. See ${Jw}`}function Zw(e){return e.startsWith(`$ba$`)?!0:e.length%2==0&&/^[0-9a-f]+$/i.test(e)}function Qw(e,t){return e&&(t.options.account?.encryptOAuthTokens&&Zw(e)?ma({key:t.secretConfig,data:e}):e)}function $w(e,t){return t.options.account?.encryptOAuthTokens&&e?Zi({key:t.secretConfig,data:e}):e}function eT(e){return e.callbackPath?e.callbackPath.startsWith(`/`)?e.callbackPath:`/${e.callbackPath}`:`/callback/${e.id}`}function tT(e){if(e)try{return e.clone()}catch{return new Request(e.url,{cache:e.cache,credentials:e.credentials,headers:e.headers,integrity:e.integrity,keepalive:e.keepalive,method:e.method,mode:e.mode,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal})}}async function nT(e,t,n,r=3600,i){return await ea({email:t.toLowerCase(),updateTo:n?.toLowerCase(),...i},e,r)}async function rT(e,t){if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),V.from(`BAD_REQUEST`,B.VERIFICATION_EMAIL_NOT_ENABLED);let n=await nT(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),r=e.body.callbackURL?encodeURIComponent(e.body.callbackURL):`%2F`,i=`${e.context.baseURL}/verify-email?token=${n}&callbackURL=${r}`;await e.context.options.emailVerification.sendVerificationEmail({user:t,url:i,token:n},e.request)}var iT=wa(`/send-verification-email`,{method:`POST`,operationId:`sendVerificationEmail`,cloneRequest:!0,body:z({email:rr().meta({description:`The email to send the verification email to`}),callbackURL:R().meta({description:`The URL to use for email verification callback`}).optional()}),metadata:{openapi:{operationId:`sendVerificationEmail`,description:`Send a verification email to the user`,requestBody:{content:{"application/json":{schema:{type:`object`,properties:{email:{type:`string`,description:`The email to send the verification email to`,example:`user@example.com`},callbackURL:{type:`string`,description:`The URL to use for email verification callback`,example:`https://example.com/callback`,nullable:!0}},required:[`email`]}}}},responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{status:{type:`boolean`,description:`Indicates if the email was sent successfully`,example:!0}}}}}},400:{description:`Bad Request`,content:{"application/json":{schema:{type:`object`,properties:{message:{type:`string`,description:`Error message`,example:`Verification email isn't enabled`}}}}}}}}}},async e=>{if(!e.context.options.emailVerification?.sendVerificationEmail)throw e.context.logger.error(`Verification email isn't enabled.`),V.from(`BAD_REQUEST`,B.VERIFICATION_EMAIL_NOT_ENABLED);let{email:t}=e.body,n=await Zr(e);if(!n){let n=Date.now(),r=await e.context.internalAdapter.findUserByEmail(t),i;if(!r||r.user.emailVerified)await nT(e.context.secret,t,void 0,e.context.options.emailVerification?.expiresIn);else try{await rT(e,r.user)}catch(e){i=e}let a=500-(Date.now()-n);if(a>0&&await new Promise(e=>setTimeout(e,a)),i)throw i;return e.json({status:!0})}if(n?.user.email.toLowerCase()!==t.toLowerCase())throw V.from(`BAD_REQUEST`,B.EMAIL_MISMATCH);if(n?.user.emailVerified)throw V.from(`BAD_REQUEST`,B.EMAIL_ALREADY_VERIFIED);return await rT(e,n.user),e.json({status:!0})}),aT=wa(`/verify-email`,{method:`GET`,operationId:`verifyEmail`,query:z({token:R().meta({description:`The token to verify the email`}),callbackURL:R().meta({description:`The URL to redirect to after email verification`}).optional()}),use:[ow(e=>e.query.callbackURL)],metadata:{openapi:{description:`Verify the email of the user`,parameters:[{name:`token`,in:`query`,description:`The token to verify the email`,required:!0,schema:{type:`string`}},{name:`callbackURL`,in:`query`,description:`The URL to redirect to after email verification`,required:!1,schema:{type:`string`}}],responses:{200:{description:`Success`,content:{"application/json":{schema:{type:`object`,properties:{user:{type:`object`,$ref:`#/components/schemas/User`},status:{type:`boolean`,description:`Indicates if the email was verified successfully`}},required:[`user`,`status`]}}}}}}}},async e=>{function t(t){if(e.query.callbackURL){let n=new URLSearchParams({error:t.code}),r=Yi(e.query.callbackURL,n);throw e.redirect(r)}throw V.from(`UNAUTHORIZED`,t)}let{token:n}=e.query,r;try{r=await ra(n,new TextEncoder().encode(e.context.secret),{algorithms:[`HS256`]})}catch(e){return e instanceof vi?t(B.TOKEN_EXPIRED):t(B.INVALID_TOKEN)}let i=z({email:rr(),updateTo:R().optional(),requestType:R().optional()}).parse(r.payload),a=await e.context.internalAdapter.findUserByEmail(i.email);if(!a)return t(B.USER_NOT_FOUND);if(i.updateTo){let n=await Zr(e);if(n&&n.user.email!==i.email)return t(B.INVALID_USER);switch(i.requestType){case`change-email-confirmation`:{let t=await nT(e.context.secret,i.email,i.updateTo,e.context.options.emailVerification?.expiresIn,{requestType:`change-email-verification`}),n=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`,r=`${e.context.baseURL}/verify-email?token=${t}&callbackURL=${n}`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:{...a.user,email:i.updateTo},url:r,token:t},tT(e.request))),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0})}case`change-email-verification`:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(r,e.request),await Kr(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!0}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:ur(e.context.options,r)})}default:{let t=n;if(!t){let n=await e.context.internalAdapter.createSession(a.user.id);if(!n)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);t={session:n,user:a.user}}let r=await e.context.internalAdapter.updateUserByEmail(i.email,{email:i.updateTo,emailVerified:!1}),o=await nT(e.context.secret,i.updateTo),s=e.query.callbackURL?encodeURIComponent(e.query.callbackURL):`%2F`;if(e.context.options.emailVerification?.sendVerificationEmail&&await e.context.runInBackgroundOrAwait(e.context.options.emailVerification.sendVerificationEmail({user:r,url:`${e.context.baseURL}/verify-email?token=${o}&callbackURL=${s}`,token:o},tT(e.request))),await Kr(e,{session:t.session,user:{...t.user,email:i.updateTo,emailVerified:!1}}),e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:ur(e.context.options,r)})}}}if(a.user.emailVerified){if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})}e.context.options.emailVerification?.beforeEmailVerification&&await e.context.options.emailVerification.beforeEmailVerification(a.user,e.request);let o=await e.context.internalAdapter.updateUserByEmail(i.email,{emailVerified:!0});if(e.context.options.emailVerification?.afterEmailVerification&&await e.context.options.emailVerification.afterEmailVerification(o,e.request),e.context.options.emailVerification?.autoSignInAfterVerification){let t=await Zr(e);if(!t||t.user.email!==i.email){let t=await e.context.internalAdapter.createSession(a.user.id);if(!t)throw V.from(`INTERNAL_SERVER_ERROR`,B.FAILED_TO_CREATE_SESSION);await Kr(e,{session:t,user:{...a.user,emailVerified:!0}})}else await Kr(e,{session:t.session,user:{...t.user,emailVerified:!0}})}if(e.query.callbackURL)throw e.redirect(e.query.callbackURL);return e.json({status:!0,user:null})});function oT(e,t){return{linked:!1,error:{code:e,message:t}}}async function sT(e,{link:t,userInfo:n,account:r,profile:i,scopes:a}){try{await kw(e,{user:{...n,id:t.userId,email:n.email??void 0},source:{action:`link-account`,method:`oauth`,oauth:{providerId:r.providerId,profile:i}}})}catch(e){if(!Hr(e)||!e.body?.code)throw e;return oT(e.body.code,e.body.message)}if(!e.context.trustedProviders.includes(r.providerId)&&!n.emailVerified||e.context.options.account?.accountLinking?.enabled===!1)return e.context.logger.error(`Unable to link account - untrusted provider`),oT(qw.UNABLE_TO_LINK_ACCOUNT);if(n.email?.toLowerCase()!==t.email.toLowerCase()&&e.context.options.account?.accountLinking?.allowDifferentEmails!==!0)return oT(qw.EMAIL_DOES_NOT_MATCH);let o=await e.context.internalAdapter.findAccountByKey(r);if(o){if(o.userId.toString()!==t.userId.toString())return oT(qw.ACCOUNT_ALREADY_LINKED_TO_DIFFERENT_USER);let n=oi(o.scope,a),i=Object.fromEntries(Object.entries({providerId:r.providerId,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:n||void 0}).filter(([e,t])=>t!==void 0));await e.context.internalAdapter.updateAccount(o.id,i)}else if(!await e.context.internalAdapter.createAccount({userId:t.userId,...r,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),scope:a?.join(`,`)??r.scope}))return oT(qw.UNABLE_TO_LINK_ACCOUNT);return await uT(e,t.userId,n),{linked:!0}}async function cT(e,t){let{userInfo:n,account:r,callbackURL:i,disableSignUp:a,overrideUserInfo:o}=t,s=t.source??{method:`oauth`,oauth:{providerId:r.providerId}},c=!!t.selectedUser||t.requireExactAccountBinding===!0,l=null,u=await e.context.internalAdapter.findAccountOwnerByKey({providerId:r.providerId,accountId:r.accountId}).catch(t=>{e.context.logger.error(`Better auth was unable to query your database.
76
76
  Error: `,t),Yw(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)});if(u?.kind===`orphaned`)return e.context.logger.error(`OAuth account references a missing user. Repair the account before retrying authentication.`),{error:`unable to link account`,data:null,isRegister:!1};let d=await(async()=>{if(u?.kind===`owned`){if(t.selectedUser&&u.user.id!==t.selectedUser.userId)throw new V(`CONFLICT`,{code:`account_ownership_conflict`,message:`Account is already linked to another user`});return{user:u.user,linkedAccount:u.account,accounts:[u.account]}}if(t.selectedUser){let n=await e.context.internalAdapter.findUserById(t.selectedUser.userId);if(!n)throw new V(`NOT_FOUND`,{code:`user_not_found`,message:`User not found`});return{user:n,linkedAccount:null,accounts:[]}}let r=await e.context.internalAdapter.findUserByEmail(n.email.toLowerCase(),{includeAccounts:!0});return r?{user:r.user,linkedAccount:null,accounts:r.accounts}:null})().catch(t=>{if(Hr(t))throw t;e.context.logger.error(`Better auth was unable to query your database.
77
77
  Error: `,t),Yw(e,e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,`internal_server_error`)}),f=d?.user,p=!f;if(d){let i=d.linkedAccount??d.accounts.find(e=>e.providerId===r.providerId&&e.accountId===r.accountId);if(i){let{id:a,...o}=n;await kw(e,{user:{...o,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`sign-in`}});let u=e.context.options.account?.updateAccountOnSignIn===!1?{}:Object.fromEntries(Object.entries({providerId:r.providerId,idToken:r.idToken,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt}).filter(([e,t])=>t!==void 0));if(e.context.options.account?.storeAccountCookie){let n={...i,...u};t.deferNonDatabaseWrites?l=n:await $r(e,n)}if(Object.keys(u).length>0){let n=await e.context.internalAdapter.updateAccount(i.id,u);if(!n)return{error:`unable to update account`,data:null};if(c&&(n.accountId!==r.accountId||n.providerId!==r.providerId||n.userId!==d.user.id))throw new V(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});t.deferNonDatabaseWrites&&l&&(l=n)}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0})}else{let i=e.context.options.account?.accountLinking,a=t.isTrustedProvider||t.trustProviderByName!==!1&&e.context.trustedProviders.includes(r.providerId),o=i?.requireLocalEmailVerified??!0;if(!t.selectedUser&&(!a&&!n.emailVerified||o&&!d.user.emailVerified||i?.enabled===!1||i?.disableImplicitLinking===!0))return Ha()&&e.context.logger.warn(`User already exist but account isn't linked to ${r.providerId}. To read more about how account linking works in Better Auth see https://www.better-auth.com/docs/concepts/users-accounts#account-linking.`),{error:`account not linked`,data:null};try{let{id:i,...a}=n;await kw(e,{user:{...a,id:d.user.id,email:n.email.toLowerCase()},source:{...s,action:`link-account`}});let o=await e.context.internalAdapter.linkAccount({providerId:r.providerId,accountId:r.accountId,userId:d.user.id,accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope});if(!o)return{error:`unable to link account`,data:null};if(c&&(o.accountId!==r.accountId||o.providerId!==r.providerId||o.userId!==d.user.id))throw new V(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=o:await $r(e,o))}catch(t){if(Hr(t))throw t;return e.context.logger.error(`Unable to link account`,t),{error:`unable to link account`,data:null}}!t.selectedUser&&n.emailVerified&&!d.user.emailVerified&&n.email.toLowerCase()===d.user.email&&await e.context.internalAdapter.updateUser(d.user.id,{emailVerified:!0}),t.selectedUser||(f=await uT(e,d.user.id,n)??f)}if(t.selectedUser?t.selectedUser.profile===`update`:o){let{id:r,email:i,emailVerified:a,name:o,image:s,...c}=n,l=si(e.context.options,c,`update`),u=await e.context.internalAdapter.updateUser(d.user.id,{name:o,image:s,...l,email:n.email.toLowerCase(),emailVerified:n.email.toLowerCase()===d.user.email&&d.user.emailVerified||n.emailVerified});if(u??e.context.logger.warn(`Could not update user info during OAuth sign in; preserving existing user for session.`),t.selectedUser&&u&&u.id!==t.selectedUser.userId)throw new V(`CONFLICT`,{code:`user_hook_selection_conflict`,message:`User hook changed the selected user`});f=u??f}}else{if(a)return{error:`signup disabled`,data:null,isRegister:!1};try{let{id:i,email:a,emailVerified:o,name:u,image:d,...p}=n,m=si(e.context.options,p,`create`),h={accessToken:await $w(r.accessToken,e.context),refreshToken:await $w(r.refreshToken,e.context),idToken:r.idToken,accessTokenExpiresAt:r.accessTokenExpiresAt,refreshTokenExpiresAt:r.refreshTokenExpiresAt,scope:r.scope,providerId:r.providerId,accountId:r.accountId},{createdUser:g,createdAccount:_}=await Si(e.context.adapter,async()=>{let t=await e.context.internalAdapter.createUser({name:u,image:d,...m,email:n.email.toLowerCase(),emailVerified:n.emailVerified},s);return{createdUser:t,createdAccount:await e.context.internalAdapter.createAccount({...h,userId:t.id})}});if(c&&(_.accountId!==r.accountId||_.providerId!==r.providerId||_.userId!==g.id))throw new V(`CONFLICT`,{code:`account_hook_binding_conflict`,message:`Account hook changed the selected authentication binding`});f=g,e.context.options.account?.storeAccountCookie&&(t.deferNonDatabaseWrites?l=_:await $r(e,_))}catch(t){if(Hr(t))throw t;return e.context.logger.error(`Unable to create OAuth user`,t),{error:`unable to create user`,data:null,isRegister:!1}}}if(!f)return{error:`unable to create user`,data:null,isRegister:!1};let m=e.context.socialProviders.find(e=>e.id===r.providerId)?.options?.requireEmailVerification;if(p&&!f.emailVerified&&(e.context.options.emailVerification?.sendOnSignUp??m)&&await lT(e,f,i),m&&!f.emailVerified)return!p&&e.context.options.emailVerification?.sendOnSignIn&&await lT(e,f,i),{error:qw.EMAIL_NOT_VERIFIED,data:null,isRegister:p};let h=await e.context.internalAdapter.createSession(f.id,void 0,void 0,void 0,{deferSecondaryStorageWrites:!0});if(!h)return{error:`unable to create session`,data:null,isRegister:!1};if(c&&h.userId!==(t.selectedUser?.userId??f.id))throw new V(`CONFLICT`,{code:`session_hook_user_conflict`,message:`Session hook changed the selected user`});return{data:{session:h,user:f},error:null,isRegister:p,accountCookie:l}}async function lT(e,t,n){let r=e.context.options.emailVerification?.sendVerificationEmail;r&&await ta(async()=>{try{let i=await nT(e.context.secret,t.email,void 0,e.context.options.emailVerification?.expiresIn),a=`${e.context.baseURL}/verify-email?token=${i}&callbackURL=${encodeURIComponent(n||`/`)}`;await e.context.runInBackgroundOrAwait(r({user:t,url:a,token:i},e.request))}catch(t){e.context.logger.error(`Failed to send OAuth verification email`,t)}})}async function uT(e,t,n){if(e.context.options.account?.accountLinking?.updateUserInfoOnLink===!0)try{let{email:r,emailVerified:i,name:a,image:o,...s}=n,c=si(e.context.options,s,`update`);return await e.context.internalAdapter.updateUser(t,{name:a,image:o,...c})}catch(t){e.context.logger.warn(`Could not update user info on account link`,t);return}}var dT=eo(`better-auth:oauth-encryption:v1`);function fT(e,t){return Ga(_r(Yr,eo(e),dT,eo(`better-auth:${t}:v1`),32))}function pT(e,t){return typeof e==`string`?fT(e,t):{keys:new Map(Array.from(e.keys,([e,n])=>[e,fT(n,t)])),currentVersion:e.currentVersion,...e.legacySecret&&{legacySecret:fT(e.legacySecret,t)}}}var mT=cr({callbackURL:R(),codeVerifier:R(),errorURL:R().optional(),newUserURL:R().optional(),expiresAt:Zn(),oauthState:R().optional(),link:z({email:R(),userId:Ca()}).optional(),requestSignUp:nr().optional(),idTokenNonce:R().optional(),serverContext:Wn(R(),qn()).optional()}),hT=e=>`auth-state:${e}`;new Set(Object.keys(mT.shape));var gT=class extends H{code;details;errorURL;constructor(e,t){super(e,t),this.code=t.code,this.details=t.details,this.errorURL=t.errorURL}};async function _T(e,t,n){let r=Ri(32);if(e.context.oauthConfig.storeStateStrategy===`cookie`){let i={...t,oauthState:r},a=await Zi({key:pT(e.context.secretConfig,`oauth-state-cookie`),data:JSON.stringify(i)}),o=e.context.createAuthCookie(n?.cookieName??`oauth_state`,{maxAge:600});return e.setCookie(o.name,a,o.attributes),{state:r,codeVerifier:t.codeVerifier}}let i=e.context.createAuthCookie(n?.cookieName??`state`,{maxAge:300});await e.setSignedCookie(i.name,r,e.context.secret,i.attributes);let a=new Date;if(a.setMinutes(a.getMinutes()+10),!await e.context.internalAdapter.createVerificationValue({value:JSON.stringify({...t,oauthState:r}),identifier:hT(r),expiresAt:a}))throw new gT(`Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database`,{code:`state_generation_error`});return{state:r,codeVerifier:t.codeVerifier}}async function vT(e,t,n){if(!t)throw new gT(`State not found in OAuth callback`,{code:`state_not_found`});let r=e.context.oauthConfig.storeStateStrategy,i;if(r===`cookie`){let r=e.context.createAuthCookie(n?.cookieName??`oauth_state`),a=e.getCookie(r.name);if(!a)throw new gT(`State mismatch: auth state cookie not found`,{code:`state_mismatch`,details:{state:t}});try{let t=await ma({key:pT(e.context.secretConfig,`oauth-state-cookie`),data:a});i=mT.parse(JSON.parse(t))}catch(e){throw new gT(`State invalid: Failed to decrypt or parse auth state`,{code:`state_invalid`,details:{state:t},cause:e})}if(!i.oauthState||i.oauthState!==t)throw new gT(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});Cr(e,r)}else{let r=await e.context.internalAdapter.findVerificationValue(hT(t));if(!r)throw new gT(`State mismatch: verification not found`,{code:`state_mismatch`,details:{state:t}});if(i=mT.parse(JSON.parse(r.value)),i.oauthState!==void 0&&i.oauthState!==t)throw new gT(`State mismatch: OAuth state parameter does not match stored state`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});let a=e.context.createAuthCookie(n?.cookieName??`state`),o=await e.getSignedCookie(a.name,e.context.secret);if(!(n?.skipStateCookieCheck??e.context.oauthConfig.skipStateCookieCheck)&&(!o||o!==t))throw new gT(`State mismatch: State not persisted correctly`,{code:`state_security_mismatch`,details:{state:t},errorURL:i.errorURL});Cr(e,a),await e.context.internalAdapter.deleteVerificationByIdentifier(hT(t))}if(i.expiresAt<Date.now())throw new gT(`Invalid state: request expired`,{code:`state_mismatch`,details:{expiresAt:i.expiresAt},errorURL:i.errorURL});return i}function yT(e){return e.requiresIdTokenNonce?Ri(32):void 0}async function bT(e,t){let n=e.body?.callbackURL||e.context.options.baseURL;if(!n)throw V.from(`BAD_REQUEST`,B.CALLBACK_URL_REQUIRED);let r=t?.codeVerifier??Ri(128),i=await la(),a=i&&Object.keys(i).length?i:void 0,o={...t?.additionalData?t.additionalData:{},callbackURL:n,codeVerifier:r,errorURL:e.body?.errorCallbackURL,newUserURL:e.body?.newUserCallbackURL,link:t?.link,serverContext:a,expiresAt:Date.now()+6e5,requestSignUp:e.body?.requestSignUp,idTokenNonce:t?.idTokenNonce};await zi(o);try{return _T(e,o)}catch(t){throw e.context.logger.error(`Failed to create verification`,t),new V(`INTERNAL_SERVER_ERROR`,{message:`Unable to create verification`,cause:t})}}async function xT(e){let t=e.query.state||e.body?.state,n=e.context.options.onAPIError?.errorURL||`${e.context.baseURL}/error`,r;try{r=await vT(e,t)}catch(t){e.context.logger.error(`Failed to parse state`,t);let r=`internal_server_error`,i=n;t instanceof gT&&(r=t.code===`state_security_mismatch`?`state_mismatch`:t.code,i=t.errorURL||n),Yw(e,i,r)}return r.errorURL||(r.errorURL=n),r&&await zi(r),r}var ST=e=>{let t=`https://appleid.apple.com/auth/token`;return{id:`apple`,name:`Apple`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i,codeVerifier:a}){if(!ci(e.clientId)||!e.clientSecret)throw oo.error(`Client ID and client secret are required for Apple. Make sure to provide them in the options.`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`name`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await SC({id:`apple`,options:e,authorizationEndpoint:`https://appleid.apple.com/auth/authorize`,scopes:o,state:t,redirectURI:r,codeVerifier:a,responseMode:`form_post`,responseType:`code id_token`,additionalParams:i})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),idToken:{jwks:e=>CT(e.kid),issuer:`https://appleid.apple.com`,algorithms:[`RS256`],audience:e.audience&&e.audience.length?e.audience:e.appBundleIdentifier?e.appBundleIdentifier:e.clientId,maxTokenAge:`1h`,nonceComparison:`exact-or-sha256`},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:e,tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=da(t.idToken);if(!n)return null;let r;r=t.user?.name?`${t.user.name.firstName||``} ${t.user.name.lastName||``}`.trim():n.name||``;let i=typeof n.email_verified==`boolean`?n.email_verified:n.email_verified===`true`,a={...n,name:r},o=await e.mapProfileToUser?.(a);return{user:{name:a.name,emailVerified:i,email:n.email,...o},data:a}},options:e}},CT=async e=>{let{data:t}=await ei(`https://appleid.apple.com/auth/keys`);if(!t?.keys)throw new V(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await Gi(n,n.alg)},wT=e=>{let t=`https://auth.atlassian.com/oauth/token`;return{id:`atlassian`,name:`Atlassian`,accountSubject:({profile:e})=>e.account_id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw oo.error(`Client Id and Secret are required for Atlassian`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new H(`codeVerifier is required for Atlassian`);let o=e.disableDefaultScope?[]:[`read:jira-user`,`offline_access`];return e.scope&&o.push(...e.scope),n&&o.push(...n),SC({id:`atlassian`,options:e,authorizationEndpoint:`https://auth.atlassian.com/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:{...a??{},audience:`api.atlassian.com`},prompt:e.prompt})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.accessToken)return null;try{let{data:n}=await ei(`https://api.atlassian.com/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}catch(e){return oo.error(`Failed to fetch user info from Atlassian:`,e),null}},options:e}},TT=`https://dash.cloudflare.com/oauth2/auth`,ET=`https://dash.cloudflare.com/oauth2/token`,DT=`https://api.cloudflare.com/client/v4/user`,OT=e=>{let t=e.clientSecret?`client_secret_basic`:`none`;return{method:e.tokenEndpointAuthMethod??t}},kT=e=>({id:`cloudflare`,name:`Cloudflare`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i}){let a=e.disableDefaultScope?[]:[`user-details.read`];return e.scope?.length&&a.push(...e.scope),n?.length&&a.push(...n),SC({id:`cloudflare`,options:e,authorizationEndpoint:TT,scopes:a.length?[...new Set(a)]:void 0,state:t,codeVerifier:r,redirectURI:i})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>BC({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:ET,tokenEndpointAuth:OT(e)}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:ET,tokenEndpointAuth:OT(e)}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(DT,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r||!n?.success||!n.result)return oo.error(`Failed to fetch user info from Cloudflare:`,r??n?.errors),null;let i=n.result,a=[i.first_name,i.last_name].filter(Boolean).join(` `)||i.email,o=await e.mapProfileToUser?.(i);return{user:{name:a,email:i.email,emailVerified:!1,...o},data:i}},options:e}),AT=e=>{if(!e.domain||!e.region||!e.userPoolId)throw oo.error(`Domain, region and userPoolId are required for Amazon Cognito. Make sure to provide them in the options.`),new H(`DOMAIN_AND_REGION_REQUIRED`);let t=e.domain.replace(/^https?:\/\//,``),n=`https://${t}/oauth2/authorize`,r=`https://${t}/oauth2/token`,i=`https://${t}/oauth2/userinfo`;return{id:`cognito`,name:`Cognito`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:r,codeVerifier:i,redirectURI:a,additionalParams:o}){if(!ci(e.clientId))throw oo.error(`ClientId is required for Amazon Cognito. Make sure to provide them in the options.`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);if(e.requireClientSecret&&!e.clientSecret)throw oo.error(`Client Secret is required when requireClientSecret is true. Make sure to provide it in the options.`),new H(`CLIENT_SECRET_REQUIRED`);let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];e.scope&&s.push(...e.scope),r&&s.push(...r);let c=await SC({id:`cognito`,options:{...e},authorizationEndpoint:n,scopes:s,state:t,codeVerifier:i,redirectURI:a,prompt:e.prompt,additionalParams:{...e.identityProvider?{identity_provider:e.identityProvider}:{},...o??{}}}),l=c.searchParams.get(`scope`);if(l){c.searchParams.delete(`scope`);let e=encodeURIComponent(l),t=c.toString(),n=t.includes(`?`)?`&`:`?`;return new URL(`${t}${n}scope=${e}`)}return c},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:i})=>BC({code:t,codeVerifier:n,redirectURI:i,options:e,tokenEndpoint:r}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:r}),idToken:{jwks:t=>jT(t.kid,e.region,e.userPoolId),issuer:`https://cognito-idp.${e.region}.amazonaws.com/${e.userPoolId}`,audience:e.clientId,algorithms:[`RS256`],maxTokenAge:`1h`},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(t.idToken)try{let n=da(t.idToken);if(!n)return null;let r=n.name||n.given_name||n.username||``,i={...n,name:r},a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:n.email,image:n.picture,emailVerified:n.email_verified,...a},data:i}}catch(e){oo.error(`Failed to decode ID token:`,e)}if(t.accessToken)try{let{data:n}=await ei(i,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(n){let t=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.given_name||n.username||``,email:n.email,image:n.picture,emailVerified:n.email_verified,...t},data:n}}}catch(e){oo.error(`Failed to fetch user info from Cognito:`,e)}return null},options:e}},jT=async(e,t,n)=>{let r=`https://cognito-idp.${t}.amazonaws.com/${n}/.well-known/jwks.json`;try{let{data:t}=await ei(r);if(!t?.keys)throw new V(`BAD_REQUEST`,{message:`Keys not found`});let n=t.keys.find(t=>t.kid===e);if(!n)throw Error(`JWK with kid ${e} not found`);return await Gi(n,n.alg)}catch(e){throw oo.error(`Failed to fetch Cognito public key:`,e),e}},MT=e=>{let t=`https://discord.com/api/oauth2/token`;return{id:`discord`,name:`Discord`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`identify`,`email`];n&&a.push(...n),e.scope&&a.push(...e.scope);let o=a.includes(`bot`);return SC({id:`discord`,options:e,authorizationEndpoint:`https://discord.com/api/oauth2/authorize`,scopes:a,state:t,redirectURI:r,prompt:e.prompt||`none`,additionalParams:{...o&&e.permissions!==void 0?{permissions:String(e.permissions)}:{},...i??{}}})},validateAuthorizationCode:async({code:n,redirectURI:r})=>BC({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://discord.com/api/users/@me`,{headers:{authorization:`Bearer ${t.accessToken}`}});if(r)return null;if(n.avatar===null)n.image_url=`https://cdn.discordapp.com/embed/avatars/${n.discriminator===`0`?Number(BigInt(n.id)>>BigInt(22))%6:parseInt(n.discriminator)%5}.png`;else{let e=n.avatar.startsWith(`a_`)?`gif`:`png`;n.image_url=`https://cdn.discordapp.com/avatars/${n.id}/${n.avatar}.${e}`}let i=await e.mapProfileToUser?.(n);return{user:{name:n.global_name||n.username||``,email:n.email,emailVerified:n.verified,image:n.image_url,...i},data:n}},options:e}},NT=e=>{let t=`https://api.dropboxapi.com/oauth2/token`;return{id:`dropbox`,name:`Dropbox`,accountSubject:({profile:e})=>e.account_id,createAuthorizationURL:async({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a})=>{let o=e.disableDefaultScope?[]:[`account_info.read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await SC({id:`dropbox`,options:e,authorizationEndpoint:`https://www.dropbox.com/oauth2/authorize`,scopes:o,state:t,redirectURI:i,codeVerifier:r,additionalParams:{...e.accessType?{token_access_type:e.accessType}:{},...a??{}}})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>await BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://api.dropboxapi.com/2/users/get_current_account`,{method:`POST`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name?.display_name,email:n.email,emailVerified:n.email_verified||!1,image:n.profile_photo_url,...i},data:n}},options:e}};async function PT(e,t){let n=ci(t.clientId);if(!n||!t.clientSecret)return null;let r=Array.isArray(t.clientId)?t.clientId:[t.clientId],{data:i,error:a}=await ei(`https://graph.facebook.com/debug_token`,{query:{input_token:e,access_token:`${n}|${t.clientSecret}`}});if(a||!i?.data)return null;let{is_valid:o,app_id:s,user_id:c}=i.data;return o!==!0||!s||!r.includes(s)||!c?null:c}var FT=e=>({id:`facebook`,name:`Facebook`,accountSubject:({profile:e})=>`sub`in e?e.sub:e.id,async createAuthorizationURL({state:t,scopes:n,redirectURI:r,loginHint:i,additionalParams:a}){if(!ci(e.clientId)||!e.clientSecret)throw oo.error(`Client ID and client secret are required for Facebook. Make sure to provide them in the options.`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);let o=e.disableDefaultScope?[]:[`email`,`public_profile`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await SC({id:`facebook`,options:e,authorizationEndpoint:`https://www.facebook.com/v24.0/dialog/oauth`,scopes:o,state:t,redirectURI:r,loginHint:i,additionalParams:{...e.configId?{config_id:e.configId}:{},...a??{}}})},validateAuthorizationCode:async({code:t,redirectURI:n})=>BC({code:t,redirectURI:n,options:e,tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),idToken:{jwks:pC(new URL(`https://limited.facebook.com/.well-known/oauth/openid/jwks/`)),issuer:`https://www.facebook.com`,audience:e.clientId,algorithms:[`RS256`],allowOpaqueToken:!0},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://graph.facebook.com/v24.0/oauth/access_token`}),async getUserInfo(t){if(e.getUserInfo){let n=!!t.idToken&&t.idToken.split(`.`).length!==3,r=t.accessToken||(n?t.idToken:void 0);return r&&!await PT(r,e)?null:e.getUserInfo(t)}if(t.idToken&&t.idToken.split(`.`).length===3){let n=da(t.idToken),r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}}let n=t.accessToken;if(!n)return null;let r=await PT(n,e);if(!r)return null;let{data:i,error:a}=await ei(`https://graph.facebook.com/me?fields=`+[`id`,`name`,`email`,`picture`,...e?.fields||[]].join(`,`),{auth:{type:`Bearer`,token:n}});if(a||i.id!==r)return null;let o=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.picture.data.url,emailVerified:i.email_verified??!1,...o},data:i}},options:e}),IT=e=>{let t=`https://api.figma.com/v1/oauth/token`;return{id:`figma`,name:`Figma`,accountSubject:({profile:e})=>e.id,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){if(!e.clientId||!e.clientSecret)throw oo.error(`Client Id and Client Secret are required for Figma. Make sure to provide them in the options.`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new H(`codeVerifier is required for Figma`);let o=e.disableDefaultScope?[]:[`current_user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),await SC({id:`figma`,options:e,authorizationEndpoint:`https://www.figma.com/oauth`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t,authentication:`basic`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t,authentication:`basic`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);try{let{data:n}=await ei(`https://api.figma.com/v1/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(!n)return oo.error(`Failed to fetch user from Figma`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.handle,email:n.email,image:n.img_url,emailVerified:!1,...r},data:n}}catch(e){return oo.error(`Failed to fetch user info from Figma:`,e),null}},options:e}},LT=e=>{let t=`https://github.com/login/oauth/access_token`;return{id:`github`,name:`GitHub`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,codeVerifier:i,redirectURI:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`read:user`,`user:email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),SC({id:`github`,options:e,authorizationEndpoint:`https://github.com/login/oauth/authorize`,scopes:s,state:t,codeVerifier:i,redirectURI:a,loginHint:r,prompt:e.prompt,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>{let{body:a,headers:o}=await RC({code:n,codeVerifier:r,redirectURI:i,options:e}),{data:s,error:c}=await ei(t,{method:`POST`,body:a,headers:o});return c?(oo.error(`GitHub OAuth token exchange failed:`,c),null):`error`in s?(oo.error(`GitHub OAuth token exchange failed:`,s),null):Mr(s)},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://api.github.com/user`,{headers:{"User-Agent":`better-auth`,authorization:`Bearer ${t.accessToken}`}});if(r)return null;let{data:i}=await ei(`https://api.github.com/user/emails`,{headers:{Authorization:`Bearer ${t.accessToken}`,"User-Agent":`better-auth`}});!n.email&&i&&(n.email=(i.find(e=>e.primary)??i[0])?.email);let a=i?.find(e=>e.email===n.email)?.verified??!1,o=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.login||``,email:n.email,image:n.avatar_url,emailVerified:a,...o},data:n}},options:e}},RT=(e=``)=>e.split(`://`).map(e=>e.replace(/\/{2,}/g,`/`)).join(`://`),zT=e=>{let t=e||`https://gitlab.com`;return{authorizationEndpoint:RT(`${t}/oauth/authorize`),tokenEndpoint:RT(`${t}/oauth/token`),userinfoEndpoint:RT(`${t}/api/v4/user`)}},BT=e=>{let{authorizationEndpoint:t,tokenEndpoint:n,userinfoEndpoint:r}=zT(e.issuer),i=`gitlab`;return{id:i,name:`Gitlab`,accountSubject:({profile:e})=>e.id,createAuthorizationURL:async({state:n,scopes:r,codeVerifier:a,loginHint:o,redirectURI:s,additionalParams:c})=>{let l=e.disableDefaultScope?[]:[`read_user`];return e.scope&&l.push(...e.scope),r&&l.push(...r),await SC({id:i,options:e,authorizationEndpoint:t,scopes:l,state:n,redirectURI:s,codeVerifier:a,loginHint:o,additionalParams:c})},validateAuthorizationCode:async({code:t,redirectURI:r,codeVerifier:i})=>BC({code:t,redirectURI:r,options:e,codeVerifier:i,tokenEndpoint:n}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:n}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:i}=await ei(r,{headers:{authorization:`Bearer ${t.accessToken}`}});if(i||n.state!==`active`||n.locked)return null;let a=await e.mapProfileToUser?.(n);return{user:{name:n.name??n.username??``,email:n.email,image:n.avatar_url,emailVerified:n.email_verified??!1,...a},data:n}},options:e}},VT=`1h`,HT=`RS256`,UT=[HT],WT=(e,t)=>e?typeof t!=`string`||!t?!1:e===`*`||t===e:!0,GT=e=>({id:`google`,name:`Google`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,display:o,additionalParams:s}){if(!ci(e.clientId)||!e.clientSecret)throw oo.error(`Client Id and Client Secret is required for Google. Make sure to provide them in the options.`),new H(`CLIENT_ID_AND_SECRET_REQUIRED`);if(!r)throw new H(`codeVerifier is required for Google`);let c=e.disableDefaultScope?[]:[`email`,`profile`,`openid`];return e.scope&&c.push(...e.scope),n&&c.push(...n),await SC({id:`google`,options:e,authorizationEndpoint:`https://accounts.google.com/o/oauth2/v2/auth`,scopes:c,state:t,codeVerifier:r,redirectURI:i,prompt:e.prompt,accessType:e.accessType,display:o||e.display,loginHint:a,hd:e.hd,additionalParams:{...e.includeGrantedScopes===!1?{}:{include_granted_scopes:`true`},...s??{}}})},validateAuthorizationCode:async({code:t,codeVerifier:n,redirectURI:r})=>BC({code:t,codeVerifier:n,redirectURI:r,options:e,tokenEndpoint:`https://oauth2.googleapis.com/token`}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:`https://oauth2.googleapis.com/token`}),idToken:{jwks:e=>KT(e.kid),issuer:[`https://accounts.google.com`,`accounts.google.com`],audience:e.clientId,algorithms:UT,maxTokenAge:VT,verifyClaims:e.hd?t=>WT(e.hd,t.hd):void 0},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);if(!t.idToken)return null;let n=da(t.idToken);if(!WT(e.hd,n.hd))return oo.error(`Google sign-in rejected: id token hosted domain (hd) "${n.hd??`<missing>`}" does not satisfy the configured "hd" option "${e.hd}".`),null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...r},data:n}},options:e}),KT=async e=>{let[t]=await qT(e);if(!t)throw Error(`JWK with kid ${e} not found`);return t},qT=async e=>{let{data:t}=await ei(`https://www.googleapis.com/oauth2/v3/certs`);if(!t?.keys)throw new V(`BAD_REQUEST`,{message:`Keys not found`});let n=e?t.keys.filter(t=>t.kid===e):t.keys;if(!n.length)throw Error(`JWK with kid ${e} not found`);return Promise.all(n.map(e=>Gi(e,HT)))},JT=e=>{let t=`https://huggingface.co/oauth/token`;return{id:`huggingface`,name:`Hugging Face`,accountSubject:({profile:e})=>e.sub,createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&o.push(...e.scope),n&&o.push(...n),SC({id:`huggingface`,options:e,authorizationEndpoint:`https://huggingface.co/oauth/authorize`,scopes:o,state:t,codeVerifier:r,redirectURI:i,additionalParams:a})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://huggingface.co/oauth/userinfo`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=await e.mapProfileToUser?.(n);return{user:{name:n.name||n.preferred_username||``,email:n.email,image:n.picture,emailVerified:n.email_verified??!1,...i},data:n}},options:e}},YT=e=>{let t=`https://kauth.kakao.com/oauth/token`;return{id:`kakao`,name:`Kakao`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,additionalParams:i}){let a=e.disableDefaultScope?[]:[`account_email`,`profile_image`,`profile_nickname`];return e.scope&&a.push(...e.scope),n&&a.push(...n),SC({id:`kakao`,options:e,authorizationEndpoint:`https://kauth.kakao.com/oauth/authorize`,scopes:a,scopeJoiner:`,`,state:t,redirectURI:r,additionalParams:i})},validateAuthorizationCode:async({code:n,redirectURI:r})=>BC({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://kapi.kakao.com/v2/user/me`,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(r||!n)return null;let i=await e.mapProfileToUser?.(n),a=n.kakao_account||{},o=a.profile||{};return{user:{name:o.nickname||a.name||``,email:a.email,image:o.profile_image_url||o.thumbnail_image_url,emailVerified:!!a.is_email_valid&&!!a.is_email_verified,...i},data:n}},options:e}},XT=e=>({id:`kick`,name:`Kick`,accountSubject:({profile:e})=>e.user_id,createAuthorizationURL({state:t,scopes:n,redirectURI:r,codeVerifier:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`user:read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),SC({id:`kick`,redirectURI:r,options:e,authorizationEndpoint:`https://id.kick.com/oauth/authorize`,scopes:o,codeVerifier:i,state:t,additionalParams:a})},async validateAuthorizationCode({code:t,redirectURI:n,codeVerifier:r}){return BC({code:t,redirectURI:n,options:e,tokenEndpoint:`https://id.kick.com/oauth/token`,codeVerifier:r})},refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async t=>LC({refreshToken:t,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:`https://id.kick.com/oauth/token`}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://api.kick.com/public/v1/users`,{method:`GET`,headers:{Authorization:`Bearer ${t.accessToken}`}});if(r)return null;let i=n.data[0],a=await e.mapProfileToUser?.(i);return{user:{name:i.name,email:i.email,image:i.profile_picture,emailVerified:!1,...a},data:i}},options:e}),ZT=e=>{let t=`https://api.line.me/oauth2/v2.1/token`;return{id:`line`,name:`LINE`,accountSubject:({profile:e})=>e.sub,async createAuthorizationURL({state:t,scopes:n,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o}){let s=e.disableDefaultScope?[]:[`openid`,`profile`,`email`];return e.scope&&s.push(...e.scope),n&&s.push(...n),await SC({id:`line`,options:e,authorizationEndpoint:`https://access.line.me/oauth2/v2.1/authorize`,scopes:s,state:t,codeVerifier:r,redirectURI:i,loginHint:a,additionalParams:o})},validateAuthorizationCode:async({code:n,codeVerifier:r,redirectURI:i})=>BC({code:n,codeVerifier:r,redirectURI:i,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientSecret:e.clientSecret},tokenEndpoint:t}),idToken:{verify:async(t,n)=>{let r=new URLSearchParams;r.set(`id_token`,t),r.set(`client_id`,e.clientId),n&&r.set(`nonce`,n);let{data:i,error:a}=await ei(`https://api.line.me/oauth2/v2.1/verify`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:r});return!(a||!i||i.aud!==e.clientId||i.nonce&&i.nonce!==n)}},async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let n=null;if(t.idToken)try{n=da(t.idToken)}catch{}if(!n){let{data:e}=await ei(`https://api.line.me/oauth2/v2.1/userinfo`,{headers:{authorization:`Bearer ${t.accessToken}`}});n=e||null}if(!n)return null;let r=await e.mapProfileToUser?.(n);return{user:{name:n.name||``,email:n.email,image:n.picture,emailVerified:!1,...r},data:n}},options:e}},QT=e=>{let t=`https://api.linear.app/oauth/token`;return{id:`linear`,name:`Linear`,accountSubject:({profile:e})=>e.id,createAuthorizationURL({state:t,scopes:n,loginHint:r,redirectURI:i,additionalParams:a}){let o=e.disableDefaultScope?[]:[`read`];return e.scope&&o.push(...e.scope),n&&o.push(...n),SC({id:`linear`,options:e,authorizationEndpoint:`https://linear.app/oauth/authorize`,scopes:o,state:t,redirectURI:i,loginHint:r,additionalParams:a})},validateAuthorizationCode:async({code:n,redirectURI:r})=>BC({code:n,redirectURI:r,options:e,tokenEndpoint:t}),refreshAccessToken:e.refreshAccessToken?e.refreshAccessToken:async n=>LC({refreshToken:n,options:{clientId:e.clientId,clientKey:e.clientKey,clientSecret:e.clientSecret},tokenEndpoint:t}),async getUserInfo(t){if(e.getUserInfo)return e.getUserInfo(t);let{data:n,error:r}=await ei(`https://api.linear.app/graphql`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${t.accessToken}`},body:JSON.stringify({query:`
78
78
  query {
@@ -498,7 +498,7 @@ To prepare for this change:
498
498
  - If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${e}'
499
499
 
500
500
  See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}n.exports=r,r.parse=r,r.toClientConfig=a,r.parseIntoClientConfig=o})),l4=t(((t,n)=>{var r=(a4(),e(i4)),i=K2(),a=c4().parse,o=function(e,t,n){return t[e]?t[e]:(n===void 0?n=process.env[`PG`+e.toUpperCase()]:n===!1||(n=process.env[n]),n||i[e])},s=function(){switch(process.env.PGSSLMODE){case`disable`:return!1;case`prefer`:case`require`:case`verify-ca`:case`verify-full`:return!0;case`no-verify`:return{rejectUnauthorized:!1}}return i.ssl},c=function(e){return`'`+(``+e).replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)+`'`},l=function(e,t,n){let r=t[n];r!=null&&e.push(n+`=`+c(r))};n.exports=class{constructor(e){if(e=typeof e==`string`?a(e):e||{},e.connectionString&&(e=Object.assign({},e,a(e.connectionString))),this.user=o(`user`,e),this.database=o(`database`,e),this.database===void 0&&(this.database=this.user),this.port=parseInt(o(`port`,e),10),this.host=o(`host`,e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:o(`password`,e)}),this.binary=o(`binary`,e),this.options=o(`options`,e),this.ssl=e.ssl===void 0?s():e.ssl,typeof this.ssl==`string`&&this.ssl===`true`&&(this.ssl=!0),this.ssl===`no-verify`&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=o(`sslnegotiation`,e,`PGSSLNEGOTIATION`),this.sslnegotiation!==void 0&&this.sslnegotiation!==`postgres`&&this.sslnegotiation!==`direct`)throw Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation===`direct`&&!this.ssl)throw Error(`sslnegotiation=direct requires SSL to be enabled`);this.client_encoding=o(`client_encoding`,e),this.replication=o(`replication`,e),this.isDomainSocket=!(this.host||``).indexOf(`/`),this.application_name=o(`application_name`,e,`PGAPPNAME`),this.fallback_application_name=o(`fallback_application_name`,e,!1),this.statement_timeout=o(`statement_timeout`,e,!1),this.lock_timeout=o(`lock_timeout`,e,!1),this.idle_in_transaction_session_timeout=o(`idle_in_transaction_session_timeout`,e,!1),this.query_timeout=o(`query_timeout`,e,!1),this.connect_timeout=e.connectionTimeoutMillis===void 0?process.env.PGCONNECT_TIMEOUT||0:Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis==`number`&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let t=[];l(t,this,`user`),l(t,this,`password`),l(t,this,`port`),l(t,this,`application_name`),l(t,this,`fallback_application_name`),l(t,this,`connect_timeout`),l(t,this,`options`);let n=typeof this.ssl==`object`?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(l(t,n,`sslmode`),l(t,n,`sslca`),l(t,n,`sslkey`),l(t,n,`sslcert`),l(t,n,`sslrootcert`),l(t,this,`sslnegotiation`),this.database&&t.push(`dbname=`+c(this.database)),this.replication&&t.push(`replication=`+c(this.replication)),this.host&&t.push(`host=`+c(this.host)),this.isDomainSocket)return e(null,t.join(` `));this.client_encoding&&t.push(`client_encoding=`+c(this.client_encoding)),r.lookup(this.host,function(n,r){return n?e(n,null):(t.push(`hostaddr=`+c(r)),e(null,t.join(` `)))})}}})),u4=t(((e,t)=>{var n=G2(),r=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;t.exports=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e===`array`,this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let t;t=e.text?r.exec(e.text):r.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){let t=Array(e.length);for(let n=0,r=e.length;n<r;n++){let r=e[n];r===null?t[n]=null:t[n]=this._parsers[n](r)}return t}parseRow(e){let t={...this._prebuiltEmptyResultObject};for(let n=0,r=e.length;n<r;n++){let r=e[n],i=this.fields[n].name;if(r!==null){let e=this.fields[n].format===`binary`?Buffer.from(r):r;t[i]=this._parsers[n](e)}else t[i]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=Array(e.length));let t=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];t[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||`text`):this._parsers[r]=n.getTypeParser(i.dataTypeID,i.format||`text`)}this._prebuiltEmptyResultObject={...t}}}})),d4=t(((t,n)=>{var{EventEmitter:r}=(P2(),e(N2)),i=u4(),a=Z2();n.exports=class extends r{constructor(e,t,n){super(),e=a.normalizeQueryConfig(e,t,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||``,this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new i(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode===`extended`||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new i(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners(`row`).length}handleDataRow(e){let t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(e){this._canceledDueToError=e;return}this.emit(`row`,t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){if(this._canceledDueToError&&=(e=this._canceledDueToError,!1),this.callback)return this.callback(e);this.emit(`error`,e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(e){process.nextTick(()=>{throw e})}this.emit(`end`,this._results)}submit(e){if(typeof this.text!=`string`&&typeof this.name!=`string`)return Error(`A query must have either text or a name. Supplying neither is unsupported.`);let t=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&t&&this.text!==t)return Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return Error(`Query values must be an array`);if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,t){e.execute({portal:this.portal,rows:t}),t?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:a.prepareValue})}catch(t){e.close({type:`S`,name:this.name}),e.sync(),this.handleError(t,e);return}e.describe({type:`P`,name:this.portal||``}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail(`No source stream defined`)}handleCopyData(e,t){}}})),f4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoticeMessage=e.DataRowMessage=e.CommandCompleteMessage=e.ReadyForQueryMessage=e.NotificationResponseMessage=e.BackendKeyDataMessage=e.AuthenticationMD5Password=e.ParameterStatusMessage=e.ParameterDescriptionMessage=e.RowDescriptionMessage=e.Field=e.CopyResponse=e.CopyDataMessage=e.DatabaseError=e.copyDone=e.emptyQuery=e.replicationStart=e.portalSuspended=e.noData=e.closeComplete=e.bindComplete=e.parseComplete=void 0,e.parseComplete={name:`parseComplete`,length:5},e.bindComplete={name:`bindComplete`,length:5},e.closeComplete={name:`closeComplete`,length:5},e.noData={name:`noData`,length:5},e.portalSuspended={name:`portalSuspended`,length:5},e.replicationStart={name:`replicationStart`,length:4},e.emptyQuery={name:`emptyQuery`,length:4},e.copyDone={name:`copyDone`,length:4},e.DatabaseError=class extends Error{constructor(e,t,n){super(e),this.length=t,this.name=n}},e.CopyDataMessage=class{constructor(e,t){this.length=e,this.chunk=t,this.name=`copyData`}},e.CopyResponse=class{constructor(e,t,n,r){this.length=e,this.name=t,this.binary=n,this.columnTypes=Array(r)}},e.Field=class{constructor(e,t,n,r,i,a,o){this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=r,this.dataTypeSize=i,this.dataTypeModifier=a,this.format=o}},e.RowDescriptionMessage=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name=`rowDescription`,this.fields=Array(this.fieldCount)}},e.ParameterDescriptionMessage=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name=`parameterDescription`,this.dataTypeIDs=Array(this.parameterCount)}},e.ParameterStatusMessage=class{constructor(e,t,n){this.length=e,this.parameterName=t,this.parameterValue=n,this.name=`parameterStatus`}},e.AuthenticationMD5Password=class{constructor(e,t){this.length=e,this.salt=t,this.name=`authenticationMD5Password`}},e.BackendKeyDataMessage=class{constructor(e,t,n){this.length=e,this.processID=t,this.secretKey=n,this.name=`backendKeyData`}},e.NotificationResponseMessage=class{constructor(e,t,n,r){this.length=e,this.processId=t,this.channel=n,this.payload=r,this.name=`notification`}},e.ReadyForQueryMessage=class{constructor(e,t){this.length=e,this.status=t,this.name=`readyForQuery`}},e.CommandCompleteMessage=class{constructor(e,t){this.length=e,this.text=t,this.name=`commandComplete`}},e.DataRowMessage=class{constructor(e,t){this.length=e,this.fields=t,this.name=`dataRow`,this.fieldCount=t.length}},e.NoticeMessage=class{constructor(e,t){this.length=e,this.message=t,this.name=`notice`}}})),p4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Writer=void 0,e.Writer=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let t=this.buffer,n=t.length+(t.length>>1)+e;this.buffer=Buffer.allocUnsafe(n),t.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,`utf-8`),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=``){let t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}addInt32PrefixedString(e){let t=Buffer.byteLength(e);this.ensure(4+t);let n=this.buffer,r=this.offset;return n[r++]=t>>>24&255,n[r++]=t>>>16&255,n[r++]=t>>>8&255,n[r++]=t>>>0&255,n.write(e,r,`utf-8`),this.offset=r+t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let t=this.offset;return this.ensure(e),this.offset+=e,t}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}clear(){this.offset=5,this.headerPosition=0}}})),m4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.serialize=void 0;var t=p4(),n=new t.Writer,r=e=>{n.addInt16(3).addInt16(0);for(let t of Object.keys(e))n.addCString(t).addCString(e[t]);n.addCString(`client_encoding`).addCString(`UTF8`);let r=n.addCString(``).flush(),i=r.length+4;return new t.Writer().addInt32(i).add(r).flush()},i=()=>{let e=Buffer.allocUnsafe(8);return e.writeInt32BE(8,0),e.writeInt32BE(80877103,4),e},a=e=>n.addCString(e).flush(112),o=function(e,t){return n.addCString(e).addInt32PrefixedString(t),n.flush(112)},s=function(e){return n.addString(e).flush(112)},c=e=>n.addCString(e).flush(81),l=[],u=e=>{let t=e.name||``;t.length>63&&(console.error(`Warning! Postgres only supports 63 characters for query names.`),console.error(`You supplied %s (%s)`,t,t.length),console.error(`This can cause conflicts and silent errors executing queries`));let r=e.types||l,i=r.length,a=n.addCString(t).addCString(e.text).addInt16(i);for(let e=0;e<i;e++)a.addInt32(r[e]);return n.flush(80)},d=function(e,t,r){let i=e.length;for(let a=0;a<i;a++){let i=t?t(e[a],a):e[a],o=0;i==null?n.addInt32(-1):i instanceof Buffer?(o=1,n.addInt32(i.length),n.add(i)):n.addInt32PrefixedString(i);let s=n.buffer;s[r++]=0,s[r++]=o}},f=(e={})=>{let t=e.portal||``,r=e.statement||``,i=e.binary||!1,a=e.values||l,o=a.length;n.addCString(t).addCString(r),n.addInt16(o);let s=n.reserveUnsafe(o*2);n.addInt16(o);try{d(a,e.valueMapper,s)}catch(e){throw n.clear(),e}return n.addInt16(1),n.addInt16(+!!i),n.flush(66)},p=Buffer.from([69,0,0,0,9,0,0,0,0,0]),m=e=>{if(!e||!e.portal&&!e.rows)return p;let t=e.portal||``,n=e.rows||0,r=Buffer.byteLength(t),i=4+r+1+4,a=Buffer.allocUnsafe(1+i);return a[0]=69,a.writeInt32BE(i,1),a.write(t,5,`utf-8`),a[r+5]=0,a.writeUInt32BE(n,a.length-4),a},h=(e,t)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(e,8),n.writeInt32BE(t,12),n},g=(e,t)=>{let n=4+Buffer.byteLength(t)+1,r=Buffer.allocUnsafe(1+n);return r[0]=e,r.writeInt32BE(n,1),r.write(t,5,`utf-8`),r[n]=0,r},_=n.addCString(`P`).flush(68),v=n.addCString(`S`).flush(68),y=e=>e.name?g(68,`${e.type}${e.name||``}`):e.type===`P`?_:v,b=e=>g(67,`${e.type}${e.name||``}`),x=e=>n.add(e).flush(100),S=e=>g(102,e),C=e=>Buffer.from([e,0,0,0,4]),w=C(72),E=C(83),D=C(88),O=C(99);e.serialize={startup:r,password:a,requestSsl:i,sendSASLInitialResponseMessage:o,sendSCRAMClientFinalMessage:s,query:c,parse:u,bind:f,execute:m,describe:y,close:b,flush:()=>w,sync:()=>E,end:()=>D,copyData:x,copyDone:()=>O,copyFail:S,cancel:h}})),h4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BufferReader=void 0,e.BufferReader=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding=`utf-8`}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++];);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}}})),g4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Parser=void 0;var t=f4(),n=h4(),r=1,i=5,a=-1,o=Buffer.allocUnsafe(0);e.Parser=class{constructor(e){if(this.buffer=o,this.bufferLength=0,this.bufferOffset=0,this.reader=new n.BufferReader,e?.mode===`binary`)throw Error(`Binary mode not supported yet`);this.mode=e?.mode||`text`}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,a=this.bufferOffset;for(;a+i<=n;){let e=this.buffer[a],o=this.buffer.readUInt32BE(a+r),s=r+o;if(s+a<=n)t(this.handlePacket(a+i,e,o,this.buffer)),a+=s;else break}a===n?(this.buffer=o,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-a,this.bufferOffset=a)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let e;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)e=this.buffer;else{let n=this.buffer.byteLength*2;for(;t>=n;)n*=2;e=Buffer.allocUnsafe(n)}this.buffer.copy(e,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=e,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:a}=this;a.setBuffer(e,i);let f;switch(n){case 50:f=t.bindComplete;break;case 49:f=t.parseComplete;break;case 51:f=t.closeComplete;break;case 110:f=t.noData;break;case 115:f=t.portalSuspended;break;case 99:f=t.copyDone;break;case 87:f=t.replicationStart;break;case 73:f=t.emptyQuery;break;case 68:f=_(a);break;case 67:f=c(a);break;case 90:f=s(a);break;case 65:f=p(a);break;case 82:f=b(a,r);break;case 83:f=v(a);break;case 75:f=y(a);break;case 69:f=x(a,`error`);break;case 78:f=x(a,`notice`);break;case 84:f=m(a);break;case 116:f=g(a);break;case 71:f=u(a);break;case 72:f=d(a);break;case 100:f=l(a,r);break;default:return new t.DatabaseError(`received invalid response: `+n.toString(16),r,`error`)}return a.setBuffer(0,o),f.length=r,f}};var s=e=>{let n=e.string(1);return new t.ReadyForQueryMessage(a,n)},c=e=>{let n=e.cstring();return new t.CommandCompleteMessage(a,n)},l=(e,n)=>{let r=e.bytes(n-4);return new t.CopyDataMessage(a,r)},u=e=>f(e,`copyInResponse`),d=e=>f(e,`copyOutResponse`),f=(e,n)=>{let r=e.byte()!==0,i=e.int16(),o=new t.CopyResponse(a,n,r,i);for(let t=0;t<i;t++)o.columnTypes[t]=e.int16();return o},p=e=>{let n=e.int32(),r=e.cstring(),i=e.cstring();return new t.NotificationResponseMessage(a,n,r,i)},m=e=>{let n=e.int16(),r=new t.RowDescriptionMessage(a,n);for(let t=0;t<n;t++)r.fields[t]=h(e);return r},h=e=>{let n=e.cstring(),r=e.uint32(),i=e.int16(),a=e.uint32(),o=e.int16(),s=e.int32(),c=e.int16()===0?`text`:`binary`;return new t.Field(n,r,i,a,o,s,c)},g=e=>{let n=e.int16(),r=new t.ParameterDescriptionMessage(a,n);for(let t=0;t<n;t++)r.dataTypeIDs[t]=e.uint32();return r},_=e=>{let n=e.int16(),r=Array(n);for(let t=0;t<n;t++){let n=e.int32();r[t]=n===-1?null:e.string(n)}return new t.DataRowMessage(a,r)},v=e=>{let n=e.cstring(),r=e.cstring();return new t.ParameterStatusMessage(a,n,r)},y=e=>{let n=e.int32(),r=e.int32();return new t.BackendKeyDataMessage(a,n,r)},b=(e,n)=>{let r=e.int32(),i={name:`authenticationOk`,length:n};switch(r){case 0:break;case 3:i.length===8&&(i.name=`authenticationCleartextPassword`);break;case 5:if(i.length===12){i.name=`authenticationMD5Password`;let n=e.bytes(4);return new t.AuthenticationMD5Password(a,n)}break;case 10:{i.name=`authenticationSASL`,i.mechanisms=[];let t;do t=e.cstring(),t&&i.mechanisms.push(t);while(t)}break;case 11:i.name=`authenticationSASLContinue`,i.data=e.string(n-8);break;case 12:i.name=`authenticationSASLFinal`,i.data=e.string(n-8);break;default:throw Error(`Unknown authenticationOk message type `+r)}return i},x=(e,n)=>{let r={},i=e.string(1);for(;i!==`\0`;)r[i]=e.cstring(),i=e.string(1);let o=r.M,s=n===`notice`?new t.NoticeMessage(a,o):new t.DatabaseError(o,a,n);return s.severity=r.S,s.code=r.C,s.detail=r.D,s.hint=r.H,s.position=r.P,s.internalPosition=r.p,s.internalQuery=r.q,s.where=r.W,s.schema=r.s,s.table=r.t,s.column=r.c,s.dataType=r.d,s.constraint=r.n,s.file=r.F,s.line=r.L,s.routine=r.R,s}})),_4=t((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DatabaseError=e.serialize=void 0,e.parse=i;var t=f4();Object.defineProperty(e,"DatabaseError",{enumerable:!0,get:function(){return t.DatabaseError}});var n=m4();Object.defineProperty(e,"serialize",{enumerable:!0,get:function(){return n.serialize}});var r=g4();function i(e,t){let n=new r.Parser;return e.on(`data`,e=>n.parse(e,t)),new Promise(t=>e.on(`end`,()=>t()))}})),v4=c({"module.exports":()=>es}),y4=r(()=>{}),b4=c({"module.exports":()=>ts}),x4=r(()=>{}),S4=t((t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CloudflareSocket=void 0;var n=(P2(),e(N2));t.CloudflareSocket=class extends n.EventEmitter{constructor(e){super(),this.ssl=e,this.writable=!1,this.destroyed=!1,this._upgrading=!1,this._upgraded=!1,this._cfSocket=null,this._cfWriter=null,this._cfReader=null}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}async connect(e,t,n){try{n&&this.once(`connect`,n);let r=this.ssl?{secureTransport:`starttls`}:{},i=(await import(`cloudflare:sockets`)).connect;return this._cfSocket=i(`${t}:${e}`,r),this._cfWriter=this._cfSocket.writable.getWriter(),this._addClosedHandler(),this._cfReader=this._cfSocket.readable.getReader(),this.ssl?this._listenOnce().catch(e=>this.emit(`error`,e)):this._listen().catch(e=>this.emit(`error`,e)),await this._cfWriter.ready,this.writable=!0,this.emit(`connect`),this}catch(e){this.emit(`error`,e)}}async _listen(){for(;;){let{done:e,value:t}=await this._cfReader.read();if(e)break;this.emit(`data`,Buffer.from(t))}}async _listenOnce(){let{done:e,value:t}=await this._cfReader.read();this.emit(`data`,Buffer.from(t))}write(e,t=`utf8`,n=()=>{}){let r=typeof t==`function`?`utf8`:t;return typeof t==`function`&&(n=t),e.length===0?n():(typeof e==`string`&&(e=Buffer.from(e,r)),this._cfWriter.write(e).then(()=>{n()},e=>{n(e)}),!0)}end(e=Buffer.alloc(0),t=`utf8`,n=()=>{}){return this.write(e,t,e=>{let t=this._cfSocket;(t?.close())?.then(()=>{this._cfSocket===t&&(this._cfSocket=null,this.emit(`close`))}).catch(e=>this.emit(`error`,e)),n&&n(e)}),this}destroy(e){return this.destroyed=!0,this.end()}startTls(e){this._upgraded?this.emit(`error`,"Cannot call `startTls()` more than once on a socket"):(this._cfWriter.releaseLock(),this._cfReader.releaseLock(),this._upgrading=!0,this._cfSocket=this._cfSocket.startTls(e),this._cfWriter=this._cfSocket.writable.getWriter(),this._cfReader=this._cfSocket.readable.getReader(),this._addClosedHandler(),this._listen().catch(e=>this.emit(`error`,e)))}_addClosedHandler(){let e=this._cfSocket;e.closed.then(()=>{this._upgrading?(this._upgrading=!1,this._upgraded=!0):this._cfSocket===e&&(this._cfSocket=null,this.emit(`close`))}).catch(e=>this.emit(`error`,e))}}})),C4=t(((t,n)=>{var{getStream:r,getSecureStream:i}=c();n.exports={getStream:r,getSecureStream:i};function a(){function t(t){return new(y4(),e(v4)).Socket}function n(t){return(x4(),e(b4)).connect(t)}return{getStream:t,getSecureStream:n}}function o(){function e(e){let{CloudflareSocket:t}=S4();return new t(e)}function t(e){return e.socket.startTls(e),e.socket}return{getStream:e,getSecureStream:t}}function s(){if(typeof navigator==`object`&&navigator!==null&&typeof navigator.userAgent==`string`)return navigator.userAgent===`Cloudflare-Workers`;if(typeof Response==`function`){let e=new Response(null,{cf:{thing:!0}});if(typeof e.cf==`object`&&e.cf!==null&&e.cf.thing)return!0}return!1}function c(){return s()?o():a()}})),w4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,{parse:i,serialize:a}=_4(),o=C4(),{getStream:s}=o,c=a.flush(),l=a.sync(),u=a.end();n.exports=class extends r{constructor(e){super(),e||={},this.stream=e.stream||s(e.ssl),typeof this.stream==`function`&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||`postgres`,this._ending=!1,this._emitMessage=!1;let t=this;this.on(`newListener`,function(e){e===`message`&&(t._emitMessage=!0)})}connect(e,t){let n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once(`connect`,function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit(`connect`)});let r=function(e){(!n._ending||e.code!==`ECONNRESET`&&e.code!==`EPIPE`)&&n.emit(`error`,e)};if(this.stream.on(`error`,r),this.stream.on(`close`,function(){n.emit(`end`)}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation===`direct`)return this.stream.once(`connect`,function(){n.upgradeToSSL(t,r)});this.stream.once(`data`,function(e){switch(e.toString(`utf8`)){case`S`:break;case`N`:return n.stream.end(),n.emit(`error`,Error(`The server does not support SSL connections`));default:return n.stream.end(),n.emit(`error`,Error(`There was an error establishing an SSL connection`))}n.upgradeToSSL(t,r)})}upgradeToSSL(t,n){let r=this,i={socket:r.stream,host:t};r.ssl!==!0&&(Object.assign(i,r.ssl),`key`in r.ssl&&(i.key=r.ssl.key)),r.sslNegotiation===`direct`&&(i.ALPNProtocols=[`postgresql`]);let a=(y4(),e(v4));a.isIP&&a.isIP(t)===0&&(i.servername=t);try{r.stream=o.getSecureStream(i)}catch(e){return r.emit(`error`,e)}r.attachListeners(r.stream),r.stream.on(`error`,n),r.emit(`sslconnect`)}attachListeners(e){i(e,e=>{let t=e.name===`error`?`errorMessage`:e.name;this._emitMessage&&this.emit(`message`,e),this.emit(t,e)})}requestSsl(){this.stream.write(a.requestSsl())}startup(e){this.stream.write(a.startup(e))}cancel(e,t){this._send(a.cancel(e,t))}password(e){this._send(a.password(e))}sendSASLInitialResponseMessage(e,t){this._send(a.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){this._send(a.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(a.query(e))}parse(e){this._send(a.parse(e))}bind(e){this._send(a.bind(e))}execute(e){this._send(a.execute(e))}flush(){this.stream.writable&&this.stream.write(c)}sync(){this._send(l)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable)this.stream.end();else return this.stream.write(u,()=>{this.stream.end()})}close(e){this._send(a.close(e))}describe(e){this._send(a.describe(e))}sendCopyFromChunk(e){this._send(a.copyData(e))}endCopyFrom(){this._send(a.copyDone())}sendCopyFail(e){this._send(a.copyFail(e))}}})),T4=c({"module.exports":()=>ns}),E4=r(()=>{}),D4=c({"module.exports":()=>Uo}),O4=r(()=>{}),k4=c({"module.exports":()=>rs}),A4=r(()=>{}),j4=t(((t,n)=>{var{Transform:r}=(O4(),e(D4)),{StringDecoder:i}=(A4(),e(k4)),a=Symbol(`last`),o=Symbol(`decoder`);function s(e,t,n){let r;if(this.overflow){if(r=this[o].write(e).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[a]+=this[o].write(e),r=this[a].split(this.matcher);this[a]=r.pop();for(let e=0;e<r.length;e++)try{l(this,this.mapper(r[e]))}catch(e){return n(e)}this.overflow=this[a].length>this.maxLength,this.overflow&&!this.skipOverflow?n(Error(`maximum buffer reached`)):n()}function c(e){if(this[a]+=this[o].end(),this[a])try{l(this,this.mapper(this[a]))}catch(t){return e(t)}e()}function l(e,t){t!==void 0&&e.push(t)}function u(e){return e}function d(e,t,n){switch(e||=/\r?\n/,t||=u,n||={},arguments.length){case 1:typeof e==`function`?(t=e,e=/\r?\n/):typeof e==`object`&&!(e instanceof RegExp)&&!e[Symbol.split]&&(n=e,e=/\r?\n/);break;case 2:typeof e==`function`?(n=t,t=e,e=/\r?\n/):typeof t==`object`&&(n=t,t=u)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=s,n.flush=c,n.readableObjectMode=!0;let l=new r(n);return l[a]=``,l[o]=new i(`utf8`),l.matcher=e,l.mapper=t,l.maxLength=n.maxLength,l.skipOverflow=n.skipOverflow||!1,l.overflow=!1,l._destroy=function(e,t){this._writableState.errorEmitted=!1,t(e)},l}n.exports=d})),M4=t(((t,n)=>{var r=(E4(),e(T4)),i=(O4(),e(D4)).Stream,a=j4(),o=(J2(),e(q2)),s=5432,c=process.platform===`win32`,l=process.stderr,u=56,d=7,f=61440,p=32768;function m(e){return(e&f)==p}var h=[`host`,`port`,`database`,`user`,`password`],g=h.length,_=h[g-1];function v(){if(l instanceof i&&!0===l.writable){var e=Array.prototype.slice.call(arguments).concat(`
501
- `);l.write(o.format.apply(o,e))}}Object.defineProperty(n.exports,"isWin",{get:function(){return c},set:function(e){c=e}}),n.exports.warnTo=function(e){var t=l;return l=e,t},n.exports.getFileName=function(e){var t=e||process.env;return t.PGPASSFILE||(c?r.join(t.APPDATA||`./`,`postgresql`,`pgpass.conf`):r.join(t.HOME||`./`,`.pgpass`))},n.exports.usePgPass=function(e,t){return Object.prototype.hasOwnProperty.call(process.env,`PGPASSWORD`)?!1:c?!0:(t||=`<unkn>`,m(e.mode)?e.mode&(u|d)?(v(`WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less`,t),!1):!0:(v(`WARNING: password file "%s" is not a plain file`,t),!1))};var y=n.exports.match=function(e,t){return h.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(e[r]||s)===Number(t[r])?n&&!0:n&&(t[r]===`*`||t[r]===e[r])},!0)};n.exports.getPassword=function(e,t,n){var r,i=t.pipe(a());function o(t){var n=b(t);n&&x(n)&&y(e,n)&&(r=n[_],i.end())}var s=function(){t.destroy(),n(r)},c=function(e){t.destroy(),v(`WARNING: error on reading file: %s`,e),n(void 0)};t.on(`error`,c),i.on(`data`,o).on(`end`,s).on(`error`,c)};var b=n.exports.parseLine=function(e){if(e.length<11||e.match(/^\s+#/))return null;for(var t=``,n=``,r=0,i=0,a={},o=!1,s=function(t,n,r){var i=e.substring(n,r);Object.hasOwnProperty.call(process.env,`PGPASS_NO_DEESCAPE`)||(i=i.replace(/\\([:\\])/g,`$1`)),a[h[t]]=i},c=0;c<e.length-1;c+=1){if(t=e.charAt(c+1),n=e.charAt(c),o=r==g-1,o){s(r,i);break}c>=0&&t==`:`&&n!==`\\`&&(s(r,i,c+1),i=c+2,r+=1)}return a=Object.keys(a).length===g?a:null,a},x=n.exports.isValidEntry=function(e){for(var t={0:function(e){return e.length>0},1:function(e){return e===`*`||(e=Number(e),isFinite(e)&&e>0&&e<9007199254740992&&Math.floor(e)===e)},2:function(e){return e.length>0},3:function(e){return e.length>0},4:function(e){return e.length>0}},n=0;n<h.length;n+=1){var r=t[n];if(!r(e[h[n]]||``))return!1}return!0}})),N4=t(((t,n)=>{E4();var r=(s4(),e(o4)),i=M4();n.exports=function(e,t){var n=i.getFileName();r.stat(n,function(a,o){if(a||!i.usePgPass(o,n))return t(void 0);var s=r.createReadStream(n);i.getPassword(e,s,t)})},n.exports.warnTo=i.warnTo})),P4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=Z2(),a=(J2(),e(q2)),o=n4(),s=r4(),c=l4(),l=d4(),u=K2(),d=w4(),f=e4(),p=a.deprecate(()=>{},`Client.activeQuery is deprecated and will be removed in pg@9.0`),m=a.deprecate(()=>{},`Client.queryQueue is deprecated and will be removed in pg@9.0.`),h=a.deprecate(()=>{},`pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code.`),g=a.deprecate(()=>{},`Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0.`),_=a.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`);function v(e,t){if(typeof e==`number`)return Number.isFinite(e)?e:t;if(typeof e==`string`&&e.trim()!==``){let n=Number(e);return Number.isFinite(n)?n:t}return t}var y=class extends r{constructor(e){super(),this.connectionParameters=new c(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let t=e||{};t.Promise&&g(),this._Promise=t.Promise||global.Promise,this._types=new s(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!t.enableChannelBinding,this.scramMaxIterations=v(t.scramMaxIterations,o.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=t.connection||new d({stream:t.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||`utf8`}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!t.pipeline,this.binary=t.binary||u.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||`postgres`,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return p(),this._activeQuery}set activeQuery(e){p(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=t=>{process.nextTick(()=>{t.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._sentQueryQueue.forEach(t),this._sentQueryQueue.length=0,this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let t=Error(`Client has already been connected. You cannot reuse a client.`);process.nextTick(()=>{e(t)})}else this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(Error(`timeout expired`))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf(`/`)===0?n.connect(this.host+`/.s.PGSQL.`+this.port):n.connect(this.port,this.host),n.on(`connect`,function(){t.ssl?t.sslNegotiation!==`direct`&&n.requestSsl():n.startup(t.getStartupConf())}),n.on(`sslconnect`,function(){n.startup(t.getStartupConf())}),this._attachListeners(n),n.once(`end`,()=>{let e=this._ending?Error(`Connection terminated`):Error(`Connection terminated unexpectedly`);clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(e),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(e):this._handleErrorEvent(e):this._connectionError||this._handleErrorEvent(e)),process.nextTick(()=>{this.emit(`end`)})})}connect(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})}_attachListeners(e){e.on(`authenticationCleartextPassword`,this._handleAuthCleartextPassword.bind(this)),e.on(`authenticationMD5Password`,this._handleAuthMD5Password.bind(this)),e.on(`authenticationSASL`,this._handleAuthSASL.bind(this)),e.on(`authenticationSASLContinue`,this._handleAuthSASLContinue.bind(this)),e.on(`authenticationSASLFinal`,this._handleAuthSASLFinal.bind(this)),e.on(`backendKeyData`,this._handleBackendKeyData.bind(this)),e.on(`error`,this._handleErrorEvent.bind(this)),e.on(`errorMessage`,this._handleErrorMessage.bind(this)),e.on(`readyForQuery`,this._handleReadyForQuery.bind(this)),e.on(`notice`,this._handleNotice.bind(this)),e.on(`rowDescription`,this._handleRowDescription.bind(this)),e.on(`dataRow`,this._handleDataRow.bind(this)),e.on(`portalSuspended`,this._handlePortalSuspended.bind(this)),e.on(`emptyQuery`,this._handleEmptyQuery.bind(this)),e.on(`commandComplete`,this._handleCommandComplete.bind(this)),e.on(`parseComplete`,this._handleParseComplete.bind(this)),e.on(`copyInResponse`,this._handleCopyInResponse.bind(this)),e.on(`copyData`,this._handleCopyData.bind(this)),e.on(`notification`,this._handleNotification.bind(this))}_getPassword(e){let t=this.connection;if(typeof this.password==`function`)this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(n=>{if(n!==void 0){if(typeof n!=`string`){t.emit(`error`,TypeError(`Password must be a string`));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(e=>{t.emit(`error`,e)});else if(this.password!==null)e();else try{N4()(this.connectionParameters,t=>{t!==void 0&&(h(),this.connectionParameters.password=this.password=t),e()})}catch(e){this.emit(`error`,e)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let t=await f.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(e){this.emit(`error`,e)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=o.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}})}async _handleAuthSASLContinue(e){try{await o.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}}_handleAuthSASLFinal(e){try{o.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(e){this.connection.emit(`error`,e)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&=(this._connectionCallback(null,this),null),this.emit(`connect`));let t=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit(`error`,e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit(`error`,e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();t?(this._activeQuery=null,t.name&&delete this.connection.submittedNamedStatements[t.name],t.handleError(e,this.connection)):this._handleErrorEvent(e)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected rowDescription message from backend.`);this._handleErrorEvent(e)}else t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected dataRow message from backend.`);this._handleErrorEvent(e)}else t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected portalSuspended message from backend.`);this._handleErrorEvent(e)}else t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected emptyQuery message from backend.`);this._handleErrorEvent(e)}else t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected commandComplete message from backend.`);this._handleErrorEvent(e)}else t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let e=Error(`Received unexpected parseComplete message from backend.`);this._handleErrorEvent(e)}else e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyInResponse message from backend.`);this._handleErrorEvent(e)}else t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyData message from backend.`);this._handleErrorEvent(e)}else t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit(`notification`,e)}_handleNotice(e){this.emit(`notice`,e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=``+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){let t=this.connection;this.host&&this.host.indexOf(`/`)===0?t.connect(this.host+`/.s.PGSQL.`+this.port):t.connect(this.port,this.host),t.on(`connect`,function(){t.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(t)===-1?e._sentQueryQueue.indexOf(t)!==-1&&(t.callback=()=>{}):e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return i.escapeIdentifier(e)}escapeLiteral(e){return i.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline)this._pulsePipelinedQueryQueue();else if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit(`drain`))}}_pulsePipelinedQueryQueue(){if(this._connected&&this._queryable){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let t=e.submit(this.connection);t?process.nextTick(()=>{e.handleError(t,this.connection)}):this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit(`drain`)}}query(e,t,n){let r,i;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)i=r=e,r.callback||(typeof t==`function`?r.callback=t:n&&(r.callback=n));else if(r=new l(e,t,n),!r.callback)i=new this._Promise((e,t)=>{r.callback=(n,r)=>n?t(n):e(r)}).catch(e=>{throw Error.captureStackTrace(e),e});else if(typeof r.callback!=`function`)throw TypeError(`callback is not a function`);let a=e.query_timeout||this.connectionParameters.query_timeout;if(a){let e=r.callback||(()=>{}),t=setTimeout(()=>{let t=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(t,this.connection)}),e(t),r.callback=()=>{};let n=this._queryQueue.indexOf(r);if(n>-1)this._queryQueue.splice(n,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},a);r.callback=(n,r)=>{clearTimeout(t),e(n,r)}}if(this.binary&&!r.binary&&(r.binary=!0),r._result&&!r._result._types&&(r._result._types=this._types),this.pipeline){let t=typeof e.submit==`function`&&!(r instanceof l)?`Custom query classes such as pg-cursor and pg-query-stream are`:r.rows?"The `rows` option is":null;if(t)return process.nextTick(()=>{r.handleError(Error(`${t} not supported in pipeline mode`),this.connection)}),i}return this._queryable?this._ending?(process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`),this.connection)}),i):(this._queryQueue.length>0&&!this.pipeline&&_(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended){if(e){e();return}return this._Promise.resolve()}if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once(`drain`,()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once(`end`,e);else return new this._Promise(e=>{this.connection.once(`end`,e)})}get queryQueue(){return m(),this._queryQueue}};y.Query=l,n.exports=y})),F4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=function(){},a=(e,t)=>{let n=e.findIndex(t);return n===-1?void 0:e.splice(n,1)[0]},o=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},s=class{constructor(e){this.callback=e}};function c(){throw Error(`Release called on client which has already been released to the pool.`)}function l(e,t){if(t)return{callback:t,result:void 0};let n,r;return{callback:function(e,t){e?n(e):r(t)},result:new e(function(e,t){r=e,n=t}).catch(e=>{throw Error.captureStackTrace(e),e})}}function u(e,t){return function n(r){r.client=t,t.removeListener(`error`,n),t.on(`error`,()=>{e.log(`additional client error after disconnection due to error`,r)}),e._remove(t),e.emit(`error`,r,t)}}n.exports=class extends r{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&`password`in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||t||H4().Client,this.Promise=this.options.Promise||global.Promise,this.options.idleTimeoutMillis===void 0&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let t=this.Promise;return typeof t.try==`function`?t.try(e):new t(t=>t(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log(`pulse queue`),this.ended){this.log(`pulse queue ended`);return}if(this.ending){this.log(`pulse queue on ending`),this._idle.length&&this._idle.slice().map(e=>{this._remove(e.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log(`no queued requests`);return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let r=t.idleListener;return this._acquireClient(n,e,r,!1)}if(!this._isFull())return this.newClient(e);throw Error(`unexpected condition`)}_remove(e,t){let n=a(this._idle,t=>t.client===e);n!==void 0&&clearTimeout(n.timeoutId),this._clients=this._clients.filter(t=>t!==e);let r=this;e.end(()=>{r.emit(`remove`,e),typeof t==`function`&&t()})}connect(e){if(this.ending){let t=Error(`Cannot use a pool after calling end on the pool`);return e?e(t):this.Promise.reject(t)}let t=l(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new s(t.callback)),n;let e=(e,n,r)=>{clearTimeout(i),t.callback(e,n,r)},r=new s(e),i=setTimeout(()=>{a(this._pendingQueue,t=>t.callback===e),r.timedOut=!0,t.callback(Error(`timeout exceeded when trying to connect`))},this.options.connectionTimeoutMillis);return i.unref&&i.unref(),this._pendingQueue.push(r),n}return this.newClient(new s(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=u(this,t);this.log(`checking client timeout`);let r,a=!1;this.options.connectionTimeoutMillis&&(r=setTimeout(()=>{t.connection?(this.log(`ending client due to timeout`),a=!0,t.connection.stream.destroy()):t.isConnected()||(this.log(`ending client due to timeout`),a=!0,t.end())},this.options.connectionTimeoutMillis)),this.log(`connecting new client`),t.connect(o=>{if(r&&clearTimeout(r),t.on(`error`,n),o)this.log(`client failed to connect`,o),this._clients=this._clients.filter(e=>e!==t),a&&(o=Error(`Connection terminated due to connection timeout`,{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,i);else{if(this.log(`new client connected`),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},n=>{this._clients=this._clients.filter(e=>e!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(n,void 0,i)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,n){if(this.options.maxLifetimeSeconds!==0){let t=setTimeout(()=>{this.log(`ending client due to expired lifetime`),this._expired.add(e),this._idle.findIndex(t=>t.client===e)!==-1&&this._acquireClient(e,new s((e,t,n)=>n()),n,!1)},this.options.maxLifetimeSeconds*1e3);t.unref(),e.once(`end`,()=>clearTimeout(t))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,r){r&&this.emit(`connect`,e),this.emit(`acquire`,e),e.release=this._releaseOnce(e,n),e.removeListener(`error`,n),t.timedOut?r&&this.options.verify?this.options.verify(e,e.release):e.release():r&&this.options.verify?this.options.verify(e,n=>{if(n)return e.release(n),t.callback(n,void 0,i);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return r=>{n&&c(),n=!0,this._release(e,t,r)}}_release(e,t,n){if(e.on(`error`,t),e._poolUseCount=(e._poolUseCount||0)+1,this.emit(`release`,n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log(`remove expended client`),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log(`remove expired client`),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let r;this.options.idleTimeoutMillis&&this._isAboveMin()&&(r=setTimeout(()=>{this._isAboveMin()&&(this.log(`remove idle client`),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&r.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new o(e,t,r)),this._pulseQueue()}query(e,t,n){if(typeof e==`function`){let t=l(this.Promise,e);return setImmediate(function(){return t.callback(Error(`Passing a function as the first parameter to pool.query is not supported`))}),t.result}typeof t==`function`&&(n=t,t=void 0);let r=l(this.Promise,n);return n=r.callback,this.connect((r,i)=>{if(r)return n(r);let a=!1,o=e=>{a||(a=!0,i.release(e),n(e))};i.once(`error`,o),this.log(`dispatching query`);try{i.query(e,t,(e,t)=>{if(this.log(`query dispatched`),i.removeListener(`error`,o),!a)return a=!0,i.release(e),e?n(e):n(void 0,t)})}catch(e){return i.release(e),n(e)}}),r.result}end(e){if(this.log(`ending`),this.ending){let t=Error(`Called end on pool more than once`);return e?e(t):this.Promise.reject(t)}this.ending=!0;let t=l(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+ +!!this._expired.has(t),0)}get totalCount(){return this._clients.length}}})),I4=c({default:()=>L4}),L4,R4=r(()=>{throw L4={},Error(`Could not resolve "pg-native" imported by "pg". Is it installed?`)}),z4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=(J2(),e(q2)),a=Z2(),o=n.exports=function(e,t,n){r.call(this),e=a.normalizeQueryConfig(e,t,n),this.text=e.text,this.values=e.values,this.name=e.name,this.queryMode=e.queryMode,this.callback=e.callback,this.state=`new`,this._arrayMode=e.rowMode===`array`,this._emitRowEvents=!1,this.on(`newListener`,function(e){e===`row`&&(this._emitRowEvents=!0)}.bind(this))};i.inherits(o,r);var s={sqlState:`code`,statementPosition:`position`,messagePrimary:`message`,messageDetail:`detail`,messageHint:`hint`,context:`where`,schemaName:`schema`,tableName:`table`,columnName:`column`,dataTypeName:`dataType`,constraintName:`constraint`,sourceFile:`file`,sourceLine:`line`,sourceFunction:`routine`};o.prototype.handleError=function(e){let t=this.native&&this.native.pq.resultErrorFields();if(t)for(let n in t){let r=s[n]||n;e[r]=t[n]}this.callback?this.callback(e):this.emit(`error`,e),this.state=`error`},o.prototype.then=function(e,t){return this._getPromise().then(e,t)},o.prototype.catch=function(e){return this._getPromise().catch(e)},o.prototype._getPromise=function(){return this._promise||=new Promise(function(e,t){this._once(`end`,e),this._once(`error`,t)}.bind(this)),this._promise},o.prototype.submit=function(e){this.state=`running`;let t=this;this.native=e.native,e.native.arrayMode=this._arrayMode;let n=function(n,r,i){if(e.native.arrayMode=!1,setImmediate(function(){t.emit(`_done`)}),n)return t.handleError(n);t._emitRowEvents&&(i.length>1?r.forEach((e,n)=>{e.forEach(e=>{t.emit(`row`,e,i[n])})}):r.forEach(function(e){t.emit(`row`,e,i)})),t.state=`end`,t.emit(`end`,i),t.callback&&t.callback(null,i)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error(`Warning! Postgres only supports 63 characters for query names.`),console.error(`You supplied %s (%s)`,this.name,this.name.length),console.error(`This can cause conflicts and silent errors executing queries`));let r=(this.values||[]).map(a.prepareValue);if(e.namedQueries[this.name]!==void 0){if(this.text&&e.namedQueries[this.name]!==this.text){let e=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(e)}return e.native.execute(this.name,r,n)}return e.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(e.namedQueries[t.name]=t.text,t.native.execute(t.name,r,n))})}if(this.values){if(!Array.isArray(this.values))return n(Error(`Query values must be an array`));let t=this.values.map(a.prepareValue);e.native.query(this.text,t,n)}else this.queryMode===`extended`?e.native.query(this.text,[],n):e.native.query(this.text,n)}})),B4=t(((t,n)=>{var r=(J2(),e(q2)),i;try{i=(R4(),e(I4))}catch(e){throw e}var a=r4(),o=(P2(),e(N2)).EventEmitter,s=(J2(),e(q2)),c=l4(),l=z4(),u=r.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`),d=n.exports=function(e){o.call(this),e||={},this._Promise=e.Promise||global.Promise,this._types=new a(e.types),this.native=new i({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!e.pipeline,this._pipelineInFlight=!1;let t=this.connectionParameters=new c(e);e.nativeConnectionString&&(t.nativeConnectionString=e.nativeConnectionString),this.user=t.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:t.password}),this.database=t.database,this.host=t.host,this.port=t.port,this.namedQueries={}};d.Query=l,s.inherits(d,o),d.prototype._errorAllQueries=function(e){let t=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(e)})};this._hasActiveQuery()&&(t(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0},d.prototype._connect=function(e){let t=this;this._connecting?process.nextTick(()=>e(Error(`Client has already been connected. You cannot reuse a client.`))):(this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(t.connectionParameters.nativeConnectionString&&(r=t.connectionParameters.nativeConnectionString),n)return e(n);t.native.connect(r,function(n){if(n)return t.native.end(),e(n);t._connected=!0,t.native.on(`error`,function(e){t._queryable=!1,t._errorAllQueries(e),t.emit(`error`,e)}),t.native.on(`notification`,function(e){t.emit(`notification`,{channel:e.relname,payload:e.extra})}),t.emit(`connect`),t._pulseQueryQueue(!0),e(null,this)})}))},d.prototype.connect=function(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})},d.prototype.query=function(e,t,n){let r,i,a,o,s;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)a=e.query_timeout||this.connectionParameters.query_timeout,i=r=e,typeof t==`function`&&(e.callback=t);else if(a=e.query_timeout||this.connectionParameters.query_timeout,r=new l(e,t,n),!r.callback){let e,t;i=new this._Promise((n,r)=>{e=n,t=r}).catch(e=>{throw Error.captureStackTrace(e),e}),r.callback=(n,r)=>n?t(n):e(r)}return a&&(s=r.callback||(()=>{}),o=setTimeout(()=>{let e=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(e,this.connection)}),s(e),r.callback=()=>{};let t=this._queryQueue.indexOf(r);t>-1&&this._queryQueue.splice(t,1),this._pulseQueryQueue()},a),r.callback=(e,t)=>{clearTimeout(o),s(e,t)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`))}),i):(this._queryQueue.length>0&&!this.pipeline&&u(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`))}),i)},d.prototype.end=function(e){let t=this;this._ending=!0,this._connecting&&!this._connected&&this.once(`connect`,()=>{this.end(()=>{})});let n;e||(n=new this._Promise(function(t,n){e=e=>e?n(e):t()}));let r=function(){t.native.end(function(){t._connected=!1,t._errorAllQueries(Error(`Connection terminated`)),process.nextTick(()=>{t.emit(`end`),e&&e()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once(`drain`,r):r(),n},d.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!==`error`&&this._activeQuery.state!==`end`},d.prototype._pulseQueryQueue=function(e){if(!this._connected)return;if(this.pipeline&&!e)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let t=this._queryQueue.shift();if(!t){e||this.emit(`drain`);return}this._activeQuery=t,t.submit(this);let n=this;t.once(`_done`,function(){n._pulseQueryQueue()})},d.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit(`drain`);return}this._pipelineInFlight=!0;let e=this,t=[],n=[],r=Z2();for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0,n.push(e);let i=e.values?e.values.map(r.prepareValue):null,a={text:e.text,name:e.name,arrayMode:e._arrayMode};i&&(a.values=i),e.name&&this.namedQueries[e.name]&&(a._alreadyPrepared=!0),t.push(a)}this.native.pipeline(t,function(t,r){if(e._pipelineInFlight=!1,t){e._connected=!1,e._queryable=!1;for(let r=0;r<n.length;r++){let i=n[r];i.native=e.native,i.handleError(t)}e._errorAllQueries(t),e.emit(`error`,t),e.emit(`end`)}else{for(let t=0;t<n.length;t++){let i=n[t],a=r[t];i.native=e.native,a.err?i.handleError(a.err):(i.name&&(e.namedQueries[i.name]=i.text),i.state=`end`,i.emit(`end`,a.result),i.callback&&i.callback(null,a.result)),setImmediate(function(){i.emit(`_done`)})}e._pulsePipelinedQueryQueue()}})},d.prototype.cancel=function(e){this._activeQuery===e?this.native.cancel(function(){}):this._queryQueue.indexOf(e)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(e),1)},d.prototype.ref=function(){},d.prototype.unref=function(){},d.prototype.setTypeParser=function(e,t,n){return this._types.setTypeParser(e,t,n)},d.prototype.getTypeParser=function(e,t){return this._types.getTypeParser(e,t)},d.prototype.isConnected=function(){return this._connected},d.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}})),V4=t(((e,t)=>{t.exports=B4()})),H4=t(((e,t)=>{var n=P4(),r=K2(),i=w4(),a=u4(),o=Z2(),s=F4(),c=r4(),{DatabaseError:l}=_4(),{escapeIdentifier:u,escapeLiteral:d}=Z2(),f=e=>class extends s{constructor(t){super(t,e)}},p=function(e){this.defaults=r,this.Client=e,this.Query=this.Client.Query,this.Pool=f(this.Client),this._pools=[],this.Connection=i,this.types=G2(),this.DatabaseError=l,this.TypeOverrides=c,this.escapeIdentifier=u,this.escapeLiteral=d,this.Result=a,this.utils=o},m=n,h=!1;try{h=!!process.env.NODE_PG_FORCE_NATIVE}catch{}h&&(m=V4()),t.exports=new p(m),Object.defineProperty(t.exports,"native",{configurable:!0,enumerable:!1,get(){let e=null;try{e=new p(V4())}catch(e){if(e.code!==`MODULE_NOT_FOUND`)throw e}return Object.defineProperty(t.exports,"native",{value:e}),e}})})),U4=s(H4(),1);U4.default.Client,U4.default.Pool,U4.default.Connection,U4.default.types,U4.default.Query,U4.default.DatabaseError,U4.default.escapeIdentifier,U4.default.escapeLiteral,U4.default.Result,U4.default.TypeOverrides,U4.default.defaults;var W4=U4.default,{Pool:G4,types:K4}=W4,q4=class extends gP{constructor(e,t,n,r,i,a,o,s,c,l,u){super({sql:t,params:n},i,a,o),this.client=e,this.queryString=t,this.params=n,this.logger=r,this.fields=s,this._isResponseInArrayMode=l,this.customResultMapper=u,this.rawQueryConfig={name:c,text:t,types:{getTypeParser:(e,t)=>e===K4.builtins.TIMESTAMPTZ||e===K4.builtins.TIMESTAMP||e===K4.builtins.DATE||e===K4.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:K4.getTypeParser(e,t)}},this.queryConfig={name:c,text:t,rowMode:`array`,types:{getTypeParser:(e,t)=>e===K4.builtins.TIMESTAMPTZ||e===K4.builtins.TIMESTAMP||e===K4.builtins.DATE||e===K4.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:K4.getTypeParser(e,t)}}}static[W]=`NodePgPreparedQuery`;rawQueryConfig;queryConfig;async execute(e={}){return Mk.startActiveSpan(`drizzle.execute`,async()=>{let t=eA(this.params,e);this.logger.logQuery(this.rawQueryConfig.text,t);let{fields:n,rawQueryConfig:r,client:i,queryConfig:a,joinsNotNullableMap:o,customResultMapper:s}=this;if(!n&&!s)return Mk.startActiveSpan(`drizzle.driver.execute`,async e=>(e?.setAttributes({"drizzle.query.name":r.name,"drizzle.query.text":r.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(r.text,t,async()=>await i.query(r,t))));let c=await Mk.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":a.name,"drizzle.query.text":a.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(a.text,t,async()=>await i.query(a,t))));return Mk.startActiveSpan(`drizzle.mapResponse`,()=>s?s(c.rows):c.rows.map(e=>gA(n,e,o)))})}all(e={}){return Mk.startActiveSpan(`drizzle.execute`,()=>{let t=eA(this.params,e);return this.logger.logQuery(this.rawQueryConfig.text,t),Mk.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":this.rawQueryConfig.name,"drizzle.query.text":this.rawQueryConfig.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(this.rawQueryConfig.text,t,async()=>this.client.query(this.rawQueryConfig,t)).then(e=>e.rows)))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},J4=class e extends _P{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new mA,this.cache=r.cache??new mP}static[W]=`NodePgSession`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new q4(this.client,e.sql,e.params,this.logger,this.cache,a,o,t,n,r,i)}async transaction(t,n){let r=this.client instanceof G4||Object.getPrototypeOf(this.client).constructor.name.includes(`Pool`),i=r?new e(await this.client.connect(),this.dialect,this.schema,this.options):this,a=new Y4(this.dialect,i,this.schema);await a.execute(q`begin${n?q` ${a.getTransactionConfigSQL(n)}`:void 0}`);try{let e=await t(a);return await a.execute(q`commit`),e}catch(e){throw await a.execute(q`rollback`),e}finally{r&&i.client.release()}}async count(e){let t=await this.execute(e);return Number(t.rows[0].count)}},Y4=class e extends vP{static[W]=`NodePgTransaction`;async transaction(t){let n=`sp${this.nestedIndex+1}`,r=new e(this.dialect,this.session,this.schema,this.nestedIndex+1);await r.execute(q.raw(`savepoint ${n}`));try{let e=await t(r);return await r.execute(q.raw(`release savepoint ${n}`)),e}catch(e){throw await r.execute(q.raw(`rollback to savepoint ${n}`)),e}}},X4=class{constructor(e,t,n={}){this.client=e,this.dialect=t,this.options=n}static[W]=`NodePgDriver`;createSession(e){return new J4(this.client,this.dialect,e,{logger:this.options.logger,cache:this.options.cache})}},Z4=class extends fP{static[W]=`NodePgDatabase`};function Q4(e,t={}){let n=new VN({casing:t.casing}),r;t.logger===!0?r=new pA:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=yee(t.schema,Cee);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new Z4(n,new X4(e,n,{logger:r,cache:t.cache}).createSession(i),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}function $4(...e){if(typeof e[0]==`string`)return Q4(new W4.Pool({connectionString:e[0]}),e[1]);if(wA(e[0])){let{connection:t,client:n,...r}=e[0];return Q4(n||(typeof t==`string`?new W4.Pool({connectionString:t}):new W4.Pool(t)),r)}return Q4(e[0],e[1])}(e=>{function t(e){return Q4({},e)}e.mock=t})($4||={});var e3={};function t3(){let e=by(`DATABASE_URL`);if(e)return e;let t=by(`HYPERDRIVE`);if(t?.connectionString)return t.connectionString;throw Error(`db: PostgreSQL is not configured. Add DATABASE_URL to .env for local dev, or configure Hyperdrive for production.`)}function n3(){return $4({connection:{connectionString:t3(),max:1,idleTimeoutMillis:1e3}}).$client}function r3(){return hy(e3,n3,n3)}function i3(e,t={}){let n=new Map,r;return new Proxy({},{get(n,r){if(Object.hasOwn(t,r))return t[r];let i=e(),a=Reflect.get(i,r);return typeof a==`function`?a.bind(i):a},has(r,i){return Object.hasOwn(t,i)?!0:(n.has(i)||n.set(i,Reflect.has(e(),i)),n.get(i))},getPrototypeOf:()=>r??=Object.getPrototypeOf(e())})}var a3,o3=new Proxy({},{get(e,t){hy(e3,n3,()=>void 0),a3??=$4({client:i3(r3),schema:VP});let n=Reflect.get(a3,t);return typeof n==`function`?n.bind(a3):n}}),$=o3;async function s3(e,t){let{account:n,assertion:r,client:i,credential:a,userId:o}=t,s=await Z(e,BB($,{account:n,authenticatorData:r.metadata.authenticatorData,clientId:CV,clientDataJSON:r.metadata.clientDataJSON,credentialId:r.id,expiry:Math.floor(Date.now()/1e3)+300,signature:r.signature,userId:o,verify:e=>e.account===n.toLowerCase()&&e.clientId===`tempo-id:account-config`&&e.credential.id===a.id&&e.credential.publicKey===a.publicKey&&r.id===a.id&&WB(r,{challenge:e.digest,origin:new URL(U.URL).origin,publicKey:a.publicKey,rpId:a.rpId})}),`Passkey.takeSignature`),c=s?await Z(e,BV($,{digest:s.digest,userId:o}),`ConfigurableAccount.takePending`):void 0;if(!s||!c)return new cB;let l=t.link?await Z(e,t.link(),`Configure.link`):void 0;if(l)return l;let u=await _3(e,()=>RV({assertion:r,client:i,current:c.current,digest:s.digest,publicKey:a.publicKey,target:c.target,transaction:c.transaction}));return await Z(e,IV($,{config:u,userId:o}),`db.accountConfig.save`),u}(function(e){e.errors=[...OI.errors,vV,cB,y2]})(s3||={});async function c3(e,t){let{account:n,clientId:r,userId:i}=t,a=d3({chain:t.chain});if(a instanceof vI)return a;let o=await Z(e,l3(e,{clientId:r}),`Configure.reach`),s=await Z(e,C2(e,{chainId:a.chainId,db:$,env:U,realms:o,userId:i}),`TempoAccount.held`),c=s.find(e=>Yz(e).toLowerCase()===n.toLowerCase());return c?{chain:a,client:kV({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:a.chainId}),chain:a}),current:PV(c),owner:c,owners:s,realms:o}:new y2({account:n})}(function(e){e.errors=[...C2.errors,yV,y2]})(c3||={});async function l3(e,t){let n=await Z(e,oW(e,{clientId:t.clientId,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`);return await Z(e,uW(e,{db:$,origin:U.URL,realms:n}),`Realm.withDefaults`)}async function u3(e,t){let{account:n,client:r,credential:i,current:a,target:o,userId:s}=t,c=await _3(e,()=>FV({client:r,current:a,publicKey:i.publicKey,target:o}));return await Z(e,MB($,{account:n,clientId:CV,credential:i,digest:c.digest,userId:s}),`Passkey.requestSignature`),await Z(e,zV($,{current:a,digest:c.digest,target:o,transaction:c.transaction,userId:s}),`ConfigurableAccount.storePending`),eC({challenge:c.digest,credentialId:[i.id],rpId:i.rpId,userVerification:`required`}).options}function d3(e){let t=DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS});return(e.chain===void 0?t[0]:t.find(t=>t.name===e.chain))||new yV({chain:e.chain,configured:t.map(e=>e.name)})}async function f3(e,t){let{email:n,realms:r}=t;if(!r.some(e=>e.id==="default")||!(DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).length>0)||!e.env.WALLET)return!1;let i=await Z(e,j2(e.env.WALLET,{email:n}),`Wallet.credentials`).catch(t=>{Zt(e,{error:t,message:`The wallet service failed a passkey lookup by email, so no cloud wallet was created.`})});return!i||(await v3(e,{listed:i})).length>0}async function p3(e,t){return e.env.WALLET?await v3(e,{listed:await Z(e,j2(e.env.WALLET,{email:t.email}),`Wallet.credentials`).catch(t=>(Zt(e,{error:t,message:`The wallet service failed a passkey lookup by email.`}),[]))}):[]}async function m3(e,t){let{clientId:n,credentialId:r,email:i,userId:a}=t;if(t.account){let r=await Z(e,c3(e,{account:t.account,chain:t.chain,clientId:n,userId:a}),`Configure.find`);if(r instanceof vI)return r;let{owner:i}=r,o=Yz(i);return r.current?new xV({account:o,owner:`configurable`}):i.credential?{account:o,chain:r.chain,client:r.client,credential:i.credential,link:void 0,owners:r.owners,realm:i.realm}:new bV({account:o,reason:`cloud`})}let o=d3({chain:t.chain});if(o instanceof vI)return o;let s=await Z(e,l3(e,{clientId:n}),`Configure.reach`),c=s.find(e=>e.id===rW),l=c?OB([c],{origin:U.URL}):void 0;if(!c||!l)return new oB({clientId:n});let u=r,d=new y2({account:u,field:`credentialId`}),f=e.env.WALLET?await Z(e,A2(e.env.WALLET,{id:u}),`Wallet.credential`).catch(t=>{throw Zt(e,{error:t,message:`The wallet service failed a passkey lookup.`}),t instanceof Error&&OI(t)||new TI}):void 0;if(!f||f.email?.toLowerCase()!==i.toLowerCase())return d;let p=await Z(e,C2(e,{chainId:o.chainId,db:$,env:U,realms:s,userId:a}),`TempoAccount.held`),m=L(f.address);return p.some(e=>e.configurable&&Se(Xz(e),m))?new xV({account:m,owner:`configurable`}):{account:m,chain:o,client:kV({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:o.chainId}),chain:o}),credential:{id:u,publicKey:f.publicKey,rpId:l.rpId},link:async()=>await Z(e,xB($,{credential:f,id:u,rpId:l.rpId,userId:a}),`Passkey.link`)===a?void 0:d,owners:p,realm:c}}(function(e){e.errors=[...OI.errors,...c3.errors,bV,xV,oB]})(m3||={});async function h3(e,t){let{client:n,current:r,signing:i,target:a,userId:o}=t,s=await Z(e,i.signer(e,{auth:e.var.auth}),`Owner.signer`),c=await _3(e,()=>LV({account:s,client:n,current:r,target:a}));return await Z(e,IV($,{config:c,userId:o}),`db.accountConfig.save`),c}(function(e){e.errors=[...OI.errors,vV]})(h3||={});function g3(e,t){return t.current?e.configurable.owner:e}async function _3(e,t){try{return await Z(e,t(),`ConfigurableAccount.send`)}catch(t){if(t instanceof vI)throw t;if(t instanceof Error){let e=OI(t);if(e)throw e}throw Zt(e,{error:t,message:`The chain did not install the account configuration.`}),new TI}}(function(e){e.errors=[...OI.errors,vV]})(_3||={});async function v3(e,t){let{listed:n}=t;if(n.length===0)return[];let r=await Z(e,$.select({id:KP.id}).from(KP).where($M(KP.id,n.map(e=>e.credentialId))),`db.keys.linked`);return n.filter(e=>!r.some(t=>t.id===e.credentialId))}var y3=`__Host-tempo-id-account`,b3=3456e4,x3;(function(e){e.value=z({apps:Wn(R(),R()),session:R()})})(x3||={});async function S3(e,t){return(await Z(e,O3(e,t),`AccountStep.held`)).map(O2)}(function(e){e.errors=C2.errors})(S3||={});function C3(){return ce(y3,``,{httpOnly:!0,maxAge:0,path:`/`,sameSite:`Lax`,secure:!0})}async function w3(e,t){let n=await Z(e,P3(e,t),`AccountStep.realms`),r={chainId:t.chainId,db:$,env:U,realms:n,userId:t.userId},[i]=await Z(e,$.select({email:RP.email}).from(RP).where(Y(RP.id,t.userId)),`db.user.get`);return i&&await Z(e,f3(e,{email:i.email,realms:n}),`Configure.awaitsUpgrade`)?await Z(e,C2(e,r),`TempoAccount.held`):await Z(e,S2(e,r),`TempoAccount.create`)}(function(e){e.errors=S2.errors})(w3||={});async function T3(e,t){let n=(await Z(e,P3(e,t),`AccountStep.realms`))[0];return n!==void 0&&(n.privy!==void 0||n.secp256k1)}async function E3(e,t){if(!(await Z(e,e.env.ACCOUNT_LIMIT.limit({key:t.userId}),`ratelimit.limit`)).success)return!1;let n=await Z(e,S3(e,t),`AccountStep.accounts`).catch(n=>(Zt(e,{error:n,fields:{clientId:t.clientId},message:`The account step skipped an authorization whose accounts failed to load.`}),[]));return n.length<=1?!1:!D3(n,j3(t))}function D3(e,t){if(t)return e.find(e=>e.address.toLowerCase()===t.toLowerCase())}async function O3(e,t){let n=await Z(e,P3(e,t),`AccountStep.realms`);return await Z(e,C2(e,{chainId:t.chainId,db:$,env:U,realms:n,userId:t.userId}),`TempoAccount.held`)}(function(e){e.errors=C2.errors})(O3||={});function k3(e,t){let n=D3(e,j3(t));return n?[n,...e.filter(e=>e!==n)]:e}function A3(e){let t=(e.cookie??``).split(`;`).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`__Host-tempo-id-account=`)),n=M3(e.clientId),{[n]:r,...i}=N3(e),a=JSON.stringify({apps:{...Object.fromEntries(Object.entries(i).slice(-15)),[n]:e.account},session:e.sessionId});return{header:[...t,`${y3}=${encodeURIComponent(a)}`].join(`; `),setCookie:ce(y3,a,{httpOnly:!0,maxAge:b3,path:`/`,sameSite:`Lax`,secure:!0})}}function j3(e){let t=N3(e),n=M3(e.clientId);return Object.hasOwn(t,n)?t[n]:void 0}function M3(e){if(!ZF(e))return e;let t=Pt(pt(e));return`cimd:${Lt(t.slice(0,16),{pad:!1,url:!0})}`}function N3(e){let t=ue(e.cookie??``,y3)[y3];if(!t)return{};try{let n=x3.value.safeParse(JSON.parse(t));return!n.success||n.data.session!==e.sessionId?{}:n.data.apps}catch{return{}}}async function P3(e,t){let n=await Z(e,hV(e,()=>aW($,{clientId:t.clientId}),[`realm.forApp`,t.clientId]),`Realm.forApp`);return await Z(e,uW(e,{db:$,origin:U.URL,realms:n}),`Realm.withDefaults`)}var F3=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}},I3=({limitLength:e=255,headerName:t=`X-Request-Id`,generator:n=()=>crypto.randomUUID()}={})=>async function(r,i){let a=t?r.req.header(t):void 0;(!a||a.length>e||/[^\w\-=]/.test(a))&&(a=n(r)),r.set(`requestId`,a),t&&r.header(t,a),await i()},L3=`X-Request-Id`;function R3(){let e=I3({generator:H3,headerName:``});return QB(async(t,n)=>{await e(t,n);let r=t.var.requestId,i=t.res,a=V3(i)?await Z(t,W3(i),`response.json`):void 0;a&&t.set(`refusal`,z3(t,{body:a,id:r})),t.header(L3,r)})}function z3(e,t){let n=e.res;return e.res=new Response(JSON.stringify({...t.body,request_id:t.id}),{headers:n.headers,status:n.status,statusText:n.statusText}),e.header(`content-length`,void 0),{error:B3(t.body.error),reason:B3(t.body.reason)}}function B3(e){return typeof e==`string`&&/^[a-z_]{1,64}$/.test(e)?e:void 0}function V3(e){return e.status>=400&&!!e.headers.get(`content-type`)?.startsWith(`application/json`)}function H3(e){let t=e.req.header(`cf-ray`);return t&&/^[\da-f]{16}(?:-[A-Z]{3})?$/.test(t)?t:crypto.randomUUID()}function U3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function W3(e){let t=await e.clone().json().catch(()=>void 0);return U3(t)&&typeof t.error==`string`?t:void 0}var G3;(function(e){e.refusal=Xn([`foreign_account`,`no_account`,`passkey`,`unavailable`,`upgrade`]).meta({description:"Why approval cannot sign the key: the key names an account that is not the user's (`foreign_account`), the user holds no account and none can be created (`no_account`), a passkey that this page cannot use owns the account (`passkey`), the accounts could not be read (`unavailable`), or the account must upgrade to a configurable account on the key's chain first (`upgrade`). Absent when approval can sign it.",examples:[`passkey`]})})(G3||={});async function K3(e,t){let{account:n,clientId:r,key:i,owner:a,userId:o}=t,s=a.credential,c=$R({account:$z(a),key:i});return await Z(e,MB($,{account:n,clientId:r,credential:s,digest:c,userId:o}),`Passkey.requestSignature`),eC({challenge:c,credentialId:s.id,rpId:s.rpId,userVerification:`required`}).options}async function q3(e,t){let{clientId:n,sessionId:r,userId:i}=t,a=t.chainId===void 0?void 0:Number(t.chainId),o=await(async()=>{if((await Z(e,e.env.ACCOUNT_LIMIT.limit({key:i}),`ratelimit.limit`)).success)try{let o=await Z(e,O3(e,{chainId:a,clientId:n,userId:i}),`AccountStep.held`);return{owners:o,signing:await Z(e,J3(e,{account:t.account,chainId:a,clientId:n,cookie:e.req.header(`cookie`),owners:o,passkey:!0,sessionId:r,userId:i}),`KeySigner.resolve`)}}catch(t){Zt(e,{error:t,fields:{clientId:n},message:`An approval page's account owners failed to load.`});return}})(),s=o?.signing,c=s instanceof fz&&await Z(e,T3(e,{clientId:n}),`AccountStep.creates`),l=s?s instanceof kR||s instanceof SV?s.response.meta?.account:s instanceof vI?t.account:s.account:t.account,u=(()=>{if(!s)return`unavailable`;if(s instanceof y2)return`foreign_account`;if(s instanceof kR)return`passkey`;if(s instanceof SV)return`upgrade`;if(s instanceof fz&&!c)return`no_account`})();return{account:l,accounts:o?o.owners.map(O2):[],refusal:u}}async function J3(e,t){let{clientId:n,cookie:r,sessionId:i,userId:a}=t,o=t.chainId===void 0?void 0:Number(t.chainId),s=t.owners??(t.create&&!t.account?await Z(e,w3(e,{chainId:o,clientId:n,userId:a}),`AccountStep.create`):await Z(e,O3(e,{chainId:o,clientId:n,userId:a}),`AccountStep.held`)),c=s.map(O2),l=t.account,u=s.find(e=>t.oneTap!==void 0&&e.credential?.id===t.oneTap),d=l?void 0:(u&&O2(u).address)??D3(c,j3({clientId:n,cookie:r,sessionId:i}))?.address;if(t.single&&!l&&!d&&c.length>1)return new fz({description:"Several Tempo Accounts: the user holds more than one account in the app's realms and chose none. Choose the account on the account step, or name it in `key_authorization.account`."});let f=l?D3(c,l)?.address:d??c[0]?.address;if(l&&!f)return new y2({account:l,field:`key_authorization.account`});let p=f?s.find(e=>O2(e).address.toLowerCase()===f.toLowerCase()):void 0;if(!f||!p)return new fz({description:t.create?"No Tempo Account: the user holds no account in the app's realms, and the app's first realm has no Privy app to create one. Authorize without `key_authorization`.":"No Tempo Account: the user holds no account in the app's realms, so no owner signs the key. Create the account with `POST /v1/account`, or authorize without `key_authorization`."});if(p.linked&&!p.configurable&&OV({chainId:o,env:U}))return new SV({account:f});let m=eB(p,{chainId:o});return!m.signer&&!(t.passkey&&X3(m))&&(t.oneTap===void 0||m!==p||m.credential?.id!==t.oneTap)?new kR({account:f}):{account:f,owner:m}}(function(e){e.errors=[...w3.errors,...O3.errors,fz,SV,kR,y2]})(J3||={});async function Y3(e,t){let{account:n,assertion:r,key:i,owner:a}=t;if(!a.signer){if(!r||!a.credential)return new kR({account:n});let o=a.credential;return await Z(e,BB($,{account:n,authenticatorData:r.metadata.authenticatorData,clientId:t.clientId,clientDataJSON:r.metadata.clientDataJSON,credentialId:r.id,expiry:i.expiry,signature:r.signature,userId:t.userId,verify:e=>e.account===n.toLowerCase()&&e.clientId===t.clientId&&e.credential.id===o.id&&e.credential.publicKey===o.publicKey&&r.id===o.id&&e.digest===$R({account:$z(a),key:i})&&WB(r,{challenge:e.digest,origin:t.origin??new URL(U.URL).origin,publicKey:o.publicKey,rpId:o.rpId})}),`Passkey.takeSignature`)?await Z(e,tz(r,{account:$z(a),key:i,publicKey:o.publicKey}),`KeyAuthorization.signWithAssertion`):new cB}return await Z(e,ez(await Z(e,a.signer(e,{auth:e.var.auth}),`Owner.signer`),{key:i}),`KeyAuthorization.sign`)}(function(e){e.errors=[kR,cB]})(Y3||={});function X3(e){return e.credential?OB([e.realm],{origin:U.URL})?.rpId===e.credential.rpId:!1}var Z3=600,Q3=`sign-in-grant-held:`,$3=3600,e6=`sign-in-grant-spent:`,t6;(function(e){e.held=z({assertion:qn().optional(),witness:Kn([`0x`,R()]).optional()})})(t6||={});async function n6(e,t){await e.insert(BP).values({expiresAt:new Date(Date.now()+Z3*1e3),id:crypto.randomUUID(),identifier:s6(t),value:JSON.stringify(t6.held.parse({assertion:t.oneTap?.assertion,witness:t.oneTap?.witness}))})}function r6(e){let t=[`client_id`,`redirect_uri`,`state`,`code_challenge`,`key_authorization`,`challenge`,`scope`].map(t=>e.get(t)??``);return dt(Pt(pt(JSON.stringify(t))))}async function i6(e,t){let n=e6+r6(t.query),r=Number(t.query.get(`exp`));return await rB(e,{expiresAt:new Date(Number.isSafeInteger(r)&&r>0?r*1e3:Date.now()+$3*1e3),identifier:n,value:`{}`})}async function a6(e,t){let[n]=await e.select({id:BP.id}).from(BP).where(KM(Y(BP.identifier,e6+r6(t.query)),YM(BP.expiresAt,new Date))).limit(1);return n!==void 0}async function o6(e,t){let[n]=await e.delete(BP).where(KM(Y(BP.identifier,s6(t)),YM(BP.expiresAt,new Date))).returning({value:BP.value});if(n)return t6.held.parse(JSON.parse(n.value))}function s6(e){return`${Q3}${r6(e.query)}:${e.sessionId}`}async function c6(e,t){let{clientId:n,codeChallenge:r,expiry:i,key:a,userId:o}=t,s={account:a.account,expiresAt:new Date(Math.min(Date.now()+6e5,i*1e3)),keyAuthorization:a.keyAuthorization,userId:o};await e.insert(qP).values({...s,clientId:n,codeChallenge:r}).onConflictDoUpdate({set:{...s,createdAt:new Date},setWhere:Y(qP.userId,o),target:[qP.clientId,qP.codeChallenge]})}async function l6(e,t){let{clientId:n,codeChallenge:r,userId:i}=t,[a]=await e.delete(qP).where(KM(Y(qP.clientId,n),Y(qP.codeChallenge,r),YM(qP.expiresAt,new Date),Y(qP.userId,i))).returning({account:qP.account,keyAuthorization:qP.keyAuthorization});if(a)return{account:a.account,keyAuthorization:a.keyAuthorization}}var u6=z({url:R().min(1)});async function d6(e,t){let{headers:n,oauthQuery:r,session:i}=t,a=await Z(e,e.var.auth.$context,`auth.context`);if(!await Z(e,ni(r,a.secret),`auth.verifyOAuthQueryParams`))return new KB;let o=new URLSearchParams(r);p6(o);let s=f6(o)?await Z(e,m6(e,{account:t.account,assertion:t.assertion,oneTap:t.oneTap,query:o,session:i,single:t.single}),`Consent.approveKey`):void 0;if(s instanceof vI)return s;if(s&&`options`in s)return{options:s.options};let c=await Z(e,e.var.auth.api.oauth2Consent({asResponse:!1,body:{accept:!0,oauth_query:r},headers:n,request:new Request(e.req.url,{headers:n,method:`POST`})}),`auth.oauth2Consent`).catch(e=>{if(Hr(e)&&e.body?.error===`invalid_signature`)return new KB;throw e});if(c instanceof vI)return c;let l=u6.parse(c).url,u=URL.parse(l)?.searchParams.get(`code`);return s&&u&&await Z(e,c6($,{clientId:s.clientId,codeChallenge:s.codeChallenge,expiry:s.expiry,key:{account:s.account,keyAuthorization:s.signed},userId:i.user.id}),`PendingKey.put`),{redirect:l}}(function(e){e.errors=[...hz.errors,...J3.errors,...Y3.errors,KB,fz,kR,cB,lz]})(d6||={});function f6(e){return e.has(`key_authorization`)||e.has(`challenge`)}function p6(e){let t=URL.parse(e.get(`redirect_uri`)??``);if(!t||t.protocol!==`http:`&&t.protocol!==`https:`&&!ji(t))throw Error(`The app's redirect URI uses a refused scheme.`)}async function m6(e,t){let{oneTap:n,query:r,session:i}=t,a=gz(r);if(!a||a instanceof vI)return a;let o=r.get(`client_id`),s=r.get(`code_challenge`),c=await Z(e,GF($,{clientId:o}).catch(e=>{if(!(e instanceof RF))throw e}),`Apps.get`),l=hz({app:c,clientId:o,codeChallenge:s,key:a,query:r});if(l)return l;let u=await Z(e,J3(e,{account:a.account??t.account,chainId:a.chainId,clientId:o,cookie:e.req.header(`cookie`),create:!0,passkey:!0,sessionId:i.session.id,single:t.single,userId:i.user.id}),`KeySigner.resolve`);if(u instanceof kR){let e=u.response.meta?.account;return new kR({account:e,description:`Passkey required: the passkey of Tempo Account ${e} signs only at its own relying party, which the approval page is not part of. Name another account, or deny the request.`})}if(u instanceof vI)return u;let d=n&&!$z(u.owner)&&u.owner.credential?.id===n.assertion.id?n:void 0,f=d?{...a,witness:d.witness}:a,p=d?.assertion??t.assertion;if(t.assertion&&u.owner.signer)return new cB;if(!p&&!u.owner.signer)return{options:await Z(e,K3(e,{account:u.account,clientId:o,key:f,owner:u.owner,userId:i.user.id}),`KeySigner.challenge`)};d&&await Z(e,MB($,{account:u.account,clientId:o,credential:u.owner.credential,digest:$R({key:f}),userId:i.user.id}),`Passkey.requestSignature`);let m=await Z(e,Y3(e,{account:u.account,assertion:u.owner.signer?void 0:p,clientId:o,key:f,owner:u.owner,userId:i.user.id}),`KeySigner.sign`);return m instanceof vI?m:{account:u.account,clientId:o,codeChallenge:s,expiry:f.expiry,signed:m}}async function h6(e,t){return await Z(e,v6(e,t),`SignInConsent.accountStep`).catch(n=>(Zt(e,{error:n,message:`An account step kept its redirect, since its grant failed.`}),{redirect:t.redirect}))}async function g6(e,t){return await Z(e,x6(e,t),`SignInConsent.signIn`).catch(n=>(Zt(e,{error:n,message:`A sign-in kept its redirect, since its grant failed.`}),t.redirect))}async function _6(e,t){let n=new URLSearchParams(t.oauthQuery);if(!n.has(`key_authorization`)||n.has(`challenge`)||ZF(n.get(`client_id`)??``))return;let r=await Z(e,e.var.auth.$context,`auth.context`);if(!await Z(e,ni(t.oauthQuery,r.secret),`auth.verifyOAuthQueryParams`)||await Z(e,a6($,{query:n}),`SignInGrant.spent`))return;let i=gz(n);if(!i||i instanceof vI)return;let a=dt(crypto.getRandomValues(new Uint8Array(32)));return{digest:$R({key:{...i,witness:a}}),witness:a}}async function v6(e,t){let{account:n,assertion:r,headers:i,redirect:a,session:o}=t,s=URL.parse(a,U.URL);if(!s||s.origin!==new URL(U.URL).origin||s.pathname!==`/authorize`||s.searchParams.has(`challenge`))return{redirect:a};let c=await Z(e,o6($,{query:s.searchParams,sessionId:o.session.id}),`SignInGrant.take`);if(!c)return{redirect:a};let l=await y6(e,{account:n,assertion:r,headers:i,oneTap:(()=>{let e=gB.assertion.safeParse(c.assertion);if(e.success&&c.witness)return{assertion:e.data,witness:c.witness}})(),redirect:a,session:o,url:s});return`options`in l&&await Z(e,n6($,{oneTap:c.witness?{assertion:c.assertion,witness:c.witness}:void 0,query:s.searchParams,sessionId:o.session.id}),`SignInGrant.hold`),l}async function y6(e,t){let{headers:n,redirect:r,session:i,url:a}=t;if(await Z(e,sU(e,{limits:[{binding:`AUTHORIZE_LIMIT`,key:i.user.id}]}),`RateLimit.check`))return{redirect:r};let o=await Z(e,d6(e,{account:t.account,assertion:t.assertion,headers:n,oauthQuery:a.search.slice(1),oneTap:t.oneTap,session:i,single:!0}),`Consent.approve`).catch(t=>{Zt(e,{error:t,message:`A sign-in could not grant the key that the sign-in page showed.`})});return!o||o instanceof vI?{redirect:r}:`options`in o?{options:o.options}:{redirect:o.redirect}}function b6(e,t){let n=new Map((e.req.header(`cookie`)??``).split(`;`).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(`=`);return[e.slice(0,t),e.slice(t+1)]}));for(let e of t.setCookie){let[t=``]=e.split(`;`),r=t.indexOf(`=`);r>0&&n.set(t.slice(0,r).trim(),t.slice(r+1))}let r=new Headers(e.req.raw.headers);return r.set(`cookie`,[...n].map(([e,t])=>`${e}=${t}`).join(`; `)),r}async function x6(e,t){let{oneTap:n,redirect:r,setCookie:i}=t,a=URL.parse(r,U.URL);if(!a||a.origin!==new URL(U.URL).origin||a.pathname!==`/authorize`&&a.pathname!==`/choose-account`)return r;let o=a.searchParams;if(!o.has(`key_authorization`)||o.has(`challenge`)||ZF(o.get(`client_id`)??``))return r;let s=b6(e,{setCookie:i}),c=e.var.newSession;if(!c||!await Z(e,i6($,{query:o}),`SignInGrant.spend`))return r;if(a.pathname===`/choose-account`)return await Z(e,n6($,{oneTap:n,query:o,sessionId:c.session.id}),`SignInGrant.hold`),r;let l=await y6(e,{headers:s,oneTap:n,redirect:r,session:c,url:a});return`options`in l?r:l.redirect}var S6=`Tempo-Id-Signed-In`,C6={pad:!1,url:!0},w6=z({url:R().min(1)});async function T6(e,t){let{clientId:n}=t;return e.var.firstParty?.find(e=>e.clientId===n)||await Z(e,GF($,{clientId:n,enabled:!0}).catch(e=>{if(!(e instanceof RF))throw e}),`Apps.get`)}async function E6(e,t){let{headers:n,oneTap:r,request:i,session:a}=t,o=i.client_id,s=n.get(`cookie`)??void 0;if(!i.code_challenge&&t.secret)return new fz({description:"Tokens refused: the app holds a client secret, so its backend redeems a code. Send `code_challenge`, then redeem the code with the secret."});let c=await Z(e,sU(e,{limits:[{binding:`AUTHORIZE_LIMIT`,key:a.user.id},...r?[{binding:`ACCOUNT_LIMIT`,key:a.user.id}]:[]]}),`RateLimit.check`);if(c)return c;let l=i.key_authorization,u=l?await Z(e,J3(e,{account:l.account,chainId:l.chainId,clientId:o,cookie:s,create:!!r,oneTap:r?.assertion.id,sessionId:a.session.id,userId:a.user.id}),`KeySigner.resolve`):void 0;if(u instanceof vI)return u;let d=r&&u&&!$z(u.owner)&&u.owner.credential?.id===r.assertion.id?r:void 0,f=l&&d?{...l,witness:d.witness}:l,p=await(async()=>{if(u)return u.account;let t=await Z(e,S3(e,{chainId:l?.chainId===void 0?void 0:Number(l.chainId),clientId:o,userId:a.user.id}),`AccountStep.accounts`).catch(t=>(Zt(e,{error:t,fields:{clientId:o},message:`The headless authorization skipped an account selection whose accounts failed to load.`}),[]));return D3(t,j3({clientId:o,cookie:s,sessionId:a.session.id}))?.address??t[0]?.address})(),m=p?A3({account:p.toLowerCase(),clientId:o,cookie:s,sessionId:a.session.id}):void 0,h=new Headers(n);m&&h.set(`cookie`,m.header),e.set(`accountChosen`,!0);let g=i.code_challenge?void 0:Lt(ht(32),C6),_={client_id:o,code_challenge:i.code_challenge??Lt(Pt(pt(g)),C6),code_challenge_method:`S256`,redirect_uri:i.redirect_uri,resource:U.URL,response_type:`code`,scope:i.scope??`openid`,...i.state?{state:i.state}:{}},v=new URL(`/oauth2/authorize`,U.URL);v.search=new URLSearchParams(_).toString(),h.set(`accept`,`application/json`);let y=await Z(e,e.var.auth.api.oauth2Authorize({asResponse:!1,body:{},headers:h,query:_,request:new Request(v,{headers:h})}),`auth.oauth2Authorize`),b=w6.safeParse(y),x=b.success?URL.parse(b.data.url,U.URL):null,S=new URL(i.redirect_uri).searchParams,C=x?.searchParams.get(`code`);if(!x||!C||x.searchParams.getAll(`error`).length>S.getAll(`error`).length||!`${x.origin}${x.pathname}`.startsWith(new URL(i.redirect_uri).origin))return new fz({description:`Authorization refused: the app's request needs the user's approval, which no page shows here. Authorize through a redirect, or register the app to skip consent.`});f&&u&&d&&await Z(e,MB($,{account:u.account,clientId:o,credential:u.owner.credential,digest:$R({key:f}),userId:a.user.id}),`Passkey.requestSignature`);let w=f&&u?await Z(e,Y3(e,{account:u.account,assertion:d?.assertion,clientId:o,key:f,origin:d?.origin,owner:u.owner,userId:a.user.id}),`KeySigner.sign`):void 0;if(w instanceof vI)return w;let E={...p&&w?{account:p,key_authorization:w}:{},...i.state?{state:i.state}:{}};if(m&&(l?.account||d)&&e.header(`set-cookie`,m.setCookie,{append:!0}),e.header(`cache-control`,`no-store`),!g)return{...E,code:C};let D=await Z(e,e.var.auth.api.oauth2Token({body:{client_id:o,code:C,code_verifier:g,grant_type:`authorization_code`,redirect_uri:i.redirect_uri,resource:U.URL},headers:new Headers({"content-type":`application/x-www-form-urlencoded`})}),`auth.oauth2Token`);return{...E,tokens:pz.tokens.parse(D)}}(function(e){e.errors=[...J3.errors,...Y3.errors,fz]})(E6||={});async function D6(e,t){let{assertion:n,challenge:r,setCookie:i}=t,a=pz.request.parse(r.authorize),o=await Z(e,T6(e,{clientId:a.client_id}),`Headless.app`),s=mz(a,{app:o,origin:e.req.header(`origin`)});if(s)return s;let c=b6(e,{setCookie:i}),l=e.var.newSession;if(!l)throw Error(`The one-tap session is missing.`);return await Z(e,E6(e,{headers:c,oneTap:r.witness&&r.origin?{assertion:n,origin:r.origin,witness:r.witness}:void 0,request:a,secret:!!o.secret,session:l}),`Headless.authorize`)}(function(e){e.errors=[...mz.errors,...E6.errors]})(D6||={});async function O6(e,t){let{assertion:n,challenge:r}=t;if(r.authorize===void 0)return!0;let i=pz.request.parse(r.authorize);return i.key_authorization?i.key_authorization.expiry<=Date.now()/1e3?!1:await Z(e,zB($,{authenticatorData:n.metadata.authenticatorData,expiry:i.key_authorization.expiry,signature:n.signature}),`Passkey.spendSignIn`):!0}var k6=[...oU,L3],A6=7200,j6=new Set([`/v1/account`,`/v1/auth/code`,`/v1/auth/code/verify`,`/v1/auth/logout`,`/v1/auth/passkey/options`,`/v1/auth/passkey/verify`,`/v1/auth/providers`,`/v1/auth/session`,`/v1/authorize`,`/v1/realms`]);function M6(e){let t=e.req.header(`origin`);if(t&&![new URL(U.URL).origin,new URL(e.req.url).origin].includes(t))return t}var N6=QB(async(e,t)=>{if(!j6.has(e.req.path))return t();let n=M6(e),r=![`GET`,`HEAD`,`OPTIONS`].includes(e.req.method),i=n!==void 0&&await Z(e,(async()=>{if(r){let t=await WF($,{origin:n});return e.set(`firstParty`,t),t.length>0}return await hV(e,async()=>(await WF($,{origin:n})).length>0,[`apps.firstPartyOrigin`,n],{keep:e=>e})})(),`Apps.firstPartyOrigin`);return n&&!i&&r?X(e,new bI):F3({credentials:!0,exposeHeaders:[...k6,S6],maxAge:A6,origin:()=>i?n:null})(e,t)}),P6=F3({exposeHeaders:k6});function F6(e){let t=e.req.header(`sec-fetch-site`);if(t!==`same-origin`&&(t!==void 0||!e.req.header(`origin`)||M6(e)))return new bI}(function(e){e.errors=[bI]})(F6||={});function I6(e,t){if(t.oauth_query&&M6(e))return new bI}(function(e){e.errors=[bI]})(I6||={});async function L6(e){let t=await Z(e,e.var.auth.api.signOut({headers:new Headers,returnHeaders:!0}),`auth.signOut`);for(let n of t.headers.getSetCookie())e.header(`set-cookie`,n,{append:!0})}async function R6(e){let t=await Z(e,e.var.auth.api.getSession({headers:e.req.raw.headers,returnHeaders:!0}),`auth.getSession`);for(let n of t.headers.getSetCookie())e.header(`set-cookie`,n,{append:!0});return t.response}async function z6(e){let t=await Z(e,e.var.auth.$context,`auth.context`);return await Z(e,XV(e,t.secret,t.authCookies.sessionToken.name),`cookie.verify`)||void 0}var B6;(function(e){let t=Kn([`0x`,R().regex(/^[0-9a-fA-F]{40}$/)]),n;(function(e){e.query=z({chain:en.optional().meta({description:"The chain whose balance each account carries: `mainnet`, `testnet`, or another chain that the deployment lists. Without it, the accounts carry no balance.",examples:[`testnet`]}),client_id:R().min(1).max(255).optional().meta({description:"The app's client ID, whose realms select the accounts. A browser page from an origin that none of the app's redirect URIs has receives the `default` realm, as does a request without one.",examples:[`client_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]})}),e.response=z({email:rr().meta({description:`The user's email address.`,examples:[`ada@example.com`]}),id:R().meta({description:"The user's ID, which is the `sub` of every token Tempo ID issues for the user.",examples:[`user_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]}),name:R().nullable().meta({description:"The user's name, or `null` for a user who signed up without one.",examples:[`Ada Lovelace`]}),passkeys:nr().meta({description:"Whether the realms the request reaches hold passkeys that sign in at Tempo ID's origin. Without `client_id`, the `default` realm's, where `POST /v1/account/passkey/options` registers a passkey.",examples:[!0]}),tempo:or(x2.tempoAccount.extend({balance:aV.balance.nullable().optional().meta({description:"The value of the account's verified holdings on the chain that `chain` names, in USD, or `null` when the chain has no Tempo API URL or the read fails or takes longer than 3 seconds. Absent without `chain`."})})).readonly().meta({description:`The user's Tempo Accounts in the realms the request reaches: the account that the user selected for the app first, then oldest first.`})}).meta({id:`Account`})})(n||=e.account||={});let r;(function(e){e.json=n.query,e.response=n.response})(r||=e.create||={});let i;(function(e){e.json=z({}),e.response=z({options:z({publicKey:z({attestation:Yn(`none`).meta({description:`Tempo ID requests no attestation statement from the authenticator.`}),authenticatorSelection:z({requireResidentKey:Yn(!0).meta({description:`The passkey must be discoverable, so it signs in without an email.`}),residentKey:Yn(`required`).meta({description:`The passkey must be discoverable, so it signs in without an email.`}),userVerification:Yn(`required`).meta({description:`Every passkey registration requires user verification.`})}).meta({description:`The authenticator that the passkey requires.`}),challenge:Kn([`0x`,R()]).meta({description:`The single-use challenge, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),excludeCredentials:or(z({id:R().meta({description:`A credential ID, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`A passkey that the user holds already.`})).optional().meta({description:`The user's passkeys of the relying party, which an authenticator that holds one of them refuses to replace. Absent for a user with none.`}),pubKeyCredParams:or(z({alg:Yn(-7).meta({description:`ES256: ECDSA over P-256 with SHA-256.`}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The only key type that a Tempo Account accepts.`})).meta({description:`The key types the passkey may use: P-256 alone, which a Tempo Account verifies.`}),rp:z({id:R().meta({description:"The relying party ID of the `default` realm.",examples:[`tempo.xyz`]}),name:R().meta({description:"The `default` realm's display name.",examples:[`Tempo`]})}).meta({description:`The relying party.`}),user:z({displayName:R().meta({description:`The user's name, or the email address for a user without one.`,examples:[`Ada Lovelace`]}),id:R().meta({description:`A random user handle for this passkey, base64url, so a new passkey never replaces another in the authenticator.`,examples:[`3q2-7wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`]}),name:rr().meta({description:`The user's email address.`,examples:[`ada@example.com`]})}).meta({description:`The user, as the authenticator labels the passkey.`})}).meta({description:"The `PublicKeyCredentialCreationOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.create()`."})})})(i||=e.passkeyOptions||={});let a;(function(e){e.json=z({credential:gB.credential}),e.response=z({step:z({options:z({publicKey:z({allowCredentials:or(z({id:gB.credentialId.meta({description:`The credential ID of the new passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The new passkey.`})).meta({description:`The new passkey, the only one the browser offers.`}),challenge:Kn([`0x`,R()]).meta({description:`The single-use proof challenge, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),rpId:R().meta({description:"The relying party ID of the `default` realm.",examples:[`tempo.xyz`]}),userVerification:Yn(`required`).meta({description:`Every passkey signature requires user verification.`})}).meta({description:"The `PublicKeyCredentialRequestOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.get()`."}),type:Yn(`passkey`).meta({description:"Sign the options with the new passkey, then send the assertion to `POST /v1/account/passkey/verify`."})}).meta({description:`The next step: the new passkey's signature, which proves that the authenticator holds its private key.`})})})(a||=e.passkey||={});let o;(function(e){e.json=z({account:t.optional().meta({description:"One of the user's configurable Tempo Accounts in the `default` realm that a cloud wallet owns, on `chain`, which the passkey joins as a second owner through an update of its configuration. Absent, the passkey owns an account of its own.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),assertion:gB.assertion,chain:en.optional().meta({description:"The chain whose accounts are configurable, where `account` is, and whose address of the passkey's own account the response returns. Without it, the first such chain for `account`, and the passkey's own address otherwise.",examples:[`local`]})}),e.response=z({address:R().meta({description:"The address of the Tempo Account that the passkey owns: `account`, or the passkey's own account on `chain`, which is the address that its initial configuration derives on a chain whose accounts are configurable, and the one that its public key derives otherwise.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),id:gB.credentialId.meta({description:`The credential ID of the passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]})})})(o||=e.passkeyVerify||={});let s;(function(e){e.query=n.query.omit({chain:!0}),e.response=z({realms:or(x2.realm).readonly().meta({description:`The realms the app reaches, never empty. The first holds a user's first account.`})})})(s||=e.realms||={});let c;(function(e){e.response=z({chains:or(z({chainId:Zn().int().meta({description:`The ID of the Tempo chain that serves the name.`,examples:[42431]}),configurable:nr().meta({description:`Whether Tempo Accounts can be upgraded to configurable accounts (TIP-1107) on the chain, as the deployment sets.`,examples:[!1]}),name:en.meta({description:"The name that the `chain` parameter carries.",examples:[`testnet`]})}).meta({description:`A chain that a page can select.`})).readonly().meta({description:"The chains in order: `mainnet`, `testnet`, then the deployment's listed chains."})})})(c||=e.chains||={});let l;(function(e){e.response=z({chains:or(z({api:Xn([`down`,`none`,`up`]).meta({description:"Whether the chain's Tempo API responds on `/health`: `up`, `down`, or `none` when `TEMPO_API_URLS` lists none for the chain.",examples:[`up`]}),chainId:Zn().int().meta({description:`The ID of the Tempo chain that serves the name.`,examples:[1337]}),name:en.meta({description:"The name that the `chain` parameter carries.",examples:[`local`]}),node:Xn([`down`,`up`]).meta({description:"Whether the chain's node serves the chain ID: `up`, or `down` when it does not respond or serves another.",examples:[`up`]})}).meta({description:`The status of a listed chain.`})).readonly().meta({description:"The deployment's listed chains in order, apart from `mainnet` and `testnet`."})})})(l||=e.chainStatus||={});let u;(function(e){e.json=z({address:Kn([`0x`,R().regex(/^[0-9a-fA-F]{40}$/)]).meta({description:"The Tempo Account that receives the tokens, one of the user's accounts in the `default` realm.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`],pattern:`^0x[0-9a-fA-F]{40}$`}),chain:en.meta({description:"The test chain whose faucet drips the tokens: `testnet`, or a name that `GET /i/chains` lists. Tempo mainnet has no faucet.",examples:[`testnet`]})}),e.response=z({transactions:or(Kn([`0x`,R().regex(/^[0-9a-f]{64}$/)]).meta({description:`The hash of one transfer from the faucet.`,examples:[`0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060`]})).readonly().meta({description:`The hashes of the transfers, one for each token that the faucet drips, each one landed.`,examples:[[`0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060`]]})})})(u||=e.fund||={});let d;(function(e){e.json=z({account:t.optional().meta({description:"One of the user's Tempo Accounts in the app's realms on `chain`, which a linked wallet.tempo passkey owns and the upgrade makes configurable. Absent with `credentialId`.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),chain:en.optional().meta({description:`The chain whose accounts are configurable, where the upgrade runs. Defaults to the first such chain that the deployment names.`,examples:[`local`]}),client_id:R().min(1).max(255).optional().meta({description:"The app whose realms hold the account. Without it, the `default` realm.",examples:[`client_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]}),credentialId:gB.credentialId.optional().meta({description:"A wallet.tempo passkey of the user's email that has not linked to the user yet, as `GET /i/account/passkeys` lists it. Its assertion over the upgrade links it. Absent with `account`.",examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),passkey:z({assertion:gB.assertion}).optional().meta({description:`The passkey step's result: the passkey's assertion over the step's challenge. Absent on the first request.`})}).refine(e=>e.account===void 0!=(e.credentialId===void 0),{message:"Name exactly one of `account` or `credentialId`.",path:[`account`]}),e.response=Gn([z({account:x2.tempoAccount}).meta({description:`The installed configuration.`}),z({step:z({options:z({publicKey:z({allowCredentials:or(z({id:gB.credentialId.meta({description:`The credential ID of the account's passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The account's passkey.`})).meta({description:`The account's passkey, the only one the browser offers.`}),challenge:Kn([`0x`,R()]).meta({description:`The digest of the transaction that installs the configuration, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),rpId:R().meta({description:`The passkey's relying party ID.`,examples:[`tempo.xyz`]}),userVerification:Yn(`required`).meta({description:`Every passkey signature requires user verification.`})}).meta({description:"The `PublicKeyCredentialRequestOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.get()`."}),type:Yn(`passkey`).meta({description:"Sign the options with the passkey, then repeat the request with `passkey.assertion`."})}).meta({description:`The next step: the passkey's signature of the transaction, since only the passkey signs for the account.`})}).meta({description:`The passkey step.`})])})(d||=e.upgrade||={});let f;(function(e){e.response=z({passkeys:or(z({address:t.meta({description:`The address of the passkey's Tempo Account, which its public key derives.`,examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),credentialId:gB.credentialId.meta({description:`The credential ID of the passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]})}).meta({description:`A wallet.tempo passkey of the email.`})).readonly().meta({description:`The passkeys that wallet.tempo stores for the user's email and that link to no user yet, oldest first. Empty without the wallet service.`})})})(f||=e.passkeys||={})})(B6||={});var V6=2e3,H6=new sb().get(`/v1/account`,HH({description:"Reads the signed-in user and their Tempo Accounts in the realms of the app that `client_id` names: the account that the user selected for the app first, then oldest first. Without `client_id`, the `default` realm's. With `chain`, each account carries its balance on that chain. `passkeys` states whether those realms hold passkeys at Tempo ID's origin. Creates no account: `POST /v1/account` creates the first one.",responses:ZH({errors:[...QH.errors,...sU.errors,...w2.errors,YB,bI],success:{description:`The user and their Tempo Accounts.`,schema:B6.account.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`query`,B6.account.query),async e=>{if(e.req.header(`sec-fetch-site`)===`cross-site`)return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let{chain:n}=e.req.valid(`query`),r=n?pn({name:n,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS}):void 0;if(n&&!r)return X(e,J6({chain:n}));let i=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(i)return i;let a=await Z(e,oW(e,{clientId:e.req.valid(`query`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),o=await Z(e,uW(e,{db:$,origin:U.URL,realms:a}),`Realm.withDefaults`),s=await Z(e,w2(e,{chainId:r?.chainId,db:$,env:U,realms:o,userId:t.user.id}),`TempoAccount.list`),{client_id:c}=e.req.valid(`query`),l=c?k3(s,{clientId:c,cookie:e.req.header(`cookie`),sessionId:t.session.id}):s,u=r?await Z(e,sV(e,{accounts:l,apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:r.chainId}),chainId:r.chainId}),`Balance.list`):void 0;return e.header(`cache-control`,`private, no-store`),e.json({email:t.user.email,id:t.user.id,name:t.user.name||null,passkeys:!!OB(o,{origin:U.URL}),tempo:l.map((e,t)=>u?{...e,balance:u[t]??null}:e)},200)}).post(`/v1/account`,HH({description:"Returns the signed-in user and their Tempo Accounts, as `GET /v1/account` does, with each balance on the chain that `chain` names, and creates a Privy-owned account in the first realm for a user with none, when that realm has a Privy app. On a deployment with configurable accounts, the new account is configurable from its creation, at the address that its initial configuration derives. A user with a linked wallet.tempo passkey, or a registered passkey, in the realms receives none, as does one whose email has a wallet.tempo passkey that has not linked, on a deployment with configurable accounts. The JSON body needs a CORS preflight, which Tempo ID grants only to the origins of first-party apps, so another app's page cannot send the request.",responses:ZH({errors:[...dV,...QH.errors,...sU.errors,...S2.errors,YB,bI],success:{description:`The user and their Tempo Accounts.`,schema:B6.create.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.create.json),async e=>{let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let{chain:n}=e.req.valid(`json`),r=n?pn({name:n,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS}):void 0;if(n&&!r)return X(e,J6({chain:n}));let i=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(i)return i;let a=await Z(e,oW(e,{clientId:e.req.valid(`json`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),o=await Z(e,uW(e,{db:$,origin:U.URL,realms:a}),`Realm.withDefaults`),s=await Z(e,f3(e,{email:t.user.email,realms:o}),`Configure.awaitsUpgrade`),c={chainId:r?.chainId,db:$,env:U,realms:o,userId:t.user.id},l=(await Z(e,s?C2(e,c):S2(e,c),`TempoAccount.create`)).map(O2),{client_id:u}=e.req.valid(`json`),d=u?k3(l,{clientId:u,cookie:e.req.header(`cookie`),sessionId:t.session.id}):l,f=r?await Z(e,sV(e,{accounts:d,apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:r.chainId}),chainId:r.chainId}),`Balance.list`):void 0;return e.header(`cache-control`,`private, no-store`),e.json({email:t.user.email,id:t.user.id,name:t.user.name||null,passkeys:!!OB(o,{origin:U.URL}),tempo:d.map((e,t)=>f?{...e,balance:f[t]??null}:e)},200)}).post(`/v1/account/passkey/options`,HH({description:"Issues a single-use registration challenge for the signed-in user, and returns creation options for a passkey of the `default` realm's relying party. The passkey that `POST /v1/account/passkey` and `POST /v1/account/passkey/verify` then store signs in, and owns the Tempo Account at the address that its public key derives. Requires a sign-in within the last 10 minutes, and fewer than 10 registered passkeys. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...QH.errors,...sU.errors,YB,bI,iB,oB,sB],success:{description:`The creation options.`,schema:B6.passkeyOptions.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkeyOptions.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let r=t.user.id,i=await Z(e,CB($,{userId:r}),`Passkey.list`);if(i.filter(e=>e.registered).length>=10)return X(e,new iB);let a=await Z(e,uW(e,{db:$,origin:U.URL,realms:[await Z(e,hV(e,()=>cW($,{id:rW}),[`realm.get`,rW]),`Realm.get`)]}),`Realm.withDefaults`),o=OB(a,{origin:U.URL}),s=a.find(e=>e.id===o?.realmId);if(!o||!s)return X(e,new oB);let c=await Z(e,AB($,{rpId:o.rpId,userId:r}),`Passkey.requestRegistration`),l=i.flatMap(e=>e.rpId===o.rpId?[e.id]:[]),u=B6.passkeyOptions.response.shape.options.parse(iC({authenticatorSelection:{requireResidentKey:!0,residentKey:`required`,userVerification:`required`},challenge:c,...l.length>0?{excludeCredentialIds:l}:{},rp:{id:o.rpId,name:s.name},user:{displayName:t.user.name||t.user.email,id:crypto.getRandomValues(new Uint8Array(32)),name:t.user.email}}).options);return e.header(`cache-control`,`private, no-store`),e.json({options:u},200)}).post(`/v1/account/passkey`,HH({description:"Verifies the credential of a new passkey over a challenge from `POST /v1/account/passkey/options`, and returns the next step: the passkey's signature of a proof challenge, which `POST /v1/account/passkey/verify` takes. The attestation carries no signature, so only that step stores the passkey. Requires a sign-in within the last 10 minutes. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...OI.errors,...QH.errors,...sU.errors,YB,bI,iB,sB,cB],success:{description:`The proof step.`,schema:B6.passkey.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkey.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let{credential:r}=e.req.valid(`json`),i=t.user.id,a=await Z(e,RB($,{clientDataJSON:r.clientDataJSON,userId:i}),`Passkey.takeRegistration`),o=a?GB(r,{challenge:a.challenge,origin:new URL(U.URL).origin,rpId:a.rpId}):void 0;if(!a||!o)return X(e,new cB);let[s,c]=await Promise.all([(async()=>{if(e.env.WALLET)try{return await Z(e,A2(e.env.WALLET,{id:o.id}),`Wallet.credential`)}catch(t){return Zt(e,{error:t,message:`The wallet service failed a passkey lookup.`}),t instanceof Error&&OI(t)||new TI}})(),Z(e,TB($,{userId:i}),`Passkey.registered`)]);if(s instanceof vI)return X(e,s);if(s)return X(e,new cB);if(c>=10)return X(e,new iB);let l=await Z(e,kB($,{credential:o,rpId:a.rpId,userId:i}),`Passkey.requestProof`),u=B6.passkey.response.shape.step.shape.options.parse(eC({challenge:l,credentialId:[o.id],rpId:a.rpId,userVerification:`required`}).options);return e.header(`cache-control`,`private, no-store`),e.json({step:{options:u,type:`passkey`}},200)}).post(`/v1/account/passkey/verify`,HH({description:"Registers a passkey for the signed-in user, with the new passkey's assertion over the proof challenge from `POST /v1/account/passkey`. The passkey signs in, and owns the Tempo Account at the address that its public key derives, in the `default` realm, beside the user's other accounts. On a deployment with configurable accounts, the passkey's account is configurable from its creation, at the address that its initial configuration derives. With `account`, the passkey instead joins that configurable account as a second owner beside its cloud wallet, which signs the configuration update. Requires a sign-in within the last 10 minutes. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...c3.errors,...h3.errors,...QH.errors,...sU.errors,bV,xV,YB,bI,iB,sB,cB],success:{description:`The passkey and the address of the account it owns.`,schema:B6.passkeyVerify.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkeyVerify.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let{assertion:r}=e.req.valid(`json`),i=t.user.id,a=await Z(e,LB($,{clientDataJSON:r.metadata.clientDataJSON,userId:i}),`Passkey.takeProof`);if(!a||r.id!==a.id||!WB(r,{challenge:a.challenge,origin:new URL(U.URL).origin,publicKey:a.publicKey,rpId:a.rpId}))return X(e,new cB);let{account:o,chain:s}=e.req.valid(`json`),c=o?await Z(e,c3(e,{account:o,chain:s,userId:i}),`Configure.find`):void 0;if(c instanceof vI)return X(e,c);if(c&&!c.current)return X(e,new bV({account:Yz(c.owner),reason:`upgrade`}));if(c&&(c.owner.type===`webAuthn`||c.current?.owners.some(e=>e.type===`webAuthn`)))return X(e,new xV({account:Yz(c.owner),owner:`passkey`}));let l=await Z(e,EB($,{id:a.id,publicKey:a.publicKey,rpId:a.rpId,userId:i}),`Passkey.register`);if(l===`limit`)return X(e,new iB);if(l!==`stored`)return X(e,new cB);let u=L(_e(It(a.publicKey)));if(e.header(`cache-control`,`private, no-store`),!c){let t=s?DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).find(e=>e.name===s):void 0;if(!t)return e.json({address:u,id:a.id},200);let n=AV({chainId:t.chainId,key:u,type:`webAuthn`});return e.json({address:n.address,id:a.id},200)}let{client:d,current:f,owner:p}=c,m=NV({add:[{address:u,type:`webAuthn`,weight:1}],address:Yz(p),chainId:c.chain.chainId,current:f,type:p.type});return await h3(e,{client:d,current:f,signing:g3(p,{current:f}),target:m,userId:i}),e.json({address:m.address,id:a.id},200)}).get(`/v1/realms`,HH({description:"Lists the realms that the app `client_id` names reaches, in order. An app without realms reaches the `default` realm alone.",responses:ZH({errors:[...QH.errors],success:{description:`The realms.`,schema:B6.realms.response}}),tags:[`Account`]}),QH(`query`,B6.realms.query),async e=>{let t=await Z(e,oW(e,{clientId:e.req.valid(`query`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`);return e.header(`cache-control`,`private, no-store`),e.json({realms:t.map(e=>({id:e.id,name:e.name}))},200)}).get(`/v1/chains`,HH({description:"Lists the chains that the `chain` parameter of `GET /v1/account` and `POST /v1/account` selects: `mainnet`, `testnet`, then the chains that the deployment lists, each with its chain ID.",responses:ZH({success:{description:`The chains.`,schema:B6.chains.response}}),tags:[`Account`]}),e=>e.json({chains:X6()},200)).get(`/i/chains`,HH({description:"Lists the chains that the `chain` parameter of `GET /v1/account` and `POST /v1/account` selects, as `GET /v1/chains` does. Internal: only Tempo ID's own pages send the request, so the public document leaves it out.",hide:!0,responses:ZH({success:{description:`The chains.`,schema:B6.chains.response}}),tags:[`Account`]}),e=>e.json({chains:X6()},200)).get(`/i/chains/status`,HH({description:"Returns whether the node and the Tempo API of each chain that the deployment lists respond, apart from `mainnet` and `testnet`. A probe that fails or takes longer than a second reads as `down`, and a status can be up to 2 seconds old. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...F6.errors],success:{description:`The status of each listed chain.`,schema:B6.chainStatus.response}}),tags:[`Account`]}),async e=>{let t=F6(e);if(t)return X(e,t);let n=Qt({value:U.RPC_URLS}).filter(e=>!(e.name in fn)),r=await Promise.all(n.map(async t=>({...await Z(e,hV(e,()=>_V({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:t.chainId}),chainId:t.chainId,rpcUrl:t.url}),[`ChainStatus.get`,t.name],{ttl:V6}),`ChainStatus.get`),chainId:t.chainId,name:t.name})));return e.header(`cache-control`,`no-store`),e.json({chains:r},200)}).post(`/i/account/fund`,HH({description:"Funds one of the signed-in user's Tempo Accounts in the `default` realm from the faucet of the test chain that `chain` names, and waits until each transfer lands. Tempo mainnet has no faucet. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...dV,...F6.errors,...QH.errors,...OI.errors,...sU.errors,...w2.errors,YB,bI],success:{description:`The transfers from the faucet.`,schema:B6.fund.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.fund.json),async e=>{let t=F6(e);if(t)return X(e,t);let n=await Z(e,R6(e),`Session.get`);if(!n)return X(e,new YB);let{address:r,chain:i}=e.req.valid(`json`),a=pn({name:i,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS});if(!a)return X(e,J6({chain:i}));let o=Mo.find(e=>e.id===a.chainId);if(!o)return X(e,q6({chain:i}));let s=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:n.user.id}]}),`RateLimit.check`);if(s)return s;let c=await Z(e,oW(e,{clientId:void 0,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),l=await Z(e,uW(e,{db:$,origin:U.URL,realms:c}),`Realm.withDefaults`),u=(await Z(e,w2(e,{chainId:a.chainId,db:$,env:U,realms:l,userId:n.user.id}),`TempoAccount.list`)).find(e=>e.address.toLowerCase()===r.toLowerCase());if(!u)return X(e,K6({address:r}));let d=await(async()=>{try{return await Z(e,ko({address:u.address,chain:o,rpcUrl:a.rpcUrl}),`Faucet.fund`)}catch(t){throw!(t instanceof Error)||OI(t)?t:(Zt(e,{error:t,message:`The faucet did not fund the account.`}),new TI)}})();return e.json({transactions:d},200)}).post(`/i/account/upgrade`,HH({description:"Upgrades one of the signed-in user's Tempo Accounts in place to a configurable account (TIP-1113), on a chain whose accounts the deployment makes configurable. The account is a wallet.tempo passkey's: one that linked, which `account` names, or one of the user's email that has not linked yet, which `credentialId` names and the upgrade links. The account keeps its address, and the passkey stays its only owner. The passkey signs in the browser: the first request returns the passkey step, and the repeated request with `passkey.assertion` sends the upgrade. Requires a sign-in within the last 10 minutes. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...dV,...s3.errors,...m3.errors,...F6.errors,...QH.errors,...sU.errors,YB,kR,sB],success:{description:`The upgraded account, or the passkey step.`,schema:B6.upgrade.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.upgrade.json),async e=>{let t=await U6(e);if(t instanceof Response)return t;let n=t.user.id,{account:r,chain:i,client_id:a,credentialId:o,passkey:s}=e.req.valid(`json`),c=await Z(e,m3(e,{account:r,chain:i,clientId:a,credentialId:o,email:t.user.email,userId:n}),`Configure.root`);if(c instanceof vI)return X(e,c);if(e.header(`cache-control`,`private, no-store`),s){let t=await Z(e,s3(e,{account:c.account,assertion:s.assertion,client:c.client,credential:c.credential,link:c.link,userId:n}),`Configure.confirm`);if(t instanceof vI)return X(e,t);let r=await Z(e,G6(e,{account:c.account,chain:c.chain,clientId:a,userId:n}),`reread`);return e.json({account:r},200)}if(OB([c.realm],{origin:U.URL})?.rpId!==c.credential.rpId)return X(e,W6({account:c.account}));let l=NV({add:[],address:c.account,chainId:c.chain.chainId,current:void 0,type:`webAuthn`});if(await Z(e,UV({client:c.client,target:l}),`ConfigurableAccount.installed`)){let t=c.link?await Z(e,c.link(),`Configure.link`):void 0;if(t)return X(e,t);await Z(e,IV($,{config:l,userId:n}),`db.accountConfig.save`);let r=await Z(e,G6(e,{account:c.account,chain:c.chain,clientId:a,userId:n}),`reread`);return e.json({account:r},200)}let u=B6.upgrade.response.options[1].shape.step.shape.options.parse(await Z(e,u3(e,{account:c.account,client:c.client,credential:c.credential,current:void 0,target:l,userId:n}),`Configure.request`));return e.json({step:{options:u,type:`passkey`}},200)}).get(`/i/account/passkeys`,HH({description:"Lists the wallet.tempo passkeys of the signed-in user's email that link to no user yet, which `POST /i/account/upgrade` takes as `credentialId`. The sign-in proved the email, so the list reveals nothing to another person. Counts against the user's `ACCOUNT_LIMIT`. Refuses a cross-site navigation with `cross_site_request`. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...OI.errors,...sU.errors,YB,bI],success:{description:`The passkeys.`,schema:B6.passkeys.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),async e=>{if(e.req.header(`sec-fetch-site`)===`cross-site`)return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let r=await Z(e,p3(e,{email:t.user.email}),`Configure.unlinked`);return e.header(`cache-control`,`private, no-store`),e.json({passkeys:r.map(e=>({address:L(e.address),credentialId:e.credentialId}))},200)});async function U6(e){let t=F6(e);if(t)return X(e,t);let n=await Z(e,R6(e),`Session.get`);return n?Y6(n)?await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:n.user.id}]}),`RateLimit.check`)||n:X(e,new sB):X(e,new YB)}function W6(e){return new kR({account:e.account,description:`Passkey required: the passkey of Tempo Account ${e.account} signs only at its own relying party, which this page is not part of. Change the account there.`})}async function G6(e,t){let{account:n,chain:r,clientId:i,userId:a}=t,o=await Z(e,l3(e,{clientId:i}),`Configure.reach`),s=(await Z(e,C2(e,{chainId:r.chainId,db:$,env:U,realms:o,userId:a}),`TempoAccount.held`)).find(e=>Yz(e).toLowerCase()===n.toLowerCase());if(!s)throw new y2({account:n});return O2(s)}function K6(e){return new lz({issues:[{message:`The signed-in user has no Tempo Account at ${e.address}. Use an address that \`GET /v1/account\` lists`,path:[`address`]}]})}function q6(e){return new lz({issues:[{message:`The chain "${e.chain}" has no faucet. Use \`testnet\`, or a test chain that the deployment lists`,path:[`chain`]}]})}function J6(e){return new lz({issues:[{message:`No chain is named "${e.chain}". Use \`mainnet\`, \`testnet\`, or another chain that the deployment lists`,path:[`chain`]}]})}function Y6(e){return Date.now()-e.session.createdAt.getTime()<6e5}function X6(){let e=DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).map(e=>e.chainId);return[{chainId:fn.mainnet,name:`mainnet`},{chainId:fn.testnet,name:`testnet`},...Qt({value:U.RPC_URLS}).filter(e=>!(e.name in fn)).map(e=>({chainId:e.chainId,name:e.name}))].map(t=>({...t,configurable:e.includes(t.chainId)}))}var Z6=60,Q6;(function(e){e.continuation=z({client_id:R().optional(),expiresAt:Zn(),id_token_hint:R(),post_logout_redirect_uri:R().optional(),state:R().optional()})})(Q6||={});var $6=class extends yI(`invalid_id_token_hint`){name=`Logout.HintInvalidError`;constructor(){super({error_description:`Invalid id_token_hint: it is not an ID token that this issuer signed for the app. Send the ID token that the app received at sign-in.`,field:`id_token_hint`})}},e8=class extends yI(`logout_not_permitted`){name=`Logout.NotPermittedError`;constructor(e){super({error_description:`Logout not permitted: the app ${e.clientId} may not end the session. Register the app for logout, then retry.`,meta:{client_id:e.clientId}})}},t8=class extends yI(`post_logout_redirect_not_permitted`){name=`Logout.RedirectNotPermittedError`;constructor(e){super({error_description:`Invalid post_logout_redirect_uri: ${e.uri} is not registered for the app. Use one of its post-logout redirect URIs, or leave it out.`,field:`post_logout_redirect_uri`,meta:{post_logout_redirect_uri:e.uri}})}};async function n8(e,t){let n=await o8(t);if(n instanceof $6)return n;let[r]=await e.select({disabled:TP.disabled,enableEndSession:TP.enableEndSession,postLogoutRedirectUris:TP.postLogoutRedirectUris}).from(TP).where(Y(TP.clientId,n.clientId));if(!r||r.disabled||!r.enableEndSession)return new e8({clientId:n.clientId});let i=(()=>{let e=t.postLogoutRedirectUri;if(e===void 0)return;if(!(r.postLogoutRedirectUris??[]).includes(e))return new t8({uri:e});let n=new URL(e);return t.state!==void 0&&n.searchParams.set(`state`,t.state),n.href})();return i instanceof t8?i:{redirect:i,sessionId:n.sessionId}}(function(e){e.errors=[$6,e8,t8]})(n8||={});async function r8(e,t){return await Zi({data:JSON.stringify(Q6.continuation.parse({...e,expiresAt:Math.floor(Date.now()/1e3)+Z6})),key:await s8(t.secret)})}async function i8(e,t){let n=await ma({data:e,key:await s8(t.secret)}).then(e=>Q6.continuation.safeParse(JSON.parse(e))).catch(()=>void 0);if(n?.success&&!(n.data.expiresAt<=Date.now()/1e3))return n.data}async function a8(e,t){let n=new Date,r=e.$with(`ended`).as(e.delete(IP).where(KM(Y(IP.token,t.token),t.sessionId===void 0?void 0:Y(IP.id,t.sessionId),q`set_config('tempo_id.logout', 'on', true) = 'on'`)).returning({id:IP.id})),i=e.$with(`access_tokens`).as(e.update(CP).set({revoked:n}).where(KM($M(CP.sessionId,e.select({id:r.id}).from(r)),tN(CP.revoked))).returning({id:CP.id})),a=e.$with(`refresh_tokens`).as(e.update(MP).set({revoked:n}).where(KM($M(MP.sessionId,e.select({id:r.id}).from(r)),tN(MP.revoked))).returning({id:MP.id})),[o]=await e.with(r,i,a).select({id:r.id}).from(r);return o?.id}async function o8(e){let{clientId:t,issuer:n,jwks:r}=e,i=await(async()=>{try{let t=await Ji(e.hint,wi(r),{algorithms:[`RS256`]});return JSON.parse(new TextDecoder().decode(t.payload))}catch{return}})();if(!i||typeof i!=`object`)return new $6;let a=i,o=typeof a.aud==`string`?[a.aud]:Array.isArray(a.aud)?a.aud.filter(e=>typeof e==`string`):[],s=t??(o.length===1?o[0]:void 0);return a.iss!==n||!s||!o.includes(s)||typeof a.sid!=`string`||!a.sid||typeof a.sub!=`string`||!a.sub?new $6:{clientId:s,sessionId:a.sid,userId:a.sub}}async function s8(e){let t=new TextEncoder,n=await crypto.subtle.importKey(`raw`,t.encode(e),`HKDF`,!1,[`deriveBits`]),r=await crypto.subtle.deriveBits({hash:`SHA-256`,info:t.encode(`tempo-id:logout-continuation:v1`),name:`HKDF`,salt:new Uint8Array},n,256);return dt(new Uint8Array(r))}async function c8(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=Ya(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./assets/dist-SBl0rlY-.js`);n=i(r)(e)}return n.transaction||(oo.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function l8(e){return c8(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./assets/kysely-adapter-BVql8na5.js`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new H(`Failed to initialize database adapter`);return n(r,{type:i||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:a})(e)})}var u8={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`int8`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function d8(e,t){return`${so(e)}\u0000${so(t)}`}function f8(e,t){return`${e}\u0000${t}`}function p8(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,n)=>e===t.columns[n])}function m8(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function h8(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[d8(e.table,e.name),{columns:t.flatMap(e=>e.name===null?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>e.name!==null&&e.fullLength)}]}))}async function g8(e,t,n,r){if(r)return h8(await r(n));let i;switch(t.type){case`sqlite`:i=(await Io`
501
+ `);l.write(o.format.apply(o,e))}}Object.defineProperty(n.exports,"isWin",{get:function(){return c},set:function(e){c=e}}),n.exports.warnTo=function(e){var t=l;return l=e,t},n.exports.getFileName=function(e){var t=e||process.env;return t.PGPASSFILE||(c?r.join(t.APPDATA||`./`,`postgresql`,`pgpass.conf`):r.join(t.HOME||`./`,`.pgpass`))},n.exports.usePgPass=function(e,t){return Object.prototype.hasOwnProperty.call(process.env,`PGPASSWORD`)?!1:c?!0:(t||=`<unkn>`,m(e.mode)?e.mode&(u|d)?(v(`WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less`,t),!1):!0:(v(`WARNING: password file "%s" is not a plain file`,t),!1))};var y=n.exports.match=function(e,t){return h.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(e[r]||s)===Number(t[r])?n&&!0:n&&(t[r]===`*`||t[r]===e[r])},!0)};n.exports.getPassword=function(e,t,n){var r,i=t.pipe(a());function o(t){var n=b(t);n&&x(n)&&y(e,n)&&(r=n[_],i.end())}var s=function(){t.destroy(),n(r)},c=function(e){t.destroy(),v(`WARNING: error on reading file: %s`,e),n(void 0)};t.on(`error`,c),i.on(`data`,o).on(`end`,s).on(`error`,c)};var b=n.exports.parseLine=function(e){if(e.length<11||e.match(/^\s+#/))return null;for(var t=``,n=``,r=0,i=0,a={},o=!1,s=function(t,n,r){var i=e.substring(n,r);Object.hasOwnProperty.call(process.env,`PGPASS_NO_DEESCAPE`)||(i=i.replace(/\\([:\\])/g,`$1`)),a[h[t]]=i},c=0;c<e.length-1;c+=1){if(t=e.charAt(c+1),n=e.charAt(c),o=r==g-1,o){s(r,i);break}c>=0&&t==`:`&&n!==`\\`&&(s(r,i,c+1),i=c+2,r+=1)}return a=Object.keys(a).length===g?a:null,a},x=n.exports.isValidEntry=function(e){for(var t={0:function(e){return e.length>0},1:function(e){return e===`*`||(e=Number(e),isFinite(e)&&e>0&&e<9007199254740992&&Math.floor(e)===e)},2:function(e){return e.length>0},3:function(e){return e.length>0},4:function(e){return e.length>0}},n=0;n<h.length;n+=1){var r=t[n];if(!r(e[h[n]]||``))return!1}return!0}})),N4=t(((t,n)=>{E4();var r=(s4(),e(o4)),i=M4();n.exports=function(e,t){var n=i.getFileName();r.stat(n,function(a,o){if(a||!i.usePgPass(o,n))return t(void 0);var s=r.createReadStream(n);i.getPassword(e,s,t)})},n.exports.warnTo=i.warnTo})),P4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=Z2(),a=(J2(),e(q2)),o=n4(),s=r4(),c=l4(),l=d4(),u=K2(),d=w4(),f=e4(),p=a.deprecate(()=>{},`Client.activeQuery is deprecated and will be removed in pg@9.0`),m=a.deprecate(()=>{},`Client.queryQueue is deprecated and will be removed in pg@9.0.`),h=a.deprecate(()=>{},`pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code.`),g=a.deprecate(()=>{},`Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0.`),_=a.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`);function v(e,t){if(typeof e==`number`)return Number.isFinite(e)?e:t;if(typeof e==`string`&&e.trim()!==``){let n=Number(e);return Number.isFinite(n)?n:t}return t}var y=class extends r{constructor(e){super(),this.connectionParameters=new c(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let t=e||{};t.Promise&&g(),this._Promise=t.Promise||global.Promise,this._types=new s(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!t.enableChannelBinding,this.scramMaxIterations=v(t.scramMaxIterations,o.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=t.connection||new d({stream:t.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||`utf8`}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!t.pipeline,this.binary=t.binary||u.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||`postgres`,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return p(),this._activeQuery}set activeQuery(e){p(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=t=>{process.nextTick(()=>{t.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._sentQueryQueue.forEach(t),this._sentQueryQueue.length=0,this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let t=Error(`Client has already been connected. You cannot reuse a client.`);process.nextTick(()=>{e(t)})}else this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(Error(`timeout expired`))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf(`/`)===0?n.connect(this.host+`/.s.PGSQL.`+this.port):n.connect(this.port,this.host),n.on(`connect`,function(){t.ssl?t.sslNegotiation!==`direct`&&n.requestSsl():n.startup(t.getStartupConf())}),n.on(`sslconnect`,function(){n.startup(t.getStartupConf())}),this._attachListeners(n),n.once(`end`,()=>{let e=this._ending?Error(`Connection terminated`):Error(`Connection terminated unexpectedly`);clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(e),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(e):this._handleErrorEvent(e):this._connectionError||this._handleErrorEvent(e)),process.nextTick(()=>{this.emit(`end`)})})}connect(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})}_attachListeners(e){e.on(`authenticationCleartextPassword`,this._handleAuthCleartextPassword.bind(this)),e.on(`authenticationMD5Password`,this._handleAuthMD5Password.bind(this)),e.on(`authenticationSASL`,this._handleAuthSASL.bind(this)),e.on(`authenticationSASLContinue`,this._handleAuthSASLContinue.bind(this)),e.on(`authenticationSASLFinal`,this._handleAuthSASLFinal.bind(this)),e.on(`backendKeyData`,this._handleBackendKeyData.bind(this)),e.on(`error`,this._handleErrorEvent.bind(this)),e.on(`errorMessage`,this._handleErrorMessage.bind(this)),e.on(`readyForQuery`,this._handleReadyForQuery.bind(this)),e.on(`notice`,this._handleNotice.bind(this)),e.on(`rowDescription`,this._handleRowDescription.bind(this)),e.on(`dataRow`,this._handleDataRow.bind(this)),e.on(`portalSuspended`,this._handlePortalSuspended.bind(this)),e.on(`emptyQuery`,this._handleEmptyQuery.bind(this)),e.on(`commandComplete`,this._handleCommandComplete.bind(this)),e.on(`parseComplete`,this._handleParseComplete.bind(this)),e.on(`copyInResponse`,this._handleCopyInResponse.bind(this)),e.on(`copyData`,this._handleCopyData.bind(this)),e.on(`notification`,this._handleNotification.bind(this))}_getPassword(e){let t=this.connection;if(typeof this.password==`function`)this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(n=>{if(n!==void 0){if(typeof n!=`string`){t.emit(`error`,TypeError(`Password must be a string`));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(e=>{t.emit(`error`,e)});else if(this.password!==null)e();else try{N4()(this.connectionParameters,t=>{t!==void 0&&(h(),this.connectionParameters.password=this.password=t),e()})}catch(e){this.emit(`error`,e)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let t=await f.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(e){this.emit(`error`,e)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=o.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}})}async _handleAuthSASLContinue(e){try{await o.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(e){this.connection.emit(`error`,e)}}_handleAuthSASLFinal(e){try{o.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(e){this.connection.emit(`error`,e)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&=(this._connectionCallback(null,this),null),this.emit(`connect`));let t=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit(`error`,e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit(`error`,e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();t?(this._activeQuery=null,t.name&&delete this.connection.submittedNamedStatements[t.name],t.handleError(e,this.connection)):this._handleErrorEvent(e)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected rowDescription message from backend.`);this._handleErrorEvent(e)}else t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected dataRow message from backend.`);this._handleErrorEvent(e)}else t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected portalSuspended message from backend.`);this._handleErrorEvent(e)}else t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected emptyQuery message from backend.`);this._handleErrorEvent(e)}else t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected commandComplete message from backend.`);this._handleErrorEvent(e)}else t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let e=Error(`Received unexpected parseComplete message from backend.`);this._handleErrorEvent(e)}else e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyInResponse message from backend.`);this._handleErrorEvent(e)}else t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let e=Error(`Received unexpected copyData message from backend.`);this._handleErrorEvent(e)}else t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit(`notification`,e)}_handleNotice(e){this.emit(`notice`,e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=``+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){let t=this.connection;this.host&&this.host.indexOf(`/`)===0?t.connect(this.host+`/.s.PGSQL.`+this.port):t.connect(this.port,this.host),t.on(`connect`,function(){t.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(t)===-1?e._sentQueryQueue.indexOf(t)!==-1&&(t.callback=()=>{}):e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return i.escapeIdentifier(e)}escapeLiteral(e){return i.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline)this._pulsePipelinedQueryQueue();else if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit(`drain`))}}_pulsePipelinedQueryQueue(){if(this._connected&&this._queryable){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let t=e.submit(this.connection);t?process.nextTick(()=>{e.handleError(t,this.connection)}):this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit(`drain`)}}query(e,t,n){let r,i;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)i=r=e,r.callback||(typeof t==`function`?r.callback=t:n&&(r.callback=n));else if(r=new l(e,t,n),!r.callback)i=new this._Promise((e,t)=>{r.callback=(n,r)=>n?t(n):e(r)}).catch(e=>{throw Error.captureStackTrace(e),e});else if(typeof r.callback!=`function`)throw TypeError(`callback is not a function`);let a=e.query_timeout||this.connectionParameters.query_timeout;if(a){let e=r.callback||(()=>{}),t=setTimeout(()=>{let t=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(t,this.connection)}),e(t),r.callback=()=>{};let n=this._queryQueue.indexOf(r);if(n>-1)this._queryQueue.splice(n,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},a);r.callback=(n,r)=>{clearTimeout(t),e(n,r)}}if(this.binary&&!r.binary&&(r.binary=!0),r._result&&!r._result._types&&(r._result._types=this._types),this.pipeline){let t=typeof e.submit==`function`&&!(r instanceof l)?`Custom query classes such as pg-cursor and pg-query-stream are`:r.rows?"The `rows` option is":null;if(t)return process.nextTick(()=>{r.handleError(Error(`${t} not supported in pipeline mode`),this.connection)}),i}return this._queryable?this._ending?(process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`),this.connection)}),i):(this._queryQueue.length>0&&!this.pipeline&&_(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended){if(e){e();return}return this._Promise.resolve()}if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once(`drain`,()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once(`end`,e);else return new this._Promise(e=>{this.connection.once(`end`,e)})}get queryQueue(){return m(),this._queryQueue}};y.Query=l,n.exports=y})),F4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=function(){},a=(e,t)=>{let n=e.findIndex(t);return n===-1?void 0:e.splice(n,1)[0]},o=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},s=class{constructor(e){this.callback=e}};function c(){throw Error(`Release called on client which has already been released to the pool.`)}function l(e,t){if(t)return{callback:t,result:void 0};let n,r;return{callback:function(e,t){e?n(e):r(t)},result:new e(function(e,t){r=e,n=t}).catch(e=>{throw Error.captureStackTrace(e),e})}}function u(e,t){return function n(r){r.client=t,t.removeListener(`error`,n),t.on(`error`,()=>{e.log(`additional client error after disconnection due to error`,r)}),e._remove(t),e.emit(`error`,r,t)}}n.exports=class extends r{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&`password`in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||t||H4().Client,this.Promise=this.options.Promise||global.Promise,this.options.idleTimeoutMillis===void 0&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let t=this.Promise;return typeof t.try==`function`?t.try(e):new t(t=>t(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log(`pulse queue`),this.ended){this.log(`pulse queue ended`);return}if(this.ending){this.log(`pulse queue on ending`),this._idle.length&&this._idle.slice().map(e=>{this._remove(e.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log(`no queued requests`);return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let r=t.idleListener;return this._acquireClient(n,e,r,!1)}if(!this._isFull())return this.newClient(e);throw Error(`unexpected condition`)}_remove(e,t){let n=a(this._idle,t=>t.client===e);n!==void 0&&clearTimeout(n.timeoutId),this._clients=this._clients.filter(t=>t!==e);let r=this;e.end(()=>{r.emit(`remove`,e),typeof t==`function`&&t()})}connect(e){if(this.ending){let t=Error(`Cannot use a pool after calling end on the pool`);return e?e(t):this.Promise.reject(t)}let t=l(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new s(t.callback)),n;let e=(e,n,r)=>{clearTimeout(i),t.callback(e,n,r)},r=new s(e),i=setTimeout(()=>{a(this._pendingQueue,t=>t.callback===e),r.timedOut=!0,t.callback(Error(`timeout exceeded when trying to connect`))},this.options.connectionTimeoutMillis);return i.unref&&i.unref(),this._pendingQueue.push(r),n}return this.newClient(new s(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=u(this,t);this.log(`checking client timeout`);let r,a=!1;this.options.connectionTimeoutMillis&&(r=setTimeout(()=>{t.connection?(this.log(`ending client due to timeout`),a=!0,t.connection.stream.destroy()):t.isConnected()||(this.log(`ending client due to timeout`),a=!0,t.end())},this.options.connectionTimeoutMillis)),this.log(`connecting new client`),t.connect(o=>{if(r&&clearTimeout(r),t.on(`error`,n),o)this.log(`client failed to connect`,o),this._clients=this._clients.filter(e=>e!==t),a&&(o=Error(`Connection terminated due to connection timeout`,{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,i);else{if(this.log(`new client connected`),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},n=>{this._clients=this._clients.filter(e=>e!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(n,void 0,i)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,n){if(this.options.maxLifetimeSeconds!==0){let t=setTimeout(()=>{this.log(`ending client due to expired lifetime`),this._expired.add(e),this._idle.findIndex(t=>t.client===e)!==-1&&this._acquireClient(e,new s((e,t,n)=>n()),n,!1)},this.options.maxLifetimeSeconds*1e3);t.unref(),e.once(`end`,()=>clearTimeout(t))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,r){r&&this.emit(`connect`,e),this.emit(`acquire`,e),e.release=this._releaseOnce(e,n),e.removeListener(`error`,n),t.timedOut?r&&this.options.verify?this.options.verify(e,e.release):e.release():r&&this.options.verify?this.options.verify(e,n=>{if(n)return e.release(n),t.callback(n,void 0,i);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return r=>{n&&c(),n=!0,this._release(e,t,r)}}_release(e,t,n){if(e.on(`error`,t),e._poolUseCount=(e._poolUseCount||0)+1,this.emit(`release`,n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log(`remove expended client`),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log(`remove expired client`),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let r;this.options.idleTimeoutMillis&&this._isAboveMin()&&(r=setTimeout(()=>{this._isAboveMin()&&(this.log(`remove idle client`),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&r.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new o(e,t,r)),this._pulseQueue()}query(e,t,n){if(typeof e==`function`){let t=l(this.Promise,e);return setImmediate(function(){return t.callback(Error(`Passing a function as the first parameter to pool.query is not supported`))}),t.result}typeof t==`function`&&(n=t,t=void 0);let r=l(this.Promise,n);return n=r.callback,this.connect((r,i)=>{if(r)return n(r);let a=!1,o=e=>{a||(a=!0,i.release(e),n(e))};i.once(`error`,o),this.log(`dispatching query`);try{i.query(e,t,(e,t)=>{if(this.log(`query dispatched`),i.removeListener(`error`,o),!a)return a=!0,i.release(e),e?n(e):n(void 0,t)})}catch(e){return i.release(e),n(e)}}),r.result}end(e){if(this.log(`ending`),this.ending){let t=Error(`Called end on pool more than once`);return e?e(t):this.Promise.reject(t)}this.ending=!0;let t=l(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+ +!!this._expired.has(t),0)}get totalCount(){return this._clients.length}}})),I4=c({default:()=>L4}),L4,R4=r(()=>{throw L4={},Error(`Could not resolve "pg-native" imported by "pg". Is it installed?`)}),z4=t(((t,n)=>{var r=(P2(),e(N2)).EventEmitter,i=(J2(),e(q2)),a=Z2(),o=n.exports=function(e,t,n){r.call(this),e=a.normalizeQueryConfig(e,t,n),this.text=e.text,this.values=e.values,this.name=e.name,this.queryMode=e.queryMode,this.callback=e.callback,this.state=`new`,this._arrayMode=e.rowMode===`array`,this._emitRowEvents=!1,this.on(`newListener`,function(e){e===`row`&&(this._emitRowEvents=!0)}.bind(this))};i.inherits(o,r);var s={sqlState:`code`,statementPosition:`position`,messagePrimary:`message`,messageDetail:`detail`,messageHint:`hint`,context:`where`,schemaName:`schema`,tableName:`table`,columnName:`column`,dataTypeName:`dataType`,constraintName:`constraint`,sourceFile:`file`,sourceLine:`line`,sourceFunction:`routine`};o.prototype.handleError=function(e){let t=this.native&&this.native.pq.resultErrorFields();if(t)for(let n in t){let r=s[n]||n;e[r]=t[n]}this.callback?this.callback(e):this.emit(`error`,e),this.state=`error`},o.prototype.then=function(e,t){return this._getPromise().then(e,t)},o.prototype.catch=function(e){return this._getPromise().catch(e)},o.prototype._getPromise=function(){return this._promise||=new Promise(function(e,t){this._once(`end`,e),this._once(`error`,t)}.bind(this)),this._promise},o.prototype.submit=function(e){this.state=`running`;let t=this;this.native=e.native,e.native.arrayMode=this._arrayMode;let n=function(n,r,i){if(e.native.arrayMode=!1,setImmediate(function(){t.emit(`_done`)}),n)return t.handleError(n);t._emitRowEvents&&(i.length>1?r.forEach((e,n)=>{e.forEach(e=>{t.emit(`row`,e,i[n])})}):r.forEach(function(e){t.emit(`row`,e,i)})),t.state=`end`,t.emit(`end`,i),t.callback&&t.callback(null,i)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error(`Warning! Postgres only supports 63 characters for query names.`),console.error(`You supplied %s (%s)`,this.name,this.name.length),console.error(`This can cause conflicts and silent errors executing queries`));let r=(this.values||[]).map(a.prepareValue);if(e.namedQueries[this.name]!==void 0){if(this.text&&e.namedQueries[this.name]!==this.text){let e=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(e)}return e.native.execute(this.name,r,n)}return e.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(e.namedQueries[t.name]=t.text,t.native.execute(t.name,r,n))})}if(this.values){if(!Array.isArray(this.values))return n(Error(`Query values must be an array`));let t=this.values.map(a.prepareValue);e.native.query(this.text,t,n)}else this.queryMode===`extended`?e.native.query(this.text,[],n):e.native.query(this.text,n)}})),B4=t(((t,n)=>{var r=(J2(),e(q2)),i;try{i=(R4(),e(I4))}catch(e){throw e}var a=r4(),o=(P2(),e(N2)).EventEmitter,s=(J2(),e(q2)),c=l4(),l=z4(),u=r.deprecate(()=>{},`Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.`),d=n.exports=function(e){o.call(this),e||={},this._Promise=e.Promise||global.Promise,this._types=new a(e.types),this.native=new i({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!e.pipeline,this._pipelineInFlight=!1;let t=this.connectionParameters=new c(e);e.nativeConnectionString&&(t.nativeConnectionString=e.nativeConnectionString),this.user=t.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:t.password}),this.database=t.database,this.host=t.host,this.port=t.port,this.namedQueries={}};d.Query=l,s.inherits(d,o),d.prototype._errorAllQueries=function(e){let t=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(e)})};this._hasActiveQuery()&&(t(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0},d.prototype._connect=function(e){let t=this;this._connecting?process.nextTick(()=>e(Error(`Client has already been connected. You cannot reuse a client.`))):(this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(t.connectionParameters.nativeConnectionString&&(r=t.connectionParameters.nativeConnectionString),n)return e(n);t.native.connect(r,function(n){if(n)return t.native.end(),e(n);t._connected=!0,t.native.on(`error`,function(e){t._queryable=!1,t._errorAllQueries(e),t.emit(`error`,e)}),t.native.on(`notification`,function(e){t.emit(`notification`,{channel:e.relname,payload:e.extra})}),t.emit(`connect`),t._pulseQueryQueue(!0),e(null,this)})}))},d.prototype.connect=function(e){if(e)this._connect(e);else return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})},d.prototype.query=function(e,t,n){let r,i,a,o,s;if(e==null)throw TypeError(`Client was passed a null or undefined query`);if(typeof e.submit==`function`)a=e.query_timeout||this.connectionParameters.query_timeout,i=r=e,typeof t==`function`&&(e.callback=t);else if(a=e.query_timeout||this.connectionParameters.query_timeout,r=new l(e,t,n),!r.callback){let e,t;i=new this._Promise((n,r)=>{e=n,t=r}).catch(e=>{throw Error.captureStackTrace(e),e}),r.callback=(n,r)=>n?t(n):e(r)}return a&&(s=r.callback||(()=>{}),o=setTimeout(()=>{let e=Error(`Query read timeout`);process.nextTick(()=>{r.handleError(e,this.connection)}),s(e),r.callback=()=>{};let t=this._queryQueue.indexOf(r);t>-1&&this._queryQueue.splice(t,1),this._pulseQueryQueue()},a),r.callback=(e,t)=>{clearTimeout(o),s(e,t)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client was closed and is not queryable`))}),i):(this._queryQueue.length>0&&!this.pipeline&&u(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(Error(`Client has encountered a connection error and is not queryable`))}),i)},d.prototype.end=function(e){let t=this;this._ending=!0,this._connecting&&!this._connected&&this.once(`connect`,()=>{this.end(()=>{})});let n;e||(n=new this._Promise(function(t,n){e=e=>e?n(e):t()}));let r=function(){t.native.end(function(){t._connected=!1,t._errorAllQueries(Error(`Connection terminated`)),process.nextTick(()=>{t.emit(`end`),e&&e()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once(`drain`,r):r(),n},d.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!==`error`&&this._activeQuery.state!==`end`},d.prototype._pulseQueryQueue=function(e){if(!this._connected)return;if(this.pipeline&&!e)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let t=this._queryQueue.shift();if(!t){e||this.emit(`drain`);return}this._activeQuery=t,t.submit(this);let n=this;t.once(`_done`,function(){n._pulseQueryQueue()})},d.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit(`drain`);return}this._pipelineInFlight=!0;let e=this,t=[],n=[],r=Z2();for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0,n.push(e);let i=e.values?e.values.map(r.prepareValue):null,a={text:e.text,name:e.name,arrayMode:e._arrayMode};i&&(a.values=i),e.name&&this.namedQueries[e.name]&&(a._alreadyPrepared=!0),t.push(a)}this.native.pipeline(t,function(t,r){if(e._pipelineInFlight=!1,t){e._connected=!1,e._queryable=!1;for(let r=0;r<n.length;r++){let i=n[r];i.native=e.native,i.handleError(t)}e._errorAllQueries(t),e.emit(`error`,t),e.emit(`end`)}else{for(let t=0;t<n.length;t++){let i=n[t],a=r[t];i.native=e.native,a.err?i.handleError(a.err):(i.name&&(e.namedQueries[i.name]=i.text),i.state=`end`,i.emit(`end`,a.result),i.callback&&i.callback(null,a.result)),setImmediate(function(){i.emit(`_done`)})}e._pulsePipelinedQueryQueue()}})},d.prototype.cancel=function(e){this._activeQuery===e?this.native.cancel(function(){}):this._queryQueue.indexOf(e)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(e),1)},d.prototype.ref=function(){},d.prototype.unref=function(){},d.prototype.setTypeParser=function(e,t,n){return this._types.setTypeParser(e,t,n)},d.prototype.getTypeParser=function(e,t){return this._types.getTypeParser(e,t)},d.prototype.isConnected=function(){return this._connected},d.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}})),V4=t(((e,t)=>{t.exports=B4()})),H4=t(((e,t)=>{var n=P4(),r=K2(),i=w4(),a=u4(),o=Z2(),s=F4(),c=r4(),{DatabaseError:l}=_4(),{escapeIdentifier:u,escapeLiteral:d}=Z2(),f=e=>class extends s{constructor(t){super(t,e)}},p=function(e){this.defaults=r,this.Client=e,this.Query=this.Client.Query,this.Pool=f(this.Client),this._pools=[],this.Connection=i,this.types=G2(),this.DatabaseError=l,this.TypeOverrides=c,this.escapeIdentifier=u,this.escapeLiteral=d,this.Result=a,this.utils=o},m=n,h=!1;try{h=!!process.env.NODE_PG_FORCE_NATIVE}catch{}h&&(m=V4()),t.exports=new p(m),Object.defineProperty(t.exports,"native",{configurable:!0,enumerable:!1,get(){let e=null;try{e=new p(V4())}catch(e){if(e.code!==`MODULE_NOT_FOUND`)throw e}return Object.defineProperty(t.exports,"native",{value:e}),e}})})),U4=s(H4(),1);U4.default.Client,U4.default.Pool,U4.default.Connection,U4.default.types,U4.default.Query,U4.default.DatabaseError,U4.default.escapeIdentifier,U4.default.escapeLiteral,U4.default.Result,U4.default.TypeOverrides,U4.default.defaults;var W4=U4.default,{Pool:G4,types:K4}=W4,q4=class extends gP{constructor(e,t,n,r,i,a,o,s,c,l,u){super({sql:t,params:n},i,a,o),this.client=e,this.queryString=t,this.params=n,this.logger=r,this.fields=s,this._isResponseInArrayMode=l,this.customResultMapper=u,this.rawQueryConfig={name:c,text:t,types:{getTypeParser:(e,t)=>e===K4.builtins.TIMESTAMPTZ||e===K4.builtins.TIMESTAMP||e===K4.builtins.DATE||e===K4.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:K4.getTypeParser(e,t)}},this.queryConfig={name:c,text:t,rowMode:`array`,types:{getTypeParser:(e,t)=>e===K4.builtins.TIMESTAMPTZ||e===K4.builtins.TIMESTAMP||e===K4.builtins.DATE||e===K4.builtins.INTERVAL||e===1231||e===1115||e===1185||e===1187||e===1182?e=>e:K4.getTypeParser(e,t)}}}static[W]=`NodePgPreparedQuery`;rawQueryConfig;queryConfig;async execute(e={}){return Mk.startActiveSpan(`drizzle.execute`,async()=>{let t=eA(this.params,e);this.logger.logQuery(this.rawQueryConfig.text,t);let{fields:n,rawQueryConfig:r,client:i,queryConfig:a,joinsNotNullableMap:o,customResultMapper:s}=this;if(!n&&!s)return Mk.startActiveSpan(`drizzle.driver.execute`,async e=>(e?.setAttributes({"drizzle.query.name":r.name,"drizzle.query.text":r.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(r.text,t,async()=>await i.query(r,t))));let c=await Mk.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":a.name,"drizzle.query.text":a.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(a.text,t,async()=>await i.query(a,t))));return Mk.startActiveSpan(`drizzle.mapResponse`,()=>s?s(c.rows):c.rows.map(e=>gA(n,e,o)))})}all(e={}){return Mk.startActiveSpan(`drizzle.execute`,()=>{let t=eA(this.params,e);return this.logger.logQuery(this.rawQueryConfig.text,t),Mk.startActiveSpan(`drizzle.driver.execute`,e=>(e?.setAttributes({"drizzle.query.name":this.rawQueryConfig.name,"drizzle.query.text":this.rawQueryConfig.text,"drizzle.query.params":JSON.stringify(t)}),this.queryWithCache(this.rawQueryConfig.text,t,async()=>this.client.query(this.rawQueryConfig,t)).then(e=>e.rows)))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},J4=class e extends _P{constructor(e,t,n,r={}){super(t),this.client=e,this.schema=n,this.options=r,this.logger=r.logger??new mA,this.cache=r.cache??new mP}static[W]=`NodePgSession`;logger;cache;prepareQuery(e,t,n,r,i,a,o){return new q4(this.client,e.sql,e.params,this.logger,this.cache,a,o,t,n,r,i)}async transaction(t,n){let r=this.client instanceof G4||Object.getPrototypeOf(this.client).constructor.name.includes(`Pool`),i=r?new e(await this.client.connect(),this.dialect,this.schema,this.options):this,a=new Y4(this.dialect,i,this.schema);await a.execute(q`begin${n?q` ${a.getTransactionConfigSQL(n)}`:void 0}`);try{let e=await t(a);return await a.execute(q`commit`),e}catch(e){throw await a.execute(q`rollback`),e}finally{r&&i.client.release()}}async count(e){let t=await this.execute(e);return Number(t.rows[0].count)}},Y4=class e extends vP{static[W]=`NodePgTransaction`;async transaction(t){let n=`sp${this.nestedIndex+1}`,r=new e(this.dialect,this.session,this.schema,this.nestedIndex+1);await r.execute(q.raw(`savepoint ${n}`));try{let e=await t(r);return await r.execute(q.raw(`release savepoint ${n}`)),e}catch(e){throw await r.execute(q.raw(`rollback to savepoint ${n}`)),e}}},X4=class{constructor(e,t,n={}){this.client=e,this.dialect=t,this.options=n}static[W]=`NodePgDriver`;createSession(e){return new J4(this.client,this.dialect,e,{logger:this.options.logger,cache:this.options.cache})}},Z4=class extends fP{static[W]=`NodePgDatabase`};function Q4(e,t={}){let n=new VN({casing:t.casing}),r;t.logger===!0?r=new pA:t.logger!==!1&&(r=t.logger);let i;if(t.schema){let e=yee(t.schema,Cee);i={fullSchema:t.schema,schema:e.tables,tableNamesMap:e.tableNamesMap}}let a=new Z4(n,new X4(e,n,{logger:r,cache:t.cache}).createSession(i),i);return a.$client=e,a.$cache=t.cache,a.$cache&&(a.$cache.invalidate=t.cache?.onMutate),a}function $4(...e){if(typeof e[0]==`string`)return Q4(new W4.Pool({connectionString:e[0]}),e[1]);if(wA(e[0])){let{connection:t,client:n,...r}=e[0];return Q4(n||(typeof t==`string`?new W4.Pool({connectionString:t}):new W4.Pool(t)),r)}return Q4(e[0],e[1])}(e=>{function t(e){return Q4({},e)}e.mock=t})($4||={});var e3={};function t3(){let e=by(`DATABASE_URL`);if(e)return e;let t=by(`HYPERDRIVE`);if(t?.connectionString)return t.connectionString;throw Error(`db: PostgreSQL is not configured. Add DATABASE_URL to .env for local dev, or configure Hyperdrive for production.`)}function n3(){return $4({connection:{connectionString:t3(),max:1,idleTimeoutMillis:1e3}}).$client}function r3(){return hy(e3,n3,n3)}function i3(e,t={}){let n=new Map,r;return new Proxy({},{get(n,r){if(Object.hasOwn(t,r))return t[r];let i=e(),a=Reflect.get(i,r);return typeof a==`function`?a.bind(i):a},has(r,i){return Object.hasOwn(t,i)?!0:(n.has(i)||n.set(i,Reflect.has(e(),i)),n.get(i))},getPrototypeOf:()=>r??=Object.getPrototypeOf(e())})}var a3,o3=new Proxy({},{get(e,t){hy(e3,n3,()=>void 0),a3??=$4({client:i3(r3),schema:VP});let n=Reflect.get(a3,t);return typeof n==`function`?n.bind(a3):n}}),$=o3;async function s3(e,t){let{account:n,assertion:r,client:i,credential:a,userId:o}=t,s=await Z(e,BB($,{account:n,authenticatorData:r.metadata.authenticatorData,clientId:CV,clientDataJSON:r.metadata.clientDataJSON,credentialId:r.id,expiry:Math.floor(Date.now()/1e3)+300,signature:r.signature,userId:o,verify:e=>e.account===n.toLowerCase()&&e.clientId===`tempo-id:account-config`&&e.credential.id===a.id&&e.credential.publicKey===a.publicKey&&r.id===a.id&&WB(r,{challenge:e.digest,origin:new URL(U.URL).origin,publicKey:a.publicKey,rpId:a.rpId})}),`Passkey.takeSignature`),c=s?await Z(e,BV($,{digest:s.digest,userId:o}),`ConfigurableAccount.takePending`):void 0;if(!s||!c)return new cB;let l=t.link?await Z(e,t.link(),`Configure.link`):void 0;if(l)return l;let u=await _3(e,()=>RV({assertion:r,client:i,current:c.current,digest:s.digest,publicKey:a.publicKey,target:c.target,transaction:c.transaction}));return await Z(e,IV($,{config:u,userId:o}),`db.accountConfig.save`),u}(function(e){e.errors=[...OI.errors,vV,cB,y2]})(s3||={});async function c3(e,t){let{account:n,clientId:r,userId:i}=t,a=d3({chain:t.chain});if(a instanceof vI)return a;let o=await Z(e,l3(e,{clientId:r}),`Configure.reach`),s=await Z(e,C2(e,{chainId:a.chainId,db:$,env:U,realms:o,userId:i}),`TempoAccount.held`),c=s.find(e=>Yz(e).toLowerCase()===n.toLowerCase());return c?{chain:a,client:kV({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:a.chainId}),chain:a}),current:PV(c),owner:c,owners:s,realms:o}:new y2({account:n})}(function(e){e.errors=[...C2.errors,yV,y2]})(c3||={});async function l3(e,t){let n=await Z(e,oW(e,{clientId:t.clientId,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`);return await Z(e,uW(e,{db:$,origin:U.URL,realms:n}),`Realm.withDefaults`)}async function u3(e,t){let{account:n,client:r,credential:i,current:a,target:o,userId:s}=t,c=await _3(e,()=>FV({client:r,current:a,publicKey:i.publicKey,target:o}));return await Z(e,MB($,{account:n,clientId:CV,credential:i,digest:c.digest,userId:s}),`Passkey.requestSignature`),await Z(e,zV($,{current:a,digest:c.digest,target:o,transaction:c.transaction,userId:s}),`ConfigurableAccount.storePending`),eC({challenge:c.digest,credentialId:[i.id],rpId:i.rpId,userVerification:`required`}).options}function d3(e){let t=DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS});return(e.chain===void 0?t[0]:t.find(t=>t.name===e.chain))||new yV({chain:e.chain,configured:t.map(e=>e.name)})}async function f3(e,t){let{email:n,realms:r}=t;if(!r.some(e=>e.id==="default")||!(DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).length>0)||!e.env.WALLET)return!1;let i=await Z(e,j2(e.env.WALLET,{email:n}),`Wallet.credentials`).catch(t=>{Zt(e,{error:t,message:`The wallet service failed a passkey lookup by email, so no cloud wallet was created.`})});return!i||(await v3(e,{listed:i})).length>0}async function p3(e,t){return e.env.WALLET?await v3(e,{listed:await Z(e,j2(e.env.WALLET,{email:t.email}),`Wallet.credentials`).catch(t=>(Zt(e,{error:t,message:`The wallet service failed a passkey lookup by email.`}),[]))}):[]}async function m3(e,t){let{clientId:n,credentialId:r,email:i,userId:a}=t;if(t.account){let r=await Z(e,c3(e,{account:t.account,chain:t.chain,clientId:n,userId:a}),`Configure.find`);if(r instanceof vI)return r;let{owner:i}=r,o=Yz(i);return r.current?new xV({account:o,owner:`configurable`}):i.credential?{account:o,chain:r.chain,client:r.client,credential:i.credential,link:void 0,owners:r.owners,realm:i.realm}:new bV({account:o,reason:`cloud`})}let o=d3({chain:t.chain});if(o instanceof vI)return o;let s=await Z(e,l3(e,{clientId:n}),`Configure.reach`),c=s.find(e=>e.id===rW),l=c?OB([c],{origin:U.URL}):void 0;if(!c||!l)return new oB({clientId:n});let u=r,d=new y2({account:u,field:`credentialId`}),f=e.env.WALLET?await Z(e,A2(e.env.WALLET,{id:u}),`Wallet.credential`).catch(t=>{throw Zt(e,{error:t,message:`The wallet service failed a passkey lookup.`}),t instanceof Error&&OI(t)||new TI}):void 0;if(!f||f.email?.toLowerCase()!==i.toLowerCase())return d;let p=await Z(e,C2(e,{chainId:o.chainId,db:$,env:U,realms:s,userId:a}),`TempoAccount.held`),m=L(f.address);return p.some(e=>e.configurable&&Se(Xz(e),m))?new xV({account:m,owner:`configurable`}):{account:m,chain:o,client:kV({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:o.chainId}),chain:o}),credential:{id:u,publicKey:f.publicKey,rpId:l.rpId},link:async()=>await Z(e,xB($,{credential:f,id:u,rpId:l.rpId,userId:a}),`Passkey.link`)===a?void 0:d,owners:p,realm:c}}(function(e){e.errors=[...OI.errors,...c3.errors,bV,xV,oB]})(m3||={});async function h3(e,t){let{client:n,current:r,signing:i,target:a,userId:o}=t,s=await Z(e,i.signer(e,{auth:e.var.auth}),`Owner.signer`),c=await _3(e,()=>LV({account:s,client:n,current:r,target:a}));return await Z(e,IV($,{config:c,userId:o}),`db.accountConfig.save`),c}(function(e){e.errors=[...OI.errors,vV]})(h3||={});function g3(e,t){return t.current?e.configurable.owner:e}async function _3(e,t){try{return await Z(e,t(),`ConfigurableAccount.send`)}catch(t){if(t instanceof vI)throw t;if(t instanceof Error){let e=OI(t);if(e)throw e}throw Zt(e,{error:t,message:`The chain did not install the account configuration.`}),new TI}}(function(e){e.errors=[...OI.errors,vV]})(_3||={});async function v3(e,t){let{listed:n}=t;if(n.length===0)return[];let r=await Z(e,$.select({id:KP.id}).from(KP).where($M(KP.id,n.map(e=>e.credentialId))),`db.keys.linked`);return n.filter(e=>!r.some(t=>t.id===e.credentialId))}var y3=`__Host-tempo-id-account`,b3=3456e4,x3;(function(e){e.value=z({apps:Wn(R(),R()),session:R()})})(x3||={});async function S3(e,t){return(await Z(e,O3(e,t),`AccountStep.held`)).map(O2)}(function(e){e.errors=C2.errors})(S3||={});function C3(){return ce(y3,``,{httpOnly:!0,maxAge:0,path:`/`,sameSite:`Lax`,secure:!0})}async function w3(e,t){let n=await Z(e,P3(e,t),`AccountStep.realms`),r={chainId:t.chainId,db:$,env:U,realms:n,userId:t.userId},[i]=await Z(e,$.select({email:RP.email}).from(RP).where(Y(RP.id,t.userId)),`db.user.get`);return i&&await Z(e,f3(e,{email:i.email,realms:n}),`Configure.awaitsUpgrade`)?await Z(e,C2(e,r),`TempoAccount.held`):await Z(e,S2(e,r),`TempoAccount.create`)}(function(e){e.errors=S2.errors})(w3||={});async function T3(e,t){let n=(await Z(e,P3(e,t),`AccountStep.realms`))[0];return n!==void 0&&(n.privy!==void 0||n.secp256k1)}async function E3(e,t){if(!(await Z(e,e.env.ACCOUNT_LIMIT.limit({key:t.userId}),`ratelimit.limit`)).success)return!1;let n=await Z(e,S3(e,t),`AccountStep.accounts`).catch(n=>(Zt(e,{error:n,fields:{clientId:t.clientId},message:`The account step skipped an authorization whose accounts failed to load.`}),[]));return n.length<=1?!1:!D3(n,j3(t))}function D3(e,t){if(t)return e.find(e=>e.address.toLowerCase()===t.toLowerCase())}async function O3(e,t){let n=await Z(e,P3(e,t),`AccountStep.realms`);return await Z(e,C2(e,{chainId:t.chainId,db:$,env:U,realms:n,userId:t.userId}),`TempoAccount.held`)}(function(e){e.errors=C2.errors})(O3||={});function k3(e,t){let n=D3(e,j3(t));return n?[n,...e.filter(e=>e!==n)]:e}function A3(e){let t=(e.cookie??``).split(`;`).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`__Host-tempo-id-account=`)),n=M3(e.clientId),{[n]:r,...i}=N3(e),a=JSON.stringify({apps:{...Object.fromEntries(Object.entries(i).slice(-15)),[n]:e.account},session:e.sessionId});return{header:[...t,`${y3}=${encodeURIComponent(a)}`].join(`; `),setCookie:ce(y3,a,{httpOnly:!0,maxAge:b3,path:`/`,sameSite:`Lax`,secure:!0})}}function j3(e){let t=N3(e),n=M3(e.clientId);return Object.hasOwn(t,n)?t[n]:void 0}function M3(e){if(!ZF(e))return e;let t=Pt(pt(e));return`cimd:${Lt(t.slice(0,16),{pad:!1,url:!0})}`}function N3(e){let t=ue(e.cookie??``,y3)[y3];if(!t)return{};try{let n=x3.value.safeParse(JSON.parse(t));return!n.success||n.data.session!==e.sessionId?{}:n.data.apps}catch{return{}}}async function P3(e,t){let n=await Z(e,hV(e,()=>aW($,{clientId:t.clientId}),[`realm.forApp`,t.clientId]),`Realm.forApp`);return await Z(e,uW(e,{db:$,origin:U.URL,realms:n}),`Realm.withDefaults`)}var F3=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}},I3=({limitLength:e=255,headerName:t=`X-Request-Id`,generator:n=()=>crypto.randomUUID()}={})=>async function(r,i){let a=t?r.req.header(t):void 0;(!a||a.length>e||/[^\w\-=]/.test(a))&&(a=n(r)),r.set(`requestId`,a),t&&r.header(t,a),await i()},L3=`X-Request-Id`;function R3(){let e=I3({generator:H3,headerName:``});return QB(async(t,n)=>{await e(t,n);let r=t.var.requestId,i=t.res,a=V3(i)?await Z(t,W3(i),`response.json`):void 0;a&&t.set(`refusal`,z3(t,{body:a,id:r})),t.header(L3,r)})}function z3(e,t){let n=e.res;return e.res=new Response(JSON.stringify({...t.body,request_id:t.id}),{headers:n.headers,status:n.status,statusText:n.statusText}),e.header(`content-length`,void 0),{error:B3(t.body.error),reason:B3(t.body.reason)}}function B3(e){return typeof e==`string`&&/^[a-z_]{1,64}$/.test(e)?e:void 0}function V3(e){return e.status>=400&&!!e.headers.get(`content-type`)?.startsWith(`application/json`)}function H3(e){let t=e.req.header(`cf-ray`);return t&&/^[\da-f]{16}(?:-[A-Z]{3})?$/.test(t)?t:crypto.randomUUID()}function U3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function W3(e){let t=await e.clone().json().catch(()=>void 0);return U3(t)&&typeof t.error==`string`?t:void 0}var G3;(function(e){e.refusal=Xn([`foreign_account`,`no_account`,`passkey`,`unavailable`,`upgrade`]).meta({description:"Why approval cannot sign the key: the key names an account that is not the user's (`foreign_account`), the user holds no account and none can be created (`no_account`), a passkey that this page cannot use owns the account (`passkey`), the accounts could not be read (`unavailable`), or the account must upgrade to a configurable account on the key's chain first (`upgrade`). Absent when approval can sign it.",examples:[`passkey`]})})(G3||={});async function K3(e,t){let{account:n,clientId:r,key:i,owner:a,userId:o}=t,s=a.credential,c=$R({account:$z(a),key:i});return await Z(e,MB($,{account:n,clientId:r,credential:s,digest:c,userId:o}),`Passkey.requestSignature`),eC({challenge:c,credentialId:s.id,rpId:s.rpId,userVerification:`required`}).options}async function q3(e,t){let{clientId:n,sessionId:r,userId:i}=t,a=t.chainId===void 0?void 0:Number(t.chainId),o=await(async()=>{if((await Z(e,e.env.ACCOUNT_LIMIT.limit({key:i}),`ratelimit.limit`)).success)try{let o=await Z(e,O3(e,{chainId:a,clientId:n,userId:i}),`AccountStep.held`);return{owners:o,signing:await Z(e,J3(e,{account:t.account,chainId:a,clientId:n,cookie:e.req.header(`cookie`),owners:o,passkey:!0,sessionId:r,userId:i}),`KeySigner.resolve`)}}catch(t){Zt(e,{error:t,fields:{clientId:n},message:`An approval page's account owners failed to load.`});return}})(),s=o?.signing,c=s instanceof fz&&await Z(e,T3(e,{clientId:n}),`AccountStep.creates`),l=s?s instanceof kR||s instanceof SV?s.response.meta?.account:s instanceof vI?t.account:s.account:t.account,u=(()=>{if(!s)return`unavailable`;if(s instanceof y2)return`foreign_account`;if(s instanceof kR)return`passkey`;if(s instanceof SV)return`upgrade`;if(s instanceof fz&&!c)return`no_account`})();return{account:l,accounts:o?o.owners.map(O2):[],refusal:u}}async function J3(e,t){let{clientId:n,cookie:r,sessionId:i,userId:a}=t,o=t.chainId===void 0?void 0:Number(t.chainId),s=t.owners??(t.create&&!t.account?await Z(e,w3(e,{chainId:o,clientId:n,userId:a}),`AccountStep.create`):await Z(e,O3(e,{chainId:o,clientId:n,userId:a}),`AccountStep.held`)),c=s.map(O2),l=t.account,u=s.find(e=>t.oneTap!==void 0&&e.credential?.id===t.oneTap),d=l?void 0:(u&&O2(u).address)??D3(c,j3({clientId:n,cookie:r,sessionId:i}))?.address;if(t.single&&!l&&!d&&c.length>1)return new fz({description:"Several Tempo Accounts: the user holds more than one account in the app's realms and chose none. Choose the account on the account step, or name it in `key_authorization.account`."});let f=l?D3(c,l)?.address:d??c[0]?.address;if(l&&!f)return new y2({account:l,field:`key_authorization.account`});let p=f?s.find(e=>O2(e).address.toLowerCase()===f.toLowerCase()):void 0;if(!f||!p)return new fz({description:t.create?"No Tempo Account: the user holds no account in the app's realms, and the app's first realm has no Privy app to create one. Authorize without `key_authorization`.":"No Tempo Account: the user holds no account in the app's realms, so no owner signs the key. Create the account with `POST /v1/account`, or authorize without `key_authorization`."});if(p.linked&&!p.configurable&&OV({chainId:o,env:U}))return new SV({account:f});let m=eB(p,{chainId:o});return!m.signer&&!(t.passkey&&X3(m))&&(t.oneTap===void 0||m!==p||m.credential?.id!==t.oneTap)?new kR({account:f}):{account:f,owner:m}}(function(e){e.errors=[...w3.errors,...O3.errors,fz,SV,kR,y2]})(J3||={});async function Y3(e,t){let{account:n,assertion:r,key:i,owner:a}=t;if(!a.signer){if(!r||!a.credential)return new kR({account:n});let o=a.credential;return await Z(e,BB($,{account:n,authenticatorData:r.metadata.authenticatorData,clientId:t.clientId,clientDataJSON:r.metadata.clientDataJSON,credentialId:r.id,expiry:i.expiry,signature:r.signature,userId:t.userId,verify:e=>e.account===n.toLowerCase()&&e.clientId===t.clientId&&e.credential.id===o.id&&e.credential.publicKey===o.publicKey&&r.id===o.id&&e.digest===$R({account:$z(a),key:i})&&WB(r,{challenge:e.digest,origin:t.origin??new URL(U.URL).origin,publicKey:o.publicKey,rpId:o.rpId})}),`Passkey.takeSignature`)?await Z(e,tz(r,{account:$z(a),key:i,publicKey:o.publicKey}),`KeyAuthorization.signWithAssertion`):new cB}return await Z(e,ez(await Z(e,a.signer(e,{auth:e.var.auth}),`Owner.signer`),{key:i}),`KeyAuthorization.sign`)}(function(e){e.errors=[kR,cB]})(Y3||={});function X3(e){return e.credential?OB([e.realm],{origin:U.URL})?.rpId===e.credential.rpId:!1}var Z3=600,Q3=`sign-in-grant-held:`,$3=3600,e6=`sign-in-grant-spent:`,t6;(function(e){e.held=z({assertion:qn().optional(),witness:Kn([`0x`,R()]).optional()})})(t6||={});async function n6(e,t){await e.insert(BP).values({expiresAt:new Date(Date.now()+Z3*1e3),id:crypto.randomUUID(),identifier:s6(t),value:JSON.stringify(t6.held.parse({assertion:t.oneTap?.assertion,witness:t.oneTap?.witness}))})}function r6(e){let t=[`client_id`,`redirect_uri`,`state`,`code_challenge`,`key_authorization`,`challenge`,`scope`].map(t=>e.get(t)??``);return dt(Pt(pt(JSON.stringify(t))))}async function i6(e,t){let n=e6+r6(t.query),r=Number(t.query.get(`exp`));return await rB(e,{expiresAt:new Date(Number.isSafeInteger(r)&&r>0?r*1e3:Date.now()+$3*1e3),identifier:n,value:`{}`})}async function a6(e,t){let[n]=await e.select({id:BP.id}).from(BP).where(KM(Y(BP.identifier,e6+r6(t.query)),YM(BP.expiresAt,new Date))).limit(1);return n!==void 0}async function o6(e,t){let[n]=await e.delete(BP).where(KM(Y(BP.identifier,s6(t)),YM(BP.expiresAt,new Date))).returning({value:BP.value});if(n)return t6.held.parse(JSON.parse(n.value))}function s6(e){return`${Q3}${r6(e.query)}:${e.sessionId}`}async function c6(e,t){let{clientId:n,codeChallenge:r,expiry:i,key:a,userId:o}=t,s={account:a.account,expiresAt:new Date(Math.min(Date.now()+6e5,i*1e3)),keyAuthorization:a.keyAuthorization,userId:o};await e.insert(qP).values({...s,clientId:n,codeChallenge:r}).onConflictDoUpdate({set:{...s,createdAt:new Date},setWhere:Y(qP.userId,o),target:[qP.clientId,qP.codeChallenge]})}async function l6(e,t){let{clientId:n,codeChallenge:r,userId:i}=t,[a]=await e.delete(qP).where(KM(Y(qP.clientId,n),Y(qP.codeChallenge,r),YM(qP.expiresAt,new Date),Y(qP.userId,i))).returning({account:qP.account,keyAuthorization:qP.keyAuthorization});if(a)return{account:a.account,keyAuthorization:a.keyAuthorization}}var u6=z({url:R().min(1)});async function d6(e,t){let{headers:n,oauthQuery:r,session:i}=t,a=await Z(e,e.var.auth.$context,`auth.context`);if(!await Z(e,ni(r,a.secret),`auth.verifyOAuthQueryParams`))return new KB;let o=new URLSearchParams(r);p6(o);let s=f6(o)?await Z(e,m6(e,{account:t.account,assertion:t.assertion,oneTap:t.oneTap,query:o,session:i,single:t.single}),`Consent.approveKey`):void 0;if(s instanceof vI)return s;if(s&&`options`in s)return{options:s.options};let c=await Z(e,e.var.auth.api.oauth2Consent({asResponse:!1,body:{accept:!0,oauth_query:r},headers:n,request:new Request(e.req.url,{headers:n,method:`POST`})}),`auth.oauth2Consent`).catch(e=>{if(Hr(e)&&e.body?.error===`invalid_signature`)return new KB;throw e});if(c instanceof vI)return c;let l=u6.parse(c).url,u=URL.parse(l)?.searchParams.get(`code`);return s&&u&&await Z(e,c6($,{clientId:s.clientId,codeChallenge:s.codeChallenge,expiry:s.expiry,key:{account:s.account,keyAuthorization:s.signed},userId:i.user.id}),`PendingKey.put`),{redirect:l}}(function(e){e.errors=[...hz.errors,...J3.errors,...Y3.errors,KB,fz,kR,cB,lz]})(d6||={});function f6(e){return e.has(`key_authorization`)||e.has(`challenge`)}function p6(e){let t=URL.parse(e.get(`redirect_uri`)??``);if(!t||t.protocol!==`http:`&&t.protocol!==`https:`&&!ji(t))throw Error(`The app's redirect URI uses a refused scheme.`)}async function m6(e,t){let{oneTap:n,query:r,session:i}=t,a=gz(r);if(!a||a instanceof vI)return a;let o=r.get(`client_id`),s=r.get(`code_challenge`),c=await Z(e,GF($,{clientId:o}).catch(e=>{if(!(e instanceof RF))throw e}),`Apps.get`),l=hz({app:c,clientId:o,codeChallenge:s,key:a,query:r});if(l)return l;let u=await Z(e,J3(e,{account:a.account??t.account,chainId:a.chainId,clientId:o,cookie:e.req.header(`cookie`),create:!0,passkey:!0,sessionId:i.session.id,single:t.single,userId:i.user.id}),`KeySigner.resolve`);if(u instanceof kR){let e=u.response.meta?.account;return new kR({account:e,description:`Passkey required: the passkey of Tempo Account ${e} signs only at its own relying party, which the approval page is not part of. Name another account, or deny the request.`})}if(u instanceof vI)return u;let d=n&&!$z(u.owner)&&u.owner.credential?.id===n.assertion.id?n:void 0,f=d?{...a,witness:d.witness}:a,p=d?.assertion??t.assertion;if(t.assertion&&u.owner.signer)return new cB;if(!p&&!u.owner.signer)return{options:await Z(e,K3(e,{account:u.account,clientId:o,key:f,owner:u.owner,userId:i.user.id}),`KeySigner.challenge`)};d&&await Z(e,MB($,{account:u.account,clientId:o,credential:u.owner.credential,digest:$R({key:f}),userId:i.user.id}),`Passkey.requestSignature`);let m=await Z(e,Y3(e,{account:u.account,assertion:u.owner.signer?void 0:p,clientId:o,key:f,owner:u.owner,userId:i.user.id}),`KeySigner.sign`);return m instanceof vI?m:{account:u.account,clientId:o,codeChallenge:s,expiry:f.expiry,signed:m}}async function h6(e,t){return await Z(e,v6(e,t),`SignInConsent.accountStep`).catch(n=>(Zt(e,{error:n,message:`An account step kept its redirect, since its grant failed.`}),{redirect:t.redirect}))}async function g6(e,t){return await Z(e,x6(e,t),`SignInConsent.signIn`).catch(n=>(Zt(e,{error:n,message:`A sign-in kept its redirect, since its grant failed.`}),t.redirect))}async function _6(e,t){let n=new URLSearchParams(t.oauthQuery);if(!n.has(`key_authorization`)||n.has(`challenge`)||ZF(n.get(`client_id`)??``))return;let r=await Z(e,e.var.auth.$context,`auth.context`);if(!await Z(e,ni(t.oauthQuery,r.secret),`auth.verifyOAuthQueryParams`)||await Z(e,a6($,{query:n}),`SignInGrant.spent`))return;let i=gz(n);if(!i||i instanceof vI)return;let a=dt(crypto.getRandomValues(new Uint8Array(32)));return{digest:$R({key:{...i,witness:a}}),witness:a}}async function v6(e,t){let{account:n,assertion:r,headers:i,redirect:a,session:o}=t,s=URL.parse(a,U.URL);if(!s||s.origin!==new URL(U.URL).origin||s.pathname!==`/authorize`||s.searchParams.has(`challenge`))return{redirect:a};let c=await Z(e,o6($,{query:s.searchParams,sessionId:o.session.id}),`SignInGrant.take`);if(!c)return{redirect:a};let l=await y6(e,{account:n,assertion:r,headers:i,oneTap:(()=>{let e=gB.assertion.safeParse(c.assertion);if(e.success&&c.witness)return{assertion:e.data,witness:c.witness}})(),redirect:a,session:o,url:s});return`options`in l&&await Z(e,n6($,{oneTap:c.witness?{assertion:c.assertion,witness:c.witness}:void 0,query:s.searchParams,sessionId:o.session.id}),`SignInGrant.hold`),l}async function y6(e,t){let{headers:n,redirect:r,session:i,url:a}=t;if(await Z(e,sU(e,{limits:[{binding:`AUTHORIZE_LIMIT`,key:i.user.id}]}),`RateLimit.check`))return{redirect:r};let o=await Z(e,d6(e,{account:t.account,assertion:t.assertion,headers:n,oauthQuery:a.search.slice(1),oneTap:t.oneTap,session:i,single:!0}),`Consent.approve`).catch(t=>{Zt(e,{error:t,message:`A sign-in could not grant the key that the sign-in page showed.`})});return!o||o instanceof vI?{redirect:r}:`options`in o?{options:o.options}:{redirect:o.redirect}}function b6(e,t){let n=new Map((e.req.header(`cookie`)??``).split(`;`).map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf(`=`);return[e.slice(0,t),e.slice(t+1)]}));for(let e of t.setCookie){let[t=``]=e.split(`;`),r=t.indexOf(`=`);r>0&&n.set(t.slice(0,r).trim(),t.slice(r+1))}let r=new Headers(e.req.raw.headers);return r.set(`cookie`,[...n].map(([e,t])=>`${e}=${t}`).join(`; `)),r}async function x6(e,t){let{oneTap:n,redirect:r,setCookie:i}=t,a=URL.parse(r,U.URL);if(!a||a.origin!==new URL(U.URL).origin||a.pathname!==`/authorize`&&a.pathname!==`/choose-account`)return r;let o=a.searchParams;if(!o.has(`key_authorization`)||o.has(`challenge`)||ZF(o.get(`client_id`)??``))return r;let s=b6(e,{setCookie:i}),c=e.var.newSession;if(!c||!await Z(e,i6($,{query:o}),`SignInGrant.spend`))return r;if(a.pathname===`/choose-account`)return await Z(e,n6($,{oneTap:n,query:o,sessionId:c.session.id}),`SignInGrant.hold`),r;let l=await y6(e,{headers:s,oneTap:n,redirect:r,session:c,url:a});return`options`in l?r:l.redirect}var S6=`Tempo-Id-Signed-In`,C6={pad:!1,url:!0},w6=z({url:R().min(1)});async function T6(e,t){let{clientId:n}=t;return e.var.firstParty?.find(e=>e.clientId===n)||await Z(e,GF($,{clientId:n,enabled:!0}).catch(e=>{if(!(e instanceof RF))throw e}),`Apps.get`)}async function E6(e,t){let{headers:n,oneTap:r,request:i,session:a}=t,o=i.client_id,s=n.get(`cookie`)??void 0;if(!i.code_challenge&&t.secret)return new fz({description:"Tokens refused: the app holds a client secret, so its backend redeems a code. Send `code_challenge`, then redeem the code with the secret."});let c=await Z(e,sU(e,{limits:[{binding:`AUTHORIZE_LIMIT`,key:a.user.id},...r?[{binding:`ACCOUNT_LIMIT`,key:a.user.id}]:[]]}),`RateLimit.check`);if(c)return c;let l=i.key_authorization,u=l?await Z(e,J3(e,{account:l.account,chainId:l.chainId,clientId:o,cookie:s,create:!!r,oneTap:r?.assertion.id,sessionId:a.session.id,userId:a.user.id}),`KeySigner.resolve`):void 0;if(u instanceof vI)return u;let d=r&&u&&!$z(u.owner)&&u.owner.credential?.id===r.assertion.id?r:void 0,f=l&&d?{...l,witness:d.witness}:l,p=await(async()=>{if(u)return u.account;let t=await Z(e,S3(e,{chainId:l?.chainId===void 0?void 0:Number(l.chainId),clientId:o,userId:a.user.id}),`AccountStep.accounts`).catch(t=>(Zt(e,{error:t,fields:{clientId:o},message:`The headless authorization skipped an account selection whose accounts failed to load.`}),[]));return D3(t,j3({clientId:o,cookie:s,sessionId:a.session.id}))?.address??t[0]?.address})(),m=p?A3({account:p.toLowerCase(),clientId:o,cookie:s,sessionId:a.session.id}):void 0,h=new Headers(n);m&&h.set(`cookie`,m.header),e.set(`accountChosen`,!0);let g=i.code_challenge?void 0:Lt(ht(32),C6),_={client_id:o,code_challenge:i.code_challenge??Lt(Pt(pt(g)),C6),code_challenge_method:`S256`,redirect_uri:i.redirect_uri,resource:U.URL,response_type:`code`,scope:i.scope??`openid`,...i.state?{state:i.state}:{}},v=new URL(`/oauth2/authorize`,U.URL);v.search=new URLSearchParams(_).toString(),h.set(`accept`,`application/json`);let y=await Z(e,e.var.auth.api.oauth2Authorize({asResponse:!1,body:{},headers:h,query:_,request:new Request(v,{headers:h})}),`auth.oauth2Authorize`),b=w6.safeParse(y),x=b.success?URL.parse(b.data.url,U.URL):null,S=new URL(i.redirect_uri).searchParams,C=x?.searchParams.get(`code`);if(!x||!C||x.searchParams.getAll(`error`).length>S.getAll(`error`).length||!`${x.origin}${x.pathname}`.startsWith(new URL(i.redirect_uri).origin))return new fz({description:`Authorization refused: the app's request needs the user's approval, which no page shows here. Authorize through a redirect, or register the app to skip consent.`});f&&u&&d&&await Z(e,MB($,{account:u.account,clientId:o,credential:u.owner.credential,digest:$R({key:f}),userId:a.user.id}),`Passkey.requestSignature`);let w=f&&u?await Z(e,Y3(e,{account:u.account,assertion:d?.assertion,clientId:o,key:f,origin:d?.origin,owner:u.owner,userId:a.user.id}),`KeySigner.sign`):void 0;if(w instanceof vI)return w;let E={...p&&w?{account:p,key_authorization:w}:{},...i.state?{state:i.state}:{}};if(m&&(l?.account||d)&&e.header(`set-cookie`,m.setCookie,{append:!0}),e.header(`cache-control`,`no-store`),!g)return{...E,code:C};let D=await Z(e,e.var.auth.api.oauth2Token({body:{client_id:o,code:C,code_verifier:g,grant_type:`authorization_code`,redirect_uri:i.redirect_uri,resource:U.URL},headers:new Headers({"content-type":`application/x-www-form-urlencoded`})}),`auth.oauth2Token`);return{...E,tokens:pz.tokens.parse(D)}}(function(e){e.errors=[...J3.errors,...Y3.errors,fz]})(E6||={});async function D6(e,t){let{assertion:n,challenge:r,setCookie:i}=t,a=pz.request.parse(r.authorize),o=await Z(e,T6(e,{clientId:a.client_id}),`Headless.app`),s=mz(a,{app:o,origin:e.req.header(`origin`)});if(s)return s;let c=b6(e,{setCookie:i}),l=e.var.newSession;if(!l)throw Error(`The one-tap session is missing.`);return await Z(e,E6(e,{headers:c,oneTap:r.witness&&r.origin?{assertion:n,origin:r.origin,witness:r.witness}:void 0,request:a,secret:!!o.secret,session:l}),`Headless.authorize`)}(function(e){e.errors=[...mz.errors,...E6.errors]})(D6||={});async function O6(e,t){let{assertion:n,challenge:r}=t;if(r.authorize===void 0)return!0;let i=pz.request.parse(r.authorize);return i.key_authorization?i.key_authorization.expiry<=Date.now()/1e3?!1:await Z(e,zB($,{authenticatorData:n.metadata.authenticatorData,expiry:i.key_authorization.expiry,signature:n.signature}),`Passkey.spendSignIn`):!0}var k6=[...oU,L3],A6=7200,j6=new Set([`/v1/account`,`/v1/auth/code`,`/v1/auth/code/verify`,`/v1/auth/logout`,`/v1/auth/passkey/options`,`/v1/auth/passkey/verify`,`/v1/auth/providers`,`/v1/auth/session`,`/v1/authorize`,`/v1/realms`]);function M6(e){let t=e.req.header(`origin`);if(t&&![new URL(U.URL).origin,new URL(e.req.url).origin].includes(t))return t}var N6=QB(async(e,t)=>{if(!j6.has(e.req.path))return t();let n=M6(e),r=![`GET`,`HEAD`,`OPTIONS`].includes(e.req.method),i=n!==void 0&&await Z(e,(async()=>{if(r){let t=await WF($,{origin:n});return e.set(`firstParty`,t),t.length>0}return await hV(e,async()=>(await WF($,{origin:n})).length>0,[`apps.firstPartyOrigin`,n],{keep:e=>e})})(),`Apps.firstPartyOrigin`);return n&&!i&&r?X(e,new bI):F3({credentials:!0,exposeHeaders:[...k6,S6],maxAge:A6,origin:()=>i?n:null})(e,t)}),P6=F3({exposeHeaders:k6});function F6(e){let t=e.req.header(`sec-fetch-site`);if(t!==`same-origin`&&(t!==void 0||!e.req.header(`origin`)||M6(e)))return new bI}(function(e){e.errors=[bI]})(F6||={});function I6(e,t){if(t.oauth_query&&M6(e))return new bI}(function(e){e.errors=[bI]})(I6||={});async function L6(e){let t=await Z(e,e.var.auth.api.signOut({headers:new Headers,returnHeaders:!0}),`auth.signOut`);for(let n of t.headers.getSetCookie())e.header(`set-cookie`,n,{append:!0})}async function R6(e){let t=await Z(e,e.var.auth.api.getSession({headers:e.req.raw.headers,returnHeaders:!0}),`auth.getSession`);for(let n of t.headers.getSetCookie())e.header(`set-cookie`,n,{append:!0});return t.response}async function z6(e){let t=await Z(e,e.var.auth.$context,`auth.context`);return await Z(e,XV(e,t.secret,t.authCookies.sessionToken.name),`cookie.verify`)||void 0}var B6;(function(e){let t=Kn([`0x`,R().regex(/^[0-9a-fA-F]{40}$/)]),n;(function(e){e.query=z({chain:en.optional().meta({description:"The chain whose balance each account carries: `mainnet`, `testnet`, or another chain that the deployment lists. Without it, the accounts carry no balance.",examples:[`testnet`]}),client_id:R().min(1).max(255).optional().meta({description:"The app's client ID, whose realms select the accounts. A browser page from an origin that none of the app's redirect URIs has receives the `default` realm, as does a request without one.",examples:[`client_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]})}),e.response=z({email:rr().meta({description:`The user's email address.`,examples:[`ada@example.com`]}),id:R().meta({description:"The user's ID, which is the `sub` of every token Tempo ID issues for the user.",examples:[`user_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]}),name:R().nullable().meta({description:"The user's name, or `null` for a user who signed up without one.",examples:[`Ada Lovelace`]}),passkeys:nr().meta({description:"Whether the realms the request reaches hold passkeys that sign in at Tempo ID's origin. Without `client_id`, the `default` realm's, where `POST /v1/account/passkey/options` registers a passkey.",examples:[!0]}),tempo:or(x2.tempoAccount.extend({balance:aV.balance.nullable().optional().meta({description:"The value of the account's verified holdings on the chain that `chain` names, in USD, or `null` when the chain has no Tempo API URL or the read fails or takes longer than 3 seconds. Absent without `chain`."})})).readonly().meta({description:`The user's Tempo Accounts in the realms the request reaches: the account that the user selected for the app first, then oldest first.`})}).meta({id:`Account`})})(n||=e.account||={});let r;(function(e){e.json=n.query,e.response=n.response})(r||=e.create||={});let i;(function(e){e.json=z({}),e.response=z({options:z({publicKey:z({attestation:Yn(`none`).meta({description:`Tempo ID requests no attestation statement from the authenticator.`}),authenticatorSelection:z({requireResidentKey:Yn(!0).meta({description:`The passkey must be discoverable, so it signs in without an email.`}),residentKey:Yn(`required`).meta({description:`The passkey must be discoverable, so it signs in without an email.`}),userVerification:Yn(`required`).meta({description:`Every passkey registration requires user verification.`})}).meta({description:`The authenticator that the passkey requires.`}),challenge:Kn([`0x`,R()]).meta({description:`The single-use challenge, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),excludeCredentials:or(z({id:R().meta({description:`A credential ID, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`A passkey that the user holds already.`})).optional().meta({description:`The user's passkeys of the relying party, which an authenticator that holds one of them refuses to replace. Absent for a user with none.`}),pubKeyCredParams:or(z({alg:Yn(-7).meta({description:`ES256: ECDSA over P-256 with SHA-256.`}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The only key type that a Tempo Account accepts.`})).meta({description:`The key types the passkey may use: P-256 alone, which a Tempo Account verifies.`}),rp:z({id:R().meta({description:"The relying party ID of the `default` realm.",examples:[`tempo.xyz`]}),name:R().meta({description:"The `default` realm's display name.",examples:[`Tempo`]})}).meta({description:`The relying party.`}),user:z({displayName:R().meta({description:`The user's name, or the email address for a user without one.`,examples:[`Ada Lovelace`]}),id:R().meta({description:`A random user handle for this passkey, base64url, so a new passkey never replaces another in the authenticator.`,examples:[`3q2-7wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`]}),name:rr().meta({description:`The user's email address.`,examples:[`ada@example.com`]})}).meta({description:`The user, as the authenticator labels the passkey.`})}).meta({description:"The `PublicKeyCredentialCreationOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.create()`."})})})(i||=e.passkeyOptions||={});let a;(function(e){e.json=z({credential:gB.credential}),e.response=z({step:z({options:z({publicKey:z({allowCredentials:or(z({id:gB.credentialId.meta({description:`The credential ID of the new passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The new passkey.`})).meta({description:`The new passkey, the only one the browser offers.`}),challenge:Kn([`0x`,R()]).meta({description:`The single-use proof challenge, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),rpId:R().meta({description:"The relying party ID of the `default` realm.",examples:[`tempo.xyz`]}),userVerification:Yn(`required`).meta({description:`Every passkey signature requires user verification.`})}).meta({description:"The `PublicKeyCredentialRequestOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.get()`."}),type:Yn(`passkey`).meta({description:"Sign the options with the new passkey, then send the assertion to `POST /v1/account/passkey/verify`."})}).meta({description:`The next step: the new passkey's signature, which proves that the authenticator holds its private key.`})})})(a||=e.passkey||={});let o;(function(e){e.json=z({account:t.optional().meta({description:"One of the user's configurable Tempo Accounts in the `default` realm that a cloud wallet owns, on `chain`, which the passkey joins as a second owner through an update of its configuration. Absent, the passkey owns an account of its own.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),assertion:gB.assertion,chain:en.optional().meta({description:"The chain whose accounts are configurable, where `account` is, and whose address of the passkey's own account the response returns. Without it, the first such chain for `account`, and the passkey's own address otherwise.",examples:[`local`]})}),e.response=z({address:R().meta({description:"The address of the Tempo Account that the passkey owns: `account`, or the passkey's own account on `chain`, which is the address that its initial configuration derives on a chain whose accounts are configurable, and the one that its public key derives otherwise.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),id:gB.credentialId.meta({description:`The credential ID of the passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]})})})(o||=e.passkeyVerify||={});let s;(function(e){e.query=n.query.omit({chain:!0}),e.response=z({realms:or(x2.realm).readonly().meta({description:`The realms the app reaches, never empty. The first holds a user's first account.`})})})(s||=e.realms||={});let c;(function(e){e.response=z({chains:or(z({chainId:Zn().int().meta({description:`The ID of the Tempo chain that serves the name.`,examples:[42431]}),configurable:nr().meta({description:`Whether Tempo Accounts can be upgraded to configurable accounts (TIP-1107) on the chain, as the deployment sets.`,examples:[!1]}),name:en.meta({description:"The name that the `chain` parameter carries.",examples:[`testnet`]})}).meta({description:`A chain that a page can select.`})).readonly().meta({description:"The chains in order: `mainnet`, `testnet`, then the deployment's listed chains."})})})(c||=e.chains||={});let l;(function(e){e.response=z({chains:or(z({api:Xn([`down`,`none`,`up`]).meta({description:"Whether the chain's Tempo API responds on `/health`: `up`, `down`, or `none` when `TEMPO_API_URLS` lists none for the chain.",examples:[`up`]}),chainId:Zn().int().meta({description:`The ID of the Tempo chain that serves the name.`,examples:[1337]}),name:en.meta({description:"The name that the `chain` parameter carries.",examples:[`local`]}),node:Xn([`down`,`up`]).meta({description:"Whether the chain's node serves the chain ID: `up`, or `down` when it does not respond or serves another.",examples:[`up`]})}).meta({description:`The status of a listed chain.`})).readonly().meta({description:"The deployment's listed chains in order, apart from `mainnet` and `testnet`."})})})(l||=e.chainStatus||={});let u;(function(e){e.json=z({address:Kn([`0x`,R().regex(/^[0-9a-fA-F]{40}$/)]).meta({description:"The Tempo Account that receives the tokens, one of the user's accounts in the `default` realm.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`],pattern:`^0x[0-9a-fA-F]{40}$`}),chain:en.meta({description:"The test chain whose faucet drips the tokens: `testnet`, or a name that `GET /i/chains` lists. Tempo mainnet has no faucet.",examples:[`testnet`]})}),e.response=z({transactions:or(Kn([`0x`,R().regex(/^[0-9a-f]{64}$/)]).meta({description:`The hash of one transfer from the faucet.`,examples:[`0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060`]})).readonly().meta({description:`The hashes of the transfers, one for each token that the faucet drips, each one landed.`,examples:[[`0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060`]]})})})(u||=e.fund||={});let d;(function(e){e.json=z({account:t.optional().meta({description:"One of the user's Tempo Accounts in the app's realms on `chain`, which a linked wallet.tempo passkey owns and the upgrade makes configurable. Absent with `credentialId`.",examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),chain:en.optional().meta({description:`The chain whose accounts are configurable, where the upgrade runs. Defaults to the first such chain that the deployment names.`,examples:[`local`]}),client_id:R().min(1).max(255).optional().meta({description:"The app whose realms hold the account. Without it, the `default` realm.",examples:[`client_01JZ8Q6W3N1R5B4V7C2X9K0M3T`]}),credentialId:gB.credentialId.optional().meta({description:"A wallet.tempo passkey of the user's email that has not linked to the user yet, as `GET /i/account/passkeys` lists it. Its assertion over the upgrade links it. Absent with `account`.",examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),passkey:z({assertion:gB.assertion}).optional().meta({description:`The passkey step's result: the passkey's assertion over the step's challenge. Absent on the first request.`})}).refine(e=>e.account===void 0!=(e.credentialId===void 0),{message:"Name exactly one of `account` or `credentialId`.",path:[`account`]}),e.response=Gn([z({account:x2.tempoAccount}).meta({description:`The installed configuration.`}),z({step:z({options:z({publicKey:z({allowCredentials:or(z({id:gB.credentialId.meta({description:`The credential ID of the account's passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]}),type:Yn(`public-key`).meta({description:`The credential type.`})}).meta({description:`The account's passkey.`})).meta({description:`The account's passkey, the only one the browser offers.`}),challenge:Kn([`0x`,R()]).meta({description:`The digest of the transaction that installs the configuration, as hex. It expires after 5 minutes, and only the same user spends it.`,examples:[`0xf6310589abb21116acc6e123967ed0a125b5041c43f8e157237093e07eaa354c`]}),rpId:R().meta({description:`The passkey's relying party ID.`,examples:[`tempo.xyz`]}),userVerification:Yn(`required`).meta({description:`Every passkey signature requires user verification.`})}).meta({description:"The `PublicKeyCredentialRequestOptions`, serialized with the challenge as hex."})}).meta({description:"The options for `navigator.credentials.get()`."}),type:Yn(`passkey`).meta({description:"Sign the options with the passkey, then repeat the request with `passkey.assertion`."})}).meta({description:`The next step: the passkey's signature of the transaction, since only the passkey signs for the account.`})}).meta({description:`The passkey step.`})])})(d||=e.upgrade||={});let f;(function(e){e.response=z({passkeys:or(z({address:t.meta({description:`The address of the passkey's Tempo Account, which its public key derives.`,examples:[`0x7a3f9c2b1e5d8a4f6c0b3e7d9a2f5c8b1e4d7a0f`]}),credentialId:gB.credentialId.meta({description:`The credential ID of the passkey, base64url.`,examples:[`KEbWNCc7NgaYnUyrNeFGX9_3Y-8`]})}).meta({description:`A wallet.tempo passkey of the email.`})).readonly().meta({description:`The passkeys that wallet.tempo stores for the user's email and that link to no user yet, oldest first. Empty without the wallet service.`})})})(f||=e.passkeys||={})})(B6||={});var V6=2e3,H6=new sb().get(`/v1/account`,HH({description:"Reads the signed-in user and their Tempo Accounts in the realms of the app that `client_id` names: the account that the user selected for the app first, then oldest first. Without `client_id`, the `default` realm's. With `chain`, each account carries its balance on that chain. `passkeys` states whether those realms hold passkeys at Tempo ID's origin. Creates no account: `POST /v1/account` creates the first one.",responses:ZH({errors:[...QH.errors,...sU.errors,...w2.errors,YB,bI],success:{description:`The user and their Tempo Accounts.`,schema:B6.account.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`query`,B6.account.query),async e=>{if(e.req.header(`sec-fetch-site`)===`cross-site`)return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let{chain:n}=e.req.valid(`query`),r=n?pn({name:n,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS}):void 0;if(n&&!r)return X(e,J6({chain:n}));let i=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(i)return i;let a=await Z(e,oW(e,{clientId:e.req.valid(`query`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),o=await Z(e,uW(e,{db:$,origin:U.URL,realms:a}),`Realm.withDefaults`),s=await Z(e,w2(e,{chainId:r?.chainId,db:$,env:U,realms:o,userId:t.user.id}),`TempoAccount.list`),{client_id:c}=e.req.valid(`query`),l=c?k3(s,{clientId:c,cookie:e.req.header(`cookie`),sessionId:t.session.id}):s,u=r?await Z(e,sV(e,{accounts:l,apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:r.chainId}),chainId:r.chainId}),`Balance.list`):void 0;return e.header(`cache-control`,`private, no-store`),e.json({email:t.user.email,id:t.user.id,name:t.user.name||null,passkeys:!!OB(o,{origin:U.URL}),tempo:l.map((e,t)=>u?{...e,balance:u[t]??null}:e)},200)}).post(`/v1/account`,HH({description:"Returns the signed-in user and their Tempo Accounts, as `GET /v1/account` does, with each balance on the chain that `chain` names, and creates a Privy-owned account in the first realm for a user with none, when that realm has a Privy app. On a deployment with configurable accounts, the new account is configurable from its creation, at the address that its initial configuration derives. A user with a linked wallet.tempo passkey, or a registered passkey, in the realms receives none, as does one whose email has a wallet.tempo passkey that has not linked, on a deployment with configurable accounts. The JSON body needs a CORS preflight, which Tempo ID grants only to the origins of first-party apps, so another app's page cannot send the request.",responses:ZH({errors:[...dV,...QH.errors,...sU.errors,...S2.errors,YB,bI],success:{description:`The user and their Tempo Accounts.`,schema:B6.create.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.create.json),async e=>{let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let{chain:n}=e.req.valid(`json`),r=n?pn({name:n,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS}):void 0;if(n&&!r)return X(e,J6({chain:n}));let i=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(i)return i;let a=await Z(e,oW(e,{clientId:e.req.valid(`json`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),o=await Z(e,uW(e,{db:$,origin:U.URL,realms:a}),`Realm.withDefaults`),s=await Z(e,f3(e,{email:t.user.email,realms:o}),`Configure.awaitsUpgrade`),c={chainId:r?.chainId,db:$,env:U,realms:o,userId:t.user.id},l=(await Z(e,s?C2(e,c):S2(e,c),`TempoAccount.create`)).map(O2),{client_id:u}=e.req.valid(`json`),d=u?k3(l,{clientId:u,cookie:e.req.header(`cookie`),sessionId:t.session.id}):l,f=r?await Z(e,sV(e,{accounts:d,apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:r.chainId}),chainId:r.chainId}),`Balance.list`):void 0;return e.header(`cache-control`,`private, no-store`),e.json({email:t.user.email,id:t.user.id,name:t.user.name||null,passkeys:!!OB(o,{origin:U.URL}),tempo:d.map((e,t)=>f?{...e,balance:f[t]??null}:e)},200)}).post(`/v1/account/passkey/options`,HH({description:"Issues a single-use registration challenge for the signed-in user, and returns creation options for a passkey of the `default` realm's relying party. The passkey that `POST /v1/account/passkey` and `POST /v1/account/passkey/verify` then store signs in, and owns the Tempo Account at the address that its public key derives. Requires a sign-in within the last 10 minutes, and fewer than 10 registered passkeys. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...QH.errors,...sU.errors,YB,bI,iB,oB,sB],success:{description:`The creation options.`,schema:B6.passkeyOptions.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkeyOptions.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let r=t.user.id,i=await Z(e,CB($,{userId:r}),`Passkey.list`);if(i.filter(e=>e.registered).length>=10)return X(e,new iB);let a=await Z(e,uW(e,{db:$,origin:U.URL,realms:[await Z(e,hV(e,()=>cW($,{id:rW}),[`realm.get`,rW]),`Realm.get`)]}),`Realm.withDefaults`),o=OB(a,{origin:U.URL}),s=a.find(e=>e.id===o?.realmId);if(!o||!s)return X(e,new oB);let c=await Z(e,AB($,{rpId:o.rpId,userId:r}),`Passkey.requestRegistration`),l=i.flatMap(e=>e.rpId===o.rpId?[e.id]:[]),u=B6.passkeyOptions.response.shape.options.parse(iC({authenticatorSelection:{requireResidentKey:!0,residentKey:`required`,userVerification:`required`},challenge:c,...l.length>0?{excludeCredentialIds:l}:{},rp:{id:o.rpId,name:s.name},user:{displayName:t.user.name||t.user.email,id:crypto.getRandomValues(new Uint8Array(32)),name:t.user.email}}).options);return e.header(`cache-control`,`private, no-store`),e.json({options:u},200)}).post(`/v1/account/passkey`,HH({description:"Verifies the credential of a new passkey over a challenge from `POST /v1/account/passkey/options`, and returns the next step: the passkey's signature of a proof challenge, which `POST /v1/account/passkey/verify` takes. The attestation carries no signature, so only that step stores the passkey. Requires a sign-in within the last 10 minutes. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...OI.errors,...QH.errors,...sU.errors,YB,bI,iB,sB,cB],success:{description:`The proof step.`,schema:B6.passkey.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkey.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let{credential:r}=e.req.valid(`json`),i=t.user.id,a=await Z(e,RB($,{clientDataJSON:r.clientDataJSON,userId:i}),`Passkey.takeRegistration`),o=a?GB(r,{challenge:a.challenge,origin:new URL(U.URL).origin,rpId:a.rpId}):void 0;if(!a||!o)return X(e,new cB);let[s,c]=await Promise.all([(async()=>{if(e.env.WALLET)try{return await Z(e,A2(e.env.WALLET,{id:o.id}),`Wallet.credential`)}catch(t){return Zt(e,{error:t,message:`The wallet service failed a passkey lookup.`}),t instanceof Error&&OI(t)||new TI}})(),Z(e,TB($,{userId:i}),`Passkey.registered`)]);if(s instanceof vI)return X(e,s);if(s)return X(e,new cB);if(c>=10)return X(e,new iB);let l=await Z(e,kB($,{credential:o,rpId:a.rpId,userId:i}),`Passkey.requestProof`),u=B6.passkey.response.shape.step.shape.options.parse(eC({challenge:l,credentialId:[o.id],rpId:a.rpId,userVerification:`required`}).options);return e.header(`cache-control`,`private, no-store`),e.json({step:{options:u,type:`passkey`}},200)}).post(`/v1/account/passkey/verify`,HH({description:"Registers a passkey for the signed-in user, with the new passkey's assertion over the proof challenge from `POST /v1/account/passkey`. The passkey signs in, and owns the Tempo Account at the address that its public key derives, in the `default` realm, beside the user's other accounts. On a deployment with configurable accounts, the passkey's account is configurable from its creation, at the address that its initial configuration derives. With `account`, the passkey instead joins that configurable account as a second owner beside its cloud wallet, which signs the configuration update. Requires a sign-in within the last 10 minutes. Only Tempo ID's own page sends the request.",responses:ZH({errors:[...dV,...c3.errors,...h3.errors,...QH.errors,...sU.errors,bV,xV,YB,bI,iB,sB,cB],success:{description:`The passkey and the address of the account it owns.`,schema:B6.passkeyVerify.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.passkeyVerify.json),async e=>{if(M6(e))return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);if(!Y6(t))return X(e,new sB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let{assertion:r}=e.req.valid(`json`),i=t.user.id,a=await Z(e,LB($,{clientDataJSON:r.metadata.clientDataJSON,userId:i}),`Passkey.takeProof`);if(!a||r.id!==a.id||!WB(r,{challenge:a.challenge,origin:new URL(U.URL).origin,publicKey:a.publicKey,rpId:a.rpId}))return X(e,new cB);let{account:o,chain:s}=e.req.valid(`json`),c=o?await Z(e,c3(e,{account:o,chain:s,userId:i}),`Configure.find`):void 0;if(c instanceof vI)return X(e,c);if(c&&!c.current)return X(e,new bV({account:Yz(c.owner),reason:`upgrade`}));if(c&&(c.owner.type===`webAuthn`||c.current?.owners.some(e=>e.type===`webAuthn`)))return X(e,new xV({account:Yz(c.owner),owner:`passkey`}));let l=await Z(e,EB($,{id:a.id,publicKey:a.publicKey,rpId:a.rpId,userId:i}),`Passkey.register`);if(l===`limit`)return X(e,new iB);if(l!==`stored`)return X(e,new cB);let u=L(_e(It(a.publicKey)));if(e.header(`cache-control`,`private, no-store`),!c){let t=s?DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).find(e=>e.name===s):void 0;if(!t)return e.json({address:u,id:a.id},200);let n=AV({chainId:t.chainId,key:u,type:`webAuthn`});return e.json({address:n.address,id:a.id},200)}let{client:d,current:f,owner:p}=c,m=NV({add:[{address:u,type:`webAuthn`,weight:1}],address:Yz(p),chainId:c.chain.chainId,current:f,type:p.type});return await h3(e,{client:d,current:f,signing:g3(p,{current:f}),target:m,userId:i}),e.json({address:m.address,id:a.id},200)}).get(`/v1/realms`,HH({description:"Lists the realms that the app `client_id` names reaches, in order. An app without realms reaches the `default` realm alone.",responses:ZH({errors:[...QH.errors],success:{description:`The realms.`,schema:B6.realms.response}}),tags:[`Account`]}),QH(`query`,B6.realms.query),async e=>{let t=await Z(e,oW(e,{clientId:e.req.valid(`query`).client_id,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`);return e.header(`cache-control`,`private, no-store`),e.json({realms:t.map(e=>({id:e.id,name:e.name}))},200)}).get(`/v1/chains`,HH({description:"Lists the chains that the `chain` parameter of `GET /v1/account` and `POST /v1/account` selects: `mainnet`, `testnet`, then the chains that the deployment lists, each with its chain ID.",responses:ZH({success:{description:`The chains.`,schema:B6.chains.response}}),tags:[`Account`]}),e=>e.json({chains:X6()},200)).get(`/i/chains`,HH({description:"Lists the chains that the `chain` parameter of `GET /v1/account` and `POST /v1/account` selects, as `GET /v1/chains` does. Internal: only Tempo ID's own pages send the request, so the public document leaves it out.",hide:!0,responses:ZH({success:{description:`The chains.`,schema:B6.chains.response}}),tags:[`Account`]}),e=>e.json({chains:X6()},200)).get(`/i/chains/status`,HH({description:"Returns whether the node and the Tempo API of each chain that the deployment lists respond, apart from `mainnet` and `testnet`. A probe that fails or takes longer than a second reads as `down`, and a status can be up to 2 seconds old. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...F6.errors],success:{description:`The status of each listed chain.`,schema:B6.chainStatus.response}}),tags:[`Account`]}),async e=>{let t=F6(e);if(t)return X(e,t);let n=Qt({value:U.RPC_URLS}).filter(e=>!(e.name in fn)),r=await Promise.all(n.map(async t=>({...await Z(e,hV(e,()=>_V({apiUrl:ln({apiUrls:U.TEMPO_API_URLS,chainId:t.chainId}),chainId:t.chainId,rpcUrl:t.url}),[`ChainStatus.get`,t.name],{ttl:V6}),`ChainStatus.get`),chainId:t.chainId,name:t.name})));return e.header(`cache-control`,`no-store`),e.json({chains:r},200)}).post(`/i/account/fund`,HH({description:"Funds one of the signed-in user's Tempo Accounts in the `default` realm from the faucet of the test chain that `chain` names, and waits until each transfer lands. Tempo mainnet has no faucet. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...dV,...F6.errors,...QH.errors,...OI.errors,...sU.errors,...w2.errors,YB,bI],success:{description:`The transfers from the faucet.`,schema:B6.fund.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.fund.json),async e=>{let t=F6(e);if(t)return X(e,t);let n=await Z(e,R6(e),`Session.get`);if(!n)return X(e,new YB);let{address:r,chain:i}=e.req.valid(`json`),a=pn({name:i,rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS});if(!a)return X(e,J6({chain:i}));let o=Mo.find(e=>e.id===a.chainId);if(!o)return X(e,q6({chain:i}));let s=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:n.user.id}]}),`RateLimit.check`);if(s)return s;let c=await Z(e,oW(e,{clientId:void 0,db:$,origin:e.req.header(`origin`),own:new URL(U.URL).origin}),`Realm.forRequest`),l=await Z(e,uW(e,{db:$,origin:U.URL,realms:c}),`Realm.withDefaults`),u=(await Z(e,w2(e,{chainId:a.chainId,db:$,env:U,realms:l,userId:n.user.id}),`TempoAccount.list`)).find(e=>e.address.toLowerCase()===r.toLowerCase());if(!u)return X(e,K6({address:r}));let d=await(async()=>{try{return await Z(e,ko({address:u.address,chain:o,rpcUrl:a.rpcUrl}),`Faucet.fund`)}catch(t){throw!(t instanceof Error)||OI(t)?t:(Zt(e,{error:t,message:`The faucet did not fund the account.`}),new TI)}})();return e.json({transactions:d},200)}).post(`/i/account/upgrade`,HH({description:"Upgrades one of the signed-in user's Tempo Accounts in place to a configurable account (TIP-1113), on a chain whose accounts the deployment makes configurable. The account is a wallet.tempo passkey's: one that linked, which `account` names, or one of the user's email that has not linked yet, which `credentialId` names and the upgrade links. The account keeps its address, and the passkey stays its only owner. The passkey signs in the browser: the first request returns the passkey step, and the repeated request with `passkey.assertion` sends the upgrade. Requires a sign-in within the last 10 minutes. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...dV,...s3.errors,...m3.errors,...F6.errors,...QH.errors,...sU.errors,YB,kR,sB],success:{description:`The upgraded account, or the passkey step.`,schema:B6.upgrade.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),QH(`json`,B6.upgrade.json),async e=>{let t=await U6(e);if(t instanceof Response)return t;let n=t.user.id,{account:r,chain:i,client_id:a,credentialId:o,passkey:s}=e.req.valid(`json`),c=await Z(e,m3(e,{account:r,chain:i,clientId:a,credentialId:o,email:t.user.email,userId:n}),`Configure.root`);if(c instanceof vI)return X(e,c);if(e.header(`cache-control`,`private, no-store`),s){let t=await Z(e,s3(e,{account:c.account,assertion:s.assertion,client:c.client,credential:c.credential,link:c.link,userId:n}),`Configure.confirm`);if(t instanceof vI)return X(e,t);let r=await Z(e,G6(e,{account:c.account,chain:c.chain,clientId:a,userId:n}),`reread`);return e.json({account:r},200)}if(OB([c.realm],{origin:U.URL})?.rpId!==c.credential.rpId)return X(e,W6({account:c.account}));let l=NV({add:[],address:c.account,chainId:c.chain.chainId,current:void 0,type:`webAuthn`});if(await Z(e,UV({client:c.client,target:l}),`ConfigurableAccount.installed`)){let t=c.link?await Z(e,c.link(),`Configure.link`):void 0;if(t)return X(e,t);await Z(e,IV($,{config:l,userId:n}),`db.accountConfig.save`);let r=await Z(e,G6(e,{account:c.account,chain:c.chain,clientId:a,userId:n}),`reread`);return e.json({account:r},200)}let u=B6.upgrade.response.options[1].shape.step.shape.options.parse(await Z(e,u3(e,{account:c.account,client:c.client,credential:c.credential,current:void 0,target:l,userId:n}),`Configure.request`));return e.json({step:{options:u,type:`passkey`}},200)}).get(`/i/account/passkeys`,HH({description:"Lists the wallet.tempo passkeys of the signed-in user's email that link to no user yet, which `POST /i/account/upgrade` takes as `credentialId`. The sign-in proved the email, so the list reveals nothing to another person. Counts against the user's `ACCOUNT_LIMIT`. Refuses a cross-site navigation with `cross_site_request`. Internal: only Tempo ID's own page sends the request, so the public document leaves it out.",hide:!0,responses:ZH({errors:[...OI.errors,...sU.errors,YB,bI],success:{description:`The passkeys.`,schema:B6.passkeys.response}}),security:[{sessionCookie:[]}],tags:[`Account`]}),async e=>{if(e.req.header(`sec-fetch-site`)===`cross-site`)return X(e,new bI);let t=await Z(e,R6(e),`Session.get`);if(!t)return X(e,new YB);let n=await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:t.user.id}]}),`RateLimit.check`);if(n)return n;let r=await Z(e,p3(e,{email:t.user.email}),`Configure.unlinked`);return e.header(`cache-control`,`private, no-store`),e.json({passkeys:r.map(e=>({address:L(e.address),credentialId:e.credentialId}))},200)});async function U6(e){let t=F6(e);if(t)return X(e,t);let n=await Z(e,R6(e),`Session.get`);return n?Y6(n)?await Z(e,sU(e,{limits:[{binding:`ACCOUNT_LIMIT`,key:n.user.id}]}),`RateLimit.check`)||n:X(e,new sB):X(e,new YB)}function W6(e){return new kR({account:e.account,description:`Passkey required: the passkey of Tempo Account ${e.account} signs only at its own relying party, which this page is not part of. Change the account there.`})}async function G6(e,t){let{account:n,chain:r,clientId:i,userId:a}=t,o=await Z(e,l3(e,{clientId:i}),`Configure.reach`),s=(await Z(e,C2(e,{chainId:r.chainId,db:$,env:U,realms:o,userId:a}),`TempoAccount.held`)).find(e=>Yz(e).toLowerCase()===n.toLowerCase());if(!s)throw new y2({account:n});return O2(s)}function K6(e){return new lz({issues:[{message:`The signed-in user has no Tempo Account at ${e.address}. Use an address that \`GET /v1/account\` lists`,path:[`address`]}]})}function q6(e){return new lz({issues:[{message:`The chain "${e.chain}" has no faucet. Use \`testnet\`, or a test chain that the deployment lists`,path:[`chain`]}]})}function J6(e){return new lz({issues:[{message:`No chain is named "${e.chain}". Use \`mainnet\`, \`testnet\`, or another chain that the deployment lists`,path:[`chain`]}]})}function Y6(e){return Date.now()-e.session.createdAt.getTime()<6e5}function X6(){let e=DV({rpcUrl:U.TEMPO_RPC_URL,rpcUrls:U.RPC_URLS,value:U.CONFIGURABLE_ACCOUNTS}).map(e=>e.chainId);return[{chainId:fn.mainnet,name:`mainnet`},{chainId:fn.testnet,name:`testnet`},...Qt({value:U.RPC_URLS}).filter(e=>!(e.name in fn)).map(e=>({chainId:e.chainId,name:e.name}))].map(t=>({...t,configurable:e.includes(t.chainId)}))}var Z6=60,Q6;(function(e){e.continuation=z({client_id:R().optional(),expiresAt:Zn(),id_token_hint:R(),post_logout_redirect_uri:R().optional(),state:R().optional()})})(Q6||={});var $6=class extends yI(`invalid_id_token_hint`){name=`Logout.HintInvalidError`;constructor(){super({error_description:`Invalid id_token_hint: it is not an ID token that this issuer signed for the app. Send the ID token that the app received at sign-in.`,field:`id_token_hint`})}},e8=class extends yI(`logout_not_permitted`){name=`Logout.NotPermittedError`;constructor(e){super({error_description:`Logout not permitted: the app ${e.clientId} may not end the session. Register the app for logout, then retry.`,meta:{client_id:e.clientId}})}},t8=class extends yI(`post_logout_redirect_not_permitted`){name=`Logout.RedirectNotPermittedError`;constructor(e){super({error_description:`Invalid post_logout_redirect_uri: ${e.uri} is not registered for the app. Use one of its post-logout redirect URIs, or leave it out.`,field:`post_logout_redirect_uri`,meta:{post_logout_redirect_uri:e.uri}})}};async function n8(e,t){let n=await o8(t);if(n instanceof $6)return n;let[r]=await e.select({disabled:TP.disabled,enableEndSession:TP.enableEndSession,postLogoutRedirectUris:TP.postLogoutRedirectUris}).from(TP).where(Y(TP.clientId,n.clientId));if(!r||r.disabled||!r.enableEndSession)return new e8({clientId:n.clientId});let i=(()=>{let e=t.postLogoutRedirectUri;if(e===void 0)return;if(!(r.postLogoutRedirectUris??[]).includes(e))return new t8({uri:e});let n=new URL(e);return t.state!==void 0&&n.searchParams.set(`state`,t.state),n.href})();return i instanceof t8?i:{redirect:i,sessionId:n.sessionId}}(function(e){e.errors=[$6,e8,t8]})(n8||={});async function r8(e,t){return await Zi({data:JSON.stringify(Q6.continuation.parse({...e,expiresAt:Math.floor(Date.now()/1e3)+Z6})),key:await s8(t.secret)})}async function i8(e,t){let n=await ma({data:e,key:await s8(t.secret)}).then(e=>Q6.continuation.safeParse(JSON.parse(e))).catch(()=>void 0);if(n?.success&&!(n.data.expiresAt<=Date.now()/1e3))return n.data}async function a8(e,t){let n=new Date,r=e.$with(`ended`).as(e.delete(IP).where(KM(Y(IP.token,t.token),t.sessionId===void 0?void 0:Y(IP.id,t.sessionId),q`set_config('tempo_id.logout', 'on', true) = 'on'`)).returning({id:IP.id})),i=e.$with(`access_tokens`).as(e.update(CP).set({revoked:n}).where(KM($M(CP.sessionId,e.select({id:r.id}).from(r)),tN(CP.revoked))).returning({id:CP.id})),a=e.$with(`refresh_tokens`).as(e.update(MP).set({revoked:n}).where(KM($M(MP.sessionId,e.select({id:r.id}).from(r)),tN(MP.revoked))).returning({id:MP.id})),[o]=await e.with(r,i,a).select({id:r.id}).from(r);return o?.id}async function o8(e){let{clientId:t,issuer:n,jwks:r}=e,i=await(async()=>{try{let t=await Ji(e.hint,wi(r),{algorithms:[`RS256`]});return JSON.parse(new TextDecoder().decode(t.payload))}catch{return}})();if(!i||typeof i!=`object`)return new $6;let a=i,o=typeof a.aud==`string`?[a.aud]:Array.isArray(a.aud)?a.aud.filter(e=>typeof e==`string`):[],s=t??(o.length===1?o[0]:void 0);return a.iss!==n||!s||!o.includes(s)||typeof a.sid!=`string`||!a.sid||typeof a.sub!=`string`||!a.sub?new $6:{clientId:s,sessionId:a.sid,userId:a.sub}}async function s8(e){let t=new TextEncoder,n=await crypto.subtle.importKey(`raw`,t.encode(e),`HKDF`,!1,[`deriveBits`]),r=await crypto.subtle.deriveBits({hash:`SHA-256`,info:t.encode(`tempo-id:logout-continuation:v1`),name:`HKDF`,salt:new Uint8Array},n,256);return dt(new Uint8Array(r))}async function c8(e,t){let n;if(e.database)n=typeof e.database==`function`?e.database(e):await t(e);else{let t=Ya(e),r=Object.keys(t).reduce((e,t)=>(e[t]=[],e),{}),{memoryAdapter:i}=await import(`./assets/dist-CJN10pUl.js`);n=i(r)(e)}return n.transaction||(oo.warn(`Adapter does not correctly implement transaction function, patching it automatically. Please update your adapter implementation.`),n.transaction=async e=>e(n)),n}async function l8(e){return c8(e,async e=>{let{createKyselyAdapter:t,kyselyAdapter:n}=await import(`./assets/kysely-adapter-DhztbDJz.js`),{kysely:r,databaseType:i,transaction:a}=await t(e);if(!r)throw new H(`Failed to initialize database adapter`);return n(r,{type:i||`sqlite`,debugLogs:e.database&&`debugLogs`in e.database?e.database.debugLogs:!1,transaction:a})(e)})}var u8={postgres:{string:[`character varying`,`varchar`,`text`,`uuid`],number:[`int4`,`int8`,`integer`,`bigint`,`smallint`,`numeric`,`real`,`double precision`],boolean:[`bool`,`boolean`],date:[`timestamptz`,`timestamp`,`date`],json:[`json`,`jsonb`]},mysql:{string:[`varchar`,`text`,`uuid`],number:[`integer`,`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`boolean`,`tinyint`],date:[`timestamp`,`datetime`,`date`],json:[`json`]},sqlite:{string:[`TEXT`],number:[`INTEGER`,`REAL`,`BIGINT`],boolean:[`INTEGER`,`BOOLEAN`],date:[`DATE`,`INTEGER`],json:[`TEXT`]},mssql:{string:[`varchar`,`nvarchar`,`uniqueidentifier`],number:[`int`,`bigint`,`smallint`,`decimal`,`float`,`double`],boolean:[`bit`,`smallint`],date:[`datetime2`,`date`,`datetime`],json:[`varchar`,`nvarchar`]}};function d8(e,t){return`${so(e)}\u0000${so(t)}`}function f8(e,t){return`${e}\u0000${t}`}function p8(e,t){return e.unique===(t.unique??!1)&&e.validFullColumns&&e.columns.length===t.columns.length&&e.columns.every((e,n)=>e===t.columns[n])}function m8(e){return typeof e==`boolean`?e:typeof e==`number`?e!==0:e===`1`||e?.toLowerCase()===`true`||e===`t`}function h8(e){return new Map(e.map(e=>{let t=[...e.columns].sort((e,t)=>e.position-t.position);return[d8(e.table,e.name),{columns:t.flatMap(e=>e.name===null?[]:[e.name]),name:e.name,table:e.table,unique:e.unique,validFullColumns:e.valid&&!e.partial&&t.length>0&&t.every(e=>e.name!==null&&e.fullLength)}]}))}async function g8(e,t,n,r){if(r)return h8(await r(n));let i;switch(t.type){case`sqlite`:i=(await Io`
502
502
  SELECT
503
503
  tables.name AS "tableName",
504
504
  index_list.name AS "indexName",