@ascentstudio/cue-console 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (266) hide show
  1. package/.next/BUILD_ID +1 -0
  2. package/.next/app-build-manifest.json +360 -0
  3. package/.next/app-path-routes-manifest.json +38 -0
  4. package/.next/build-manifest.json +33 -0
  5. package/.next/diagnostics/build-diagnostics.json +6 -0
  6. package/.next/diagnostics/framework.json +1 -0
  7. package/.next/export-marker.json +6 -0
  8. package/.next/images-manifest.json +58 -0
  9. package/.next/next-minimal-server.js.nft.json +1 -0
  10. package/.next/next-server.js.nft.json +1 -0
  11. package/.next/package.json +1 -0
  12. package/.next/prerender-manifest.json +11 -0
  13. package/.next/react-loadable-manifest.json +1 -0
  14. package/.next/required-server-files.json +325 -0
  15. package/.next/routes-manifest.json +307 -0
  16. package/.next/server/app/_not-found/page.js +2 -0
  17. package/.next/server/app/_not-found/page.js.nft.json +1 -0
  18. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -0
  19. package/.next/server/app/account/edge/page.js +2 -0
  20. package/.next/server/app/account/edge/page.js.nft.json +1 -0
  21. package/.next/server/app/account/edge/page_client-reference-manifest.js +1 -0
  22. package/.next/server/app/account/page.js +2 -0
  23. package/.next/server/app/account/page.js.nft.json +1 -0
  24. package/.next/server/app/account/page_client-reference-manifest.js +1 -0
  25. package/.next/server/app/api/queues/[[...path]]/route.js +139 -0
  26. package/.next/server/app/api/queues/[[...path]]/route.js.nft.json +1 -0
  27. package/.next/server/app/api/queues/[[...path]]/route_client-reference-manifest.js +1 -0
  28. package/.next/server/app/api/revision-archive/route.js +1 -0
  29. package/.next/server/app/api/revision-archive/route.js.nft.json +1 -0
  30. package/.next/server/app/api/revision-archive/route_client-reference-manifest.js +1 -0
  31. package/.next/server/app/api/run-file/route.js +1 -0
  32. package/.next/server/app/api/run-file/route.js.nft.json +1 -0
  33. package/.next/server/app/api/run-file/route_client-reference-manifest.js +1 -0
  34. package/.next/server/app/api/transient-file/route.js +1 -0
  35. package/.next/server/app/api/transient-file/route.js.nft.json +1 -0
  36. package/.next/server/app/api/transient-file/route_client-reference-manifest.js +1 -0
  37. package/.next/server/app/auth/callback/route.js +1 -0
  38. package/.next/server/app/auth/callback/route.js.nft.json +1 -0
  39. package/.next/server/app/auth/callback/route_client-reference-manifest.js +1 -0
  40. package/.next/server/app/entities/[...entityId]/page.js +2 -0
  41. package/.next/server/app/entities/[...entityId]/page.js.nft.json +1 -0
  42. package/.next/server/app/entities/[...entityId]/page_client-reference-manifest.js +1 -0
  43. package/.next/server/app/login/page.js +2 -0
  44. package/.next/server/app/login/page.js.nft.json +1 -0
  45. package/.next/server/app/login/page_client-reference-manifest.js +1 -0
  46. package/.next/server/app/organizations/[organizationId]/advanced/danger/page.js +2 -0
  47. package/.next/server/app/organizations/[organizationId]/advanced/danger/page.js.nft.json +1 -0
  48. package/.next/server/app/organizations/[organizationId]/advanced/danger/page_client-reference-manifest.js +1 -0
  49. package/.next/server/app/organizations/[organizationId]/advanced/files/[[...path]]/page.js +2 -0
  50. package/.next/server/app/organizations/[organizationId]/advanced/files/[[...path]]/page.js.nft.json +1 -0
  51. package/.next/server/app/organizations/[organizationId]/advanced/files/[[...path]]/page_client-reference-manifest.js +1 -0
  52. package/.next/server/app/organizations/[organizationId]/advanced/queues/page.js +2 -0
  53. package/.next/server/app/organizations/[organizationId]/advanced/queues/page.js.nft.json +1 -0
  54. package/.next/server/app/organizations/[organizationId]/advanced/queues/page_client-reference-manifest.js +1 -0
  55. package/.next/server/app/organizations/[organizationId]/advanced/runtimes/page.js +2 -0
  56. package/.next/server/app/organizations/[organizationId]/advanced/runtimes/page.js.nft.json +1 -0
  57. package/.next/server/app/organizations/[organizationId]/advanced/runtimes/page_client-reference-manifest.js +1 -0
  58. package/.next/server/app/organizations/[organizationId]/crons/[cron]/page.js +2 -0
  59. package/.next/server/app/organizations/[organizationId]/crons/[cron]/page.js.nft.json +1 -0
  60. package/.next/server/app/organizations/[organizationId]/crons/[cron]/page_client-reference-manifest.js +1 -0
  61. package/.next/server/app/organizations/[organizationId]/crons/page.js +2 -0
  62. package/.next/server/app/organizations/[organizationId]/crons/page.js.nft.json +1 -0
  63. package/.next/server/app/organizations/[organizationId]/crons/page_client-reference-manifest.js +1 -0
  64. package/.next/server/app/organizations/[organizationId]/developers/page.js +2 -0
  65. package/.next/server/app/organizations/[organizationId]/developers/page.js.nft.json +1 -0
  66. package/.next/server/app/organizations/[organizationId]/developers/page_client-reference-manifest.js +1 -0
  67. package/.next/server/app/organizations/[organizationId]/entities/[...identity]/page.js +2 -0
  68. package/.next/server/app/organizations/[organizationId]/entities/[...identity]/page.js.nft.json +1 -0
  69. package/.next/server/app/organizations/[organizationId]/entities/[...identity]/page_client-reference-manifest.js +1 -0
  70. package/.next/server/app/organizations/[organizationId]/environments/[environment]/import/page.js +2 -0
  71. package/.next/server/app/organizations/[organizationId]/environments/[environment]/import/page.js.nft.json +1 -0
  72. package/.next/server/app/organizations/[organizationId]/environments/[environment]/import/page_client-reference-manifest.js +1 -0
  73. package/.next/server/app/organizations/[organizationId]/environments/[environment]/kinds/[kind]/page.js +2 -0
  74. package/.next/server/app/organizations/[organizationId]/environments/[environment]/kinds/[kind]/page.js.nft.json +1 -0
  75. package/.next/server/app/organizations/[organizationId]/environments/[environment]/kinds/[kind]/page_client-reference-manifest.js +1 -0
  76. package/.next/server/app/organizations/[organizationId]/environments/[environment]/page.js +2 -0
  77. package/.next/server/app/organizations/[organizationId]/environments/[environment]/page.js.nft.json +1 -0
  78. package/.next/server/app/organizations/[organizationId]/environments/[environment]/page_client-reference-manifest.js +1 -0
  79. package/.next/server/app/organizations/[organizationId]/environments/page.js +2 -0
  80. package/.next/server/app/organizations/[organizationId]/environments/page.js.nft.json +1 -0
  81. package/.next/server/app/organizations/[organizationId]/environments/page_client-reference-manifest.js +1 -0
  82. package/.next/server/app/organizations/[organizationId]/files/[[...path]]/page.js +2 -0
  83. package/.next/server/app/organizations/[organizationId]/files/[[...path]]/page.js.nft.json +1 -0
  84. package/.next/server/app/organizations/[organizationId]/files/[[...path]]/page_client-reference-manifest.js +1 -0
  85. package/.next/server/app/organizations/[organizationId]/flows/[flow]/page.js +2 -0
  86. package/.next/server/app/organizations/[organizationId]/flows/[flow]/page.js.nft.json +1 -0
  87. package/.next/server/app/organizations/[organizationId]/flows/[flow]/page_client-reference-manifest.js +1 -0
  88. package/.next/server/app/organizations/[organizationId]/flows/page.js +2 -0
  89. package/.next/server/app/organizations/[organizationId]/flows/page.js.nft.json +1 -0
  90. package/.next/server/app/organizations/[organizationId]/flows/page_client-reference-manifest.js +1 -0
  91. package/.next/server/app/organizations/[organizationId]/page.js +2 -0
  92. package/.next/server/app/organizations/[organizationId]/page.js.nft.json +1 -0
  93. package/.next/server/app/organizations/[organizationId]/page_client-reference-manifest.js +1 -0
  94. package/.next/server/app/organizations/[organizationId]/queues/page.js +2 -0
  95. package/.next/server/app/organizations/[organizationId]/queues/page.js.nft.json +1 -0
  96. package/.next/server/app/organizations/[organizationId]/queues/page_client-reference-manifest.js +1 -0
  97. package/.next/server/app/organizations/[organizationId]/runs/[...run]/page.js +2 -0
  98. package/.next/server/app/organizations/[organizationId]/runs/[...run]/page.js.nft.json +1 -0
  99. package/.next/server/app/organizations/[organizationId]/runs/[...run]/page_client-reference-manifest.js +1 -0
  100. package/.next/server/app/organizations/[organizationId]/runs/page.js +2 -0
  101. package/.next/server/app/organizations/[organizationId]/runs/page.js.nft.json +1 -0
  102. package/.next/server/app/organizations/[organizationId]/runs/page_client-reference-manifest.js +1 -0
  103. package/.next/server/app/organizations/[organizationId]/steps/[step]/page.js +2 -0
  104. package/.next/server/app/organizations/[organizationId]/steps/[step]/page.js.nft.json +1 -0
  105. package/.next/server/app/organizations/[organizationId]/steps/[step]/page_client-reference-manifest.js +1 -0
  106. package/.next/server/app/organizations/[organizationId]/steps/page.js +2 -0
  107. package/.next/server/app/organizations/[organizationId]/steps/page.js.nft.json +1 -0
  108. package/.next/server/app/organizations/[organizationId]/steps/page_client-reference-manifest.js +1 -0
  109. package/.next/server/app/organizations/[organizationId]/supervisors/[...supervisorId]/page.js +2 -0
  110. package/.next/server/app/organizations/[organizationId]/supervisors/[...supervisorId]/page.js.nft.json +1 -0
  111. package/.next/server/app/organizations/[organizationId]/supervisors/[...supervisorId]/page_client-reference-manifest.js +1 -0
  112. package/.next/server/app/organizations/[organizationId]/supervisors/page.js +2 -0
  113. package/.next/server/app/organizations/[organizationId]/supervisors/page.js.nft.json +1 -0
  114. package/.next/server/app/organizations/[organizationId]/supervisors/page_client-reference-manifest.js +1 -0
  115. package/.next/server/app/organizations/[organizationId]/workers/[...workerId]/page.js +2 -0
  116. package/.next/server/app/organizations/[organizationId]/workers/[...workerId]/page.js.nft.json +1 -0
  117. package/.next/server/app/organizations/[organizationId]/workers/[...workerId]/page_client-reference-manifest.js +1 -0
  118. package/.next/server/app/organizations/[organizationId]/workers/page.js +2 -0
  119. package/.next/server/app/organizations/[organizationId]/workers/page.js.nft.json +1 -0
  120. package/.next/server/app/organizations/[organizationId]/workers/page_client-reference-manifest.js +1 -0
  121. package/.next/server/app/page.js +2 -0
  122. package/.next/server/app/page.js.nft.json +1 -0
  123. package/.next/server/app/page_client-reference-manifest.js +1 -0
  124. package/.next/server/app-paths-manifest.json +38 -0
  125. package/.next/server/chunks/118.js +28 -0
  126. package/.next/server/chunks/1227.js +1 -0
  127. package/.next/server/chunks/2745.js +22 -0
  128. package/.next/server/chunks/3471.js +1 -0
  129. package/.next/server/chunks/3945.js +28 -0
  130. package/.next/server/chunks/4951.js +1 -0
  131. package/.next/server/chunks/5134.js +39 -0
  132. package/.next/server/chunks/5307.js +1 -0
  133. package/.next/server/chunks/5544.js +4 -0
  134. package/.next/server/chunks/5650.js +11 -0
  135. package/.next/server/chunks/5830.js +1 -0
  136. package/.next/server/chunks/6269.js +1 -0
  137. package/.next/server/chunks/6785.js +1 -0
  138. package/.next/server/chunks/688.js +1 -0
  139. package/.next/server/chunks/7090.js +12 -0
  140. package/.next/server/chunks/7860.js +1 -0
  141. package/.next/server/chunks/9775.js +6 -0
  142. package/.next/server/edge-runtime-webpack.js +2 -0
  143. package/.next/server/edge-runtime-webpack.js.map +1 -0
  144. package/.next/server/functions-config-manifest.json +6 -0
  145. package/.next/server/interception-route-rewrite-manifest.js +1 -0
  146. package/.next/server/middleware-build-manifest.js +1 -0
  147. package/.next/server/middleware-manifest.json +32 -0
  148. package/.next/server/middleware-react-loadable-manifest.js +1 -0
  149. package/.next/server/next-font-manifest.js +1 -0
  150. package/.next/server/next-font-manifest.json +1 -0
  151. package/.next/server/pages/500.html +1 -0
  152. package/.next/server/pages/_app.js +1 -0
  153. package/.next/server/pages/_app.js.nft.json +1 -0
  154. package/.next/server/pages/_document.js +1 -0
  155. package/.next/server/pages/_document.js.nft.json +1 -0
  156. package/.next/server/pages/_error.js +19 -0
  157. package/.next/server/pages/_error.js.nft.json +1 -0
  158. package/.next/server/pages-manifest.json +5 -0
  159. package/.next/server/server-reference-manifest.js +1 -0
  160. package/.next/server/server-reference-manifest.json +1 -0
  161. package/.next/server/src/middleware.js +41 -0
  162. package/.next/server/src/middleware.js.map +1 -0
  163. package/.next/server/webpack-runtime.js +1 -0
  164. package/.next/static/chunks/1960-c6e56b942a49e961.js +28 -0
  165. package/.next/static/chunks/3583-7a56b73280ed778d.js +1 -0
  166. package/.next/static/chunks/4013-3f45637d88477c77.js +1 -0
  167. package/.next/static/chunks/4208-b4aa7c9c0d952566.js +1 -0
  168. package/.next/static/chunks/4623-63127b62a8a72903.js +1 -0
  169. package/.next/static/chunks/4676-57f27fd7212dbb4c.js +1 -0
  170. package/.next/static/chunks/6-95f9f7f8524a131c.js +1 -0
  171. package/.next/static/chunks/6314-b31a7a56d6a402fb.js +1 -0
  172. package/.next/static/chunks/644-37687fe0d6f751c0.js +1 -0
  173. package/.next/static/chunks/68d6572c-f283d2faa40588f2.js +1 -0
  174. package/.next/static/chunks/9863f86b-1206839a9b6caaa6.js +1 -0
  175. package/.next/static/chunks/app/_not-found/page-ffc618da93d34e0e.js +1 -0
  176. package/.next/static/chunks/app/account/edge/page-9fb085dfc03572a5.js +1 -0
  177. package/.next/static/chunks/app/account/page-cc2e848665ce94fc.js +1 -0
  178. package/.next/static/chunks/app/api/queues/[[...path]]/route-30bb7141897b22c1.js +1 -0
  179. package/.next/static/chunks/app/api/revision-archive/route-30bb7141897b22c1.js +1 -0
  180. package/.next/static/chunks/app/api/run-file/route-30bb7141897b22c1.js +1 -0
  181. package/.next/static/chunks/app/api/transient-file/route-30bb7141897b22c1.js +1 -0
  182. package/.next/static/chunks/app/auth/callback/route-30bb7141897b22c1.js +1 -0
  183. package/.next/static/chunks/app/entities/[...entityId]/page-30bb7141897b22c1.js +1 -0
  184. package/.next/static/chunks/app/layout-2fcefb7fa6af5176.js +1 -0
  185. package/.next/static/chunks/app/login/page-e27f2054aac555c5.js +1 -0
  186. package/.next/static/chunks/app/organizations/[organizationId]/advanced/danger/page-0175a9a98ea9986c.js +1 -0
  187. package/.next/static/chunks/app/organizations/[organizationId]/advanced/files/[[...path]]/page-359b309c015000c9.js +1 -0
  188. package/.next/static/chunks/app/organizations/[organizationId]/advanced/queues/page-8d749ffb3bc4734f.js +1 -0
  189. package/.next/static/chunks/app/organizations/[organizationId]/advanced/runtimes/page-923797cc996adbe2.js +1 -0
  190. package/.next/static/chunks/app/organizations/[organizationId]/crons/[cron]/page-13f170b4f8a0ce14.js +1 -0
  191. package/.next/static/chunks/app/organizations/[organizationId]/crons/page-4986caf57d2c35b4.js +1 -0
  192. package/.next/static/chunks/app/organizations/[organizationId]/developers/page-30bb7141897b22c1.js +1 -0
  193. package/.next/static/chunks/app/organizations/[organizationId]/entities/[...identity]/page-e0241442edba96e7.js +1 -0
  194. package/.next/static/chunks/app/organizations/[organizationId]/environments/[environment]/import/page-0c7c6e02b60dd0f1.js +1 -0
  195. package/.next/static/chunks/app/organizations/[organizationId]/environments/[environment]/kinds/[kind]/page-eb4992865971dd4c.js +1 -0
  196. package/.next/static/chunks/app/organizations/[organizationId]/environments/[environment]/page-5f0fd596e8424211.js +1 -0
  197. package/.next/static/chunks/app/organizations/[organizationId]/environments/page-040b34a033e847f4.js +1 -0
  198. package/.next/static/chunks/app/organizations/[organizationId]/files/[[...path]]/page-30bb7141897b22c1.js +1 -0
  199. package/.next/static/chunks/app/organizations/[organizationId]/flows/[flow]/page-528eb9e28c9c79cf.js +1 -0
  200. package/.next/static/chunks/app/organizations/[organizationId]/flows/page-f635b0aa92431824.js +1 -0
  201. package/.next/static/chunks/app/organizations/[organizationId]/page-204a1429b9601965.js +1 -0
  202. package/.next/static/chunks/app/organizations/[organizationId]/queues/page-30bb7141897b22c1.js +1 -0
  203. package/.next/static/chunks/app/organizations/[organizationId]/runs/[...run]/page-4c3fd3a59380f414.js +1 -0
  204. package/.next/static/chunks/app/organizations/[organizationId]/runs/page-2c523bf23dc3ab9e.js +1 -0
  205. package/.next/static/chunks/app/organizations/[organizationId]/steps/[step]/page-2791149a21c18814.js +1 -0
  206. package/.next/static/chunks/app/organizations/[organizationId]/steps/page-2791149a21c18814.js +1 -0
  207. package/.next/static/chunks/app/organizations/[organizationId]/supervisors/[...supervisorId]/page-c7b82d9359a2ec25.js +1 -0
  208. package/.next/static/chunks/app/organizations/[organizationId]/supervisors/page-d622f4cb91d97ba5.js +1 -0
  209. package/.next/static/chunks/app/organizations/[organizationId]/workers/[...workerId]/page-9fe141cf11db8c39.js +1 -0
  210. package/.next/static/chunks/app/organizations/[organizationId]/workers/page-fe66e894882cc417.js +1 -0
  211. package/.next/static/chunks/app/page-5d4f444f72ffd898.js +1 -0
  212. package/.next/static/chunks/framework-5441844c055e8ad4.js +1 -0
  213. package/.next/static/chunks/main-777df5cd01757e8d.js +1 -0
  214. package/.next/static/chunks/main-app-7efc3aa24cb65686.js +1 -0
  215. package/.next/static/chunks/pages/_app-cef802c6256b034a.js +1 -0
  216. package/.next/static/chunks/pages/_error-ab37b1ec243afbed.js +1 -0
  217. package/.next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  218. package/.next/static/chunks/webpack-34f7615e411b77e4.js +1 -0
  219. package/.next/static/css/97f395f0adbd1da3.css +1 -0
  220. package/.next/static/hztPDtxkg-AYXDOJLSokI/_buildManifest.js +1 -0
  221. package/.next/static/hztPDtxkg-AYXDOJLSokI/_ssgManifest.js +1 -0
  222. package/.next/trace +25 -0
  223. package/.next/types/app/account/edge/page.ts +84 -0
  224. package/.next/types/app/account/page.ts +84 -0
  225. package/.next/types/app/api/queues/[[...path]]/route.ts +347 -0
  226. package/.next/types/app/api/revision-archive/route.ts +347 -0
  227. package/.next/types/app/api/run-file/route.ts +347 -0
  228. package/.next/types/app/api/transient-file/route.ts +347 -0
  229. package/.next/types/app/auth/callback/route.ts +347 -0
  230. package/.next/types/app/entities/[...entityId]/page.ts +84 -0
  231. package/.next/types/app/layout.ts +84 -0
  232. package/.next/types/app/login/page.ts +84 -0
  233. package/.next/types/app/organizations/[organizationId]/advanced/danger/page.ts +84 -0
  234. package/.next/types/app/organizations/[organizationId]/advanced/files/[[...path]]/page.ts +84 -0
  235. package/.next/types/app/organizations/[organizationId]/advanced/queues/page.ts +84 -0
  236. package/.next/types/app/organizations/[organizationId]/advanced/runtimes/page.ts +84 -0
  237. package/.next/types/app/organizations/[organizationId]/crons/[cron]/page.ts +84 -0
  238. package/.next/types/app/organizations/[organizationId]/crons/page.ts +84 -0
  239. package/.next/types/app/organizations/[organizationId]/developers/page.ts +84 -0
  240. package/.next/types/app/organizations/[organizationId]/entities/[...identity]/page.ts +84 -0
  241. package/.next/types/app/organizations/[organizationId]/environments/[environment]/import/page.ts +84 -0
  242. package/.next/types/app/organizations/[organizationId]/environments/[environment]/kinds/[kind]/page.ts +84 -0
  243. package/.next/types/app/organizations/[organizationId]/environments/[environment]/page.ts +84 -0
  244. package/.next/types/app/organizations/[organizationId]/environments/page.ts +84 -0
  245. package/.next/types/app/organizations/[organizationId]/files/[[...path]]/page.ts +84 -0
  246. package/.next/types/app/organizations/[organizationId]/flows/[flow]/page.ts +84 -0
  247. package/.next/types/app/organizations/[organizationId]/flows/page.ts +84 -0
  248. package/.next/types/app/organizations/[organizationId]/page.ts +84 -0
  249. package/.next/types/app/organizations/[organizationId]/queues/page.ts +84 -0
  250. package/.next/types/app/organizations/[organizationId]/runs/[...run]/page.ts +84 -0
  251. package/.next/types/app/organizations/[organizationId]/runs/page.ts +84 -0
  252. package/.next/types/app/organizations/[organizationId]/steps/[step]/page.ts +84 -0
  253. package/.next/types/app/organizations/[organizationId]/steps/page.ts +84 -0
  254. package/.next/types/app/organizations/[organizationId]/supervisors/[...supervisorId]/page.ts +84 -0
  255. package/.next/types/app/organizations/[organizationId]/supervisors/page.ts +84 -0
  256. package/.next/types/app/organizations/[organizationId]/workers/[...workerId]/page.ts +84 -0
  257. package/.next/types/app/organizations/[organizationId]/workers/page.ts +84 -0
  258. package/.next/types/app/page.ts +84 -0
  259. package/.next/types/cache-life.d.ts +141 -0
  260. package/.next/types/package.json +1 -0
  261. package/.next/types/routes.d.ts +106 -0
  262. package/.next/types/validator.ts +376 -0
  263. package/bin/console.mjs +35 -0
  264. package/next.config.ts +44 -0
  265. package/package.json +30 -4
  266. package/README.md +0 -3
@@ -0,0 +1,41 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[550],{40:(a,b,c)=>{"use strict";a.exports=c(310)},55:(a,b,c)=>{var d;(()=>{var e={226:function(e,f){!function(g,h){"use strict";var i="function",j="undefined",k="object",l="string",m="major",n="model",o="name",p="type",q="vendor",r="version",s="architecture",t="console",u="mobile",v="tablet",w="smarttv",x="wearable",y="embedded",z="Amazon",A="Apple",B="ASUS",C="BlackBerry",D="Browser",E="Chrome",F="Firefox",G="Google",H="Huawei",I="Microsoft",J="Motorola",K="Opera",L="Samsung",M="Sharp",N="Sony",O="Xiaomi",P="Zebra",Q="Facebook",R="Chromium OS",S="Mac OS",T=function(a,b){var c={};for(var d in a)b[d]&&b[d].length%2==0?c[d]=b[d].concat(a[d]):c[d]=a[d];return c},U=function(a){for(var b={},c=0;c<a.length;c++)b[a[c].toUpperCase()]=a[c];return b},V=function(a,b){return typeof a===l&&-1!==W(b).indexOf(W(a))},W=function(a){return a.toLowerCase()},X=function(a,b){if(typeof a===l)return a=a.replace(/^\s\s*/,""),typeof b===j?a:a.substring(0,350)},Y=function(a,b){for(var c,d,e,f,g,j,l=0;l<b.length&&!g;){var m=b[l],n=b[l+1];for(c=d=0;c<m.length&&!g&&m[c];)if(g=m[c++].exec(a))for(e=0;e<n.length;e++)j=g[++d],typeof(f=n[e])===k&&f.length>0?2===f.length?typeof f[1]==i?this[f[0]]=f[1].call(this,j):this[f[0]]=f[1]:3===f.length?typeof f[1]!==i||f[1].exec&&f[1].test?this[f[0]]=j?j.replace(f[1],f[2]):void 0:this[f[0]]=j?f[1].call(this,j,f[2]):void 0:4===f.length&&(this[f[0]]=j?f[3].call(this,j.replace(f[1],f[2])):h):this[f]=j||h;l+=2}},Z=function(a,b){for(var c in b)if(typeof b[c]===k&&b[c].length>0){for(var d=0;d<b[c].length;d++)if(V(b[c][d],a))return"?"===c?h:c}else if(V(b[c],a))return"?"===c?h:c;return a},$={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},_={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[r,[o,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[r,[o,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[o,r],[/opios[\/ ]+([\w\.]+)/i],[r,[o,K+" Mini"]],[/\bopr\/([\w\.]+)/i],[r,[o,K]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[o,r],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[r,[o,"UC"+D]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[r,[o,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[r,[o,"WeChat"]],[/konqueror\/([\w\.]+)/i],[r,[o,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[r,[o,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[r,[o,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[o,/(.+)/,"$1 Secure "+D],r],[/\bfocus\/([\w\.]+)/i],[r,[o,F+" Focus"]],[/\bopt\/([\w\.]+)/i],[r,[o,K+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[r,[o,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[r,[o,"Dolphin"]],[/coast\/([\w\.]+)/i],[r,[o,K+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[r,[o,"MIUI "+D]],[/fxios\/([-\w\.]+)/i],[r,[o,F]],[/\bqihu|(qi?ho?o?|360)browser/i],[[o,"360 "+D]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[o,/(.+)/,"$1 "+D],r],[/(comodo_dragon)\/([\w\.]+)/i],[[o,/_/g," "],r],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[o,r],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[o],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[o,Q],r],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[o,r],[/\bgsa\/([\w\.]+) .*safari\//i],[r,[o,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[r,[o,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[r,[o,E+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[o,E+" WebView"],r],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[r,[o,"Android "+D]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[o,r],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[r,[o,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[r,o],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[o,[r,Z,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[o,r],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[o,"Netscape"],r],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[r,[o,F+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[o,r],[/(cobalt)\/([\w\.]+)/i],[o,[r,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[s,"amd64"]],[/(ia32(?=;))/i],[[s,W]],[/((?:i[346]|x)86)[;\)]/i],[[s,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[s,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[s,"armhf"]],[/windows (ce|mobile); ppc;/i],[[s,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[s,/ower/,"",W]],[/(sun4\w)[;\)]/i],[[s,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[s,W]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[n,[q,L],[p,v]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[n,[q,L],[p,u]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[n,[q,A],[p,u]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[n,[q,A],[p,v]],[/(macintosh);/i],[n,[q,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[n,[q,M],[p,u]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[n,[q,H],[p,v]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[n,[q,H],[p,u]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[n,/_/g," "],[q,O],[p,u]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[n,/_/g," "],[q,O],[p,v]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[n,[q,"OPPO"],[p,u]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[n,[q,"Vivo"],[p,u]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[n,[q,"Realme"],[p,u]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[n,[q,J],[p,u]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[n,[q,J],[p,v]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[n,[q,"LG"],[p,v]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[n,[q,"LG"],[p,u]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[n,[q,"Lenovo"],[p,v]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[n,/_/g," "],[q,"Nokia"],[p,u]],[/(pixel c)\b/i],[n,[q,G],[p,v]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[n,[q,G],[p,u]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[n,[q,N],[p,u]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[n,"Xperia Tablet"],[q,N],[p,v]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[n,[q,"OnePlus"],[p,u]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[n,[q,z],[p,v]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[n,/(.+)/g,"Fire Phone $1"],[q,z],[p,u]],[/(playbook);[-\w\),; ]+(rim)/i],[n,q,[p,v]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[n,[q,C],[p,u]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[n,[q,B],[p,v]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[n,[q,B],[p,u]],[/(nexus 9)/i],[n,[q,"HTC"],[p,v]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[q,[n,/_/g," "],[p,u]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[n,[q,"Acer"],[p,v]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[n,[q,"Meizu"],[p,u]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[q,n,[p,u]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[q,n,[p,v]],[/(surface duo)/i],[n,[q,I],[p,v]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[n,[q,"Fairphone"],[p,u]],[/(u304aa)/i],[n,[q,"AT&T"],[p,u]],[/\bsie-(\w*)/i],[n,[q,"Siemens"],[p,u]],[/\b(rct\w+) b/i],[n,[q,"RCA"],[p,v]],[/\b(venue[\d ]{2,7}) b/i],[n,[q,"Dell"],[p,v]],[/\b(q(?:mv|ta)\w+) b/i],[n,[q,"Verizon"],[p,v]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[n,[q,"Barnes & Noble"],[p,v]],[/\b(tm\d{3}\w+) b/i],[n,[q,"NuVision"],[p,v]],[/\b(k88) b/i],[n,[q,"ZTE"],[p,v]],[/\b(nx\d{3}j) b/i],[n,[q,"ZTE"],[p,u]],[/\b(gen\d{3}) b.+49h/i],[n,[q,"Swiss"],[p,u]],[/\b(zur\d{3}) b/i],[n,[q,"Swiss"],[p,v]],[/\b((zeki)?tb.*\b) b/i],[n,[q,"Zeki"],[p,v]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[q,"Dragon Touch"],n,[p,v]],[/\b(ns-?\w{0,9}) b/i],[n,[q,"Insignia"],[p,v]],[/\b((nxa|next)-?\w{0,9}) b/i],[n,[q,"NextBook"],[p,v]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[q,"Voice"],n,[p,u]],[/\b(lvtel\-)?(v1[12]) b/i],[[q,"LvTel"],n,[p,u]],[/\b(ph-1) /i],[n,[q,"Essential"],[p,u]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[n,[q,"Envizen"],[p,v]],[/\b(trio[-\w\. ]+) b/i],[n,[q,"MachSpeed"],[p,v]],[/\btu_(1491) b/i],[n,[q,"Rotor"],[p,v]],[/(shield[\w ]+) b/i],[n,[q,"Nvidia"],[p,v]],[/(sprint) (\w+)/i],[q,n,[p,u]],[/(kin\.[onetw]{3})/i],[[n,/\./g," "],[q,I],[p,u]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[n,[q,P],[p,v]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[n,[q,P],[p,u]],[/smart-tv.+(samsung)/i],[q,[p,w]],[/hbbtv.+maple;(\d+)/i],[[n,/^/,"SmartTV"],[q,L],[p,w]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[q,"LG"],[p,w]],[/(apple) ?tv/i],[q,[n,A+" TV"],[p,w]],[/crkey/i],[[n,E+"cast"],[q,G],[p,w]],[/droid.+aft(\w)( bui|\))/i],[n,[q,z],[p,w]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[n,[q,M],[p,w]],[/(bravia[\w ]+)( bui|\))/i],[n,[q,N],[p,w]],[/(mitv-\w{5}) bui/i],[n,[q,O],[p,w]],[/Hbbtv.*(technisat) (.*);/i],[q,n,[p,w]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[q,X],[n,X],[p,w]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[p,w]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[q,n,[p,t]],[/droid.+; (shield) bui/i],[n,[q,"Nvidia"],[p,t]],[/(playstation [345portablevi]+)/i],[n,[q,N],[p,t]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[n,[q,I],[p,t]],[/((pebble))app/i],[q,n,[p,x]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[n,[q,A],[p,x]],[/droid.+; (glass) \d/i],[n,[q,G],[p,x]],[/droid.+; (wt63?0{2,3})\)/i],[n,[q,P],[p,x]],[/(quest( 2| pro)?)/i],[n,[q,Q],[p,x]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[q,[p,y]],[/(aeobc)\b/i],[n,[q,z],[p,y]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[n,[p,u]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[n,[p,v]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[p,v]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[p,u]],[/(android[-\w\. ]{0,9});.+buil/i],[n,[q,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[r,[o,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[r,[o,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[o,r],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[r,o]],os:[[/microsoft (windows) (vista|xp)/i],[o,r],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[o,[r,Z,$]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[o,"Windows"],[r,Z,$]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[r,/_/g,"."],[o,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[o,S],[r,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[r,o],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[o,r],[/\(bb(10);/i],[r,[o,C]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[r,[o,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[r,[o,F+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[r,[o,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[r,[o,"watchOS"]],[/crkey\/([\d\.]+)/i],[r,[o,E+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[o,R],r],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[o,r],[/(sunos) ?([\w\.\d]*)/i],[[o,"Solaris"],r],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[o,r]]},aa=function(a,b){if(typeof a===k&&(b=a,a=h),!(this instanceof aa))return new aa(a,b).getResult();var c=typeof g!==j&&g.navigator?g.navigator:h,d=a||(c&&c.userAgent?c.userAgent:""),e=c&&c.userAgentData?c.userAgentData:h,f=b?T(_,b):_,t=c&&c.userAgent==d;return this.getBrowser=function(){var a,b={};return b[o]=h,b[r]=h,Y.call(b,d,f.browser),b[m]=typeof(a=b[r])===l?a.replace(/[^\d\.]/g,"").split(".")[0]:h,t&&c&&c.brave&&typeof c.brave.isBrave==i&&(b[o]="Brave"),b},this.getCPU=function(){var a={};return a[s]=h,Y.call(a,d,f.cpu),a},this.getDevice=function(){var a={};return a[q]=h,a[n]=h,a[p]=h,Y.call(a,d,f.device),t&&!a[p]&&e&&e.mobile&&(a[p]=u),t&&"Macintosh"==a[n]&&c&&typeof c.standalone!==j&&c.maxTouchPoints&&c.maxTouchPoints>2&&(a[n]="iPad",a[p]=v),a},this.getEngine=function(){var a={};return a[o]=h,a[r]=h,Y.call(a,d,f.engine),a},this.getOS=function(){var a={};return a[o]=h,a[r]=h,Y.call(a,d,f.os),t&&!a[o]&&e&&"Unknown"!=e.platform&&(a[o]=e.platform.replace(/chrome os/i,R).replace(/macos/i,S)),a},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return d},this.setUA=function(a){return d=typeof a===l&&a.length>350?X(a,350):a,this},this.setUA(d),this};aa.VERSION="1.0.35",aa.BROWSER=U([o,r,m]),aa.CPU=U([s]),aa.DEVICE=U([n,q,p,t,u,w,v,x,y]),aa.ENGINE=aa.OS=U([o,r]),typeof f!==j?(e.exports&&(f=e.exports=aa),f.UAParser=aa):c.amdO?void 0===(d=(function(){return aa}).call(b,c,b,a))||(a.exports=d):typeof g!==j&&(g.UAParser=aa);var ab=typeof g!==j&&(g.jQuery||g.Zepto);if(ab&&!ab.ua){var ac=new aa;ab.ua=ac.getResult(),ab.ua.get=function(){return ac.getUA()},ab.ua.set=function(a){ac.setUA(a);var b=ac.getResult();for(var c in b)ab.ua[c]=b[c]}}}("object"==typeof window?window:this)}},f={};function g(a){var b=f[a];if(void 0!==b)return b.exports;var c=f[a]={exports:{}},d=!0;try{e[a].call(c.exports,c,c.exports,g),d=!1}finally{d&&delete f[a]}return c.exports}g.ab="//",a.exports=g(226)})()},122:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),!function(a,b){for(var c in b)Object.defineProperty(a,c,{enumerable:!0,get:b[c]})}(b,{getTestReqInfo:function(){return g},withRequest:function(){return f}});let d=new(c(521)).AsyncLocalStorage;function e(a,b){let c=b.header(a,"next-test-proxy-port");if(!c)return;let d=b.url(a);return{url:d,proxyPort:Number(c),testData:b.header(a,"next-test-data")||""}}function f(a,b,c){let f=e(a,b);return f?d.run(f,c):c()}function g(a,b){let c=d.getStore();return c||(a&&b?e(a,b):void 0)}},138:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),!function(a,b){for(var c in b)Object.defineProperty(a,c,{enumerable:!0,get:b[c]})}(b,{interceptTestApis:function(){return f},wrapRequestHandler:function(){return g}});let d=c(122),e=c(251);function f(){return(0,e.interceptFetch)(c.g.fetch)}function g(a){return(b,c)=>(0,d.withRequest)(b,e.reader,()=>a(b,c))}},219:a=>{(()=>{"use strict";var b={993:a=>{var b=Object.prototype.hasOwnProperty,c="~";function d(){}function e(a,b,c){this.fn=a,this.context=b,this.once=c||!1}function f(a,b,d,f,g){if("function"!=typeof d)throw TypeError("The listener must be a function");var h=new e(d,f||a,g),i=c?c+b:b;return a._events[i]?a._events[i].fn?a._events[i]=[a._events[i],h]:a._events[i].push(h):(a._events[i]=h,a._eventsCount++),a}function g(a,b){0==--a._eventsCount?a._events=new d:delete a._events[b]}function h(){this._events=new d,this._eventsCount=0}Object.create&&(d.prototype=Object.create(null),(new d).__proto__||(c=!1)),h.prototype.eventNames=function(){var a,d,e=[];if(0===this._eventsCount)return e;for(d in a=this._events)b.call(a,d)&&e.push(c?d.slice(1):d);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(a)):e},h.prototype.listeners=function(a){var b=c?c+a:a,d=this._events[b];if(!d)return[];if(d.fn)return[d.fn];for(var e=0,f=d.length,g=Array(f);e<f;e++)g[e]=d[e].fn;return g},h.prototype.listenerCount=function(a){var b=c?c+a:a,d=this._events[b];return d?d.fn?1:d.length:0},h.prototype.emit=function(a,b,d,e,f,g){var h=c?c+a:a;if(!this._events[h])return!1;var i,j,k=this._events[h],l=arguments.length;if(k.fn){switch(k.once&&this.removeListener(a,k.fn,void 0,!0),l){case 1:return k.fn.call(k.context),!0;case 2:return k.fn.call(k.context,b),!0;case 3:return k.fn.call(k.context,b,d),!0;case 4:return k.fn.call(k.context,b,d,e),!0;case 5:return k.fn.call(k.context,b,d,e,f),!0;case 6:return k.fn.call(k.context,b,d,e,f,g),!0}for(j=1,i=Array(l-1);j<l;j++)i[j-1]=arguments[j];k.fn.apply(k.context,i)}else{var m,n=k.length;for(j=0;j<n;j++)switch(k[j].once&&this.removeListener(a,k[j].fn,void 0,!0),l){case 1:k[j].fn.call(k[j].context);break;case 2:k[j].fn.call(k[j].context,b);break;case 3:k[j].fn.call(k[j].context,b,d);break;case 4:k[j].fn.call(k[j].context,b,d,e);break;default:if(!i)for(m=1,i=Array(l-1);m<l;m++)i[m-1]=arguments[m];k[j].fn.apply(k[j].context,i)}}return!0},h.prototype.on=function(a,b,c){return f(this,a,b,c,!1)},h.prototype.once=function(a,b,c){return f(this,a,b,c,!0)},h.prototype.removeListener=function(a,b,d,e){var f=c?c+a:a;if(!this._events[f])return this;if(!b)return g(this,f),this;var h=this._events[f];if(h.fn)h.fn!==b||e&&!h.once||d&&h.context!==d||g(this,f);else{for(var i=0,j=[],k=h.length;i<k;i++)(h[i].fn!==b||e&&!h[i].once||d&&h[i].context!==d)&&j.push(h[i]);j.length?this._events[f]=1===j.length?j[0]:j:g(this,f)}return this},h.prototype.removeAllListeners=function(a){var b;return a?(b=c?c+a:a,this._events[b]&&g(this,b)):(this._events=new d,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=c,h.EventEmitter=h,a.exports=h},213:a=>{a.exports=(a,b)=>(b=b||(()=>{}),a.then(a=>new Promise(a=>{a(b())}).then(()=>a),a=>new Promise(a=>{a(b())}).then(()=>{throw a})))},574:(a,b)=>{Object.defineProperty(b,"__esModule",{value:!0}),b.default=function(a,b,c){let d=0,e=a.length;for(;e>0;){let f=e/2|0,g=d+f;0>=c(a[g],b)?(d=++g,e-=f+1):e=f}return d}},821:(a,b,c)=>{Object.defineProperty(b,"__esModule",{value:!0});let d=c(574);class e{constructor(){this._queue=[]}enqueue(a,b){let c={priority:(b=Object.assign({priority:0},b)).priority,run:a};if(this.size&&this._queue[this.size-1].priority>=b.priority)return void this._queue.push(c);let e=d.default(this._queue,c,(a,b)=>b.priority-a.priority);this._queue.splice(e,0,c)}dequeue(){let a=this._queue.shift();return null==a?void 0:a.run}filter(a){return this._queue.filter(b=>b.priority===a.priority).map(a=>a.run)}get size(){return this._queue.length}}b.default=e},816:(a,b,c)=>{let d=c(213);class e extends Error{constructor(a){super(a),this.name="TimeoutError"}}let f=(a,b,c)=>new Promise((f,g)=>{if("number"!=typeof b||b<0)throw TypeError("Expected `milliseconds` to be a positive number");if(b===1/0)return void f(a);let h=setTimeout(()=>{if("function"==typeof c){try{f(c())}catch(a){g(a)}return}let d="string"==typeof c?c:`Promise timed out after ${b} milliseconds`,h=c instanceof Error?c:new e(d);"function"==typeof a.cancel&&a.cancel(),g(h)},b);d(a.then(f,g),()=>{clearTimeout(h)})});a.exports=f,a.exports.default=f,a.exports.TimeoutError=e}},c={};function d(a){var e=c[a];if(void 0!==e)return e.exports;var f=c[a]={exports:{}},g=!0;try{b[a](f,f.exports,d),g=!1}finally{g&&delete c[a]}return f.exports}d.ab="//";var e={};(()=>{Object.defineProperty(e,"__esModule",{value:!0});let a=d(993),b=d(816),c=d(821),f=()=>{},g=new b.TimeoutError;class h extends a{constructor(a){var b,d,e,g;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=f,this._resolveIdle=f,!("number"==typeof(a=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:c.default},a)).intervalCap&&a.intervalCap>=1))throw TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!=(d=null==(b=a.intervalCap)?void 0:b.toString())?d:""}\` (${typeof a.intervalCap})`);if(void 0===a.interval||!(Number.isFinite(a.interval)&&a.interval>=0))throw TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!=(g=null==(e=a.interval)?void 0:e.toString())?g:""}\` (${typeof a.interval})`);this._carryoverConcurrencyCount=a.carryoverConcurrencyCount,this._isIntervalIgnored=a.intervalCap===1/0||0===a.interval,this._intervalCap=a.intervalCap,this._interval=a.interval,this._queue=new a.queueClass,this._queueClass=a.queueClass,this.concurrency=a.concurrency,this._timeout=a.timeout,this._throwOnTimeout=!0===a.throwOnTimeout,this._isPaused=!1===a.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=f,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=f,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let a=Date.now();if(void 0===this._intervalId){let b=this._intervalEnd-a;if(!(b<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},b)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let a=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let b=this._queue.dequeue();return!!b&&(this.emit("active"),b(),a&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(a){if(!("number"==typeof a&&a>=1))throw TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${a}\` (${typeof a})`);this._concurrency=a,this._processQueue()}async add(a,c={}){return new Promise((d,e)=>{let f=async()=>{this._pendingCount++,this._intervalCount++;try{let f=void 0===this._timeout&&void 0===c.timeout?a():b.default(Promise.resolve(a()),void 0===c.timeout?this._timeout:c.timeout,()=>{(void 0===c.throwOnTimeout?this._throwOnTimeout:c.throwOnTimeout)&&e(g)});d(await f)}catch(a){e(a)}this._next()};this._queue.enqueue(f,c),this._tryToStartAnother(),this.emit("add")})}async addAll(a,b){return Promise.all(a.map(async a=>this.add(a,b)))}start(){return this._isPaused&&(this._isPaused=!1,this._processQueue()),this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise(a=>{let b=this._resolveEmpty;this._resolveEmpty=()=>{b(),a()}})}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise(a=>{let b=this._resolveIdle;this._resolveIdle=()=>{b(),a()}})}get size(){return this._queue.size}sizeBy(a){return this._queue.filter(a).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(a){this._timeout=a}}e.default=h})(),a.exports=e})()},240:(a,b,c)=>{"use strict";let d,e,f,g;c.r(b),c.d(b,{default:()=>fD});var h,i,j,k,l,m,n,o,p,q={};async function r(){return"_ENTRIES"in globalThis&&_ENTRIES.middleware_instrumentation&&await _ENTRIES.middleware_instrumentation}c.r(q),c.d(q,{config:()=>fz,middleware:()=>fy});let s=null;async function t(){if("phase-production-build"===process.env.NEXT_PHASE)return;s||(s=r());let a=await s;if(null==a?void 0:a.register)try{await a.register()}catch(a){throw a.message=`An error occurred while loading instrumentation hook: ${a.message}`,a}}async function u(...a){let b=await r();try{var c;await (null==b||null==(c=b.onRequestError)?void 0:c.call(b,...a))}catch(a){console.error("Error in instrumentation.onRequestError:",a)}}let v=null;function w(){return v||(v=t()),v}function x(a){return`The edge runtime does not support Node.js '${a}' module.
2
+ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`}process!==c.g.process&&(process.env=c.g.process.env,c.g.process=process);try{Object.defineProperty(globalThis,"__import_unsupported",{value:function(a){let b=new Proxy(function(){},{get(b,c){if("then"===c)return{};throw Object.defineProperty(Error(x(a)),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})},construct(){throw Object.defineProperty(Error(x(a)),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})},apply(c,d,e){if("function"==typeof e[0])return e[0](b);throw Object.defineProperty(Error(x(a)),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}});return new Proxy({},{get:()=>b})},enumerable:!1,configurable:!1})}catch{}w();class y extends Error{constructor({page:a}){super(`The middleware "${a}" accepts an async API directly with the form:
3
+
4
+ export function middleware(request, event) {
5
+ return NextResponse.redirect('/new-location')
6
+ }
7
+
8
+ Read more: https://nextjs.org/docs/messages/middleware-new-signature
9
+ `)}}class z extends Error{constructor(){super(`The request.page has been deprecated in favour of \`URLPattern\`.
10
+ Read more: https://nextjs.org/docs/messages/middleware-request-page
11
+ `)}}class A extends Error{constructor(){super(`The request.ua has been removed in favour of \`userAgent\` function.
12
+ Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
13
+ `)}}let B="_N_T_",C={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",apiNode:"api-node",apiEdge:"api-edge",middleware:"middleware",instrument:"instrument",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",pagesDirBrowser:"pages-dir-browser",pagesDirEdge:"pages-dir-edge",pagesDirNode:"pages-dir-node"};function D(a){var b,c,d,e,f,g=[],h=0;function i(){for(;h<a.length&&/\s/.test(a.charAt(h));)h+=1;return h<a.length}for(;h<a.length;){for(b=h,f=!1;i();)if(","===(c=a.charAt(h))){for(d=h,h+=1,i(),e=h;h<a.length&&"="!==(c=a.charAt(h))&&";"!==c&&","!==c;)h+=1;h<a.length&&"="===a.charAt(h)?(f=!0,h=e,g.push(a.substring(b,d)),b=h):h=d+1}else h+=1;(!f||h>=a.length)&&g.push(a.substring(b,a.length))}return g}function E(a){let b={},c=[];if(a)for(let[d,e]of a.entries())"set-cookie"===d.toLowerCase()?(c.push(...D(e)),b[d]=1===c.length?c[0]:c):b[d]=e;return b}function F(a){try{return String(new URL(String(a)))}catch(b){throw Object.defineProperty(Error(`URL is malformed "${String(a)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:b}),"__NEXT_ERROR_CODE",{value:"E61",enumerable:!1,configurable:!0})}}({...C,GROUP:{builtinReact:[C.reactServerComponents,C.actionBrowser],serverOnly:[C.reactServerComponents,C.actionBrowser,C.instrument,C.middleware],neutralTarget:[C.apiNode,C.apiEdge],clientOnly:[C.serverSideRendering,C.appPagesBrowser],bundled:[C.reactServerComponents,C.actionBrowser,C.serverSideRendering,C.appPagesBrowser,C.shared,C.instrument,C.middleware],appPages:[C.reactServerComponents,C.serverSideRendering,C.appPagesBrowser,C.actionBrowser]}});let G=Symbol("response"),H=Symbol("passThrough"),I=Symbol("waitUntil");class J{constructor(a,b){this[H]=!1,this[I]=b?{kind:"external",function:b}:{kind:"internal",promises:[]}}respondWith(a){this[G]||(this[G]=Promise.resolve(a))}passThroughOnException(){this[H]=!0}waitUntil(a){if("external"===this[I].kind)return(0,this[I].function)(a);this[I].promises.push(a)}}class K extends J{constructor(a){var b;super(a.request,null==(b=a.context)?void 0:b.waitUntil),this.sourcePage=a.page}get request(){throw Object.defineProperty(new y({page:this.sourcePage}),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}respondWith(){throw Object.defineProperty(new y({page:this.sourcePage}),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}}function L(a){return a.replace(/\/$/,"")||"/"}function M(a){let b=a.indexOf("#"),c=a.indexOf("?"),d=c>-1&&(b<0||c<b);return d||b>-1?{pathname:a.substring(0,d?c:b),query:d?a.substring(c,b>-1?b:void 0):"",hash:b>-1?a.slice(b):""}:{pathname:a,query:"",hash:""}}function N(a,b){if(!a.startsWith("/")||!b)return a;let{pathname:c,query:d,hash:e}=M(a);return""+b+c+d+e}function O(a,b){if(!a.startsWith("/")||!b)return a;let{pathname:c,query:d,hash:e}=M(a);return""+c+b+d+e}function P(a,b){if("string"!=typeof a)return!1;let{pathname:c}=M(a);return c===b||c.startsWith(b+"/")}let Q=new WeakMap;function R(a,b){let c;if(!b)return{pathname:a};let d=Q.get(b);d||(d=b.map(a=>a.toLowerCase()),Q.set(b,d));let e=a.split("/",2);if(!e[1])return{pathname:a};let f=e[1].toLowerCase(),g=d.indexOf(f);return g<0?{pathname:a}:(c=b[g],{pathname:a=a.slice(c.length+1)||"/",detectedLocale:c})}let S=/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;function T(a,b){return new URL(String(a).replace(S,"localhost"),b&&String(b).replace(S,"localhost"))}let U=Symbol("NextURLInternal");class V{constructor(a,b,c){let d,e;"object"==typeof b&&"pathname"in b||"string"==typeof b?(d=b,e=c||{}):e=c||b||{},this[U]={url:T(a,d??e.base),options:e,basePath:""},this.analyze()}analyze(){var a,b,c,d,e;let f=function(a,b){var c,d;let{basePath:e,i18n:f,trailingSlash:g}=null!=(c=b.nextConfig)?c:{},h={pathname:a,trailingSlash:"/"!==a?a.endsWith("/"):g};e&&P(h.pathname,e)&&(h.pathname=function(a,b){if(!P(a,b))return a;let c=a.slice(b.length);return c.startsWith("/")?c:"/"+c}(h.pathname,e),h.basePath=e);let i=h.pathname;if(h.pathname.startsWith("/_next/data/")&&h.pathname.endsWith(".json")){let a=h.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/");h.buildId=a[0],i="index"!==a[1]?"/"+a.slice(1).join("/"):"/",!0===b.parseData&&(h.pathname=i)}if(f){let a=b.i18nProvider?b.i18nProvider.analyze(h.pathname):R(h.pathname,f.locales);h.locale=a.detectedLocale,h.pathname=null!=(d=a.pathname)?d:h.pathname,!a.detectedLocale&&h.buildId&&(a=b.i18nProvider?b.i18nProvider.analyze(i):R(i,f.locales)).detectedLocale&&(h.locale=a.detectedLocale)}return h}(this[U].url.pathname,{nextConfig:this[U].options.nextConfig,parseData:!0,i18nProvider:this[U].options.i18nProvider}),g=function(a,b){let c;if((null==b?void 0:b.host)&&!Array.isArray(b.host))c=b.host.toString().split(":",1)[0];else{if(!a.hostname)return;c=a.hostname}return c.toLowerCase()}(this[U].url,this[U].options.headers);this[U].domainLocale=this[U].options.i18nProvider?this[U].options.i18nProvider.detectDomainLocale(g):function(a,b,c){if(a)for(let f of(c&&(c=c.toLowerCase()),a)){var d,e;if(b===(null==(d=f.domain)?void 0:d.split(":",1)[0].toLowerCase())||c===f.defaultLocale.toLowerCase()||(null==(e=f.locales)?void 0:e.some(a=>a.toLowerCase()===c)))return f}}(null==(b=this[U].options.nextConfig)||null==(a=b.i18n)?void 0:a.domains,g);let h=(null==(c=this[U].domainLocale)?void 0:c.defaultLocale)||(null==(e=this[U].options.nextConfig)||null==(d=e.i18n)?void 0:d.defaultLocale);this[U].url.pathname=f.pathname,this[U].defaultLocale=h,this[U].basePath=f.basePath??"",this[U].buildId=f.buildId,this[U].locale=f.locale??h,this[U].trailingSlash=f.trailingSlash}formatPathname(){var a;let b;return b=function(a,b,c,d){if(!b||b===c)return a;let e=a.toLowerCase();return!d&&(P(e,"/api")||P(e,"/"+b.toLowerCase()))?a:N(a,"/"+b)}((a={basePath:this[U].basePath,buildId:this[U].buildId,defaultLocale:this[U].options.forceLocale?void 0:this[U].defaultLocale,locale:this[U].locale,pathname:this[U].url.pathname,trailingSlash:this[U].trailingSlash}).pathname,a.locale,a.buildId?void 0:a.defaultLocale,a.ignorePrefix),(a.buildId||!a.trailingSlash)&&(b=L(b)),a.buildId&&(b=O(N(b,"/_next/data/"+a.buildId),"/"===a.pathname?"index.json":".json")),b=N(b,a.basePath),!a.buildId&&a.trailingSlash?b.endsWith("/")?b:O(b,"/"):L(b)}formatSearch(){return this[U].url.search}get buildId(){return this[U].buildId}set buildId(a){this[U].buildId=a}get locale(){return this[U].locale??""}set locale(a){var b,c;if(!this[U].locale||!(null==(c=this[U].options.nextConfig)||null==(b=c.i18n)?void 0:b.locales.includes(a)))throw Object.defineProperty(TypeError(`The NextURL configuration includes no locale "${a}"`),"__NEXT_ERROR_CODE",{value:"E597",enumerable:!1,configurable:!0});this[U].locale=a}get defaultLocale(){return this[U].defaultLocale}get domainLocale(){return this[U].domainLocale}get searchParams(){return this[U].url.searchParams}get host(){return this[U].url.host}set host(a){this[U].url.host=a}get hostname(){return this[U].url.hostname}set hostname(a){this[U].url.hostname=a}get port(){return this[U].url.port}set port(a){this[U].url.port=a}get protocol(){return this[U].url.protocol}set protocol(a){this[U].url.protocol=a}get href(){let a=this.formatPathname(),b=this.formatSearch();return`${this.protocol}//${this.host}${a}${b}${this.hash}`}set href(a){this[U].url=T(a),this.analyze()}get origin(){return this[U].url.origin}get pathname(){return this[U].url.pathname}set pathname(a){this[U].url.pathname=a}get hash(){return this[U].url.hash}set hash(a){this[U].url.hash=a}get search(){return this[U].url.search}set search(a){this[U].url.search=a}get password(){return this[U].url.password}set password(a){this[U].url.password=a}get username(){return this[U].url.username}set username(a){this[U].url.username=a}get basePath(){return this[U].basePath}set basePath(a){this[U].basePath=a.startsWith("/")?a:`/${a}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new V(String(this),this[U].options)}}var W=c(429);let X=Symbol("internal request");class Y extends Request{constructor(a,b={}){let c="string"!=typeof a&&"url"in a?a.url:String(a);F(c),a instanceof Request?super(a,b):super(c,b);let d=new V(c,{headers:E(this.headers),nextConfig:b.nextConfig});this[X]={cookies:new W.RequestCookies(this.headers),nextUrl:d,url:d.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[X].cookies}get nextUrl(){return this[X].nextUrl}get page(){throw new z}get ua(){throw new A}get url(){return this[X].url}}class Z{static get(a,b,c){let d=Reflect.get(a,b,c);return"function"==typeof d?d.bind(a):d}static set(a,b,c,d){return Reflect.set(a,b,c,d)}static has(a,b){return Reflect.has(a,b)}static deleteProperty(a,b){return Reflect.deleteProperty(a,b)}}let $=Symbol("internal response"),_=new Set([301,302,303,307,308]);function aa(a,b){var c;if(null==a||null==(c=a.request)?void 0:c.headers){if(!(a.request.headers instanceof Headers))throw Object.defineProperty(Error("request.headers must be an instance of Headers"),"__NEXT_ERROR_CODE",{value:"E119",enumerable:!1,configurable:!0});let c=[];for(let[d,e]of a.request.headers)b.set("x-middleware-request-"+d,e),c.push(d);b.set("x-middleware-override-headers",c.join(","))}}class ab extends Response{constructor(a,b={}){super(a,b);let c=this.headers,d=new Proxy(new W.ResponseCookies(c),{get(a,d,e){switch(d){case"delete":case"set":return(...e)=>{let f=Reflect.apply(a[d],a,e),g=new Headers(c);return f instanceof W.ResponseCookies&&c.set("x-middleware-set-cookie",f.getAll().map(a=>(0,W.stringifyCookie)(a)).join(",")),aa(b,g),f};default:return Z.get(a,d,e)}}});this[$]={cookies:d,url:b.url?new V(b.url,{headers:E(c),nextConfig:b.nextConfig}):void 0}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,url:this.url,body:this.body,bodyUsed:this.bodyUsed,headers:Object.fromEntries(this.headers),ok:this.ok,redirected:this.redirected,status:this.status,statusText:this.statusText,type:this.type}}get cookies(){return this[$].cookies}static json(a,b){let c=Response.json(a,b);return new ab(c.body,c)}static redirect(a,b){let c="number"==typeof b?b:(null==b?void 0:b.status)??307;if(!_.has(c))throw Object.defineProperty(RangeError('Failed to execute "redirect" on "response": Invalid status code'),"__NEXT_ERROR_CODE",{value:"E529",enumerable:!1,configurable:!0});let d="object"==typeof b?b:{},e=new Headers(null==d?void 0:d.headers);return e.set("Location",F(a)),new ab(null,{...d,headers:e,status:c})}static rewrite(a,b){let c=new Headers(null==b?void 0:b.headers);return c.set("x-middleware-rewrite",F(a)),aa(b,c),new ab(null,{...b,headers:c})}static next(a){let b=new Headers(null==a?void 0:a.headers);return b.set("x-middleware-next","1"),aa(a,b),new ab(null,{...a,headers:b})}}function ac(a,b){let c="string"==typeof b?new URL(b):b,d=new URL(a,b),e=d.origin===c.origin;return{url:e?d.toString().slice(c.origin.length):d.toString(),isRelative:e}}let ad="next-router-prefetch",ae=["rsc","next-router-state-tree",ad,"next-hmr-refresh","next-router-segment-prefetch"],af="_rsc";class ag extends Error{constructor(){super("Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers")}static callable(){throw new ag}}class ah extends Headers{constructor(a){super(),this.headers=new Proxy(a,{get(b,c,d){if("symbol"==typeof c)return Z.get(b,c,d);let e=c.toLowerCase(),f=Object.keys(a).find(a=>a.toLowerCase()===e);if(void 0!==f)return Z.get(b,f,d)},set(b,c,d,e){if("symbol"==typeof c)return Z.set(b,c,d,e);let f=c.toLowerCase(),g=Object.keys(a).find(a=>a.toLowerCase()===f);return Z.set(b,g??c,d,e)},has(b,c){if("symbol"==typeof c)return Z.has(b,c);let d=c.toLowerCase(),e=Object.keys(a).find(a=>a.toLowerCase()===d);return void 0!==e&&Z.has(b,e)},deleteProperty(b,c){if("symbol"==typeof c)return Z.deleteProperty(b,c);let d=c.toLowerCase(),e=Object.keys(a).find(a=>a.toLowerCase()===d);return void 0===e||Z.deleteProperty(b,e)}})}static seal(a){return new Proxy(a,{get(a,b,c){switch(b){case"append":case"delete":case"set":return ag.callable;default:return Z.get(a,b,c)}}})}merge(a){return Array.isArray(a)?a.join(", "):a}static from(a){return a instanceof Headers?a:new ah(a)}append(a,b){let c=this.headers[a];"string"==typeof c?this.headers[a]=[c,b]:Array.isArray(c)?c.push(b):this.headers[a]=b}delete(a){delete this.headers[a]}get(a){let b=this.headers[a];return void 0!==b?this.merge(b):null}has(a){return void 0!==this.headers[a]}set(a,b){this.headers[a]=b}forEach(a,b){for(let[c,d]of this.entries())a.call(b,d,c,this)}*entries(){for(let a of Object.keys(this.headers)){let b=a.toLowerCase(),c=this.get(b);yield[b,c]}}*keys(){for(let a of Object.keys(this.headers)){let b=a.toLowerCase();yield b}}*values(){for(let a of Object.keys(this.headers)){let b=this.get(a);yield b}}[Symbol.iterator](){return this.entries()}}let ai=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class aj{disable(){throw ai}getStore(){}run(){throw ai}exit(){throw ai}enterWith(){throw ai}static bind(a){return a}}let ak="undefined"!=typeof globalThis&&globalThis.AsyncLocalStorage;function al(){return ak?new ak:new aj}let am=al();class an extends Error{constructor(){super("Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options")}static callable(){throw new an}}class ao{static seal(a){return new Proxy(a,{get(a,b,c){switch(b){case"clear":case"delete":case"set":return an.callable;default:return Z.get(a,b,c)}}})}}let ap=Symbol.for("next.mutated.cookies");class aq{static wrap(a,b){let c=new W.ResponseCookies(new Headers);for(let b of a.getAll())c.set(b);let d=[],e=new Set,f=()=>{let a=am.getStore();if(a&&(a.pathWasRevalidated=!0),d=c.getAll().filter(a=>e.has(a.name)),b){let a=[];for(let b of d){let c=new W.ResponseCookies(new Headers);c.set(b),a.push(c.toString())}b(a)}},g=new Proxy(c,{get(a,b,c){switch(b){case ap:return d;case"delete":return function(...b){e.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.delete(...b),g}finally{f()}};case"set":return function(...b){e.add("string"==typeof b[0]?b[0]:b[0].name);try{return a.set(...b),g}finally{f()}};default:return Z.get(a,b,c)}}});return g}}function ar(a,b){if("action"!==a.phase)throw new an}var as=function(a){return a.handleRequest="BaseServer.handleRequest",a.run="BaseServer.run",a.pipe="BaseServer.pipe",a.getStaticHTML="BaseServer.getStaticHTML",a.render="BaseServer.render",a.renderToResponseWithComponents="BaseServer.renderToResponseWithComponents",a.renderToResponse="BaseServer.renderToResponse",a.renderToHTML="BaseServer.renderToHTML",a.renderError="BaseServer.renderError",a.renderErrorToResponse="BaseServer.renderErrorToResponse",a.renderErrorToHTML="BaseServer.renderErrorToHTML",a.render404="BaseServer.render404",a}(as||{}),at=function(a){return a.loadDefaultErrorComponents="LoadComponents.loadDefaultErrorComponents",a.loadComponents="LoadComponents.loadComponents",a}(at||{}),au=function(a){return a.getRequestHandler="NextServer.getRequestHandler",a.getServer="NextServer.getServer",a.getServerRequestHandler="NextServer.getServerRequestHandler",a.createServer="createServer.createServer",a}(au||{}),av=function(a){return a.compression="NextNodeServer.compression",a.getBuildId="NextNodeServer.getBuildId",a.createComponentTree="NextNodeServer.createComponentTree",a.clientComponentLoading="NextNodeServer.clientComponentLoading",a.getLayoutOrPageModule="NextNodeServer.getLayoutOrPageModule",a.generateStaticRoutes="NextNodeServer.generateStaticRoutes",a.generateFsStaticRoutes="NextNodeServer.generateFsStaticRoutes",a.generatePublicRoutes="NextNodeServer.generatePublicRoutes",a.generateImageRoutes="NextNodeServer.generateImageRoutes.route",a.sendRenderResult="NextNodeServer.sendRenderResult",a.proxyRequest="NextNodeServer.proxyRequest",a.runApi="NextNodeServer.runApi",a.render="NextNodeServer.render",a.renderHTML="NextNodeServer.renderHTML",a.imageOptimizer="NextNodeServer.imageOptimizer",a.getPagePath="NextNodeServer.getPagePath",a.getRoutesManifest="NextNodeServer.getRoutesManifest",a.findPageComponents="NextNodeServer.findPageComponents",a.getFontManifest="NextNodeServer.getFontManifest",a.getServerComponentManifest="NextNodeServer.getServerComponentManifest",a.getRequestHandler="NextNodeServer.getRequestHandler",a.renderToHTML="NextNodeServer.renderToHTML",a.renderError="NextNodeServer.renderError",a.renderErrorToHTML="NextNodeServer.renderErrorToHTML",a.render404="NextNodeServer.render404",a.startResponse="NextNodeServer.startResponse",a.route="route",a.onProxyReq="onProxyReq",a.apiResolver="apiResolver",a.internalFetch="internalFetch",a}(av||{}),aw=function(a){return a.startServer="startServer.startServer",a}(aw||{}),ax=function(a){return a.getServerSideProps="Render.getServerSideProps",a.getStaticProps="Render.getStaticProps",a.renderToString="Render.renderToString",a.renderDocument="Render.renderDocument",a.createBodyResult="Render.createBodyResult",a}(ax||{}),ay=function(a){return a.renderToString="AppRender.renderToString",a.renderToReadableStream="AppRender.renderToReadableStream",a.getBodyResult="AppRender.getBodyResult",a.fetch="AppRender.fetch",a}(ay||{}),az=function(a){return a.executeRoute="Router.executeRoute",a}(az||{}),aA=function(a){return a.runHandler="Node.runHandler",a}(aA||{}),aB=function(a){return a.runHandler="AppRouteRouteHandlers.runHandler",a}(aB||{}),aC=function(a){return a.generateMetadata="ResolveMetadata.generateMetadata",a.generateViewport="ResolveMetadata.generateViewport",a}(aC||{}),aD=function(a){return a.execute="Middleware.execute",a}(aD||{});let aE=new Set(["Middleware.execute","BaseServer.handleRequest","Render.getServerSideProps","Render.getStaticProps","AppRender.fetch","AppRender.getBodyResult","Render.renderDocument","Node.runHandler","AppRouteRouteHandlers.runHandler","ResolveMetadata.generateMetadata","ResolveMetadata.generateViewport","NextNodeServer.createComponentTree","NextNodeServer.findPageComponents","NextNodeServer.getLayoutOrPageModule","NextNodeServer.startResponse","NextNodeServer.clientComponentLoading"]),aF=new Set(["NextNodeServer.findPageComponents","NextNodeServer.createComponentTree","NextNodeServer.clientComponentLoading"]);function aG(a){return null!==a&&"object"==typeof a&&"then"in a&&"function"==typeof a.then}let aH=process.env.NEXT_OTEL_PERFORMANCE_PREFIX,{context:aI,propagation:aJ,trace:aK,SpanStatusCode:aL,SpanKind:aM,ROOT_CONTEXT:aN}=d=c(812);class aO extends Error{constructor(a,b){super(),this.bubble=a,this.result=b}}let aP=(a,b)=>{(function(a){return"object"==typeof a&&null!==a&&a instanceof aO})(b)&&b.bubble?a.setAttribute("next.bubble",!0):(b&&(a.recordException(b),a.setAttribute("error.type",b.name)),a.setStatus({code:aL.ERROR,message:null==b?void 0:b.message})),a.end()},aQ=new Map,aR=d.createContextKey("next.rootSpanId"),aS=0,aT={set(a,b,c){a.push({key:b,value:c})}};class aU{getTracerInstance(){return aK.getTracer("next.js","0.0.1")}getContext(){return aI}getTracePropagationData(){let a=aI.active(),b=[];return aJ.inject(a,b,aT),b}getActiveScopeSpan(){return aK.getSpan(null==aI?void 0:aI.active())}withPropagatedContext(a,b,c){let d=aI.active();if(aK.getSpanContext(d))return b();let e=aJ.extract(d,a,c);return aI.with(e,b)}trace(...a){var b;let[c,d,e]=a,{fn:f,options:g}="function"==typeof d?{fn:d,options:{}}:{fn:e,options:{...d}},h=g.spanName??c;if(!aE.has(c)&&"1"!==process.env.NEXT_OTEL_VERBOSE||g.hideSpan)return f();let i=this.getSpanContext((null==g?void 0:g.parentSpan)??this.getActiveScopeSpan()),j=!1;i?(null==(b=aK.getSpanContext(i))?void 0:b.isRemote)&&(j=!0):(i=(null==aI?void 0:aI.active())??aN,j=!0);let k=aS++;return g.attributes={"next.span_name":h,"next.span_type":c,...g.attributes},aI.with(i.setValue(aR,k),()=>this.getTracerInstance().startActiveSpan(h,g,a=>{let b;aH&&c&&aF.has(c)&&(b="performance"in globalThis&&"measure"in performance?globalThis.performance.now():void 0);let d=!1,e=()=>{!d&&(d=!0,aQ.delete(k),b&&performance.measure(`${aH}:next-${(c.split(".").pop()||"").replace(/[A-Z]/g,a=>"-"+a.toLowerCase())}`,{start:b,end:performance.now()}))};if(j&&aQ.set(k,new Map(Object.entries(g.attributes??{}))),f.length>1)try{return f(a,b=>aP(a,b))}catch(b){throw aP(a,b),b}finally{e()}try{let b=f(a);if(aG(b))return b.then(b=>(a.end(),b)).catch(b=>{throw aP(a,b),b}).finally(e);return a.end(),e(),b}catch(b){throw aP(a,b),e(),b}}))}wrap(...a){let b=this,[c,d,e]=3===a.length?a:[a[0],{},a[1]];return aE.has(c)||"1"===process.env.NEXT_OTEL_VERBOSE?function(){let a=d;"function"==typeof a&&"function"==typeof e&&(a=a.apply(this,arguments));let f=arguments.length-1,g=arguments[f];if("function"!=typeof g)return b.trace(c,a,()=>e.apply(this,arguments));{let d=b.getContext().bind(aI.active(),g);return b.trace(c,a,(a,b)=>(arguments[f]=function(a){return null==b||b(a),d.apply(this,arguments)},e.apply(this,arguments)))}}:e}startSpan(...a){let[b,c]=a,d=this.getSpanContext((null==c?void 0:c.parentSpan)??this.getActiveScopeSpan());return this.getTracerInstance().startSpan(b,c,d)}getSpanContext(a){return a?aK.setSpan(aI.active(),a):void 0}getRootSpanAttributes(){let a=aI.active().getValue(aR);return aQ.get(a)}setRootSpanAttribute(a,b){let c=aI.active().getValue(aR),d=aQ.get(c);d&&d.set(a,b)}}let aV=(()=>{let a=new aU;return()=>a})(),aW="__prerender_bypass";Symbol("__next_preview_data"),Symbol(aW);class aX{constructor(a,b,c,d){var e;let f=a&&function(a,b){let c=ah.from(a.headers);return{isOnDemandRevalidate:c.get("x-prerender-revalidate")===b.previewModeId,revalidateOnlyGenerated:c.has("x-prerender-revalidate-if-generated")}}(b,a).isOnDemandRevalidate,g=null==(e=c.get(aW))?void 0:e.value;this._isEnabled=!!(!f&&g&&a&&g===a.previewModeId),this._previewModeId=null==a?void 0:a.previewModeId,this._mutableCookies=d}get isEnabled(){return this._isEnabled}enable(){if(!this._previewModeId)throw Object.defineProperty(Error("Invariant: previewProps missing previewModeId this should never happen"),"__NEXT_ERROR_CODE",{value:"E93",enumerable:!1,configurable:!0});this._mutableCookies.set({name:aW,value:this._previewModeId,httpOnly:!0,sameSite:"none",secure:!0,path:"/"}),this._isEnabled=!0}disable(){this._mutableCookies.set({name:aW,value:"",httpOnly:!0,sameSite:"none",secure:!0,path:"/",expires:new Date(0)}),this._isEnabled=!1}}function aY(a,b){if("x-middleware-set-cookie"in a.headers&&"string"==typeof a.headers["x-middleware-set-cookie"]){let c=a.headers["x-middleware-set-cookie"],d=new Headers;for(let a of D(c))d.append("set-cookie",a);for(let a of new W.ResponseCookies(d).getAll())b.set(a)}}let aZ=al();var a$=c(219),a_=c.n(a$);class a0 extends Error{constructor(a,b){super("Invariant: "+(a.endsWith(".")?a:a+".")+" This is a bug in Next.js.",b),this.name="InvariantError"}}class a1{constructor(a,b,c){this.prev=null,this.next=null,this.key=a,this.data=b,this.size=c}}class a2{constructor(){this.prev=null,this.next=null}}class a3{constructor(a,b,c){this.cache=new Map,this.totalSize=0,this.maxSize=a,this.calculateSize=b,this.onEvict=c,this.head=new a2,this.tail=new a2,this.head.next=this.tail,this.tail.prev=this.head}addToHead(a){a.prev=this.head,a.next=this.head.next,this.head.next.prev=a,this.head.next=a}removeNode(a){a.prev.next=a.next,a.next.prev=a.prev}moveToHead(a){this.removeNode(a),this.addToHead(a)}removeTail(){let a=this.tail.prev;return this.removeNode(a),a}set(a,b){let c=(null==this.calculateSize?void 0:this.calculateSize.call(this,b))??1;if(c<=0)throw Object.defineProperty(Error(`LRUCache: calculateSize returned ${c}, but size must be > 0. Items with size 0 would never be evicted, causing unbounded cache growth.`),"__NEXT_ERROR_CODE",{value:"E789",enumerable:!1,configurable:!0});if(c>this.maxSize)return console.warn("Single item size exceeds maxSize"),!1;let d=this.cache.get(a);if(d)d.data=b,this.totalSize=this.totalSize-d.size+c,d.size=c,this.moveToHead(d);else{let d=new a1(a,b,c);this.cache.set(a,d),this.addToHead(d),this.totalSize+=c}for(;this.totalSize>this.maxSize&&this.cache.size>0;){let a=this.removeTail();this.cache.delete(a.key),this.totalSize-=a.size,null==this.onEvict||this.onEvict.call(this,a.key,a.data)}return!0}has(a){return this.cache.has(a)}get(a){let b=this.cache.get(a);if(b)return this.moveToHead(b),b.data}*[Symbol.iterator](){let a=this.head.next;for(;a&&a!==this.tail;){let b=a;yield[b.key,b.data],a=a.next}}remove(a){let b=this.cache.get(a);b&&(this.removeNode(b),this.cache.delete(a),this.totalSize-=b.size)}get size(){return this.cache.size}get currentSize(){return this.totalSize}}c(356).Buffer,new a3(0x3200000,a=>a.size),process.env.NEXT_PRIVATE_DEBUG_CACHE&&console.debug.bind(console,"DefaultCacheHandler:"),process.env.NEXT_PRIVATE_DEBUG_CACHE&&((a,...b)=>{console.log(`use-cache: ${a}`,...b)}),Symbol.for("@next/cache-handlers");let a4=Symbol.for("@next/cache-handlers-map"),a5=Symbol.for("@next/cache-handlers-set"),a6=globalThis;function a7(){if(a6[a4])return a6[a4].entries()}async function a8(a,b){if(!a)return b();let c=a9(a);try{return await b()}finally{let b=function(a,b){let c=new Set(a.pendingRevalidatedTags),d=new Set(a.pendingRevalidateWrites);return{pendingRevalidatedTags:b.pendingRevalidatedTags.filter(a=>!c.has(a)),pendingRevalidates:Object.fromEntries(Object.entries(b.pendingRevalidates).filter(([b])=>!(b in a.pendingRevalidates))),pendingRevalidateWrites:b.pendingRevalidateWrites.filter(a=>!d.has(a))}}(c,a9(a));await bb(a,b)}}function a9(a){return{pendingRevalidatedTags:a.pendingRevalidatedTags?[...a.pendingRevalidatedTags]:[],pendingRevalidates:{...a.pendingRevalidates},pendingRevalidateWrites:a.pendingRevalidateWrites?[...a.pendingRevalidateWrites]:[]}}async function ba(a,b){if(0===a.length)return;let c=[];b&&c.push(b.revalidateTag(a));let d=function(){if(a6[a5])return a6[a5].values()}();if(d)for(let b of d)c.push(b.expireTags(...a));await Promise.all(c)}async function bb(a,b){let c=(null==b?void 0:b.pendingRevalidatedTags)??a.pendingRevalidatedTags??[],d=(null==b?void 0:b.pendingRevalidates)??a.pendingRevalidates??{},e=(null==b?void 0:b.pendingRevalidateWrites)??a.pendingRevalidateWrites??[];return Promise.all([ba(c,a.incrementalCache),...Object.values(d),...e])}let bc=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class bd{disable(){throw bc}getStore(){}run(){throw bc}exit(){throw bc}enterWith(){throw bc}static bind(a){return a}}let be="undefined"!=typeof globalThis&&globalThis.AsyncLocalStorage,bf=be?new be:new bd;class bg{constructor({waitUntil:a,onClose:b,onTaskError:c}){this.workUnitStores=new Set,this.waitUntil=a,this.onClose=b,this.onTaskError=c,this.callbackQueue=new(a_()),this.callbackQueue.pause()}after(a){if(aG(a))this.waitUntil||bh(),this.waitUntil(a.catch(a=>this.reportTaskError("promise",a)));else if("function"==typeof a)this.addCallback(a);else throw Object.defineProperty(Error("`after()`: Argument must be a promise or a function"),"__NEXT_ERROR_CODE",{value:"E50",enumerable:!1,configurable:!0})}addCallback(a){var b;this.waitUntil||bh();let c=aZ.getStore();c&&this.workUnitStores.add(c);let d=bf.getStore(),e=d?d.rootTaskSpawnPhase:null==c?void 0:c.phase;this.runCallbacksOnClosePromise||(this.runCallbacksOnClosePromise=this.runCallbacksOnClose(),this.waitUntil(this.runCallbacksOnClosePromise));let f=(b=async()=>{try{await bf.run({rootTaskSpawnPhase:e},()=>a())}catch(a){this.reportTaskError("function",a)}},be?be.bind(b):bd.bind(b));this.callbackQueue.add(f)}async runCallbacksOnClose(){return await new Promise(a=>this.onClose(a)),this.runCallbacks()}async runCallbacks(){if(0===this.callbackQueue.size)return;for(let a of this.workUnitStores)a.phase="after";let a=am.getStore();if(!a)throw Object.defineProperty(new a0("Missing workStore in AfterContext.runCallbacks"),"__NEXT_ERROR_CODE",{value:"E547",enumerable:!1,configurable:!0});return a8(a,()=>(this.callbackQueue.start(),this.callbackQueue.onIdle()))}reportTaskError(a,b){if(console.error("promise"===a?"A promise passed to `after()` rejected:":"An error occurred in a function passed to `after()`:",b),this.onTaskError)try{null==this.onTaskError||this.onTaskError.call(this,b)}catch(a){console.error(Object.defineProperty(new a0("`onTaskError` threw while handling an error thrown from an `after` task",{cause:a}),"__NEXT_ERROR_CODE",{value:"E569",enumerable:!1,configurable:!0}))}}}function bh(){throw Object.defineProperty(Error("`after()` will not work correctly, because `waitUntil` is not available in the current environment."),"__NEXT_ERROR_CODE",{value:"E91",enumerable:!1,configurable:!0})}function bi(a){let b,c={then:(d,e)=>(b||(b=a()),b.then(a=>{c.value=a}).catch(()=>{}),b.then(d,e))};return c}class bj{onClose(a){if(this.isClosed)throw Object.defineProperty(Error("Cannot subscribe to a closed CloseController"),"__NEXT_ERROR_CODE",{value:"E365",enumerable:!1,configurable:!0});this.target.addEventListener("close",a),this.listeners++}dispatchClose(){if(this.isClosed)throw Object.defineProperty(Error("Cannot close a CloseController multiple times"),"__NEXT_ERROR_CODE",{value:"E229",enumerable:!1,configurable:!0});this.listeners>0&&this.target.dispatchEvent(new Event("close")),this.isClosed=!0}constructor(){this.target=new EventTarget,this.listeners=0,this.isClosed=!1}}function bk(){return{previewModeId:process.env.__NEXT_PREVIEW_MODE_ID||"",previewModeSigningKey:process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY||"",previewModeEncryptionKey:process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY||""}}let bl=Symbol.for("@next/request-context");async function bm(a,b,c){let d=[],e=c&&c.size>0;for(let b of(a=>{let b=["/layout"];if(a.startsWith("/")){let c=a.split("/");for(let a=1;a<c.length+1;a++){let d=c.slice(0,a).join("/");d&&(d.endsWith("/page")||d.endsWith("/route")||(d=`${d}${!d.endsWith("/")?"/":""}layout`),b.push(d))}}return b})(a))b=`${B}${b}`,d.push(b);if(b.pathname&&!e){let a=`${B}${b.pathname}`;d.push(a)}return{tags:d,expirationsByCacheKind:function(a){let b=new Map,c=a7();if(c)for(let[d,e]of c)"getExpiration"in e&&b.set(d,bi(async()=>e.getExpiration(...a)));return b}(d)}}class bn extends Y{constructor(a){super(a.input,a.init),this.sourcePage=a.page}get request(){throw Object.defineProperty(new y({page:this.sourcePage}),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}respondWith(){throw Object.defineProperty(new y({page:this.sourcePage}),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}waitUntil(){throw Object.defineProperty(new y({page:this.sourcePage}),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}}let bo={keys:a=>Array.from(a.keys()),get:(a,b)=>a.get(b)??void 0},bp=(a,b)=>aV().withPropagatedContext(a.headers,b,bo),bq=!1;async function br(a){var b;let d,e;if(!bq&&(bq=!0,"true"===process.env.NEXT_PRIVATE_TEST_PROXY)){let{interceptTestApis:a,wrapRequestHandler:b}=c(138);a(),bp=b(bp)}await w();let f=void 0!==globalThis.__BUILD_MANIFEST;a.request.url=a.request.url.replace(/\.rsc($|\?)/,"$1");let g=a.bypassNextUrl?new URL(a.request.url):new V(a.request.url,{headers:a.request.headers,nextConfig:a.request.nextConfig});for(let a of[...g.searchParams.keys()]){let b=g.searchParams.getAll(a),c=function(a){for(let b of["nxtP","nxtI"])if(a!==b&&a.startsWith(b))return a.substring(b.length);return null}(a);if(c){for(let a of(g.searchParams.delete(c),b))g.searchParams.append(c,a);g.searchParams.delete(a)}}let h=process.env.__NEXT_BUILD_ID||"";"buildId"in g&&(h=g.buildId||"",g.buildId="");let i=function(a){let b=new Headers;for(let[c,d]of Object.entries(a))for(let a of Array.isArray(d)?d:[d])void 0!==a&&("number"==typeof a&&(a=a.toString()),b.append(c,a));return b}(a.request.headers),j=i.has("x-nextjs-data"),k="1"===i.get("rsc");j&&"/index"===g.pathname&&(g.pathname="/");let l=new Map;if(!f)for(let a of ae){let b=i.get(a);null!==b&&(l.set(a,b),i.delete(a))}let m=g.searchParams.get(af),n=new bn({page:a.page,input:(function(a){let b="string"==typeof a,c=b?new URL(a):a;return c.searchParams.delete(af),b?c.toString():c})(g).toString(),init:{body:a.request.body,headers:i,method:a.request.method,nextConfig:a.request.nextConfig,signal:a.request.signal}});j&&Object.defineProperty(n,"__isData",{enumerable:!1,value:!0}),!globalThis.__incrementalCacheShared&&a.IncrementalCache&&(globalThis.__incrementalCache=new a.IncrementalCache({CurCacheHandler:a.incrementalCacheHandler,minimalMode:!0,fetchCacheKeyPrefix:"",dev:!1,requestHeaders:a.request.headers,getPrerenderManifest:()=>({version:-1,routes:{},dynamicRoutes:{},notFoundRoutes:[],preview:bk()})}));let o=a.request.waitUntil??(null==(b=function(){let a=globalThis[bl];return null==a?void 0:a.get()}())?void 0:b.waitUntil),p=new K({request:n,page:a.page,context:o?{waitUntil:o}:void 0});if((d=await bp(n,()=>{if("/middleware"===a.page||"/src/middleware"===a.page){let b=p.waitUntil.bind(p),c=new bj;return aV().trace(aD.execute,{spanName:`middleware ${n.method} ${n.nextUrl.pathname}`,attributes:{"http.target":n.nextUrl.pathname,"http.method":n.method}},async()=>{try{var d,f,g,i,j,k;let l=bk(),m=await bm("/",n.nextUrl,null),o=(j=n.nextUrl,k=a=>{e=a},function(a,b,c,d,e,f,g,h,i,j,k,l){function m(a){c&&c.setHeader("Set-Cookie",a)}let n={};return{type:"request",phase:a,implicitTags:f,url:{pathname:d.pathname,search:d.search??""},rootParams:e,get headers(){return n.headers||(n.headers=function(a){let b=ah.from(a);for(let a of ae)b.delete(a);return ah.seal(b)}(b.headers)),n.headers},get cookies(){if(!n.cookies){let a=new W.RequestCookies(ah.from(b.headers));aY(b,a),n.cookies=ao.seal(a)}return n.cookies},set cookies(value){n.cookies=value},get mutableCookies(){if(!n.mutableCookies){let a=function(a,b){let c=new W.RequestCookies(ah.from(a));return aq.wrap(c,b)}(b.headers,g||(c?m:void 0));aY(b,a),n.mutableCookies=a}return n.mutableCookies},get userspaceMutableCookies(){return n.userspaceMutableCookies||(n.userspaceMutableCookies=function(a){let b=new Proxy(a.mutableCookies,{get(c,d,e){switch(d){case"delete":return function(...d){return ar(a,"cookies().delete"),c.delete(...d),b};case"set":return function(...d){return ar(a,"cookies().set"),c.set(...d),b};default:return Z.get(c,d,e)}}});return b}(this)),n.userspaceMutableCookies},get draftMode(){return n.draftMode||(n.draftMode=new aX(i,b,this.cookies,this.mutableCookies)),n.draftMode},renderResumeDataCache:h??null,isHmrRefresh:j,serverComponentsHmrCache:k||globalThis.__serverComponentsHmrCache,devFallbackParams:null}}("action",n,void 0,j,{},m,k,void 0,l,!1,void 0,null)),q=function({page:a,renderOpts:b,isPrefetchRequest:c,buildId:d,previouslyRevalidatedTags:e}){var f;let g=!b.shouldWaitOnAllReady&&!b.supportsDynamicResponse&&!b.isDraftMode&&!b.isPossibleServerAction,h=b.dev??!1,i=h||g&&(!!process.env.NEXT_DEBUG_BUILD||"1"===process.env.NEXT_SSG_FETCH_METRICS),j={isStaticGeneration:g,page:a,route:(f=a.split("/").reduce((a,b,c,d)=>b?"("===b[0]&&b.endsWith(")")||"@"===b[0]||("page"===b||"route"===b)&&c===d.length-1?a:a+"/"+b:a,"")).startsWith("/")?f:"/"+f,incrementalCache:b.incrementalCache||globalThis.__incrementalCache,cacheLifeProfiles:b.cacheLifeProfiles,isRevalidate:b.isRevalidate,isBuildTimePrerendering:b.nextExport,hasReadableErrorStacks:b.hasReadableErrorStacks,fetchCache:b.fetchCache,isOnDemandRevalidate:b.isOnDemandRevalidate,isDraftMode:b.isDraftMode,isPrefetchRequest:c,buildId:d,reactLoadableManifest:(null==b?void 0:b.reactLoadableManifest)||{},assetPrefix:(null==b?void 0:b.assetPrefix)||"",afterContext:function(a){let{waitUntil:b,onClose:c,onAfterTaskError:d}=a;return new bg({waitUntil:b,onClose:c,onTaskError:d})}(b),cacheComponentsEnabled:b.experimental.cacheComponents,dev:h,previouslyRevalidatedTags:e,refreshTagsByCacheKind:function(){let a=new Map,b=a7();if(b)for(let[c,d]of b)"refreshTags"in d&&a.set(c,bi(async()=>d.refreshTags()));return a}(),runInCleanSnapshot:be?be.snapshot():function(a,...b){return a(...b)},shouldTrackFetchMetrics:i};return b.store=j,j}({page:"/",renderOpts:{cacheLifeProfiles:null==(f=a.request.nextConfig)||null==(d=f.experimental)?void 0:d.cacheLife,experimental:{isRoutePPREnabled:!1,cacheComponents:!1,authInterrupts:!!(null==(i=a.request.nextConfig)||null==(g=i.experimental)?void 0:g.authInterrupts)},supportsDynamicResponse:!0,waitUntil:b,onClose:c.onClose.bind(c),onAfterTaskError:void 0},isPrefetchRequest:"1"===n.headers.get(ad),buildId:h??"",previouslyRevalidatedTags:[]});return await am.run(q,()=>aZ.run(o,a.handler,n,p))}finally{setTimeout(()=>{c.dispatchClose()},0)}})}return a.handler(n,p)}))&&!(d instanceof Response))throw Object.defineProperty(TypeError("Expected an instance of Response to be returned"),"__NEXT_ERROR_CODE",{value:"E567",enumerable:!1,configurable:!0});d&&e&&d.headers.set("set-cookie",e);let q=null==d?void 0:d.headers.get("x-middleware-rewrite");if(d&&q&&(k||!f)){let b=new V(q,{forceLocale:!0,headers:a.request.headers,nextConfig:a.request.nextConfig});f||b.host!==n.nextUrl.host||(b.buildId=h||b.buildId,d.headers.set("x-middleware-rewrite",String(b)));let{url:c,isRelative:e}=ac(b.toString(),g.toString());!f&&j&&d.headers.set("x-nextjs-rewrite",c),k&&e&&(g.pathname!==b.pathname&&d.headers.set("x-nextjs-rewritten-path",b.pathname),g.search!==b.search&&d.headers.set("x-nextjs-rewritten-query",b.search.slice(1)))}if(d&&q&&k&&m){let a=new URL(q);a.searchParams.has(af)||(a.searchParams.set(af,m),d.headers.set("x-middleware-rewrite",a.toString()))}let r=null==d?void 0:d.headers.get("Location");if(d&&r&&!f){let b=new V(r,{forceLocale:!1,headers:a.request.headers,nextConfig:a.request.nextConfig});d=new Response(d.body,d),b.host===g.host&&(b.buildId=h||b.buildId,d.headers.set("Location",b.toString())),j&&(d.headers.delete("Location"),d.headers.set("x-nextjs-redirect",ac(b.toString(),g.toString()).url))}let s=d||ab.next(),t=s.headers.get("x-middleware-override-headers"),u=[];if(t){for(let[a,b]of l)s.headers.set(`x-middleware-request-${a}`,b),u.push(a);u.length>0&&s.headers.set("x-middleware-override-headers",t+","+u.join(","))}return{response:s,waitUntil:("internal"===p[I].kind?Promise.all(p[I].promises).then(()=>{}):void 0)??Promise.resolve(),fetchMetrics:n.fetchMetrics}}function bs(){return"undefined"!=typeof window&&void 0!==window.document}let bt={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4},bu=/^(.*)[.](0|[1-9][0-9]*)$/;function bv(a,b){if(a===b)return!0;let c=a.match(bu);return!!c&&c[1]===b}function bw(a,b,c){let d=c??3180,e=encodeURIComponent(b);if(e.length<=d)return[{name:a,value:b}];let f=[];for(;e.length>0;){let a=e.slice(0,d),b=a.lastIndexOf("%");b>d-3&&(a=a.slice(0,b));let c="";for(;a.length>0;)try{c=decodeURIComponent(a);break}catch(b){if(b instanceof URIError&&"%"===a.at(-3)&&a.length>3)a=a.slice(0,a.length-3);else throw b}f.push(c),e=e.slice(a.length)}return f.map((b,c)=>({name:`${a}.${c}`,value:b}))}async function bx(a,b){let c=await b(a);if(c)return c;let d=[];for(let c=0;;c++){let e=`${a}.${c}`,f=await b(e);if(!f)break;d.push(f)}return d.length>0?d.join(""):null}let by="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),bz=" \n\r=".split(""),bA=(()=>{let a=Array(128);for(let b=0;b<a.length;b+=1)a[b]=-1;for(let b=0;b<bz.length;b+=1)a[bz[b].charCodeAt(0)]=-2;for(let b=0;b<by.length;b+=1)a[by[b].charCodeAt(0)]=b;return a})();function bB(a){let b=[],c=0,d=0;if(function(a,b){for(let c=0;c<a.length;c+=1){let d=a.charCodeAt(c);if(d>55295&&d<=56319){let b=(d-55296)*1024&65535;d=(a.charCodeAt(c+1)-56320&65535|b)+65536,c+=1}!function(a,b){if(a<=127)return b(a);if(a<=2047){b(192|a>>6),b(128|63&a);return}if(a<=65535){b(224|a>>12),b(128|a>>6&63),b(128|63&a);return}if(a<=1114111){b(240|a>>18),b(128|a>>12&63),b(128|a>>6&63),b(128|63&a);return}throw Error(`Unrecognized Unicode codepoint: ${a.toString(16)}`)}(d,b)}}(a,a=>{for(c=c<<8|a,d+=8;d>=6;){let a=c>>d-6&63;b.push(by[a]),d-=6}}),d>0)for(c<<=6-d,d=6;d>=6;){let a=c>>d-6&63;b.push(by[a]),d-=6}return b.join("")}function bC(a){let b=[],c=a=>{b.push(String.fromCodePoint(a))},d={utf8seq:0,codepoint:0},e=0,f=0;for(let b=0;b<a.length;b+=1){let g=bA[a.charCodeAt(b)];if(g>-1)for(e=e<<6|g,f+=6;f>=8;)(function(a,b,c){if(0===b.utf8seq){if(a<=127)return c(a);for(let c=1;c<6;c+=1)if((a>>7-c&1)==0){b.utf8seq=c;break}if(2===b.utf8seq)b.codepoint=31&a;else if(3===b.utf8seq)b.codepoint=15&a;else if(4===b.utf8seq)b.codepoint=7&a;else throw Error("Invalid UTF-8 sequence");b.utf8seq-=1}else if(b.utf8seq>0){if(a<=127)throw Error("Invalid UTF-8 sequence");b.codepoint=b.codepoint<<6|63&a,b.utf8seq-=1,0===b.utf8seq&&c(b.codepoint)}})(e>>f-8&255,d,c),f-=8;else if(-2===g)continue;else throw Error(`Invalid Base64-URL character "${a.at(b)}" at position ${b}`)}return b.join("")}var bD=c(608);let bE="base64-";async function bF({getAll:a,setAll:b,setItems:c,removedItems:d},e){let f=e.cookieEncoding,g=e.cookieOptions??null,h=await a([...c?Object.keys(c):[],...d?Object.keys(d):[]]),i=h?.map(({name:a})=>a)||[],j=Object.keys(d).flatMap(a=>i.filter(b=>bv(b,a))),k=Object.keys(c).flatMap(a=>{let b=new Set(i.filter(b=>bv(b,a))),d=c[a];"base64url"===f&&(d=bE+bB(d));let e=bw(a,d);return e.forEach(a=>{b.delete(a.name)}),j.push(...b),e}),l={...bt,...g,maxAge:0},m={...bt,...g,maxAge:bt.maxAge};delete l.name,delete m.name,await b([...j.map(a=>({name:a,value:"",options:l})),...k.map(({name:a,value:b})=>({name:a,value:b,options:m}))])}let bG=Symbol.for("@supabase/supabase-js.traceContextExtractor");function bH(a,b){var c={};for(var d in a)Object.prototype.hasOwnProperty.call(a,d)&&0>b.indexOf(d)&&(c[d]=a[d]);if(null!=a&&"function"==typeof Object.getOwnPropertySymbols)for(var e=0,d=Object.getOwnPropertySymbols(a);e<d.length;e++)0>b.indexOf(d[e])&&Object.prototype.propertyIsEnumerable.call(a,d[e])&&(c[d[e]]=a[d[e]]);return c}Object.create;Object.create,"function"==typeof SuppressedError&&SuppressedError;class bI extends Error{constructor(a,b="FunctionsError",c){super(a),this.name=b,this.context=c}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class bJ extends bI{constructor(a){super("Failed to send a request to the Edge Function","FunctionsFetchError",a)}}class bK extends bI{constructor(a){super("Relay Error invoking the Edge Function","FunctionsRelayError",a)}}class bL extends bI{constructor(a){super("Edge Function returned a non-2xx status code","FunctionsHttpError",a)}}!function(a){a.Any="any",a.ApNortheast1="ap-northeast-1",a.ApNortheast2="ap-northeast-2",a.ApSouth1="ap-south-1",a.ApSoutheast1="ap-southeast-1",a.ApSoutheast2="ap-southeast-2",a.CaCentral1="ca-central-1",a.EuCentral1="eu-central-1",a.EuWest1="eu-west-1",a.EuWest2="eu-west-2",a.EuWest3="eu-west-3",a.SaEast1="sa-east-1",a.UsEast1="us-east-1",a.UsWest1="us-west-1",a.UsWest2="us-west-2"}(h||(h={}));class bM{constructor(a,{headers:b={},customFetch:c,region:d=h.Any}={}){this.url=a,this.headers=b,this.region=d,this.fetch=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(c)}setAuth(a){this.headers.Authorization=`Bearer ${a}`}invoke(a){var b,c,d,e;return b=this,c=arguments,d=void 0,e=function*(a,b={}){var c,d;let e,f,g;try{let d,{headers:h,method:i,body:j,signal:k,timeout:l}=b,m={},{region:n}=b;n||(n=this.region);let o=new URL(`${this.url}/${a}`);n&&"any"!==n&&(m["x-region"]=n,o.searchParams.set("forceFunctionRegion",n));let p=!!h&&Object.keys(h).some(a=>"content-type"===a.toLowerCase());j&&!p?"undefined"!=typeof Blob&&j instanceof Blob||j instanceof ArrayBuffer?(m["Content-Type"]="application/octet-stream",d=j):"string"==typeof j?(m["Content-Type"]="text/plain",d=j):"undefined"!=typeof FormData&&j instanceof FormData?d=j:(m["Content-Type"]="application/json",d=JSON.stringify(j)):d=!j||"string"==typeof j||"undefined"!=typeof Blob&&j instanceof Blob||j instanceof ArrayBuffer||"undefined"!=typeof FormData&&j instanceof FormData?j:JSON.stringify(j);let q=k;l&&(f=new AbortController,e=setTimeout(()=>f.abort(),l),k?(q=f.signal,g=()=>f.abort(),k.addEventListener("abort",g)):q=f.signal);let r=yield this.fetch(o.toString(),{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),h),body:d,signal:q}).catch(a=>{throw new bJ(a)}),s=r.headers.get("x-relay-error");if(s&&"true"===s)throw new bK(r);if(!r.ok)throw new bL(r);let t=(null!=(c=r.headers.get("Content-Type"))?c:"text/plain").split(";")[0].trim().toLowerCase();return{data:"application/json"===t?yield r.json():"application/octet-stream"===t||"application/pdf"===t?yield r.blob():"text/event-stream"===t?r:"multipart/form-data"===t?yield r.formData():yield r.text(),error:null,response:r}}catch(a){return{data:null,error:a,response:a instanceof bL||a instanceof bK?a.context:void 0}}finally{e&&clearTimeout(e),g&&(null==(d=b.signal)||d.removeEventListener("abort",g))}},new(d||(d=Promise))(function(a,f){function g(a){try{i(e.next(a))}catch(a){f(a)}}function h(a){try{i(e.throw(a))}catch(a){f(a)}}function i(b){var c;b.done?a(b.value):((c=b.value)instanceof d?c:new d(function(a){a(c)})).then(g,h)}i((e=e.apply(b,c||[])).next())})}}var bN=class extends Error{constructor(a){super(a.message),this.name="PostgrestError",this.details=a.details,this.hint=a.hint,this.code=a.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};let bO=a=>Math.min(1e3*2**a,3e4),bP=[520,503],bQ=["GET","HEAD","OPTIONS"];function bR(a){return(bR="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function bS(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function bT(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?bS(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=bR(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=bR(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==bR(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):bS(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}function bU(a,b){return new Promise(c=>{if(null==b?void 0:b.aborted)return void c();let d=setTimeout(()=>{null==b||b.removeEventListener("abort",e),c()},a);function e(){clearTimeout(d),c()}null==b||b.addEventListener("abort",e)})}async function bV(a,b,c,d){let e=0;for(;;){var f,g,h,i,j;let k,l=bT({},c.headers);e>0&&(l["X-Retry-Count"]=String(e));try{k=await a(b,{method:c.method,headers:l,body:c.body,signal:c.signal})}catch(a){if((null==a?void 0:a.name)==="AbortError"||(null==a?void 0:a.code)==="ABORT_ERR"||!bQ.includes(c.method))throw a;if(d&&e<3){let a=bO(e);e++,await bU(a,c.signal);continue}throw a}if(f=c.method,g=k.status,h=e,d&&!(h>=3)&&bQ.includes(f)&&bP.includes(g)&&1){let a=null!=(i=null==(j=k.headers)?void 0:j.get("Retry-After"))?i:null,b=null!==a?1e3*Math.max(0,parseInt(a,10)||0):bO(e);await k.text(),e++,await bU(b,c.signal);continue}return k}}var bW=class{constructor(a){var b,c,d,e,f;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=a.method,this.url=a.url,this.headers=new Headers(a.headers),this.schema=a.schema,this.body=a.body,this.shouldThrowOnError=null!=(b=a.shouldThrowOnError)&&b,this.signal=a.signal,this.isMaybeSingle=null!=(c=a.isMaybeSingle)&&c,this.shouldStripNulls=null!=(d=a.shouldStripNulls)&&d,this.urlLengthLimit=null!=(e=a.urlLengthLimit)?e:8e3,this.retryEnabled=null==(f=a.retry)||f,a.fetch?this.fetch=a.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if("text/csv"===this.headers.get("Accept"))throw Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(a,b){return this.headers=new Headers(this.headers),this.headers.set(a,b),this}retry(a){return this.retryEnabled=a,this}then(a,b){var c=this;if(void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let a=this.headers.get("Accept");"application/vnd.pgrst.object+json"===a?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):a&&"application/json"!==a||this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let d=this.fetch,e=(async()=>{let a={};c.headers.forEach((b,c)=>{a[c]=b});let b=await bV(d,c.url.toString(),{method:c.method,headers:a,body:JSON.stringify(c.body,(a,b)=>"bigint"==typeof b?b.toString():b),signal:c.signal},c.retryEnabled);return await c.processResponse(b)})();return this.shouldThrowOnError||(e=e.catch(a=>{var b,c,d,e,f,g;let h="",i="",j="",k=null==a?void 0:a.cause;if(k){let b=null!=(c=null==k?void 0:k.message)?c:"",g=null!=(d=null==k?void 0:k.code)?d:"";h=`${null!=(e=null==a?void 0:a.name)?e:"FetchError"}: ${null==a?void 0:a.message}
14
+
15
+ Caused by: ${null!=(f=null==k?void 0:k.name)?f:"Error"}: ${b}`,g&&(h+=` (${g})`),(null==k?void 0:k.stack)&&(h+=`
16
+ ${k.stack}`)}else h=null!=(g=null==a?void 0:a.stack)?g:"";let l=this.url.toString().length;return(null==a?void 0:a.name)==="AbortError"||(null==a?void 0:a.code)==="ABORT_ERR"?(j="",i="Request was aborted (timeout or manual cancellation)",l>this.urlLengthLimit&&(i+=`. Note: Your request URL is ${l} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((null==k?void 0:k.name)==="HeadersOverflowError"||(null==k?void 0:k.code)==="UND_ERR_HEADERS_OVERFLOW")&&(j="",i="HTTP headers exceeded server limits (typically 16KB)",l>this.urlLengthLimit&&(i+=`. Your request URL is ${l} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${null!=(b=null==a?void 0:a.name)?b:"FetchError"}: ${null==a?void 0:a.message}`,details:h,hint:i,code:j},data:null,count:null,status:0,statusText:""}})),e.then(a,b)}async processResponse(a){var b,c,d,e;let f=null,g=null,h=null,i=a.status,j=a.statusText;if(a.ok){if("HEAD"!==this.method){let b=await a.text();if(""===b);else if("text/csv"===this.headers.get("Accept"))g=b;else if(this.headers.get("Accept")&&(null==(d=this.headers.get("Accept"))?void 0:d.includes("application/vnd.pgrst.plan+text")))g=b;else try{g=JSON.parse(b)}catch(a){if(f={message:b},g=null,this.shouldThrowOnError)throw new bN({message:b,details:"",hint:"",code:""})}}let k=null==(b=this.headers.get("Prefer"))?void 0:b.match(/count=(exact|planned|estimated)/),l=null==(c=a.headers.get("content-range"))?void 0:c.split("/");if(k&&l&&l.length>1&&(h=parseInt(l[1])),this.isMaybeSingle&&Array.isArray(g))if(g.length>1){if(f={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,h=null,i=406,j="Not Acceptable",this.shouldThrowOnError)throw new bN(bT(bT({},f),{},{hint:null!=(e=f.hint)?e:""}))}else g=1===g.length?g[0]:null}else{let b=await a.text();try{f=JSON.parse(b),Array.isArray(f)&&404===a.status&&(g=[],f=null,i=200,j="OK")}catch(c){404===a.status&&""===b?(i=204,j="No Content"):f={message:b}}if(f&&this.shouldThrowOnError)throw new bN(f)}return{success:null===f,error:f,data:g,count:h,status:i,statusText:j}}returns(){return this}overrideTypes(){return this}},bX=class extends bW{throwOnError(){return super.throwOnError()}select(a){let b=!1,c=(null!=a?a:"*").split("").map(a=>/\s/.test(a)&&!b?"":('"'===a&&(b=!b),a)).join("");return this.url.searchParams.set("select",c),this.headers.append("Prefer","return=representation"),this}order(a,{ascending:b=!0,nullsFirst:c,foreignTable:d,referencedTable:e=d}={}){let f=e?`${e}.order`:"order",g=this.url.searchParams.get(f);return this.url.searchParams.set(f,`${g?`${g},`:""}${a}.${b?"asc":"desc"}${void 0===c?"":c?".nullsfirst":".nullslast"}`),this}limit(a,{foreignTable:b,referencedTable:c=b}={}){let d=void 0===c?"limit":`${c}.limit`;return this.url.searchParams.set(d,`${a}`),this}range(a,b,{foreignTable:c,referencedTable:d=c}={}){let e=void 0===d?"offset":`${d}.offset`,f=void 0===d?"limit":`${d}.limit`;return this.url.searchParams.set(e,`${a}`),this.url.searchParams.set(f,`${b-a+1}`),this}abortSignal(a){return this.signal=a,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:a=!1,verbose:b=!1,settings:c=!1,buffers:d=!1,wal:e=!1,format:f="text"}={}){var g;let h=[a?"analyze":null,b?"verbose":null,c?"settings":null,d?"buffers":null,e?"wal":null].filter(Boolean).join("|"),i=null!=(g=this.headers.get("Accept"))?g:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${f}; for="${i}"; options=${h};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(a){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${a}`),this}};let bY=RegExp("[,()]");var bZ=class extends bX{throwOnError(){return super.throwOnError()}eq(a,b){return this.url.searchParams.append(a,`eq.${b}`),this}neq(a,b){return this.url.searchParams.append(a,`neq.${b}`),this}gt(a,b){return this.url.searchParams.append(a,`gt.${b}`),this}gte(a,b){return this.url.searchParams.append(a,`gte.${b}`),this}lt(a,b){return this.url.searchParams.append(a,`lt.${b}`),this}lte(a,b){return this.url.searchParams.append(a,`lte.${b}`),this}like(a,b){return this.url.searchParams.append(a,`like.${b}`),this}likeAllOf(a,b){return this.url.searchParams.append(a,`like(all).{${b.join(",")}}`),this}likeAnyOf(a,b){return this.url.searchParams.append(a,`like(any).{${b.join(",")}}`),this}ilike(a,b){return this.url.searchParams.append(a,`ilike.${b}`),this}ilikeAllOf(a,b){return this.url.searchParams.append(a,`ilike(all).{${b.join(",")}}`),this}ilikeAnyOf(a,b){return this.url.searchParams.append(a,`ilike(any).{${b.join(",")}}`),this}regexMatch(a,b){return this.url.searchParams.append(a,`match.${b}`),this}regexIMatch(a,b){return this.url.searchParams.append(a,`imatch.${b}`),this}is(a,b){return this.url.searchParams.append(a,`is.${b}`),this}isDistinct(a,b){return this.url.searchParams.append(a,`isdistinct.${b}`),this}in(a,b){let c=Array.from(new Set(b)).map(a=>"string"==typeof a&&bY.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(a,`in.(${c})`),this}notIn(a,b){let c=Array.from(new Set(b)).map(a=>"string"==typeof a&&bY.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(a,`not.in.(${c})`),this}contains(a,b){return"string"==typeof b?this.url.searchParams.append(a,`cs.${b}`):Array.isArray(b)?this.url.searchParams.append(a,`cs.{${b.join(",")}}`):this.url.searchParams.append(a,`cs.${JSON.stringify(b)}`),this}containedBy(a,b){return"string"==typeof b?this.url.searchParams.append(a,`cd.${b}`):Array.isArray(b)?this.url.searchParams.append(a,`cd.{${b.join(",")}}`):this.url.searchParams.append(a,`cd.${JSON.stringify(b)}`),this}rangeGt(a,b){return this.url.searchParams.append(a,`sr.${b}`),this}rangeGte(a,b){return this.url.searchParams.append(a,`nxl.${b}`),this}rangeLt(a,b){return this.url.searchParams.append(a,`sl.${b}`),this}rangeLte(a,b){return this.url.searchParams.append(a,`nxr.${b}`),this}rangeAdjacent(a,b){return this.url.searchParams.append(a,`adj.${b}`),this}overlaps(a,b){return"string"==typeof b?this.url.searchParams.append(a,`ov.${b}`):this.url.searchParams.append(a,`ov.{${b.join(",")}}`),this}textSearch(a,b,{config:c,type:d}={}){let e="";"plain"===d?e="pl":"phrase"===d?e="ph":"websearch"===d&&(e="w");let f=void 0===c?"":`(${c})`;return this.url.searchParams.append(a,`${e}fts${f}.${b}`),this}match(a){return Object.entries(a).filter(([a,b])=>void 0!==b).forEach(([a,b])=>{this.url.searchParams.append(a,`eq.${b}`)}),this}not(a,b,c){return this.url.searchParams.append(a,`not.${b}.${c}`),this}or(a,{foreignTable:b,referencedTable:c=b}={}){let d=c?`${c}.or`:"or";return this.url.searchParams.append(d,`(${a})`),this}filter(a,b,c){return this.url.searchParams.append(a,`${b}.${c}`),this}},b$=class{constructor(a,{headers:b={},schema:c,fetch:d,urlLengthLimit:e=8e3,retry:f}){this.url=a,this.headers=new Headers(b),this.schema=c,this.fetch=d,this.urlLengthLimit=e,this.retry=f}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(a,b){let{head:c=!1,count:d}=null!=b?b:{},e=!1,f=(null!=a?a:"*").split("").map(a=>/\s/.test(a)&&!e?"":('"'===a&&(e=!e),a)).join(""),{url:g,headers:h}=this.cloneRequestState();return g.searchParams.set("select",f),d&&h.append("Prefer",`count=${d}`),new bZ({method:c?"HEAD":"GET",url:g,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(a,{count:b,defaultToNull:c=!0}={}){var d;let{url:e,headers:f}=this.cloneRequestState();if(b&&f.append("Prefer",`count=${b}`),c||f.append("Prefer","missing=default"),Array.isArray(a)){let b=a.reduce((a,b)=>a.concat(Object.keys(b)),[]);if(b.length>0){let a=[...new Set(b)].map(a=>`"${a}"`);e.searchParams.set("columns",a.join(","))}}return new bZ({method:"POST",url:e,headers:f,schema:this.schema,body:a,fetch:null!=(d=this.fetch)?d:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(a,{onConflict:b,ignoreDuplicates:c=!1,count:d,defaultToNull:e=!0}={}){var f;let{url:g,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${c?"ignore":"merge"}-duplicates`),void 0!==b&&g.searchParams.set("on_conflict",b),d&&h.append("Prefer",`count=${d}`),e||h.append("Prefer","missing=default"),Array.isArray(a)){let b=a.reduce((a,b)=>a.concat(Object.keys(b)),[]);if(b.length>0){let a=[...new Set(b)].map(a=>`"${a}"`);g.searchParams.set("columns",a.join(","))}}return new bZ({method:"POST",url:g,headers:h,schema:this.schema,body:a,fetch:null!=(f=this.fetch)?f:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(a,{count:b}={}){var c;let{url:d,headers:e}=this.cloneRequestState();return b&&e.append("Prefer",`count=${b}`),new bZ({method:"PATCH",url:d,headers:e,schema:this.schema,body:a,fetch:null!=(c=this.fetch)?c:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:a}={}){var b;let{url:c,headers:d}=this.cloneRequestState();return a&&d.append("Prefer",`count=${a}`),new bZ({method:"DELETE",url:c,headers:d,schema:this.schema,fetch:null!=(b=this.fetch)?b:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function b_(a,b,c){var d;return{success:!1,error:new bN({message:`${null!=(d=null==a?void 0:a.name)?d:"FetchError"}: ${null==a?void 0:a.message}`,details:"",hint:"",code:""}),data:null,count:null,status:b,statusText:c}}var b0=class a{constructor(a,{headers:b={},schema:c,fetch:d,timeout:e,urlLengthLimit:f=8e3,retry:g}={}){this.url=a,this.headers=new Headers(b),this.schemaName=c,this.urlLengthLimit=f;let h=null!=d?d:globalThis.fetch;void 0!==e&&e>0?this.fetch=(a,b)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),e),f=null==b?void 0:b.signal;if(f){if(f.aborted)return clearTimeout(d),h(a,b);let e=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",e,{once:!0}),h(a,bT(bT({},b),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",e)})}return h(a,bT(bT({},b),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=h,this.retry=g}from(a){if(!a||"string"!=typeof a||""===a.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new b$(new URL(`${this.url}/${a}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(b){return new a(this.url,{headers:this.headers,schema:b,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var a,b;let c,d,e=new Headers(this.headers);e.set("Accept","application/openapi+json"),this.schemaName&&e.set("Accept-Profile",this.schemaName);let f={};e.forEach((a,b)=>{f[b]=a});let g=null!=(a=this.fetch)?a:globalThis.fetch;try{c=await bV(g,`${this.url}/`,{method:"GET",headers:f},null==(b=this.retry)||b)}catch(a){return b_(a,0,"")}try{d=await c.text()}catch(a){return b_(a,c.status,c.statusText)}if(c.ok)try{return{success:!0,error:null,data:JSON.parse(d),count:null,status:c.status,statusText:c.statusText}}catch(a){}return{success:!1,error:function(a,b){try{let b=JSON.parse(a);if(b&&"object"==typeof b&&!Array.isArray(b)){var c,d,e,f;return new bN({message:String(null!=(c=b.message)?c:a),details:null!=(d=b.details)?d:"",hint:null!=(e=b.hint)?e:"",code:null!=(f=b.code)?f:""})}}catch(a){}return new bN({message:a||b,details:"",hint:"",code:""})}(d,c.statusText),data:null,count:null,status:c.status,statusText:c.statusText}}rpc(a,b={},{head:c=!1,get:d=!1,count:e}={}){var f;let g,h,i=new URL(`${this.url}/rpc/${a}`),j=a=>null!==a&&"object"==typeof a&&(!Array.isArray(a)||a.some(j)),k=c&&Object.values(b).some(j);k?(g="POST",h=b):c||d?(g=c?"HEAD":"GET",Object.entries(b).filter(([a,b])=>void 0!==b).map(([a,b])=>[a,Array.isArray(b)?`{${b.join(",")}}`:`${b}`]).forEach(([a,b])=>{i.searchParams.append(a,b)})):(g="POST",h=b);let l=new Headers(this.headers);return k?l.set("Prefer",e?`count=${e},return=minimal`:"return=minimal"):e&&l.set("Prefer",`count=${e}`),new bZ({method:g,url:i,headers:l,schema:this.schemaName,body:h,fetch:null!=(f=this.fetch)?f:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class b1{constructor(){}static detectEnvironment(){var a;if("undefined"!=typeof WebSocket)return{type:"native",wsConstructor:WebSocket};let b=globalThis;if("undefined"!=typeof globalThis&&void 0!==b.WebSocket)return{type:"native",wsConstructor:b.WebSocket};let d=void 0!==c.g?c.g:void 0;if(d&&void 0!==d.WebSocket)return{type:"native",wsConstructor:d.WebSocket};if("undefined"!=typeof globalThis&&void 0!==b.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&b.EdgeRuntime||"undefined"!=typeof navigator&&(null==(a=navigator.userAgent)?void 0:a.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let e=globalThis.process;if(e){let a=e.versions;if(a&&a.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let a=this.detectEnvironment();if(a.wsConstructor)return a.wsConstructor;let b=a.error||"WebSocket not supported in this environment.";throw a.workaround&&(b+=`
17
+
18
+ Suggested solution: ${a.workaround}`),Error(b)}static isWebSocketSupported(){try{let a=this.detectEnvironment();return"native"===a.type}catch(a){return!1}}}let b2="2.0.0",b3={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},b4={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},b5={connecting:"connecting",closing:"closing",closed:"closed"};class b6{constructor(a){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=a?a:[]}encode(a,b){return a.event!==this.BROADCAST_EVENT||a.payload instanceof ArrayBuffer||"string"!=typeof a.payload.event?b(JSON.stringify([a.join_ref,a.ref,a.topic,a.event,a.payload])):b(this._binaryEncodeUserBroadcastPush(a))}_binaryEncodeUserBroadcastPush(a){var b;return this._isArrayBuffer(null==(b=a.payload)?void 0:b.payload)?this._encodeBinaryUserBroadcastPush(a):this._encodeJsonUserBroadcastPush(a)}_encodeBinaryUserBroadcastPush(a){var b,c;let d=null!=(c=null==(b=a.payload)?void 0:b.payload)?c:new ArrayBuffer(0);return this._encodeUserBroadcastPush(a,this.BINARY_ENCODING,d)}_encodeJsonUserBroadcastPush(a){var b,c;let d=null!=(c=null==(b=a.payload)?void 0:b.payload)?c:{},e=new TextEncoder().encode(JSON.stringify(d)).buffer;return this._encodeUserBroadcastPush(a,this.JSON_ENCODING,e)}_encodeUserBroadcastPush(a,b,c){let d=new TextEncoder,e=d.encode(a.topic),f=d.encode(null!=(p=a.ref)?p:""),g=d.encode(null!=(q=a.join_ref)?q:""),h=d.encode(a.payload.event),i=this.allowedMetadataKeys?this._pick(a.payload,this.allowedMetadataKeys):{},j=d.encode(0===Object.keys(i).length?"":JSON.stringify(i));if(g.length>255)throw Error(`joinRef length ${g.length} exceeds maximum of 255`);if(f.length>255)throw Error(`ref length ${f.length} exceeds maximum of 255`);if(e.length>255)throw Error(`topic length ${e.length} exceeds maximum of 255`);if(h.length>255)throw Error(`userEvent length ${h.length} exceeds maximum of 255`);if(j.length>255)throw Error(`metadata length ${j.length} exceeds maximum of 255`);let k=this.USER_BROADCAST_PUSH_META_LENGTH+g.length+f.length+e.length+h.length+j.length,l=new ArrayBuffer(this.HEADER_LENGTH+k),m=new DataView(l),n=new Uint8Array(l),o=0;m.setUint8(o++,this.KINDS.userBroadcastPush),m.setUint8(o++,g.length),m.setUint8(o++,f.length),m.setUint8(o++,e.length),m.setUint8(o++,h.length),m.setUint8(o++,j.length),m.setUint8(o++,b),n.set(g,o),o+=g.length,n.set(f,o),o+=f.length,n.set(e,o),o+=e.length,n.set(h,o),o+=h.length,n.set(j,o),o+=j.length;var p,q,r=new Uint8Array(l.byteLength+c.byteLength);return r.set(new Uint8Array(l),0),r.set(new Uint8Array(c),l.byteLength),r.buffer}decode(a,b){if(this._isArrayBuffer(a))return b(this._binaryDecode(a));if("string"==typeof a){let[c,d,e,f,g]=JSON.parse(a);return b({join_ref:c,ref:d,topic:e,event:f,payload:g})}return b({})}_binaryDecode(a){let b=new DataView(a),c=b.getUint8(0),d=new TextDecoder;if(c===this.KINDS.userBroadcast)return this._decodeUserBroadcast(a,b,d)}_decodeUserBroadcast(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=b.getUint8(4),h=this.HEADER_LENGTH+4,i=c.decode(a.slice(h,h+d));h+=d;let j=c.decode(a.slice(h,h+e));h+=e;let k=c.decode(a.slice(h,h+f));h+=f;let l=a.slice(h,a.byteLength),m=g===this.JSON_ENCODING?JSON.parse(c.decode(l)):l,n={type:this.BROADCAST_EVENT,event:j,payload:m};return f>0&&(n.meta=JSON.parse(k)),{join_ref:null,ref:null,topic:i,event:this.BROADCAST_EVENT,payload:n}}_isArrayBuffer(a){var b;return a instanceof ArrayBuffer||(null==(b=null==a?void 0:a.constructor)?void 0:b.name)==="ArrayBuffer"}_pick(a,b){return a&&"object"==typeof a?Object.fromEntries(Object.entries(a).filter(([a])=>b.includes(a))):{}}}!function(a){a.abstime="abstime",a.bool="bool",a.date="date",a.daterange="daterange",a.float4="float4",a.float8="float8",a.int2="int2",a.int4="int4",a.int4range="int4range",a.int8="int8",a.int8range="int8range",a.json="json",a.jsonb="jsonb",a.money="money",a.numeric="numeric",a.oid="oid",a.reltime="reltime",a.text="text",a.time="time",a.timestamp="timestamp",a.timestamptz="timestamptz",a.timetz="timetz",a.tsrange="tsrange",a.tstzrange="tstzrange"}(i||(i={}));let b7=(a,b,c={})=>{var d;let e=null!=(d=c.skipTypes)?d:[];return b?Object.keys(b).reduce((c,d)=>(c[d]=b8(d,a,b,e),c),{}):{}},b8=(a,b,c,d)=>{let e=b.find(b=>b.name===a),f=null==e?void 0:e.type,g=c[a];return f&&!d.includes(f)?b9(f,g):ca(g)},b9=(a,b)=>{if("_"===a.charAt(0))return ce(b,a.slice(1,a.length));switch(a){case i.bool:return cb(b);case i.float4:case i.float8:case i.int2:case i.int4:case i.int8:case i.numeric:case i.oid:return cc(b);case i.json:case i.jsonb:return cd(b);case i.timestamp:return cf(b);case i.abstime:case i.date:case i.daterange:case i.int4range:case i.int8range:case i.money:case i.reltime:case i.text:case i.time:case i.timestamptz:case i.timetz:case i.tsrange:case i.tstzrange:default:return ca(b)}},ca=a=>a,cb=a=>{switch(a){case"t":return!0;case"f":return!1;default:return a}},cc=a=>{if("string"==typeof a){let b=parseFloat(a);if(!Number.isNaN(b))return b}return a},cd=a=>{if("string"==typeof a)try{return JSON.parse(a)}catch(a){}return a},ce=(a,b)=>{if("string"!=typeof a)return a;let c=a.length-1,d=a[c];if("{"===a[0]&&"}"===d){let d,e=a.slice(1,c);try{d=JSON.parse("["+e+"]")}catch(a){d=e?e.split(","):[]}return d.map(a=>b9(b,a))}return a},cf=a=>"string"==typeof a?a.replace(" ","T"):a,cg=a=>{let b=new URL(a);return b.protocol=b.protocol.replace(/^ws/i,"http"),b.pathname=b.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===b.pathname||"/"===b.pathname?b.pathname="/api/broadcast":b.pathname=b.pathname+"/api/broadcast",b.href};var ch=a=>"function"==typeof a?a:function(){return a},ci="undefined"!=typeof window?window:null,cj=("undefined"!=typeof self?self:null)||ci||globalThis,ck={connecting:0,open:1,closing:2,closed:3},cl={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},cm={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},cn={longpoll:"longpoll",websocket:"websocket"},co={complete:4},cp="base64url.bearer.phx.",cq=class{constructor(a,b,c,d){this.channel=a,this.event=b,this.payload=c||function(){return{}},this.receivedResp=null,this.timeout=d,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(a){this.timeout=a,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(a,b){return this.hasReceived(a)&&b(this.receivedResp.response),this.recHooks.push({status:a,callback:b}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:a,response:b,_ref:c}){this.recHooks.filter(b=>b.status===a).forEach(a=>a.callback(b))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,a=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=a,this.matchReceive(a)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(a){return this.receivedResp&&this.receivedResp.status===a}trigger(a,b){this.channel.trigger(this.refEvent,{status:a,response:b})}},cr=class{constructor(a,b){this.callback=a,this.timerCalc=b,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},cs=class{constructor(a,b,c){this.state=cl.closed,this.topic=a,this.params=ch(b||{}),this.socket=c,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new cq(this,cm.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new cr(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=cl.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=cl.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=cl.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=cl.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new cq(this,cm.leave,ch({}),this.timeout).send(),this.state=cl.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(cm.reply,(a,b)=>{this.trigger(this.replyEventName(b),a)})}join(a=this.timeout){if(!this.joinedOnce)return this.timeout=a,this.joinedOnce=!0,this.rejoin(),this.joinPush;throw Error("tried to join multiple times. 'join' can only be called a single time per channel instance")}teardown(){this.pushBuffer.forEach(a=>a.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=cl.closed,this.bindings=[]}onClose(a){this.on(cm.close,a)}onError(a){return this.on(cm.error,b=>a(b))}on(a,b){let c=this.bindingRef++;return this.bindings.push({event:a,ref:c,callback:b}),c}off(a,b){this.bindings=this.bindings.filter(c=>c.event!==a||void 0!==b&&b!==c.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(a,b,c=this.timeout){if(b=b||{},!this.joinedOnce)throw Error(`tried to push '${a}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let d=new cq(this,a,function(){return b},c);return this.canPush()?d.send():(d.startTimeout(),this.pushBuffer.push(d)),d}leave(a=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=cl.leaving;let b=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(cm.close,"leave")},c=new cq(this,cm.leave,ch({}),a);return c.receive("ok",()=>b()).receive("timeout",()=>b()),c.send(),this.canPush()||c.trigger("ok",{}),c}onMessage(a,b,c){return b}filterBindings(a,b,c){return!0}isMember(a,b,c,d){return this.topic===a&&(!d||d===this.joinRef()||(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:a,event:b,payload:c,joinRef:d}),!1))}joinRef(){return this.joinPush.ref}rejoin(a=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=cl.joining,this.joinPush.resend(a))}trigger(a,b,c,d){let e=this.onMessage(a,b,c,d);if(b&&!e)throw Error("channel onMessage callbacks must return the payload, modified or unmodified");let f=this.bindings.filter(d=>d.event===a&&this.filterBindings(d,b,c));for(let a=0;a<f.length;a++)f[a].callback(e,c,d||this.joinRef())}replyEventName(a){return`chan_reply_${a}`}isClosed(){return this.state===cl.closed}isErrored(){return this.state===cl.errored}isJoined(){return this.state===cl.joined}isJoining(){return this.state===cl.joining}isLeaving(){return this.state===cl.leaving}},ct=class{static request(a,b,c,d,e,f,g){if(cj.XDomainRequest){let c=new cj.XDomainRequest;return this.xdomainRequest(c,a,b,d,e,f,g)}if(cj.XMLHttpRequest){let h=new cj.XMLHttpRequest;return this.xhrRequest(h,a,b,c,d,e,f,g)}if(cj.fetch&&cj.AbortController)return this.fetchRequest(a,b,c,d,e,f,g);throw Error("No suitable XMLHttpRequest implementation found")}static fetchRequest(a,b,c,d,e,f,g){let h={method:a,headers:c,body:d},i=null;return e&&(i=new AbortController,setTimeout(()=>i.abort(),e),h.signal=i.signal),cj.fetch(b,h).then(a=>a.text()).then(a=>this.parseJSON(a)).then(a=>g&&g(a)).catch(a=>{"AbortError"===a.name&&f?f():g&&g(null)}),i}static xdomainRequest(a,b,c,d,e,f,g){return a.timeout=e,a.open(b,c),a.onload=()=>{let b=this.parseJSON(a.responseText);g&&g(b)},f&&(a.ontimeout=f),a.onprogress=()=>{},a.send(d),a}static xhrRequest(a,b,c,d,e,f,g,h){for(let[e,g]of(a.open(b,c,!0),a.timeout=f,Object.entries(d)))a.setRequestHeader(e,g);return a.onerror=()=>h&&h(null),a.onreadystatechange=()=>{a.readyState===co.complete&&h&&h(this.parseJSON(a.responseText))},g&&(a.ontimeout=g),a.send(e),a}static parseJSON(a){if(!a||""===a)return null;try{return JSON.parse(a)}catch{return console&&console.log("failed to parse JSON response",a),null}}static serialize(a,b){let c=[];for(var d in a){if(!Object.prototype.hasOwnProperty.call(a,d))continue;let e=b?`${b}[${d}]`:d,f=a[d];"object"==typeof f?c.push(this.serialize(f,e)):c.push(encodeURIComponent(e)+"="+encodeURIComponent(f))}return c.join("&")}static appendParams(a,b){if(0===Object.keys(b).length)return a;let c=a.match(/\?/)?"&":"?";return`${a}${c}${this.serialize(b)}`}},cu=class{constructor(a,b){b&&2===b.length&&b[1].startsWith(cp)&&(this.authToken=atob(b[1].slice(cp.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(a),this.readyState=ck.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(a){return a.replace("ws://","http://").replace("wss://","https://").replace(RegExp("(.*)/"+cn.websocket),"$1/"+cn.longpoll)}endpointURL(){return ct.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(a,b,c){this.close(a,b,c),this.readyState=ck.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===ck.open||this.readyState===ck.connecting}poll(){let a={Accept:"application/json"};this.authToken&&(a["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",a,null,()=>this.ontimeout(),a=>{if(a){var{status:b,token:c,messages:d}=a;if(410===b&&null!==this.token){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=c}else b=0;switch(b){case 200:d.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ck.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw Error(`unhandled poll status ${b}`)}})}send(a){"string"!=typeof a&&(a=(a=>{let b="",c=new Uint8Array(a),d=c.byteLength;for(let a=0;a<d;a++)b+=String.fromCharCode(c[a]);return btoa(b)})(a)),this.currentBatch?this.currentBatch.push(a):this.awaitingBatchAck?this.batchBuffer.push(a):(this.currentBatch=[a],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(a,b=0){this.awaitingBatchAck=!0;let c=b+100,d=a.slice(b,c);this.ajax("POST",{"Content-Type":"application/x-ndjson"},d.join("\n"),()=>this.onerror("timeout"),b=>{b&&200===b.status?c<a.length?this.batchSend(a,c):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1:(this.awaitingBatchAck=!1,this.onerror(b&&b.status),this.closeAndRetry(1011,"internal server error",!1))})}close(a,b,c){for(let a of this.reqs)a.abort();this.readyState=ck.closed;let d=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:a,reason:b,wasClean:c});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,"undefined"!=typeof CloseEvent?this.onclose(new CloseEvent("close",d)):this.onclose(d)}ajax(a,b,c,d,e){let f,g=()=>{this.reqs.delete(f),d()};f=ct.request(a,this.endpointURL(),b,c,this.timeout,g,a=>{this.reqs.delete(f),this.isActive()&&e(a)}),this.reqs.add(f)}},cv=class a{constructor(b,c={}){let d=c.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=b,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(d.state,b=>{let{onJoin:c,onLeave:d,onSync:e}=this.caller;this.joinRef=this.channel.joinRef(),this.state=a.syncState(this.state,b,c,d),this.pendingDiffs.forEach(b=>{this.state=a.syncDiff(this.state,b,c,d)}),this.pendingDiffs=[],e()}),this.channel.on(d.diff,b=>{let{onJoin:c,onLeave:d,onSync:e}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(b):(this.state=a.syncDiff(this.state,b,c,d),e())})}onJoin(a){this.caller.onJoin=a}onLeave(a){this.caller.onLeave=a}onSync(a){this.caller.onSync=a}list(b){return a.list(this.state,b)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(a,b,c,d){let e=this.toNullProtoObj(this.clone(a));b=this.toNullProtoObj(b);let f=Object.create(null),g=Object.create(null);return this.map(e,(a,c)=>{b[a]||(g[a]=c)}),this.map(b,(a,b)=>{let c=e[a];if(c){let d=b.metas.map(a=>a.phx_ref),e=c.metas.map(a=>a.phx_ref),h=b.metas.filter(a=>0>e.indexOf(a.phx_ref)),i=c.metas.filter(a=>0>d.indexOf(a.phx_ref));h.length>0&&(f[a]=b,f[a].metas=h),i.length>0&&(g[a]=this.clone(c),g[a].metas=i)}else f[a]=b}),this.syncDiff(e,{joins:f,leaves:g},c,d)}static syncDiff(a,b,c,d){a=this.toNullProtoObj(a);let{joins:e,leaves:f}=this.clone(b);return c||(c=function(){}),d||(d=function(){}),this.map(e,(b,d)=>{let e=a[b];if(a[b]=this.clone(d),e){let c=a[b].metas.map(a=>a.phx_ref),d=e.metas.filter(a=>0>c.indexOf(a.phx_ref));a[b].metas.unshift(...d)}c(b,e,d)}),this.map(f,(b,c)=>{let e=a[b];if(!e)return;let f=c.metas.map(a=>a.phx_ref);e.metas=e.metas.filter(a=>0>f.indexOf(a.phx_ref)),d(b,e,c),0===e.metas.length&&delete a[b]}),a}static list(a,b){return b||(b=function(a,b){return b}),this.map(a,(a,c)=>b(a,c))}static map(a,b){return Object.getOwnPropertyNames(a).map(c=>b(c,a[c]))}static toNullProtoObj(a){if(null===Object.getPrototypeOf(a))return a;let b=Object.create(null);return Object.getOwnPropertyNames(a).forEach(c=>{b[c]=a[c]}),b}static clone(a){return JSON.parse(JSON.stringify(a))}},cw={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(a,b){return a.payload.constructor===ArrayBuffer?b(this.binaryEncode(a)):b(JSON.stringify([a.join_ref,a.ref,a.topic,a.event,a.payload]))},decode(a,b){if(a.constructor===ArrayBuffer)return b(this.binaryDecode(a));{let[c,d,e,f,g]=JSON.parse(a);return b({join_ref:c,ref:d,topic:e,event:f,payload:g})}},binaryEncode(a){let{join_ref:b,ref:c,event:d,topic:e,payload:f}=a,g=new TextEncoder,h=g.encode(b),i=g.encode(c),j=g.encode(e),k=g.encode(d);this.assertFieldSize(h.byteLength,"join_ref"),this.assertFieldSize(i.byteLength,"ref"),this.assertFieldSize(j.byteLength,"topic"),this.assertFieldSize(k.byteLength,"event");let l=this.META_LENGTH+h.byteLength+i.byteLength+j.byteLength+k.byteLength,m=new ArrayBuffer(this.HEADER_LENGTH+l),n=new Uint8Array(m),o=new DataView(m),p=0;o.setUint8(p++,this.KINDS.push),o.setUint8(p++,h.byteLength),o.setUint8(p++,i.byteLength),o.setUint8(p++,j.byteLength),o.setUint8(p++,k.byteLength),n.set(h,p),p+=h.byteLength,n.set(i,p),p+=i.byteLength,n.set(j,p),p+=j.byteLength,n.set(k,p),p+=k.byteLength;var q=new Uint8Array(m.byteLength+f.byteLength);return q.set(n,0),q.set(new Uint8Array(f),m.byteLength),q.buffer},assertFieldSize(a,b){if(a>255)throw Error(`unable to convert ${b} to binary: must be less than or equal to 255 bytes, but is ${a} bytes`)},binaryDecode(a){let b=new DataView(a),c=b.getUint8(0),d=new TextDecoder;switch(c){case this.KINDS.push:return this.decodePush(a,b,d);case this.KINDS.reply:return this.decodeReply(a,b,d);case this.KINDS.broadcast:return this.decodeBroadcast(a,b,d)}},decodePush(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=this.HEADER_LENGTH+this.META_LENGTH-1,h=c.decode(a.slice(g,g+d));g+=d;let i=c.decode(a.slice(g,g+e));g+=e;let j=c.decode(a.slice(g,g+f));return g+=f,{join_ref:h,ref:null,topic:i,event:j,payload:a.slice(g,a.byteLength)}},decodeReply(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=b.getUint8(3),g=b.getUint8(4),h=this.HEADER_LENGTH+this.META_LENGTH,i=c.decode(a.slice(h,h+d));h+=d;let j=c.decode(a.slice(h,h+e));h+=e;let k=c.decode(a.slice(h,h+f));h+=f;let l=c.decode(a.slice(h,h+g));h+=g;let m=a.slice(h,a.byteLength);return{join_ref:i,ref:j,topic:k,event:cm.reply,payload:{status:l,response:m}}},decodeBroadcast(a,b,c){let d=b.getUint8(1),e=b.getUint8(2),f=this.HEADER_LENGTH+2,g=c.decode(a.slice(f,f+d));f+=d;let h=c.decode(a.slice(f,f+e));return f+=e,{join_ref:null,ref:null,topic:g,event:h,payload:a.slice(f,a.byteLength)}}},cx=class{constructor(a,b={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=b.timeout||1e4,this.transport=b.transport||cj.WebSocket||cu,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=b.longPollFallbackMs,this.fallbackTimer=null;let c=null;try{c=cj&&cj.sessionStorage}catch{}this.sessionStore=b.sessionStorage||c,this.establishedConnections=0,this.defaultEncoder=cw.encode.bind(cw),this.defaultDecoder=cw.decode.bind(cw),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=b.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==cu?(this.encode=b.encode||this.defaultEncoder,this.decode=b.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let d=null;ci&&ci.addEventListener&&(ci.addEventListener("pagehide",a=>{this.conn&&(this.disconnect(),d=this.connectClock)}),ci.addEventListener("pageshow",a=>{d===this.connectClock&&(d=null,this.connect())}),ci.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState?this.pageHidden=!0:(this.pageHidden=!1,this.isConnected()||this.closeWasClean||this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=b.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=b.autoSendHeartbeat??!0,this.heartbeatCallback=b.heartbeatCallback??(()=>{}),this.rejoinAfterMs=a=>b.rejoinAfterMs?b.rejoinAfterMs(a):[1e3,2e3,5e3][a-1]||1e4,this.reconnectAfterMs=a=>b.reconnectAfterMs?b.reconnectAfterMs(a):[10,50,100,150,200,250,500,1e3,2e3][a-1]||5e3,this.logger=b.logger||null,!this.logger&&b.debug&&(this.logger=(a,b,c)=>{console.log(`${a}: ${b}`,c)}),this.longpollerTimeout=b.longpollerTimeout||2e4,this.params=ch(b.params||{}),this.endPoint=`${a}/${cn.websocket}`,this.vsn=b.vsn||"2.0.0",this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new cr(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{b.beforeReconnect&&await b.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=b.authToken&&ch(b.authToken)}getLongPollTransport(){return cu}replaceTransport(a){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=a}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let a=ct.appendParams(ct.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return"/"!==a.charAt(0)?a:"/"===a.charAt(1)?`${this.protocol()}:${a}`:`${this.protocol()}://${location.host}${a}`}disconnect(a,b,c){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,a&&a()},b,c)}connect(a){a&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=ch(a)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==cu?this.connectWithFallback(cu,this.longPollFallbackMs):this.transportConnect())}log(a,b,c){this.logger&&this.logger(a,b,c)}hasLogger(){return null!==this.logger}onOpen(a){let b=this.makeRef();return this.stateChangeCallbacks.open.push([b,a]),b}onClose(a){let b=this.makeRef();return this.stateChangeCallbacks.close.push([b,a]),b}onError(a){let b=this.makeRef();return this.stateChangeCallbacks.error.push([b,a]),b}onMessage(a){let b=this.makeRef();return this.stateChangeCallbacks.message.push([b,a]),b}onHeartbeat(a){this.heartbeatCallback=a}ping(a){if(!this.isConnected())return!1;let b=this.makeRef(),c=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:b});let d=this.onMessage(e=>{e.ref===b&&(this.off([d]),a(Date.now()-c))});return!0}transportName(a){return a===cu?"LongPoll":a.name}transportConnect(){let a;this.connectClock++,this.closeWasClean=!1,this.authToken&&(a=["phoenix",`${cp}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),a),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=a=>this.onConnError(a),this.conn.onmessage=a=>this.onConnMessage(a),this.conn.onclose=a=>this.onConnClose(a)}getSession(a){return this.sessionStore&&this.sessionStore.getItem(a)}storeSession(a,b){this.sessionStore&&this.sessionStore.setItem(a,b)}connectWithFallback(a,b=2500){let c,d;clearTimeout(this.fallbackTimer);let e=!1,f=!0,g=this.transportName(a),h=b=>{this.log("transport",`falling back to ${g}...`,b),this.off([c,d]),f=!1,this.replaceTransport(a),this.transportConnect()};if(this.getSession(`phx:fallback:${g}`))return h("memorized");this.fallbackTimer=setTimeout(h,b),d=this.onError(a=>{this.log("transport","error",a),f&&!e&&(clearTimeout(this.fallbackTimer),h(a))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(e=!0,!f){let b=this.transportName(a);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${b}`,"true"),this.log("transport",`established ${b} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(h,b),this.ping(a=>{this.log("transport","connected to primary after",a),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(a){this.log("error","error in heartbeat callback",a)}this.triggerChanError(Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),1e3,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(a,b,c){if(!this.conn)return a&&a();let d=this.conn;this.waitForBufferDone(d,()=>{b?d.close(b,c||""):d.close(),this.waitForSocketClosed(d,()=>{this.conn===d&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),a&&a()})})}waitForBufferDone(a,b,c=1){if(5===c||!a.bufferedAmount)return void b();setTimeout(()=>{this.waitForBufferDone(a,b,c+1)},150*c)}waitForSocketClosed(a,b,c=1){if(5===c||a.readyState===ck.closed)return void b();setTimeout(()=>{this.waitForSocketClosed(a,b,c+1)},150*c)}onConnClose(a){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",a),this.triggerChanError(a),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",a)}onConnError(a){this.hasLogger()&&this.log("transport","error",a);let b=this.transport,c=this.establishedConnections;this.triggerStateCallbacks("error",a,b,c),(b===this.transport||c>0)&&this.triggerChanError(a)}triggerChanError(a){this.channels.forEach(b=>{b.isErrored()||b.isLeaving()||b.isClosed()||b.trigger(cm.error,a)})}connectionState(){switch(this.conn&&this.conn.readyState){case ck.connecting:return"connecting";case ck.open:return"open";case ck.closing:return"closing";default:return"closed"}}isConnected(){return"open"===this.connectionState()}remove(a){this.off(a.stateChangeRefs),this.channels=this.channels.filter(b=>b!==a)}off(a){for(let b in this.stateChangeCallbacks)this.stateChangeCallbacks[b]=this.stateChangeCallbacks[b].filter(([b])=>-1===a.indexOf(b))}channel(a,b={}){let c=new cs(a,b,this);return this.channels.push(c),c}push(a){if(this.hasLogger()){let{topic:b,event:c,payload:d,ref:e,join_ref:f}=a;this.log("push",`${b} ${c} (${f}, ${e})`,d)}this.isConnected()?this.encode(a,a=>this.conn.send(a)):this.sendBuffer.push(()=>this.encode(a,a=>this.conn.send(a)))}makeRef(){let a=this.ref+1;return a===this.ref?this.ref=0:this.ref=a,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(a){this.log("error","error in heartbeat callback",a)}return}if(this.pendingHeartbeatRef)return void this.heartbeatTimeout();this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(a){this.log("error","error in heartbeat callback",a)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(a=>a()),this.sendBuffer=[])}onConnMessage(a){this.decode(a.data,a=>{let{topic:b,event:c,payload:d,ref:e,join_ref:f}=a;if(e&&e===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback("ok"===d.status?"ok":"error",a)}catch(a){this.log("error","error in heartbeat callback",a)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${d.status||""} ${b} ${c} ${e&&"("+e+")"||""}`.trim(),d);for(let a=0;a<this.channels.length;a++){let g=this.channels[a];g.isMember(b,c,d,f)&&g.trigger(c,d,e,f)}this.triggerStateCallbacks("message",a)})}triggerStateCallbacks(a,...b){try{this.stateChangeCallbacks[a].forEach(([c,d])=>{try{d(...b)}catch(b){this.log("error",`error in ${a} callback`,b)}})}catch(b){this.log("error",`error triggering ${a} callbacks`,b)}}leaveOpenTopic(a){let b=this.channels.find(b=>b.topic===a&&(b.isJoined()||b.isJoining()));b&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${a}"`),b.leave())}};class cy{constructor(a,b){let c=function(a){return(null==a?void 0:a.events)&&{events:a.events}}(b);this.presence=new cv(a.getChannel(),c),this.presence.onJoin((b,c,d)=>{let e=cy.onJoinPayload(b,c,d);a.getChannel().trigger("presence",e)}),this.presence.onLeave((b,c,d)=>{let e=cy.onLeavePayload(b,c,d);a.getChannel().trigger("presence",e)}),this.presence.onSync(()=>{a.getChannel().trigger("presence",{event:"sync"})})}get state(){return cy.transformState(this.presence.state)}static transformState(a){return Object.getOwnPropertyNames(a=JSON.parse(JSON.stringify(a))).reduce((b,c)=>{let d=a[c];return b[c]=cz(d),b},{})}static onJoinPayload(a,b,c){return{event:"join",key:a,currentPresences:cA(b),newPresences:cz(c)}}static onLeavePayload(a,b,c){return{event:"leave",key:a,currentPresences:cA(b),leftPresences:cz(c)}}}function cz(a){return a.metas.map(a=>{let b=Object.defineProperties({},Object.getOwnPropertyDescriptors(a));return b.presence_ref=b.phx_ref,delete b.phx_ref,delete b.phx_ref_prev,b})}function cA(a){return(null==a?void 0:a.metas)?cz(a):[]}!function(a){a.SYNC="sync",a.JOIN="join",a.LEAVE="leave"}(j||(j={}));class cB{get state(){return this.presenceAdapter.state}constructor(a,b){this.channel=a,this.presenceAdapter=new cy(this.channel.channelAdapter,b)}}class cC{constructor(a,b,c){let d={config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},c.config)};this.channel=a.getSocket().channel(b,d),this.socket=a}get state(){return this.channel.state}set state(a){this.channel.state=a}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(a,b){return this.channel.on(a,b)}off(a,b){this.channel.off(a,b)}subscribe(a){return this.channel.join(a)}unsubscribe(a){return this.channel.leave(a)}teardown(){this.channel.teardown()}onClose(a){this.channel.onClose(a)}onError(a){return this.channel.onError(a)}push(a,b,c){let d;try{d=this.channel.push(a,b,c)}catch(b){throw Error(`tried to push '${a}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>100){let a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return d}updateJoinPayload(a){let b=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},b),a)}canPush(){return this.socket.isConnected()&&this.state===b3.joined}isJoined(){return this.state===b3.joined}isJoining(){return this.state===b3.joining}isClosed(){return this.state===b3.closed}isLeaving(){return this.state===b3.leaving}updateFilterBindings(a){this.channel.filterBindings=a}updatePayloadTransform(a){this.channel.onMessage=a}getChannel(){return this.channel}}let cD=/[,()"\\]/,cE=a=>{let b=null===a?"null":String(a);return(a=>cD.test(a)||a!==a.trim())(b)?`"${b.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:b};class cF{constructor(){this.filters=[]}add(a,b,c,d=!1){return this.filters.push(`${a}=${d?"not.":""}${((a,b)=>{let c;if("in"===a){let a=Array.isArray(b)?b:[b];if(0===a.length)throw Error("Realtime `in` filter requires at least one value.");let c=Array.from(new Set(a)).map(a=>cE(a)).join(",");return`in.(${c})`}return"is"===a?`is.${null===(c=b)?"null":String(c)}`:`${a}.${cE(b)}`})(b,c)}`),this}eq(a,b){return this.add(a,"eq",b)}neq(a,b){return this.add(a,"neq",b)}gt(a,b){return this.add(a,"gt",b)}gte(a,b){return this.add(a,"gte",b)}lt(a,b){return this.add(a,"lt",b)}lte(a,b){return this.add(a,"lte",b)}in(a,b){return this.add(a,"in",b)}like(a,b){return this.add(a,"like",b)}ilike(a,b){return this.add(a,"ilike",b)}match(a,b){return this.add(a,"match",b)}imatch(a,b){return this.add(a,"imatch",b)}is(a,b){return this.add(a,"is",b)}isDistinct(a,b){return this.add(a,"isdistinct",b)}not(a,b,c){return this.add(a,b,c,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}!function(a){a.ALL="*",a.INSERT="INSERT",a.UPDATE="UPDATE",a.DELETE="DELETE"}(k||(k={})),function(a){a.BROADCAST="broadcast",a.PRESENCE="presence",a.POSTGRES_CHANGES="postgres_changes",a.SYSTEM="system"}(l||(l={})),function(a){a.SUBSCRIBED="SUBSCRIBED",a.TIMED_OUT="TIMED_OUT",a.CLOSED="CLOSED",a.CHANNEL_ERROR="CHANNEL_ERROR"}(m||(m={}));class cG{get state(){return this.channelAdapter.state}set state(a){this.channelAdapter.state=a}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(a,b={config:{}},c){var d,e;if(this.topic=a,this.params=b,this.socket=c,this.bindings={},this.subTopic=a.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},b.config),this.channelAdapter=new cC(this.socket.socketAdapter,a,this.params),this.presence=new cB(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=cg(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(null==(e=null==(d=this.params.config)?void 0:d.broadcast)?void 0:e.replay))throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(a,b=this.timeout){var c,d,e,f;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:g,presence:h,private:i,postgres_changes_options:j}}=this.params,k=null!=(d=null==(c=this.bindings.postgres_changes)?void 0:c.map(a=>a.filter))?d:[],n=!!this.bindings[l.PRESENCE]&&this.bindings[l.PRESENCE].length>0||(null==(e=this.params.config.presence)?void 0:e.enabled)===!0,o={},p=Object.assign({broadcast:g,presence:Object.assign(Object.assign({},h),{enabled:n}),postgres_changes:k,private:i},j?{postgres_changes_options:j}:{});this.socket.accessTokenValue&&(o.access_token=this.socket.accessTokenValue),this._onError(b=>{null==a||a(m.CHANNEL_ERROR,function(a){if(a instanceof Error)return a;if("string"==typeof a)return Error(a);if(a&&"object"==typeof a){if("number"==typeof a.code){let b="string"==typeof a.reason&&a.reason?` (${a.reason})`:"";return Error(`socket closed: ${a.code}${b}`,{cause:a})}return Error("channel error: transport failure",{cause:a})}return Error("channel error: connection lost")}(b))}),this._onClose(()=>null==a?void 0:a(m.CLOSED)),this.updateJoinPayload(Object.assign({config:p},o)),this._updateFilterMessage();let q=(null==j?void 0:j.wait)&&k.length>0?Math.max(b,(null!=(f=j.timeout)?f:15e3)+1e4):b;this.channelAdapter.subscribe(q).receive("ok",async({postgres_changes:b})=>{if(this.socket._isManualToken()||this.socket.setAuth(),void 0===b){null==a||a(m.SUBSCRIBED);return}this._updatePostgresBindings(b,a)}).receive("error",b=>{this.state=b3.errored;let c=Object.values(b).join(", ")||"error";null==a||a(m.CHANNEL_ERROR,Error(c,{cause:b}))}).receive("timeout",()=>{null==a||a(m.TIMED_OUT)})}return this}_updatePostgresBindings(a,b){var c;let d=this.bindings.postgres_changes,e=null!=(c=null==d?void 0:d.length)?c:0,f=[];for(let c=0;c<e;c++){let e=d[c],{filter:{event:g,schema:h,table:i,filter:j}}=e,k=a&&a[c];if(k&&k.event===g&&cG.isFilterValueEqual(k.schema,h)&&cG.isFilterValueEqual(k.table,i)&&cG.isFilterValueEqual(k.filter,j))f.push(Object.assign(Object.assign({},e),{id:k.id}));else{this.unsubscribe(),this.state=b3.errored,null==b||b(m.CHANNEL_ERROR,Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=f,this.state!=b3.errored&&b&&b(m.SUBSCRIBED)}presenceState(){return this.presence.state}async track(a,b={}){return await this.send({type:"presence",event:"track",payload:a},b)}async untrack(a={}){return await this.send({type:"presence",event:"untrack"},a)}on(a,b,c){let d=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),e=a===l.PRESENCE||a===l.POSTGRES_CHANGES;if(d&&e)throw this.socket.log("channel",`cannot add \`${a}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${a}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(a,b,c)}async httpSend(a,b,c={}){var d;if(null==b)return Promise.reject(Error("Payload is required for httpSend()"));let e=b instanceof ArrayBuffer||ArrayBuffer.isView(b),f={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":e?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(f.Authorization=`Bearer ${this.socket.accessTokenValue}`);let g=new URL(this.broadcastEndpointURL);g.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(a)}`,this.private&&g.searchParams.set("private","true");let h={method:"POST",headers:f,body:e?b:JSON.stringify(b)},i=await this._fetchWithTimeout(g.toString(),h,null!=(d=c.timeout)?d:this.timeout);if(202===i.status)return{success:!0};if(404===i.status)return Promise.reject(Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));let j=i.statusText;try{let a=await i.json();j=a.error||a.message||j}catch(a){}return Promise.reject(Error(j))}async send(a,b={}){var c,d;if(this.channelAdapter.canPush()||"broadcast"!==a.type)return new Promise(c=>{var d,e,f;let g=this.channelAdapter.push(a.type,a,b.timeout||this.timeout);"broadcast"!==a.type||(null==(f=null==(e=null==(d=this.params)?void 0:d.config)?void 0:e.broadcast)?void 0:f.ack)||c("ok"),g.receive("ok",()=>c("ok")),g.receive("error",()=>c("error")),g.receive("timeout",()=>c("timed out"))});{let e="Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.";this.socket.hasLogger()?this.socket.log("channel",e):console.warn(e);let{event:f,payload:g}=a,h={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(h.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:h,body:JSON.stringify({messages:[{topic:this.subTopic,event:f,payload:g,private:this.private}]})};try{let a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!=(c=b.timeout)?c:this.timeout);return await (null==(d=a.body)?void 0:d.cancel()),a.ok?"ok":"error"}catch(a){if(a instanceof Error&&"AbortError"===a.name)return"timed out";return"error"}}}updateJoinPayload(a){this.channelAdapter.updateJoinPayload(a)}async unsubscribe(a=this.timeout){return new Promise(b=>{this.channelAdapter.unsubscribe(a).receive("ok",()=>b("ok")).receive("timeout",()=>b("timed out")).receive("error",()=>b("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(a,b,c){let d=new AbortController,e=setTimeout(()=>d.abort(),c),f=await this.socket.fetch(a,Object.assign(Object.assign({},b),{signal:d.signal}));return clearTimeout(e),f}_on(a,b,c){var d;let e=a.toLocaleLowerCase(),f=null==b?void 0:b.filter;if((f instanceof cF||"object"==typeof f&&null!==f&&"function"==typeof f.build)&&(b=Object.assign(Object.assign({},b),{filter:f.build()})),e===l.POSTGRES_CHANGES&&(null==(d=this.bindings[e])?void 0:d.find(a=>cG.isSamePostgresFilter(a.filter,b))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,b),this;let g=this.channelAdapter.on(a,c),h={type:e,filter:b,callback:c,ref:g};return this.bindings[e]?this.bindings[e].push(h):this.bindings[e]=[h],this._updateFilterMessage(),this}_onClose(a){this.channelAdapter.onClose(a)}_onError(a){this.channelAdapter.onError(a)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((a,b,c)=>{var d,e,f,g,h,i,j;let k=a.event.toLocaleLowerCase();if(this._notThisChannelEvent(k,c))return!1;let l=null==(d=this.bindings[k])?void 0:d.find(b=>b.ref===a.ref);if(!l)return!0;if(!["broadcast","presence","postgres_changes"].includes(k))return l.type.toLocaleLowerCase()===k;if("id"in l){let a=l.id,c=null==(e=l.filter)?void 0:e.event;return a&&(null==(f=b.ids)?void 0:f.includes(a))&&("*"===c||(null==c?void 0:c.toLocaleLowerCase())===(null==(g=b.data)?void 0:g.type.toLocaleLowerCase()))}{let a=null==(i=null==(h=null==l?void 0:l.filter)?void 0:h.event)?void 0:i.toLocaleLowerCase();return"*"===a||a===(null==(j=null==b?void 0:b.event)?void 0:j.toLocaleLowerCase())}})}_notThisChannelEvent(a,b){let{close:c,error:d,leave:e,join:f}=b4;return b&&[c,d,e,f].includes(a)&&b!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((a,b,c)=>{if("object"==typeof b&&"ids"in b){let a=b.data,{schema:c,table:d,commit_timestamp:e,type:f,errors:g}=a;return Object.assign(Object.assign({},{schema:c,table:d,commit_timestamp:e,eventType:f,new:{},old:{},errors:g}),this._getPayloadRecords(a))}return b})}copyBindings(a){if(this.joinedOnce)throw Error("cannot copy bindings into joined channel");for(let b in a.bindings)for(let c of a.bindings[b])this._on(c.type,c.filter,c.callback)}static isFilterValueEqual(a,b){return(null!=a?a:void 0)===(null!=b?b:void 0)}static isSamePostgresFilter(a,b){var c,d,e,f;let g=null!=(d=null==(c=null==a?void 0:a.select)?void 0:c.join())?d:void 0,h=null!=(f=null==(e=null==b?void 0:b.select)?void 0:e.join())?f:void 0;return(null==a?void 0:a.event)===(null==b?void 0:b.event)&&cG.isFilterValueEqual(null==a?void 0:a.schema,null==b?void 0:b.schema)&&cG.isFilterValueEqual(null==a?void 0:a.table,null==b?void 0:b.table)&&cG.isFilterValueEqual(null==a?void 0:a.filter,null==b?void 0:b.filter)&&g===h}_getPayloadRecords(a){let b={new:{},old:{}};return("INSERT"===a.type||"UPDATE"===a.type)&&(b.new=b7(a.columns,a.record)),("UPDATE"===a.type||"DELETE"===a.type)&&(b.old=b7(a.columns,a.old_record)),b}}class cH{constructor(a,b){this.socket=new cx(a,b)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(a){this.socket.heartbeatCallback=a}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(a,b,c,d=1e4){return new Promise(e=>{setTimeout(()=>e("timeout"),d),this.socket.disconnect(()=>{a(),e("ok")},b,c)})}push(a){this.socket.push(a)}log(a,b,c){this.socket.log(a,b,c)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(a){this.socket.onOpen(a)}onClose(a){this.socket.onClose(a)}onError(a){this.socket.onError(a)}onMessage(a){this.socket.onMessage(a)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==b5.connecting}isDisconnecting(){return this.socket.connectionState()==b5.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}let cI={HEARTBEAT_INTERVAL:25e3},cJ=[1e3,2e3,5e3,1e4],cK=`
19
+ addEventListener("message", (e) => {
20
+ if (e.data.event === "start") {
21
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
22
+ }
23
+ });`;class cL{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(a,b){var c;if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new b6,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=a=>a?(...b)=>a(...b):(...a)=>fetch(...a),!(null==(c=null==b?void 0:b.params)?void 0:c.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=b.params.apikey;let d=this._initializeOptions(b);this.socketAdapter=new cH(a,d),this.httpEndpoint=cg(a),this.fetch=this._resolveFetch(null==b?void 0:b.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(b){let a=b.message;throw Error(`WebSocket not available: ${a}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(a,b){return(this._cancelPendingDisconnect(),this.isDisconnecting())?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},a,b)}getChannels(){return this.channels}async removeChannel(a){let b=await a.unsubscribe();return"ok"===b&&a.teardown(),b}async removeAllChannels(){let a=this.channels.map(async a=>{let b=await a.unsubscribe();return a.teardown(),b}),b=await Promise.all(a);return await this.disconnect(),b}log(a,b,c){this.socketAdapter.log(a,b,c)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||b5.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(a,b={config:{}}){let c=`realtime:${a}`,d=this.getChannels().find(a=>a.topic===c);if(d)return d;{let c=new cG(`realtime:${a}`,b,this);return this._cancelPendingDisconnect(),this.channels.push(c),c}}push(a){this.socketAdapter.push(a)}async setAuth(a=null){let b=++this._authGeneration,c=this._performAuth(a,b);b===this._authGeneration&&(this._authPromise=c);try{await c}finally{this._authPromise===c&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(a){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(a)}_makeRef(){return this.socketAdapter.makeRef()}_remove(a){this.channels=this.channels.filter(b=>b.topic!==a.topic),0===this.channels.length&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),0===this._disconnectOnEmptyChannelsAfterMs){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,0===this.channels.length&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){null!==this._pendingDisconnectTimer&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(a,b){let c,d=!1;if(a)c=a,d=!0;else if(this.accessToken)try{c=await this.accessToken()}catch(a){this.log("error","Error fetching access token from callback",a),c=this.accessTokenValue}else c=this.accessTokenValue;b===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:d&&(this._manuallySetToken=!0),this.accessTokenValue!=c&&(this.accessTokenValue=c,this.channels.forEach(a=>{let b={access_token:c,version:"realtime-js/2.117.2"};a.updateJoinPayload(b),a.joinedOnce&&a.channelAdapter.isJoined()&&a.channelAdapter.push(b4.access_token,{access_token:c})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(a="general"){this._isManualToken()||this.setAuth().catch(b=>{this.log("error",`Error setting auth in ${a}`,b)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(a=>{this.log("error","error waiting for auth on connect",a)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(a=>{a.ref&&a.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(a){return(b,c)=>{"disconnected"!==b&&("sent"==b&&this._setAuthSafely(),a&&a(b,c))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let a=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(a),this.workerRef.onerror=a=>{this.log("worker","worker error",a.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=a=>{"keepAlive"===a.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(a){let b;if(a)b=a;else{let a=new Blob([cK],{type:"application/javascript"});b=URL.createObjectURL(a)}return b}_initializeOptions(a){var b,c,d,e,f,g,h,i,j,k,l,m;let n,o;this.worker=null!=(b=null==a?void 0:a.worker)&&b,this.accessToken=null!=(c=null==a?void 0:a.accessToken)?c:null;let p={};p.timeout=null!=(d=null==a?void 0:a.timeout)?d:1e4,p.heartbeatIntervalMs=null!=(e=null==a?void 0:a.heartbeatIntervalMs)?e:cI.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=null!=(f=null==a?void 0:a.disconnectOnEmptyChannelsAfterMs)?f:2*(null!=(g=null==a?void 0:a.heartbeatIntervalMs)?g:cI.HEARTBEAT_INTERVAL),p.transport=null!=(h=null==a?void 0:a.transport)?h:b1.getWebSocketConstructor(),p.params=null==a?void 0:a.params,p.logger=null==a?void 0:a.logger,p.heartbeatCallback=this._wrapHeartbeatCallback(null==a?void 0:a.heartbeatCallback),p.sessionStorage=null!=(i=null==a?void 0:a.sessionStorage)?i:function(){try{if("undefined"!=typeof globalThis&&globalThis.sessionStorage)return globalThis.sessionStorage}catch(a){}let a=new Map;return{get length(){return a.size},clear(){a.clear()},getItem:b=>a.has(b)?a.get(b):null,key(b){var c;return null!=(c=Array.from(a.keys())[b])?c:null},removeItem(b){a.delete(b)},setItem(b,c){a.set(b,String(c))}}}(),p.reconnectAfterMs=null!=(j=null==a?void 0:a.reconnectAfterMs)?j:a=>cJ[a-1]||1e4;let q=null!=(k=null==a?void 0:a.vsn)?k:b2;switch(q){case"1.0.0":n=(a,b)=>b(JSON.stringify(a)),o=(a,b)=>b(JSON.parse(a));break;case b2:n=this.serializer.encode.bind(this.serializer),o=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${p.vsn}`)}if(p.vsn=q,p.encode=null!=(l=null==a?void 0:a.encode)?l:n,p.decode=null!=(m=null==a?void 0:a.decode)?m:o,p.beforeReconnect=this._reconnectAuth.bind(this),((null==a?void 0:a.logLevel)||(null==a?void 0:a.log_level))&&(this.logLevel=a.logLevel||a.log_level,p.params=Object.assign(Object.assign({},p.params),{log_level:this.logLevel})),this.worker){if("undefined"!=typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==a?void 0:a.workerUrl,p.autoSendHeartbeat=!this.worker}return p}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var cM=class extends Error{constructor(a,b){super(a),this.name="IcebergError",this.status=b.status,this.icebergType=b.icebergType,this.icebergCode=b.icebergCode,this.details=b.details,this.isCommitStateUnknown="CommitStateUnknownException"===b.icebergType||[500,502,504].includes(b.status)&&b.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function cN(a){return a&&"none"!==a.type?"bearer"===a.type?{Authorization:`Bearer ${a.token}`}:"header"===a.type?{[a.name]:a.value}:"custom"===a.type?await a.getHeaders():{}:{}}function cO(a){return a.join("\x1f")}var cP=class{constructor(a,b=""){this.client=a,this.prefix=b}async listNamespaces(a){let b=a?{parent:cO(a.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:b})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(a,b){let c={namespace:a.namespace,properties:b?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:c})).data}async dropNamespace(a){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${cO(a.namespace)}`})}async loadNamespaceMetadata(a){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cO(a.namespace)}`})).data.properties}}async namespaceExists(a){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${cO(a.namespace)}`}),!0}catch(a){if(a instanceof cM&&404===a.status)return!1;throw a}}async createNamespaceIfNotExists(a,b){try{return await this.createNamespace(a,b)}catch(a){if(a instanceof cM&&409===a.status)return;throw a}}};function cQ(a){return a.join("\x1f")}var cR=class{constructor(a,b="",c){this.client=a,this.prefix=b,this.accessDelegation=c}async listTables(a){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables`})).data.identifiers}async createTable(a,b){let c={};return this.accessDelegation&&(c["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables`,body:b,headers:c})).data.metadata}async updateTable(a,b){let c=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables/${a.name}`,body:b});return{"metadata-location":c.data["metadata-location"],metadata:c.data.metadata}}async dropTable(a,b){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables/${a.name}`,query:{purgeRequested:String(b?.purge??!1)}})}async loadTable(a){let b={};return this.accessDelegation&&(b["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables/${a.name}`,headers:b})).data.metadata}async tableExists(a){let b={};this.accessDelegation&&(b["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${cQ(a.namespace)}/tables/${a.name}`,headers:b}),!0}catch(a){if(a instanceof cM&&404===a.status)return!1;throw a}}async createTableIfNotExists(a,b){try{return await this.createTable(a,b)}catch(c){if(c instanceof cM&&409===c.status)return await this.loadTable({namespace:a.namespace,name:b.name});throw c}}},cS=class{constructor(a){let b="v1";a.catalogName&&(b+=`/${a.catalogName}`);let c=a.baseUrl.endsWith("/")?a.baseUrl:`${a.baseUrl}/`;this.client=function(a){let b=a.fetchImpl??globalThis.fetch;return{async request({method:c,path:d,query:e,body:f,headers:g}){let h=function(a,b,c){let d=new URL(b,a);if(c)for(let[a,b]of Object.entries(c))void 0!==b&&d.searchParams.set(a,b);return d.toString()}(a.baseUrl,d,e),i=await cN(a.auth),j=await b(h,{method:c,headers:{...f?{"Content-Type":"application/json"}:{},...i,...g},body:f?JSON.stringify(f):void 0}),k=await j.text(),l=(j.headers.get("content-type")||"").includes("application/json"),m=l&&k?JSON.parse(k):k;if(!j.ok){let a=l?m:void 0,b=a?.error;throw new cM(b?.message??`Request failed with status ${j.status}`,{status:j.status,icebergType:b?.type,icebergCode:b?.code,details:a})}return{status:j.status,headers:j.headers,data:m}}}}({baseUrl:c,auth:a.auth,fetchImpl:a.fetch}),this.accessDelegation=a.accessDelegation?.join(","),this.namespaceOps=new cP(this.client,b),this.tableOps=new cR(this.client,b,this.accessDelegation)}async listNamespaces(a){return this.namespaceOps.listNamespaces(a)}async createNamespace(a,b){return this.namespaceOps.createNamespace(a,b)}async dropNamespace(a){await this.namespaceOps.dropNamespace(a)}async loadNamespaceMetadata(a){return this.namespaceOps.loadNamespaceMetadata(a)}async listTables(a){return this.tableOps.listTables(a)}async createTable(a,b){return this.tableOps.createTable(a,b)}async updateTable(a,b){return this.tableOps.updateTable(a,b)}async dropTable(a,b){await this.tableOps.dropTable(a,b)}async loadTable(a){return this.tableOps.loadTable(a)}async namespaceExists(a){return this.namespaceOps.namespaceExists(a)}async tableExists(a){return this.tableOps.tableExists(a)}async createNamespaceIfNotExists(a,b){return this.namespaceOps.createNamespaceIfNotExists(a,b)}async createTableIfNotExists(a,b){return this.tableOps.createTableIfNotExists(a,b)}},cT=c(356).Buffer;function cU(a){return(cU="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function cV(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function cW(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?cV(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=cU(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=cU(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==cU(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):cV(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}var cX=class extends Error{constructor(a,b="storage",c,d){super(a),this.__isStorageError=!0,this.namespace=b,this.name="vectors"===b?"StorageVectorsError":"StorageError",this.status=c,this.statusCode=d}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function cY(a){return"object"==typeof a&&null!==a&&"__isStorageError"in a}var cZ=class extends cX{constructor(a,b,c,d="storage",e){super(a,d,b,c),this.name="vectors"===d?"StorageVectorsApiError":"StorageApiError",this.status=b,this.statusCode=c,this.code=e}toJSON(){return cW(cW({},super.toJSON()),{},{code:this.code})}},c$=class extends cX{constructor(a,b,c="storage"){super(a,c),this.name="vectors"===c?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=b}};function c_(a,b,c){let d=cW({},a),e=b.toLowerCase();for(let a of Object.keys(d))a.toLowerCase()===e&&delete d[a];return d[e]=c,d}let c0=a=>{if(Array.isArray(a))return a.map(a=>c0(a));if("function"==typeof a||a!==Object(a))return a;let b={};return Object.entries(a).forEach(([a,c])=>{b[a.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""))]=c0(c)}),b},c1=a=>a.split("/").map(encodeURIComponent).join("/"),c2=a=>{if("object"==typeof a&&null!==a){if("string"==typeof a.msg)return a.msg;if("string"==typeof a.message)return a.message;if("string"==typeof a.error_description)return a.error_description;if("string"==typeof a.error)return a.error;if("object"==typeof a.error&&null!==a.error){let b=a.error;if("string"==typeof b.message)return b.message}}return JSON.stringify(a)},c3=async(a,b,c,d)=>{if(null!==a&&"object"==typeof a&&"json"in a&&"function"==typeof a.json){let c=parseInt(String(a.status),10);Number.isFinite(c)||(c=500),a.json().then(a=>{let e=(null==a?void 0:a.statusCode)||(null==a?void 0:a.code)||c+"";b(new cZ(c2(a),c,e,d,null==a?void 0:a.code))}).catch(()=>{let e=c+"";b(new cZ(a.statusText||`HTTP ${c} error`,c,e,d))})}else b(new c$(c2(a),a,d))};async function c4(a,b,c,d,e,f,g){return new Promise((h,i)=>{a(c,((a,b,c,d)=>{let e={method:a,headers:(null==b?void 0:b.headers)||{}};if("GET"===a||"HEAD"===a||!d)return cW(cW({},e),c);if((a=>{if("object"!=typeof a||null===a)return!1;let b=Object.getPrototypeOf(a);return(null===b||b===Object.prototype||null===Object.getPrototypeOf(b))&&!(Symbol.toStringTag in a)&&!(Symbol.iterator in a)})(d)){var f;let a,c=(null==b?void 0:b.headers)||{};for(let[b,d]of Object.entries(c))"content-type"===b.toLowerCase()&&(a=d);e.headers=c_(c,"Content-Type",null!=(f=a)?f:"application/json"),e.body=JSON.stringify(d)}else e.body=d;return(null==b?void 0:b.duplex)&&(e.duplex=b.duplex),cW(cW({},e),c)})(b,d,e,f)).then(a=>{if(!a.ok)throw a;if(null==d?void 0:d.noResolveJson)return a;if("vectors"===g){let b=a.headers.get("content-type");if("0"===a.headers.get("content-length")||204===a.status||!b||!b.includes("application/json"))return{}}return a.json()}).then(a=>h(a)).catch(a=>c3(a,i,d,g))})}function c5(a="storage"){return{get:async(b,c,d,e)=>c4(b,"GET",c,d,e,void 0,a),post:async(b,c,d,e,f)=>c4(b,"POST",c,e,f,d,a),put:async(b,c,d,e,f)=>c4(b,"PUT",c,e,f,d,a),head:async(b,c,d,e)=>c4(b,"HEAD",c,cW(cW({},d),{},{noResolveJson:!0}),e,void 0,a),remove:async(b,c,d,e,f)=>c4(b,"DELETE",c,e,f,d,a)}}let{get:c6,post:c7,put:c8,head:c9,remove:da}=c5("storage"),db=c5("vectors");var dc=class{constructor(a,b={},c,d="storage"){this.shouldThrowOnError=!1,this.url=a,this.headers=function(a){let b={};for(let[c,d]of Object.entries(a))b[c.toLowerCase()]=d;return b}(b),this.fetch=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(c),this.namespace=d}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(a,b){return this.headers=c_(this.headers,a,b),this}async handleOperation(a){try{return{data:await a(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(cY(a))return{data:null,error:a};throw a}}};e=Symbol.toStringTag;var dd=class{constructor(a,b){this.downloadFn=a,this.shouldThrowOnError=b,this[e]="StreamDownloadBuilder",this.promise=null}then(a,b){return this.getPromise().then(a,b)}catch(a){return this.getPromise().catch(a)}finally(a){return this.getPromise().finally(a)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(cY(a))return{data:null,error:a};throw a}}};f=Symbol.toStringTag;var de=class{constructor(a,b){this.downloadFn=a,this.shouldThrowOnError=b,this[f]="BlobDownloadBuilder",this.promise=null}asStream(){return new dd(this.downloadFn,this.shouldThrowOnError)}then(a,b){return this.getPromise().then(a,b)}catch(a){return this.getPromise().catch(a)}finally(a){return this.getPromise().finally(a)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(cY(a))return{data:null,error:a};throw a}}};let df={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},dg={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var dh=class extends dc{constructor(a,b={},c,d){super(a,b,d,"storage"),this.bucketId=c}async uploadOrUpdate(a,b,c,d){var e=this;return e.handleOperation(async()=>{let f,g=cW(cW({},dg),d),h=cW(cW({},e.headers),"POST"===a&&{"x-upsert":String(g.upsert)}),i=g.metadata;if("undefined"!=typeof Blob&&c instanceof Blob?((f=new FormData).append("cacheControl",g.cacheControl),i&&f.append("metadata",e.encodeMetadata(i)),f.append("",c)):"undefined"!=typeof FormData&&c instanceof FormData?((f=c).has("cacheControl")||f.append("cacheControl",g.cacheControl),i&&!f.has("metadata")&&f.append("metadata",e.encodeMetadata(i))):(f=c,h["cache-control"]=`max-age=${g.cacheControl}`,h["content-type"]=g.contentType,i&&(h["x-metadata"]=e.toBase64(e.encodeMetadata(i))),("undefined"!=typeof ReadableStream&&f instanceof ReadableStream||f&&"object"==typeof f&&"pipe"in f&&"function"==typeof f.pipe)&&!g.duplex&&(g.duplex="half")),null==d?void 0:d.headers)for(let[a,b]of Object.entries(d.headers))h=c_(h,a,b);let j=e._removeEmptyFolders(b),k=e._getFinalPath(j),l=await ("PUT"==a?c8:c7)(e.fetch,`${e.url}/object/${k}`,f,cW({headers:h},(null==g?void 0:g.duplex)?{duplex:g.duplex}:{}));return{path:j,id:l.Id,fullPath:l.Key}})}async upload(a,b,c){return this.uploadOrUpdate("POST",a,b,c)}async uploadToSignedUrl(a,b,c,d){var e=this;let f=e._removeEmptyFolders(a),g=e._getFinalPath(f),h=new URL(e.url+`/object/upload/sign/${g}`);return h.searchParams.set("token",b),e.handleOperation(async()=>{let a,b=cW(cW({},dg),d),g=cW(cW({},e.headers),{"x-upsert":String(b.upsert)}),i=b.metadata;if("undefined"!=typeof Blob&&c instanceof Blob?((a=new FormData).append("cacheControl",b.cacheControl),i&&a.append("metadata",e.encodeMetadata(i)),a.append("",c)):"undefined"!=typeof FormData&&c instanceof FormData?((a=c).has("cacheControl")||a.append("cacheControl",b.cacheControl),i&&!a.has("metadata")&&a.append("metadata",e.encodeMetadata(i))):(a=c,g["cache-control"]=`max-age=${b.cacheControl}`,g["content-type"]=b.contentType,i&&(g["x-metadata"]=e.toBase64(e.encodeMetadata(i))),("undefined"!=typeof ReadableStream&&a instanceof ReadableStream||a&&"object"==typeof a&&"pipe"in a&&"function"==typeof a.pipe)&&!b.duplex&&(b.duplex="half")),null==d?void 0:d.headers)for(let[a,b]of Object.entries(d.headers))g=c_(g,a,b);return{path:f,fullPath:(await c8(e.fetch,h.toString(),a,cW({headers:g},(null==b?void 0:b.duplex)?{duplex:b.duplex}:{}))).Key}})}async createSignedUploadUrl(a,b){var c=this;return c.handleOperation(async()=>{let d=c._getFinalPath(a),e=cW({},c.headers);(null==b?void 0:b.upsert)&&(e["x-upsert"]="true");let f=await c7(c.fetch,`${c.url}/object/upload/sign/${d}`,{},{headers:e}),g=new URL(c.url+f.url),h=g.searchParams.get("token");if(!h)throw new cX("No token returned by API");return{signedUrl:g.toString(),path:a,token:h}})}async update(a,b,c){return this.uploadOrUpdate("PUT",a,b,c)}async move(a,b,c){var d=this;return d.handleOperation(async()=>await c7(d.fetch,`${d.url}/object/move`,{bucketId:d.bucketId,sourceKey:a,destinationKey:b,destinationBucket:null==c?void 0:c.destinationBucket,sourceVersionId:null==c?void 0:c.sourceVersionId},{headers:d.headers}))}async copy(a,b,c){var d=this;return d.handleOperation(async()=>({path:(await c7(d.fetch,`${d.url}/object/copy`,{bucketId:d.bucketId,sourceKey:a,destinationKey:b,destinationBucket:null==c?void 0:c.destinationBucket,sourceVersionId:null==c?void 0:c.sourceVersionId},{headers:d.headers})).Key}))}async createSignedUrl(a,b,c){var d=this;return d.handleOperation(async()=>{let e=d._getFinalPath(a),f="object"==typeof(null==c?void 0:c.transform)&&null!==c.transform&&Object.keys(c.transform).length>0,g=await c7(d.fetch,`${d.url}/object/sign/${e}`,cW(cW({expiresIn:b},f?{transform:c.transform}:{}),(null==c?void 0:c.versionId)!=null?{versionId:c.versionId}:{}),{headers:d.headers}),h=new URLSearchParams;(null==c?void 0:c.download)&&h.set("download",!0===c.download?"":c.download),(null==c?void 0:c.cacheNonce)!=null&&h.set("cacheNonce",String(c.cacheNonce));let i=h.toString();return{signedUrl:encodeURI(`${d.url}${g.signedURL}${i?`&${i}`:""}`)}})}async createSignedUrls(a,b,c){var d=this;return d.handleOperation(async()=>{let e=await c7(d.fetch,`${d.url}/object/sign/${d.bucketId}`,{expiresIn:b,paths:a},{headers:d.headers}),f=new URLSearchParams;(null==c?void 0:c.download)&&f.set("download",!0===c.download?"":c.download),(null==c?void 0:c.cacheNonce)!=null&&f.set("cacheNonce",String(c.cacheNonce));let g=f.toString();return e.map(a=>cW(cW({},a),{},{signedUrl:a.signedURL?encodeURI(`${d.url}${a.signedURL}${g?`&${g}`:""}`):null}))})}download(a,b,c){let d="object"==typeof(null==b?void 0:b.transform)&&null!==b.transform&&Object.keys(b.transform).length>0?"render/image/authenticated":"object",e=new URLSearchParams;(null==b?void 0:b.transform)&&this.applyTransformOptsToQuery(e,b.transform),(null==b?void 0:b.cacheNonce)!=null&&e.set("cacheNonce",String(b.cacheNonce)),(null==b?void 0:b.versionId)!=null&&e.set("versionId",String(b.versionId));let f=e.toString(),g=this._getFinalPath(a);return new de(()=>c6(this.fetch,`${this.url}/${d}/${g}${f?`?${f}`:""}`,{headers:this.headers,noResolveJson:!0},c),this.shouldThrowOnError)}async info(a,b){var c=this;let d=c._getFinalPath(a),e=new URLSearchParams;(null==b?void 0:b.versionId)!=null&&e.set("versionId",String(b.versionId));let f=e.toString();return c.handleOperation(async()=>c0(await c6(c.fetch,`${c.url}/object/info/${d}${f?`?${f}`:""}`,{headers:c.headers})))}async exists(a){var b;let c=this._getFinalPath(a);try{return await c9(this.fetch,`${this.url}/object/${c}`,{headers:this.headers}),{data:!0,error:null}}catch(a){if(this.shouldThrowOnError)throw a;if(cY(a)){let c=a instanceof cZ?a.status:a instanceof c$?null==(b=a.originalError)?void 0:b.status:void 0;if(void 0!==c&&[400,404].includes(c))return{data:!1,error:a}}throw a}}getPublicUrl(a,b){let c=this._getFinalPath(a),d=new URLSearchParams;(null==b?void 0:b.download)&&d.set("download",!0===b.download?"":b.download),(null==b?void 0:b.transform)&&this.applyTransformOptsToQuery(d,b.transform),(null==b?void 0:b.cacheNonce)!=null&&d.set("cacheNonce",String(b.cacheNonce)),(null==b?void 0:b.versionId)!=null&&d.set("versionId",String(b.versionId));let e=d.toString(),f="object"==typeof(null==b?void 0:b.transform)&&null!==b.transform&&Object.keys(b.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${f}/public/${c}`)+(e?`?${e}`:"")}}}async remove(a){var b=this;return b.handleOperation(async()=>await da(b.fetch,`${b.url}/object/${b.bucketId}`,{prefixes:a},{headers:b.headers}))}async purgeCache(a,b,c){var d=this;return d.handleOperation(async()=>{let e=c1(d._getFinalPath(a)),f=new URLSearchParams;(null==b?void 0:b.transformations)&&f.set("transformations","true");let g=f.toString();return await da(d.fetch,`${d.url}/cdn/${e}${g?`?${g}`:""}`,{},{headers:d.headers},c)})}async list(a,b,c){var d=this;return d.handleOperation(async()=>{let e=(null==b?void 0:b.sortBy)?cW(cW({},df.sortBy),b.sortBy):df.sortBy,f=cW(cW(cW({},df),b),{},{sortBy:e,prefix:a||""});return await c7(d.fetch,`${d.url}/object/list/${d.bucketId}`,f,{headers:d.headers},c)})}async listV2(a,b){var c=this;return c.handleOperation(async()=>{let d=cW({},a);return await c7(c.fetch,`${c.url}/object/list-v2/${c.bucketId}`,d,{headers:c.headers},b)})}encodeMetadata(a){return JSON.stringify(a)}toBase64(a){return void 0!==cT?cT.from(a).toString("base64"):btoa(a)}_getFinalPath(a){return`${this.bucketId}/${a.replace(/^\/+/,"")}`}_removeEmptyFolders(a){return a.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(a,b){return b.width&&a.set("width",b.width.toString()),b.height&&a.set("height",b.height.toString()),b.resize&&a.set("resize",b.resize),b.format&&a.set("format",b.format),b.quality&&a.set("quality",b.quality.toString()),a}};let di={"X-Client-Info":"storage-js/2.117.2"};var dj=class extends dc{constructor(a,b={},c,d){let e=new URL(a);(null==d?void 0:d.useNewHostname)&&/supabase\.(co|in|red)$/.test(e.hostname)&&!e.hostname.includes("storage.supabase.")&&(e.hostname=e.hostname.replace("supabase.","storage.supabase.")),super(e.href.replace(/\/$/,""),cW(cW({},di),b),c,"storage")}async listBuckets(a){var b=this;return b.handleOperation(async()=>{let c=b.listBucketOptionsToQueryString(a);return await c6(b.fetch,`${b.url}/bucket${c}`,{headers:b.headers})})}async getBucket(a){var b=this;return b.handleOperation(async()=>await c6(b.fetch,`${b.url}/bucket/${a}`,{headers:b.headers}))}async createBucket(a,b={public:!1}){var c=this;return c.handleOperation(async()=>await c7(c.fetch,`${c.url}/bucket`,{id:a,name:a,type:b.type,public:b.public,file_size_limit:b.fileSizeLimit,allowed_mime_types:b.allowedMimeTypes,versioning_status:b.versioningStatus},{headers:c.headers}))}async updateBucket(a,b){var c=this;return c.handleOperation(async()=>await c8(c.fetch,`${c.url}/bucket/${a}`,{id:a,name:a,public:b.public,file_size_limit:b.fileSizeLimit,allowed_mime_types:b.allowedMimeTypes,versioning_status:b.versioningStatus},{headers:c.headers}))}async emptyBucket(a){var b=this;return b.handleOperation(async()=>await c7(b.fetch,`${b.url}/bucket/${a}/empty`,{},{headers:b.headers}))}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await da(b.fetch,`${b.url}/bucket/${a}`,{},{headers:b.headers}))}async getBucketLifecycle(a){var b=this;return b.handleOperation(async()=>await c6(b.fetch,b.bucketLifecycleUrl(a),{headers:b.headers}))}async updateBucketLifecycle(a,b){var c=this;return c.handleOperation(async()=>await c8(c.fetch,c.bucketLifecycleUrl(a),b,{headers:c.headers}))}async deleteBucketLifecycle(a){var b=this;return b.handleOperation(async()=>await da(b.fetch,b.bucketLifecycleUrl(a),{},{headers:b.headers}))}async purgeBucketCache(a,b,c){var d=this;return d.handleOperation(async()=>{let e=new URLSearchParams;(null==b?void 0:b.transformations)&&e.set("transformations","true");let f=e.toString();return await da(d.fetch,`${d.url}/cdn/${c1(a)}${f?`?${f}`:""}`,{},{headers:d.headers},c)})}bucketLifecycleUrl(a){return`${this.url}/bucket/${c1(a)}/lifecycle`}listBucketOptionsToQueryString(a){let b={};return a&&("limit"in a&&(b.limit=String(a.limit)),"offset"in a&&(b.offset=String(a.offset)),a.search&&(b.search=a.search),a.sortColumn&&(b.sortColumn=a.sortColumn),a.sortOrder&&(b.sortOrder=a.sortOrder)),Object.keys(b).length>0?"?"+new URLSearchParams(b).toString():""}},dk=class extends dc{constructor(a,b={},c){super(a.replace(/\/$/,""),cW(cW({},di),b),c,"storage")}async createBucket(a){var b=this;return b.handleOperation(async()=>await c7(b.fetch,`${b.url}/bucket`,{name:a},{headers:b.headers}))}async listBuckets(a){var b=this;return b.handleOperation(async()=>{let c=new URLSearchParams;(null==a?void 0:a.limit)!==void 0&&c.set("limit",a.limit.toString()),(null==a?void 0:a.offset)!==void 0&&c.set("offset",a.offset.toString()),(null==a?void 0:a.sortColumn)&&c.set("sortColumn",a.sortColumn),(null==a?void 0:a.sortOrder)&&c.set("sortOrder",a.sortOrder),(null==a?void 0:a.search)&&c.set("search",a.search);let d=c.toString(),e=d?`${b.url}/bucket?${d}`:`${b.url}/bucket`;return await c6(b.fetch,e,{headers:b.headers})})}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await da(b.fetch,`${b.url}/bucket/${a}`,{},{headers:b.headers}))}from(a){var b=this;if(!(!(!a||"string"!=typeof a||0===a.length||a.length>100||a.trim()!==a||a.includes("/")||a.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(a)))throw new cX("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let c=new cS({baseUrl:this.url,catalogName:a,auth:{type:"custom",getHeaders:async()=>b.headers},fetch:this.fetch}),d=this.shouldThrowOnError;return new Proxy(c,{get(a,b){let c=a[b];return"function"!=typeof c?c:async(...b)=>{try{return{data:await c.apply(a,b),error:null}}catch(a){if(d)throw a;return{data:null,error:a}}}}})}},dl=class extends dc{constructor(a,b={},c){super(a.replace(/\/$/,""),cW(cW({},di),{},{"Content-Type":"application/json"},b),c,"vectors")}async createIndex(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/CreateIndex`,a,{headers:b.headers})||{})}async getIndex(a,b){var c=this;return c.handleOperation(async()=>await db.post(c.fetch,`${c.url}/GetIndex`,{vectorBucketName:a,indexName:b},{headers:c.headers}))}async listIndexes(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/ListIndexes`,a,{headers:b.headers}))}async deleteIndex(a,b){var c=this;return c.handleOperation(async()=>await db.post(c.fetch,`${c.url}/DeleteIndex`,{vectorBucketName:a,indexName:b},{headers:c.headers})||{})}},dm=class extends dc{constructor(a,b={},c){super(a.replace(/\/$/,""),cW(cW({},di),{},{"Content-Type":"application/json"},b),c,"vectors")}async putVectors(a){var b=this;if(a.vectors.length<1||a.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/PutVectors`,a,{headers:b.headers})||{})}async getVectors(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/GetVectors`,a,{headers:b.headers}))}async listVectors(a){var b=this;if(void 0!==a.segmentCount){if(a.segmentCount<1||a.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==a.segmentIndex&&(a.segmentIndex<0||a.segmentIndex>=a.segmentCount))throw Error(`segmentIndex must be between 0 and ${a.segmentCount-1}`)}return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/ListVectors`,a,{headers:b.headers}))}async queryVectors(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/QueryVectors`,a,{headers:b.headers}))}async deleteVectors(a){var b=this;if(a.keys.length<1||a.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/DeleteVectors`,a,{headers:b.headers})||{})}},dn=class extends dc{constructor(a,b={},c){super(a.replace(/\/$/,""),cW(cW({},di),{},{"Content-Type":"application/json"},b),c,"vectors")}async createBucket(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/CreateVectorBucket`,{vectorBucketName:a},{headers:b.headers})||{})}async getBucket(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/GetVectorBucket`,{vectorBucketName:a},{headers:b.headers}))}async listBuckets(a={}){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/ListVectorBuckets`,a,{headers:b.headers}))}async deleteBucket(a){var b=this;return b.handleOperation(async()=>await db.post(b.fetch,`${b.url}/DeleteVectorBucket`,{vectorBucketName:a},{headers:b.headers})||{})}},dp=class extends dn{constructor(a,b={}){super(a,b.headers||{},b.fetch)}from(a){return new dq(this.url,this.headers,a,this.fetch)}async createBucket(a){return super.createBucket.call(this,a)}async getBucket(a){return super.getBucket.call(this,a)}async listBuckets(a={}){return super.listBuckets.call(this,a)}async deleteBucket(a){return super.deleteBucket.call(this,a)}},dq=class extends dl{constructor(a,b,c,d){super(a,b,d),this.vectorBucketName=c}async createIndex(a){return super.createIndex.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(a={}){return super.listIndexes.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(a){return super.getIndex.call(this,this.vectorBucketName,a)}async deleteIndex(a){return super.deleteIndex.call(this,this.vectorBucketName,a)}index(a){return new dr(this.url,this.headers,this.vectorBucketName,a,this.fetch)}},dr=class extends dm{constructor(a,b,c,d,e){super(a,b,e),this.vectorBucketName=c,this.indexName=d}async putVectors(a){return super.putVectors.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(a){return super.getVectors.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(a={}){return super.listVectors.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(a){return super.queryVectors.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(a){return super.deleteVectors.call(this,cW(cW({},a),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},ds=class extends dj{constructor(a,b={},c,d){super(a,b,c,d)}from(a){return new dh(this.url,this.headers,a,this.fetch)}get vectors(){return new dp(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new dk(this.url+"/iceberg",this.headers,this.fetch)}};let dt="2.117.2",du={"X-Client-Info":`gotrue-js/${dt}`},dv="X-Supabase-Api-Version",dw={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},dx=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,dy="sb_flow_id";class dz extends Error{constructor(a,b,c){super(a),this.__isAuthError=!0,this.name="AuthError",this.status=b,this.code=c}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function dA(a){return"object"==typeof a&&null!==a&&"__isAuthError"in a}class dB extends dz{constructor(a,b,c){super(a,b,c),this.name="AuthApiError",this.status=b,this.code=c}}function dC(a){return dA(a)&&"AuthApiError"===a.name}class dD extends dz{constructor(a,b){super(a),this.name="AuthUnknownError",this.originalError=b}}class dE extends dz{constructor(a,b,c,d){super(a,c,d),this.name=b,this.status=c}}class dF extends dE{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function dG(a){return dA(a)&&"AuthSessionMissingError"===a.name}class dH extends dE{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class dI extends dE{constructor(a){super(a,"AuthInvalidCredentialsError",400,void 0)}}class dJ extends dE{constructor(a,b=null){super(a,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=b}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class dK extends dE{constructor(a,b=null){super(a,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=b}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class dL extends dE{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class dM extends dE{constructor(a,b){super(a,"AuthRetryableFetchError",b,void 0)}}function dN(a){return dA(a)&&"AuthRetryableFetchError"===a.name}class dO extends dE{constructor(a="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(a,"AuthRefreshDiscardedError",409,void 0)}}function dP(a){return dA(a)&&"AuthRefreshDiscardedError"===a.name}class dQ extends dE{constructor(a,b,c){super(a,"AuthWeakPasswordError",b,"weak_password"),this.reasons=c}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class dR extends dE{constructor(a){super(a,"AuthInvalidJwtError",400,"invalid_jwt")}}let dS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),dT=" \n\r=".split(""),dU=(()=>{let a=Array(128);for(let b=0;b<a.length;b+=1)a[b]=-1;for(let b=0;b<dT.length;b+=1)a[dT[b].charCodeAt(0)]=-2;for(let b=0;b<dS.length;b+=1)a[dS[b].charCodeAt(0)]=b;return a})();function dV(a,b,c){if(null!==a)for(b.queue=b.queue<<8|a,b.queuedBits+=8;b.queuedBits>=6;)c(dS[b.queue>>b.queuedBits-6&63]),b.queuedBits-=6;else if(b.queuedBits>0)for(b.queue=b.queue<<6-b.queuedBits,b.queuedBits=6;b.queuedBits>=6;)c(dS[b.queue>>b.queuedBits-6&63]),b.queuedBits-=6}function dW(a,b,c){let d=dU[a];if(d>-1)for(b.queue=b.queue<<6|d,b.queuedBits+=6;b.queuedBits>=8;)c(b.queue>>b.queuedBits-8&255),b.queuedBits-=8;else if(-2===d)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(a)}"`)}function dX(a){let b=[],c=a=>{b.push(String.fromCodePoint(a))},d={utf8seq:0,codepoint:0},e={queue:0,queuedBits:0},f=a=>{!function(a,b,c){if(0===b.utf8seq){if(a<=127)return c(a);for(let c=1;c<6;c+=1)if((a>>7-c&1)==0){b.utf8seq=c;break}if(2===b.utf8seq)b.codepoint=31&a;else if(3===b.utf8seq)b.codepoint=15&a;else if(4===b.utf8seq)b.codepoint=7&a;else throw Error("Invalid UTF-8 sequence");b.utf8seq-=1}else if(b.utf8seq>0){if(a<=127)throw Error("Invalid UTF-8 sequence");b.codepoint=b.codepoint<<6|63&a,b.utf8seq-=1,0===b.utf8seq&&c(b.codepoint)}}(a,d,c)};for(let b=0;b<a.length;b+=1)dW(a.charCodeAt(b),e,f);return b.join("")}function dY(a){let b=[],c={queue:0,queuedBits:0},d=a=>{b.push(a)};for(let b=0;b<a.length;b+=1)dW(a.charCodeAt(b),c,d);return new Uint8Array(b)}function dZ(a){let b=[],c={queue:0,queuedBits:0},d=a=>{b.push(a)};return a.forEach(a=>dV(a,c,d)),dV(null,c,d),b.join("")}function d$(a){return Math.round(Date.now()/1e3)+a}let d_=()=>"undefined"!=typeof window&&"undefined"!=typeof document,d0={tested:!1,writable:!1},d1=()=>{if(!d_())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(a){return!1}if(d0.tested)return d0.writable;let a=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(a,a),globalThis.localStorage.removeItem(a),d0.tested=!0,d0.writable=!0}catch(a){d0.tested=!0,d0.writable=!1}return d0.writable};function d2(a){let b={},c=new URL(a);if(c.hash&&"#"===c.hash[0])try{new URLSearchParams(c.hash.substring(1)).forEach((a,c)=>{b[c]=a})}catch(a){}return c.searchParams.forEach((a,c)=>{b[c]=a}),b}let d3=a=>a?(...b)=>a(...b):(...a)=>fetch(...a),d4=async(a,b,c)=>{await a.setItem(b,JSON.stringify(c))},d5=async(a,b)=>{let c=await a.getItem(b);if(!c)return null;try{return JSON.parse(c)}catch(a){return null}},d6=async(a,b)=>{await a.removeItem(b)};class d7{constructor(){this.promise=new d7.promiseConstructor((a,b)=>{this.resolve=a,this.reject=b})}}function d8(a){let b=a.split(".");if(3!==b.length)throw new dR("Invalid JWT structure");for(let a=0;a<b.length;a++)if(!dx.test(b[a]))throw new dR("JWT not in base64url format");return{header:JSON.parse(dX(b[0])),payload:JSON.parse(dX(b[1])),signature:dY(b[2]),raw:{header:b[0],payload:b[1]}}}async function d9(a){return await new Promise(b=>{setTimeout(()=>b(null),a)})}function ea(a){return("0"+a.toString(16)).substr(-2)}async function eb(a){let b=new TextEncoder().encode(a);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",b))).map(a=>String.fromCharCode(a)).join("")}async function ec(a){return"undefined"==typeof crypto||void 0===crypto.subtle||"undefined"==typeof TextEncoder?(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),a):btoa(await eb(a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}d7.promiseConstructor=Promise;let ed=/^[a-zA-Z0-9_-]{8,64}$/;function ee(a){return"string"==typeof a&&ed.test(a)?a:null}let ef=(a,b)=>`${a}-flow-${b}-code-verifier`,eg=a=>`${a}-flows-code-verifier`;async function eh(a,b){let c=await d5(a,eg(b));return Array.isArray(c)?c.filter(a=>null!==ee(a)):[]}async function ei(a,b,c,d,e){await d4(a,ef(b,c),d);let f=(await eh(a,b)).filter(a=>a!==c);for(f.push(c);f.length>5;){let c=f.shift();await d6(a,ef(b,c)),null==e||e(c)}await d4(a,eg(b),f),await d4(a,`${b}-code-verifier`,d)}async function ej(a,b,c){if(c){let d=await d5(a,ef(b,c));return{verifier:"string"==typeof d?d:null,flowId:c}}let d=await d5(a,`${b}-code-verifier`);return{verifier:"string"==typeof d?d:null,flowId:null}}async function ek(a,b,c){let d=`${b}-code-verifier`;if(!c)return void await d6(a,d);let e=ef(b,c),f=await d5(a,e);await d6(a,e);let g=await eh(a,b),h=g.filter(a=>a!==c);h.length!==g.length&&(h.length>0?await d4(a,eg(b),h):await d6(a,eg(b))),null!=f&&f===await d5(a,d)&&await d6(a,d)}async function el(a,b){for(let c of(await eh(a,b)))await d6(a,ef(b,c));await d6(a,eg(b)),await d6(a,`${b}-code-verifier`)}async function em(a,b,c=!1,d){let e=function(){let a=new Uint32Array(56);if("undefined"==typeof crypto){let a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",b=a.length,c="";for(let d=0;d<56;d++)c+=a.charAt(Math.floor(Math.random()*b));return c}return crypto.getRandomValues(a),Array.from(a,ea).join("")}(),f=e;c&&(f+="/recovery");let g=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues){let a=new Uint8Array(16);return crypto.getRandomValues(a),Array.from(a,ea).join("")}let a="";for(let b=0;b<32;b++)a+=Math.floor(16*Math.random()).toString(16);return a}();await ei(a,b,g,f,d);let h=await ec(e),i=e===h?"plain":"s256";return[h,i,g]}let en=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i,eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ep(a){if(!eo.test(a))throw Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function eq(a){if(!a.recoveryCodes)throw Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function er(){return new Proxy({},{get:(a,b)=>{if("__isUserNotAvailableProxy"===b)return!0;if("symbol"==typeof b){let a=b.toString();if("Symbol(Symbol.toPrimitive)"===a||"Symbol(Symbol.toStringTag)"===a||"Symbol(util.inspect.custom)"===a)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${b}" property of the session object is not supported. Please use getUser() instead.`)},set:(a,b)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${b}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(a,b)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${b}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function es(a){return JSON.parse(JSON.stringify(a))}let et=a=>{if("object"==typeof a&&null!==a){if("string"==typeof a.msg)return a.msg;if("string"==typeof a.message)return a.message;if("string"==typeof a.error_description)return a.error_description;if("string"==typeof a.error)return a.error}return JSON.stringify(a)},eu=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function ev(a){var b;let c,d;if(!("object"==typeof a&&null!==a&&"status"in a&&"ok"in a&&"json"in a&&"function"==typeof a.json))throw new dM(et(a),0);try{c=await a.json()}catch(b){if(eu.includes(a.status))throw new dM(a.statusText||`HTTP ${a.status}`,a.status);throw new dD(et(b),b)}if(eu.includes(a.status))throw new dM(et(c),a.status);let e=function(a){let b=a.headers.get(dv);if(!b||!b.match(en))return null;try{return new Date(`${b}T00:00:00.0Z`)}catch(a){return null}}(a);if(e&&e.getTime()>=dw["2024-01-01"].timestamp&&"object"==typeof c&&c&&"string"==typeof c.code?d=c.code:"object"==typeof c&&c&&"string"==typeof c.error_code&&(d=c.error_code),d){if("weak_password"===d)throw new dQ(et(c),a.status,(null==(b=c.weak_password)?void 0:b.reasons)||[]);else if("session_not_found"===d)throw new dF}else if("object"==typeof c&&c&&"object"==typeof c.weak_password&&c.weak_password&&Array.isArray(c.weak_password.reasons)&&c.weak_password.reasons.length&&c.weak_password.reasons.reduce((a,b)=>a&&"string"==typeof b,!0))throw new dQ(et(c),a.status,c.weak_password.reasons);throw new dB(et(c),a.status||500,d)}async function ew(a,b,c,d){var e;let f=Object.assign({},null==d?void 0:d.headers);f[dv]||(f[dv]=dw["2024-01-01"].name),(null==d?void 0:d.jwt)&&(f.Authorization=`Bearer ${d.jwt}`);let g=null!=(e=null==d?void 0:d.query)?e:{};(null==d?void 0:d.redirectTo)&&(g.redirect_to=d.redirectTo);let h=Object.keys(g).length?"?"+new URLSearchParams(g).toString():"",i=await ex(a,b,c+h,{headers:f,noResolveJson:null==d?void 0:d.noResolveJson},{},null==d?void 0:d.body);return(null==d?void 0:d.xform)?null==d?void 0:d.xform(i):{data:Object.assign({},i),error:null}}async function ex(a,b,c,d,e,f){let g,h=((a,b,c,d)=>{let e={method:a,headers:(null==b?void 0:b.headers)||{}};return"GET"===a?e:(e.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==b?void 0:b.headers),e.body=JSON.stringify(d),Object.assign(Object.assign({},e),c))})(b,d,e,f);try{g=await a(c,Object.assign({},h))}catch(a){throw new dM(et(a),0)}if(g.ok||await ev(g),null==d?void 0:d.noResolveJson)return g;try{return await g.json()}catch(a){await ev(a)}}function ey(a){var b,c;let d=null;return(c=a).access_token&&c.refresh_token&&c.expires_in&&(d=Object.assign({},a),a.expires_at||(d.expires_at=d$(a.expires_in))),{data:{session:d,user:null!=(b=a.user)?b:"string"==typeof(null==a?void 0:a.id)?a:null},error:null}}function ez(a){let b=ey(a);return!b.error&&a.weak_password&&"object"==typeof a.weak_password&&Array.isArray(a.weak_password.reasons)&&a.weak_password.reasons.length&&a.weak_password.message&&"string"==typeof a.weak_password.message&&a.weak_password.reasons.reduce((a,b)=>a&&"string"==typeof b,!0)&&(b.data.weak_password=a.weak_password),b}function eA(a){var b;return{data:{user:null!=(b=a.user)?b:a},error:null}}function eB(a){return{data:a,error:null}}function eC(a){let{action_link:b,email_otp:c,hashed_token:d,redirect_to:e,verification_type:f}=a;return{data:{properties:{action_link:b,email_otp:c,hashed_token:d,redirect_to:e,verification_type:f},user:Object.assign({},bH(a,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function eD(a){return a}let eE=["global","local","others"];class eF{constructor({url:a="",headers:b={},fetch:c,experimental:d}){this.url=a,this.headers=b,this.fetch=d3(c),this.experimental=null!=d?d:{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(a,b=eE[0]){if(0>eE.indexOf(b))throw Error(`@supabase/auth-js: Parameter scope must be one of ${eE.join(", ")}`);try{return await ew(this.fetch,"POST",`${this.url}/logout?scope=${b}`,{headers:this.headers,jwt:a,noResolveJson:!0}),{data:null,error:null}}catch(a){if(dA(a))return{data:null,error:a};throw a}}async inviteUserByEmail(a,b={}){try{return await ew(this.fetch,"POST",`${this.url}/invite`,{body:{email:a,data:b.data},headers:this.headers,redirectTo:b.redirectTo,xform:eA})}catch(a){if(dA(a))return{data:{user:null},error:a};throw a}}async generateLink(a){try{let{options:b}=a,c=bH(a,["options"]),d=Object.assign(Object.assign({},c),b);return"newEmail"in c&&(d.new_email=null==c?void 0:c.newEmail,delete d.newEmail),await ew(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:d,headers:this.headers,xform:eC,redirectTo:null==b?void 0:b.redirectTo})}catch(a){if(dA(a))return{data:{properties:null,user:null},error:a};throw a}}async createUser(a){try{return await ew(this.fetch,"POST",`${this.url}/admin/users`,{body:a,headers:this.headers,xform:eA})}catch(a){if(dA(a))return{data:{user:null},error:a};throw a}}async listUsers(a){var b,c,d,e,f,g,h;try{let i={nextPage:null,lastPage:0,total:0},j=await ew(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(c=null==(b=null==a?void 0:a.page)?void 0:b.toString())?c:"",per_page:null!=(e=null==(d=null==a?void 0:a.perPage)?void 0:d.toString())?e:""},xform:eD});if(j.error)throw j.error;let k=await j.json(),l=null!=(f=j.headers.get("x-total-count"))?f:0,m=null!=(h=null==(g=j.headers.get("link"))?void 0:g.split(","))?h:[];return m.length>0&&(m.forEach(a=>{let b=parseInt(a.split(";")[0].split("=")[1].substring(0,1)),c=JSON.parse(a.split(";")[1].split("=")[1]);i[`${c}Page`]=b}),i.total=parseInt(l)),{data:Object.assign(Object.assign({},k),i),error:null}}catch(a){if(dA(a))return{data:{users:[]},error:a};throw a}}async getUserById(a){ep(a);try{return await ew(this.fetch,"GET",`${this.url}/admin/users/${a}`,{headers:this.headers,xform:eA})}catch(a){if(dA(a))return{data:{user:null},error:a};throw a}}async updateUserById(a,b){ep(a);try{return await ew(this.fetch,"PUT",`${this.url}/admin/users/${a}`,{body:b,headers:this.headers,xform:eA})}catch(a){if(dA(a))return{data:{user:null},error:a};throw a}}async deleteUser(a,b=!1){ep(a);try{return await ew(this.fetch,"DELETE",`${this.url}/admin/users/${a}`,{headers:this.headers,body:{should_soft_delete:b},xform:eA})}catch(a){if(dA(a))return{data:{user:null},error:a};throw a}}async _listFactors(a){ep(a.userId);try{let{data:b,error:c}=await ew(this.fetch,"GET",`${this.url}/admin/users/${a.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:b,error:c}}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _deleteFactor(a){ep(a.userId),ep(a.id);try{return{data:await ew(this.fetch,"DELETE",`${this.url}/admin/users/${a.userId}/factors/${a.id}`,{headers:this.headers}),error:null}}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _listOAuthClients(a){var b,c,d,e,f,g,h;try{let i={nextPage:null,lastPage:0,total:0},j=await ew(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(c=null==(b=null==a?void 0:a.page)?void 0:b.toString())?c:"",per_page:null!=(e=null==(d=null==a?void 0:a.perPage)?void 0:d.toString())?e:""},xform:eD});if(j.error)throw j.error;let k=await j.json(),l=null!=(f=j.headers.get("x-total-count"))?f:0,m=null!=(h=null==(g=j.headers.get("link"))?void 0:g.split(","))?h:[];return m.length>0&&(m.forEach(a=>{let b=parseInt(a.split(";")[0].split("=")[1].substring(0,1)),c=JSON.parse(a.split(";")[1].split("=")[1]);i[`${c}Page`]=b}),i.total=parseInt(l)),{data:Object.assign(Object.assign({},k),i),error:null}}catch(a){if(dA(a))return{data:{clients:[]},error:a};throw a}}async _createOAuthClient(a){try{return await ew(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:a,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _getOAuthClient(a){try{return await ew(this.fetch,"GET",`${this.url}/admin/oauth/clients/${a}`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _updateOAuthClient(a,b){try{return await ew(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${a}`,{body:b,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(a){try{return await ew(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${a}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _regenerateOAuthClientSecret(a){try{return await ew(this.fetch,"POST",`${this.url}/admin/oauth/clients/${a}/regenerate_secret`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _listCustomProviders(a){try{let b={};return(null==a?void 0:a.type)&&(b.type=a.type),await ew(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:b,xform:a=>{var b;return{data:{providers:null!=(b=null==a?void 0:a.providers)?b:[]},error:null}}})}catch(a){if(dA(a))return{data:{providers:[]},error:a};throw a}}async _createCustomProvider(a){try{return await ew(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:a,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _getCustomProvider(a){try{return await ew(this.fetch,"GET",`${this.url}/admin/custom-providers/${a}`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _updateCustomProvider(a,b){try{return await ew(this.fetch,"PUT",`${this.url}/admin/custom-providers/${a}`,{body:b,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(a){try{return await ew(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${a}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _adminListPasskeys(a){ep(a.userId);try{return await ew(this.fetch,"GET",`${this.url}/admin/users/${a.userId}/passkeys`,{headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(dA(a))return{data:null,error:a};throw a}}async _adminDeletePasskey(a){ep(a.userId),ep(a.passkeyId);try{return await ew(this.fetch,"DELETE",`${this.url}/admin/users/${a.userId}/passkeys/${a.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(a){if(dA(a))return{data:null,error:a};throw a}}}function eG(a={}){return{getItem:b=>a[b]||null,setItem:(b,c)=>{a[b]=c},removeItem:b=>{delete a[b]}}}globalThis&&d1()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class eH extends Error{constructor(a){super(a),this.isAcquireTimeout=!0}}function eI(a){if(!/^0x[a-fA-F0-9]{40}$/.test(a))throw Error(`@supabase/auth-js: Address "${a}" is invalid.`);return a.toLowerCase()}class eJ extends Error{constructor({message:a,code:b,cause:c,name:d}){var e;super(a,{cause:c}),this.__isWebAuthnError=!0,this.name=null!=(e=null!=d?d:c instanceof Error?c.name:void 0)?e:"Unknown Error",this.code=b}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class eK extends eJ{constructor(a,b){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:b,message:a}),this.name="WebAuthnUnknownError",this.originalError=b}}class eL{createNewAbortSignal(){if(this.controller){let a=Error("Cancelling existing WebAuthn API call for new one");a.name="AbortError",this.controller.abort(a)}let a=new AbortController;return this.controller=a,a.signal}cancelCeremony(){if(this.controller){let a=Error("Manually cancelling existing WebAuthn API call");a.name="AbortError",this.controller.abort(a),this.controller=void 0}}}let eM=new eL;function eN(a){if(!a)throw Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(a);let{challenge:b,user:c,excludeCredentials:d}=a,e=bH(a,["challenge","user","excludeCredentials"]),f=dY(b).buffer,g=Object.assign(Object.assign({},c),{id:dY(c.id).buffer}),h=Object.assign(Object.assign({},e),{challenge:f,user:g});if(d&&d.length>0){h.excludeCredentials=Array(d.length);for(let a=0;a<d.length;a++){let b=d[a];h.excludeCredentials[a]=Object.assign(Object.assign({},b),{id:dY(b.id).buffer,type:b.type||"public-key",transports:b.transports})}}return h}function eO(a){if(!a)throw Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(a);let{challenge:b,allowCredentials:c}=a,d=bH(a,["challenge","allowCredentials"]),e=dY(b).buffer,f=Object.assign(Object.assign({},d),{challenge:e});if(c&&c.length>0){f.allowCredentials=Array(c.length);for(let a=0;a<c.length;a++){let b=c[a];f.allowCredentials[a]=Object.assign(Object.assign({},b),{id:dY(b.id).buffer,type:b.type||"public-key",transports:b.transports})}}return f}function eP(a){var b;return"toJSON"in a&&"function"==typeof a.toJSON?a.toJSON():{id:a.id,rawId:a.id,response:{attestationObject:dZ(new Uint8Array(a.response.attestationObject)),clientDataJSON:dZ(new Uint8Array(a.response.clientDataJSON))},type:"public-key",clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:null!=(b=a.authenticatorAttachment)?b:void 0}}function eQ(a){var b;if("toJSON"in a&&"function"==typeof a.toJSON)return a.toJSON();let c=a.getClientExtensionResults(),d=a.response;return{id:a.id,rawId:a.id,response:{authenticatorData:dZ(new Uint8Array(d.authenticatorData)),clientDataJSON:dZ(new Uint8Array(d.clientDataJSON)),signature:dZ(new Uint8Array(d.signature)),userHandle:d.userHandle?dZ(new Uint8Array(d.userHandle)):void 0},type:"public-key",clientExtensionResults:c,authenticatorAttachment:null!=(b=a.authenticatorAttachment)?b:void 0}}function eR(a){return"localhost"===a||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(a)}function eS(){var a,b;return!!(d_()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(a=null==navigator?void 0:navigator.credentials)?void 0:a.create)&&"function"==typeof(null==(b=null==navigator?void 0:navigator.credentials)?void 0:b.get))}async function eT(a){try{let b=await navigator.credentials.create(a);if(!b)return{data:null,error:new eK("Empty credential response",b)};if(!(b instanceof PublicKeyCredential))return{data:null,error:new eK("Browser returned unexpected credential type",b)};return{data:b,error:null}}catch(b){return{data:null,error:function({error:a,options:b}){var c,d,e;let{publicKey:f}=b;if(!f)throw Error("options was missing required publicKey property");if("AbortError"===a.name){if(b.signal instanceof AbortSignal)return new eJ({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:a})}else if("ConstraintError"===a.name){if((null==(c=f.authenticatorSelection)?void 0:c.requireResidentKey)===!0)return new eJ({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:a});else if("conditional"===b.mediation&&(null==(d=f.authenticatorSelection)?void 0:d.userVerification)==="required")return new eJ({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:a});else if((null==(e=f.authenticatorSelection)?void 0:e.userVerification)==="required")return new eJ({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:a})}else if("InvalidStateError"===a.name)return new eJ({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:a});else if("NotAllowedError"===a.name)return new eJ({message:a.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a});else if("NotSupportedError"===a.name)return new eJ(0===f.pubKeyCredParams.filter(a=>"public-key"===a.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:a}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:a});else if("SecurityError"===a.name){let b=window.location.hostname;if(!eR(b))return new eJ({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:a});if(f.rp.id!==b)return new eJ({message:`The RP ID "${f.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:a})}else if("TypeError"===a.name){if(f.user.id.byteLength<1||f.user.id.byteLength>64)return new eJ({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:a})}else if("UnknownError"===a.name)return new eJ({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:a});return new eJ({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a})}({error:b,options:a})}}}async function eU(a){try{let b=await navigator.credentials.get(a);if(!b)return{data:null,error:new eK("Empty credential response",b)};if(!(b instanceof PublicKeyCredential))return{data:null,error:new eK("Browser returned unexpected credential type",b)};return{data:b,error:null}}catch(b){return{data:null,error:function({error:a,options:b}){let{publicKey:c}=b;if(!c)throw Error("options was missing required publicKey property");if("AbortError"===a.name){if(b.signal instanceof AbortSignal)return new eJ({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:a})}else if("NotAllowedError"===a.name)return new eJ({message:a.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a});else if("SecurityError"===a.name){let b=window.location.hostname;if(!eR(b))return new eJ({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:a});if(c.rpId!==b)return new eJ({message:`The RP ID "${c.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:a})}else if("UnknownError"===a.name)return new eJ({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:a});return new eJ({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:a})}({error:b,options:a})}}}let eV={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},eW={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function eX(...a){let b=a=>null!==a&&"object"==typeof a&&!Array.isArray(a),c=a=>a instanceof ArrayBuffer||ArrayBuffer.isView(a),d={};for(let e of a)if(e)for(let a in e){let f=e[a];if(void 0!==f)if(Array.isArray(f))d[a]=f;else if(c(f))d[a]=f;else if(b(f)){let c=d[a];b(c)?d[a]=eX(c,f):d[a]=eX(f)}else d[a]=f}return d}class eY{constructor(a){this.client=a,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(a){return this.client.mfa.enroll(Object.assign(Object.assign({},a),{factorType:"webauthn"}))}async _challenge({factorId:a,webauthn:b,friendlyName:c,signal:d},e){var f,g,h,i,j;try{let{data:k,error:l}=await this.client.mfa.challenge({factorId:a,webauthn:b});if(!k)return{data:null,error:l};let m=null!=d?d:eM.createNewAbortSignal();if("create"===k.webauthn.type){let{user:a}=k.webauthn.credential_options.publicKey;if(!a.name)if(c)a.name=`${a.id}:${c}`;else{let b=(await this.client.getUser()).data.user,c=(null==(f=null==b?void 0:b.user_metadata)?void 0:f.name)||(null==b?void 0:b.email)||(null==b?void 0:b.id)||"User";a.name=`${a.id}:${c}`}a.displayName||(a.displayName=a.name)}switch(k.webauthn.type){case"create":{let b=(g=k.webauthn.credential_options.publicKey,h=null==e?void 0:e.create,eX(eV,g,h||{})),{data:c,error:d}=await eT({publicKey:b,signal:m});if(c)return{data:{factorId:a,challengeId:k.id,webauthn:{type:k.webauthn.type,credential_response:c}},error:null};return{data:null,error:d}}case"request":{let b=(i=k.webauthn.credential_options.publicKey,j=null==e?void 0:e.request,eX(eW,i,j||{})),{data:c,error:d}=await eU(Object.assign(Object.assign({},k.webauthn.credential_options),{publicKey:b,signal:m}));if(c)return{data:{factorId:a,challengeId:k.id,webauthn:{type:k.webauthn.type,credential_response:c}},error:null};return{data:null,error:d}}}}catch(a){if(dA(a))return{data:null,error:a};return{data:null,error:new dD("Unexpected error in challenge",a)}}}async _verify({challengeId:a,factorId:b,webauthn:c}){return this.client.mfa.verify({factorId:b,challengeId:a,webauthn:c})}async _authenticate({factorId:a,webauthn:{rpId:b="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:c="undefined"!=typeof window?[window.location.origin]:void 0,signal:d}={}},e){if(!b)return{data:null,error:new dz("rpId is required for WebAuthn authentication")};try{if(!eS())return{data:null,error:new dD("Browser does not support WebAuthn",null)};let{data:f,error:g}=await this.challenge({factorId:a,webauthn:{rpId:b,rpOrigins:c},signal:d},{request:e});if(!f)return{data:null,error:g};let{webauthn:h}=f;return this._verify({factorId:a,challengeId:f.challengeId,webauthn:{type:h.type,rpId:b,rpOrigins:c,credential_response:h.credential_response}})}catch(a){if(dA(a))return{data:null,error:a};return{data:null,error:new dD("Unexpected error in authenticate",a)}}}async _register({friendlyName:a,webauthn:{rpId:b="undefined"!=typeof window?window.location.hostname:void 0,rpOrigins:c="undefined"!=typeof window?[window.location.origin]:void 0,signal:d}={}},e){if(!b)return{data:null,error:new dz("rpId is required for WebAuthn registration")};try{if(!eS())return{data:null,error:new dD("Browser does not support WebAuthn",null)};let{data:f,error:g}=await this._enroll({friendlyName:a});if(!f)return await this.client.mfa.listFactors().then(b=>{var c;return null==(c=b.data)?void 0:c.all.find(b=>"webauthn"===b.factor_type&&b.friendly_name===a&&"unverified"===b.status)}).then(a=>a?this.client.mfa.unenroll({factorId:null==a?void 0:a.id}):void 0),{data:null,error:g};let{data:h,error:i}=await this._challenge({factorId:f.id,friendlyName:f.friendly_name,webauthn:{rpId:b,rpOrigins:c},signal:d},{create:e});if(!h)return{data:null,error:i};return this._verify({factorId:f.id,challengeId:h.challengeId,webauthn:{rpId:b,rpOrigins:c,type:h.webauthn.type,credential_response:h.webauthn.credential_response}})}catch(a){if(dA(a))return{data:null,error:a};return{data:null,error:new dD("Unexpected error in register",a)}}}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(a){"undefined"!=typeof self&&(self.globalThis=self)}let eZ={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:du,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},e$={},e_=!1;class e0{get jwks(){var a,b;return null!=(b=null==(a=e$[this.storageKey])?void 0:a.jwks)?b:{keys:[]}}set jwks(a){e$[this.storageKey]=Object.assign(Object.assign({},e$[this.storageKey]),{jwks:a})}get jwks_cached_at(){var a,b;return null!=(b=null==(a=e$[this.storageKey])?void 0:a.cachedAt)?b:Number.MIN_SAFE_INTEGER}set jwks_cached_at(a){e$[this.storageKey]=Object.assign(Object.assign({},e$[this.storageKey]),{cachedAt:a})}constructor(a){var b,c,d;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let e=Object.assign(Object.assign({},eZ),a);if(this.storageKey=e.storageKey,this.instanceID=null!=(b=e0.nextInstanceID[this.storageKey])?b:0,e0.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!e.debug,"function"==typeof e.debug&&(this.logger=e.debug),this.instanceID>0&&d_()){let a=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=e.persistSession,this.autoRefreshToken=e.autoRefreshToken,this.experimental=null!=(c=e.experimental)?c:{},this.admin=new eF({url:e.url,headers:e.headers,fetch:e.fetch,experimental:this.experimental}),this.url=e.url,this.headers=e.headers,this.fetch=d3(e.fetch),this.detectSessionInUrl=e.detectSessionInUrl,this.flowType=e.flowType,this.hasCustomAuthorizationHeader=e.hasCustomAuthorizationHeader,this.throwOnError=e.throwOnError,this.lockAcquireTimeout=e.lockAcquireTimeout,null!=e.lock&&(this.lock=e.lock,e_||(e_=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new eY(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(e.storage?this.storage=e.storage:d1()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=eG(this.memoryStorage)),e.userStorage&&(this.userStorage=e.userStorage)):(this.memoryStorage={},this.storage=eG(this.memoryStorage)),d_()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}null==(d=this.broadcastChannel)||d.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),("TOKEN_REFRESHED"===a.data.event||"SIGNED_IN"===a.data.event)&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}e.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(a){if(this.throwOnError&&a&&a.error)throw a.error;return a}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${dt}) ${new Date().toISOString()}`}_debug(...a){return this.logDebugMessages&&this.logger(this._logPrefix(),...a),this}async initialize(){var a;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();let b=await this.initializePromise,c=null!=(a=this._pendingInitNotifications)?a:[];for(let a of(this._pendingInitNotifications=null,c))await this._notifyAllSubscribers(a.event,a.session,a.broadcast);return b}async _initialize(){var a;try{let b={},c="none";if(d_()&&(b=d2(window.location.href),this._isImplicitGrantCallback(b)?c="implicit":await this._isPKCECallback(b)&&(c="pkce")),d_()&&this.detectSessionInUrl&&"none"!==c){let{data:d,error:e}=await this._getSessionFromURL(b,c);if(e){(this._debug("#_initialize()","error detecting session from URL",e),dA(e)&&"AuthImplicitGrantRedirectError"===e.name)&&(null==(a=e.details)||a.code);return{error:e}}let{session:f,redirectType:g}=d;return this._debug("#_initialize()","detected session in URL",f,"redirect type",g),await this._saveSession(f),setTimeout(async()=>{"recovery"===g?await this._notifyAllSubscribers("PASSWORD_RECOVERY",f):await this._notifyAllSubscribers("SIGNED_IN",f)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(a){if(dA(a))return this._returnResult({error:a});return this._returnResult({error:new dD("Unexpected error during initialization",a)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(a){var b,c,d;try{let{data:e,error:f}=await ew(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(c=null==(b=null==a?void 0:a.options)?void 0:b.data)?c:{},gotrue_meta_security:{captcha_token:null==(d=null==a?void 0:a.options)?void 0:d.captchaToken}},xform:ey});if(f||!e)return this._returnResult({data:{user:null,session:null},error:f});let g=e.session,h=e.user;return e.session&&(await this._saveSession(e.session),await this._notifyAllSubscribers("SIGNED_IN",g)),this._returnResult({data:{user:h,session:g},error:null})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(a){var b,c,d;let e=null;try{let f;if("email"in a){let{email:c,password:d,options:g}=a,h=null,i=null;"pkce"===this.flowType&&([h,i,e]=await this._getCodeChallengeAndMethod()),f=await ew(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(null==g?void 0:g.emailRedirectTo,e),body:{email:c,password:d,data:null!=(b=null==g?void 0:g.data)?b:{},gotrue_meta_security:{captcha_token:null==g?void 0:g.captchaToken},code_challenge:h,code_challenge_method:i},xform:ey})}else if("phone"in a){let{phone:b,password:e,options:g}=a;f=await ew(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:b,password:e,data:null!=(c=null==g?void 0:g.data)?c:{},channel:null!=(d=null==g?void 0:g.channel)?d:"sms",gotrue_meta_security:{captcha_token:null==g?void 0:g.captchaToken}},xform:ey})}else throw new dI("You must provide either an email or phone number and a password");let{data:g,error:h}=f;if(h||!g)return await ek(this.storage,this.storageKey,e),this._returnResult({data:{user:null,session:null},error:h});let i=g.session,j=g.user;return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",i)),this._returnResult({data:{user:j,session:i},error:null})}catch(a){if(await ek(this.storage,this.storageKey,e),dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(a){try{let b;if("email"in a){let{email:c,password:d,options:e}=a;b=await ew(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:c,password:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}},xform:ez})}else if("phone"in a){let{phone:c,password:d,options:e}=a;b=await ew(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:c,password:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}},xform:ez})}else throw new dI("You must provide either an email or phone number and a password");let{data:c,error:d}=b;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!c||!c.session||!c.user){let a=new dH;return this._returnResult({data:{user:null,session:null},error:a})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:Object.assign({user:c.user,session:c.session},c.weak_password?{weakPassword:c.weak_password}:null),error:d})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithOAuth(a){var b,c,d,e;return await this._handleProviderSignIn(a.provider,{redirectTo:null==(b=a.options)?void 0:b.redirectTo,scopes:null==(c=a.options)?void 0:c.scopes,queryParams:null==(d=a.options)?void 0:d.queryParams,skipBrowserRedirect:null==(e=a.options)?void 0:e.skipBrowserRedirect})}async exchangeCodeForSession(a,b){return(await this.initializePromise,null!=this.lock)?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(a,b)):this._exchangeCodeForSession(a,b)}async signInWithWeb3(a){let{chain:b}=a;switch(b){case"ethereum":return await this.signInWithEthereum(a);case"solana":return await this.signInWithSolana(a);default:throw Error(`@supabase/auth-js: Unsupported chain "${b}"`)}}async signInWithEthereum(a){var b,c,d,e,f,g,h,i,j,k,l,m;let n,o;if("message"in a)n=a.message,o=a.signature;else{let k,{chain:l,wallet:p,statement:q,options:r}=a;if(d_())if("object"==typeof p)k=p;else{let a=window;if("ethereum"in a&&"object"==typeof a.ethereum&&"request"in a.ethereum&&"function"==typeof a.ethereum.request)k=a.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof p||!(null==r?void 0:r.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=p}let s=new URL(null!=(b=null==r?void 0:r.url)?b:window.location.href),t=await k.request({method:"eth_requestAccounts"}).then(a=>a).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!t||0===t.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let u=eI(t[0]),v=null==(c=null==r?void 0:r.signInWithEthereum)?void 0:c.chainId;v||(v=parseInt(await k.request({method:"eth_chainId"}),16)),n=function(a){var b;let{chainId:c,domain:d,expirationTime:e,issuedAt:f=new Date,nonce:g,notBefore:h,requestId:i,resources:j,scheme:k,uri:l,version:m}=a;if(!Number.isInteger(c))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${c}`);if(!d)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(g&&g.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${g}`);if(!l)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==m)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(null==(b=a.statement)?void 0:b.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${a.statement}`);let n=eI(a.address),o=k?`${k}://${d}`:d,p=a.statement?`${a.statement}
24
+ `:"",q=`${o} wants you to sign in with your Ethereum account:
25
+ ${n}
26
+
27
+ ${p}`,r=`URI: ${l}
28
+ Version: ${m}
29
+ Chain ID: ${c}${g?`
30
+ Nonce: ${g}`:""}
31
+ Issued At: ${f.toISOString()}`;if(e&&(r+=`
32
+ Expiration Time: ${e.toISOString()}`),h&&(r+=`
33
+ Not Before: ${h.toISOString()}`),i&&(r+=`
34
+ Request ID: ${i}`),j){let a="\nResources:";for(let b of j){if(!b||"string"!=typeof b)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);a+=`
35
+ - ${b}`}r+=a}return`${q}
36
+ ${r}`}({domain:s.host,address:u,statement:q,uri:s.href,version:"1",chainId:v,nonce:null==(d=null==r?void 0:r.signInWithEthereum)?void 0:d.nonce,issuedAt:null!=(f=null==(e=null==r?void 0:r.signInWithEthereum)?void 0:e.issuedAt)?f:new Date,expirationTime:null==(g=null==r?void 0:r.signInWithEthereum)?void 0:g.expirationTime,notBefore:null==(h=null==r?void 0:r.signInWithEthereum)?void 0:h.notBefore,requestId:null==(i=null==r?void 0:r.signInWithEthereum)?void 0:i.requestId,resources:null==(j=null==r?void 0:r.signInWithEthereum)?void 0:j.resources}),o=await k.request({method:"personal_sign",params:[(m=n,"0x"+Array.from(new TextEncoder().encode(m),a=>a.toString(16).padStart(2,"0")).join("")),u]})}try{let{data:b,error:c}=await ew(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:n,signature:o},(null==(k=a.options)?void 0:k.captchaToken)?{gotrue_meta_security:{captcha_token:null==(l=a.options)?void 0:l.captchaToken}}:null),xform:ey});if(c)throw c;if(!b||!b.session||!b.user){let a=new dH;return this._returnResult({data:{user:null,session:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:c})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSolana(a){var b,c,d,e,f,g,h,i,j,k,l,m;let n,o;if("message"in a)n=a.message,o=a.signature;else{let l,{chain:m,wallet:p,statement:q,options:r}=a;if(d_())if("object"==typeof p)l=p;else{let a=window;if("solana"in a&&"object"==typeof a.solana&&("signIn"in a.solana&&"function"==typeof a.solana.signIn||"signMessage"in a.solana&&"function"==typeof a.solana.signMessage))l=a.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof p||!(null==r?void 0:r.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");l=p}let s=new URL(null!=(b=null==r?void 0:r.url)?b:window.location.href);if("signIn"in l&&l.signIn){let a,b=await l.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==r?void 0:r.signInWithSolana),{version:"1",domain:s.host,uri:s.href}),q?{statement:q}:null));if(Array.isArray(b)&&b[0]&&"object"==typeof b[0])a=b[0];else if(b&&"object"==typeof b&&"signedMessage"in b&&"signature"in b)a=b;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in a&&"signature"in a&&("string"==typeof a.signedMessage||a.signedMessage instanceof Uint8Array)&&a.signature instanceof Uint8Array)n="string"==typeof a.signedMessage?a.signedMessage:new TextDecoder().decode(a.signedMessage),o=a.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in l)||"function"!=typeof l.signMessage||!("publicKey"in l)||"object"!=typeof l||!l.publicKey||!("toBase58"in l.publicKey)||"function"!=typeof l.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");n=[`${s.host} wants you to sign in with your Solana account:`,l.publicKey.toBase58(),...q?["",q,""]:[""],"Version: 1",`URI: ${s.href}`,`Issued At: ${null!=(d=null==(c=null==r?void 0:r.signInWithSolana)?void 0:c.issuedAt)?d:new Date().toISOString()}`,...(null==(e=null==r?void 0:r.signInWithSolana)?void 0:e.notBefore)?[`Not Before: ${r.signInWithSolana.notBefore}`]:[],...(null==(f=null==r?void 0:r.signInWithSolana)?void 0:f.expirationTime)?[`Expiration Time: ${r.signInWithSolana.expirationTime}`]:[],...(null==(g=null==r?void 0:r.signInWithSolana)?void 0:g.chainId)?[`Chain ID: ${r.signInWithSolana.chainId}`]:[],...(null==(h=null==r?void 0:r.signInWithSolana)?void 0:h.nonce)?[`Nonce: ${r.signInWithSolana.nonce}`]:[],...(null==(i=null==r?void 0:r.signInWithSolana)?void 0:i.requestId)?[`Request ID: ${r.signInWithSolana.requestId}`]:[],...(null==(k=null==(j=null==r?void 0:r.signInWithSolana)?void 0:j.resources)?void 0:k.length)?["Resources",...r.signInWithSolana.resources.map(a=>`- ${a}`)]:[]].join("\n");let a=await l.signMessage(new TextEncoder().encode(n),"utf8");if(!a||!(a instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");o=a}}try{let{data:b,error:c}=await ew(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:n,signature:dZ(o)},(null==(l=a.options)?void 0:l.captchaToken)?{gotrue_meta_security:{captcha_token:null==(m=a.options)?void 0:m.captchaToken}}:null),xform:ey});if(c)throw c;if(!b||!b.session||!b.user){let a=new dH;return this._returnResult({data:{user:null,session:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:c})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async _exchangeCodeForSession(a,b){let c=(null==b?void 0:b.flowId)!=null,d=c?ee(null==b?void 0:b.flowId):d_()?ee(d2(window.location.href)[dy]):null;c&&!d&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",null==b?void 0:b.flowId);let{verifier:e,flowId:f}=c&&!d?{verifier:null,flowId:null}:await ej(this.storage,this.storageKey,d),[g,h]=(null!=e?e:"").split("/");try{if(!g&&"pkce"===this.flowType)throw new dL;let{data:b,error:c}=await ew(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:a,code_verifier:g},xform:ey});if(await ek(this.storage,this.storageKey,f),c)throw c;if(!b||!b.session||!b.user){let a=new dH;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("recovery"===h?"PASSWORD_RECOVERY":"SIGNED_IN",b.session)),this._returnResult({data:Object.assign(Object.assign({},b),{redirectType:null!=h?h:null}),error:c})}catch(a){if(await ek(this.storage,this.storageKey,f),dA(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(a){try{let{options:b,provider:c,token:d,access_token:e,nonce:f}=a,{data:g,error:h}=await ew(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:c,id_token:d,access_token:e,nonce:f,gotrue_meta_security:{captcha_token:null==b?void 0:b.captchaToken}},xform:ey});if(h)return this._returnResult({data:{user:null,session:null},error:h});if(!g||!g.session||!g.user){let a=new dH;return this._returnResult({data:{user:null,session:null},error:a})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:g,error:h})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithOtp(a){var b,c,d,e,f;let g=null;try{if("email"in a){let{email:d,options:e}=a,f=null,h=null;"pkce"===this.flowType&&([f,h,g]=await this._getCodeChallengeAndMethod());let{error:i}=await ew(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:d,data:null!=(b=null==e?void 0:e.data)?b:{},create_user:null==(c=null==e?void 0:e.shouldCreateUser)||c,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken},code_challenge:f,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(null==e?void 0:e.emailRedirectTo,g)});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in a){let{phone:b,options:c}=a,{data:g,error:h}=await ew(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:b,data:null!=(d=null==c?void 0:c.data)?d:{},create_user:null==(e=null==c?void 0:c.shouldCreateUser)||e,gotrue_meta_security:{captcha_token:null==c?void 0:c.captchaToken},channel:null!=(f=null==c?void 0:c.channel)?f:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==g?void 0:g.message_id},error:h})}throw new dI("You must provide either an email or phone number.")}catch(a){if(await ek(this.storage,this.storageKey,g),dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(a){var b,c;try{let d,e;"options"in a&&(d=null==(b=a.options)?void 0:b.redirectTo,e=null==(c=a.options)?void 0:c.captchaToken);let{data:f,error:g}=await ew(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},a),{gotrue_meta_security:{captcha_token:e}}),redirectTo:d,xform:ey});if(g)throw g;if(!f)throw Error("An error occurred on token verification.");let h=f.session,i=f.user;return(null==h?void 0:h.access_token)&&(await this._saveSession(h),await this._notifyAllSubscribers("recovery"==a.type?"PASSWORD_RECOVERY":"SIGNED_IN",h)),this._returnResult({data:{user:i,session:h},error:null})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSSO(a){var b,c,d,e;let f=null;try{let g=null,h=null;"pkce"===this.flowType&&([g,h,f]=await this._getCodeChallengeAndMethod());let i=await ew(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in a?{provider_id:a.providerId}:null),"domain"in a?{domain:a.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect(null==(b=a.options)?void 0:b.redirectTo,f)}),(null==(c=null==a?void 0:a.options)?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:a.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:g,code_challenge_method:h}),headers:this.headers,xform:eB});return(null==(d=i.data)?void 0:d.url)&&d_()&&!(null==(e=a.options)?void 0:e.skipBrowserRedirect)&&window.location.assign(i.data.url),this._returnResult(i)}catch(a){if(await ek(this.storage,this.storageKey,f),dA(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)throw c;if(!b)throw new dF;let{error:d}=await ew(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:b.access_token});return this._returnResult({data:{user:null,session:null},error:d})})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async resend(a){let b=null;try{let c=`${this.url}/resend`;if("email"in a){let{email:d,type:e,options:f}=a,g=null,h=null;"pkce"===this.flowType&&([g,h,b]=await this._getCodeChallengeAndMethod());let{error:i}=await ew(this.fetch,"POST",c,{headers:this.headers,body:{email:d,type:e,gotrue_meta_security:{captcha_token:null==f?void 0:f.captchaToken},code_challenge:g,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(null==f?void 0:f.emailRedirectTo,b)});return i&&await ek(this.storage,this.storageKey,b),this._returnResult({data:{user:null,session:null},error:i})}if("phone"in a){let{phone:b,type:d,options:e}=a,{data:f,error:g}=await ew(this.fetch,"POST",c,{headers:this.headers,body:{phone:b,type:d,gotrue_meta_security:{captcha_token:null==e?void 0:e.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==f?void 0:f.message_id},error:g})}throw new dI("You must provide either an email or phone number and a type")}catch(a){if(await ek(this.storage,this.storageKey,b),dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async getSession(){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async a=>a)):await this._useSession(async a=>a)}async _acquireLock(a,b){this._debug("#_acquireLock","begin",a);try{if(this.lockAcquired){let a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),c=(async()=>(await a,await b()))();return this.pendingInLock.push((async()=>{try{await c}catch(a){}})()),c}return await this.lock(`lock:${this.storageKey}`,a,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let a=b();for(this.pendingInLock.push((async()=>{try{await a}catch(a){}})()),await a;this.pendingInLock.length;){let a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(a){this._debug("#_useSession","begin");try{let b=await this.__loadSession();return await a(b)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),null==this.lock||this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let a=null,b=await d5(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",b),null!==b&&(this._isValidSession(b)?a=b:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!a)return{data:{session:null},error:null};let c=!!a.expires_at&&1e3*a.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${c?"":" not"} expired`,"expires_at",a.expires_at),!c)return{data:{session:await this._hydrateSessionUser(a)},error:null};let{data:d,error:e}=await this._callRefreshToken(a.refresh_token);if(e){let a=await d5(this.storage,this.storageKey);if(a&&this._isValidSession(a)&&a.expires_at&&1e3*a.expires_at>Date.now())return this._returnResult({data:{session:await this._hydrateSessionUser(a)},error:null});return this._returnResult({data:{session:null},error:e})}return this._returnResult({data:{session:d},error:null})}finally{this._debug("#__loadSession()","end")}}async _hydrateSessionUser(a){if(this.userStorage){let b=await d5(this.userStorage,this.storageKey+"-user");a.user=(null==b?void 0:b.user)?b.user:er()}if(this.storage.isServer&&a.user&&!a.user.__isUserNotAvailableProxy){var b;let c={value:this.suppressGetSessionWarning};b=a.user,a.user=new Proxy(b,{get:(a,b,d)=>{if("__isInsecureUserWarningProxy"===b)return!0;if("symbol"==typeof b){let c=b.toString();if("Symbol(Symbol.toPrimitive)"===c||"Symbol(Symbol.toStringTag)"===c||"Symbol(util.inspect.custom)"===c||"Symbol(nodejs.util.inspect.custom)"===c)return Reflect.get(a,b,d)}return c.value||"string"!=typeof b||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),c.value=!0),Reflect.get(a,b,d)}}),c.value&&(this.suppressGetSessionWarning=!0)}return a}async getUser(a){let b;return a?await this._getUser(a):(await this.initializePromise,(b=null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):await this._getUser()).data.user&&(this.suppressGetSessionWarning=!0),b)}async _getUser(a){try{if(a)return await ew(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:a,xform:eA});return await this._useSession(async a=>{var b,c,d;let{data:e,error:f}=a;if(f)throw f;return(null==(b=e.session)?void 0:b.access_token)||this.hasCustomAuthorizationHeader?await ew(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(d=null==(c=e.session)?void 0:c.access_token)?d:void 0,xform:eA}):{data:{user:null},error:new dF}})}catch(a){if(dA(a))return dG(a)&&await this._removeSession(),this._returnResult({data:{user:null},error:a});throw a}}async updateUser(a,b={}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(a,b)):await this._updateUser(a,b)}async _updateUser(a,b={}){let c=null;try{return await this._useSession(async d=>{let{data:e,error:f}=d;if(f)throw f;if(!e.session)throw new dF;let g=e.session,h=null,i=null;"pkce"===this.flowType&&null!=a.email&&([h,i,c]=await this._getCodeChallengeAndMethod());let{data:j,error:k}=await ew(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(null==b?void 0:b.emailRedirectTo,c),body:Object.assign(Object.assign({},a),{code_challenge:h,code_challenge_method:i}),jwt:g.access_token,xform:eA});if(k)throw k;return g.user=j.user,await this._saveSession(g),await this._notifyAllSubscribers("USER_UPDATED",g),this._returnResult({data:{user:g.user},error:null})})}catch(a){if(await ek(this.storage,this.storageKey,c),dA(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(a){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(a)):await this._setSession(a)}async _setSession(a){try{if(!a.access_token||!a.refresh_token)throw new dF;let b=Date.now()/1e3,c=b,d=!0,e=null,{payload:f}=d8(a.access_token);if(f.exp&&(d=(c=f.exp)<=b),d){let{data:b,error:c}=await this._callRefreshToken(a.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!b)return{data:{user:null,session:null},error:null};e=b}else{let{data:d,error:f}=await this._getUser(a.access_token);if(f)return this._returnResult({data:{user:null,session:null},error:f});e={access_token:a.access_token,refresh_token:a.refresh_token,user:d.user,token_type:"bearer",expires_in:c-b,expires_at:c},await this._saveSession(e),await this._notifyAllSubscribers("SIGNED_IN",e)}return this._returnResult({data:{user:e.user,session:e},error:null})}catch(a){if(dA(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}}async refreshSession(a){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(a)):await this._refreshSession(a)}async _refreshSession(a){try{return await this._useSession(async b=>{var c;if(!a){let{data:d,error:e}=b;if(e)throw e;a=null!=(c=d.session)?c:void 0}if(!(null==a?void 0:a.refresh_token))throw new dF;let{data:d,error:e}=await this._callRefreshToken(a.refresh_token);return e?this._returnResult({data:{user:null,session:null},error:e}):d?this._returnResult({data:{user:d.user,session:d},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(a){if(dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async _getSessionFromURL(a,b){var c;try{if(!d_())throw new dJ("No browser detected.");if(a.error||a.error_description||a.error_code)throw new dJ(a.error_description||"Error in URL with unspecified error_description",{error:a.error||"unspecified_error",code:a.error_code||"unspecified_code"});switch(b){case"implicit":if("pkce"===this.flowType)throw new dK("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new dJ("Not a valid implicit grant flow url.")}if("pkce"===b){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!a.code)throw new dK("No code detected.");let{data:b,error:d}=await this._exchangeCodeForSession(a.code,{flowId:a[dy]});if(d)throw d;let e=new URL(window.location.href);return e.searchParams.delete("code"),e.searchParams.delete(dy),window.history.replaceState(window.history.state,"",e.toString()),{data:{session:b.session,redirectType:null!=(c=b.redirectType)?c:null},error:null}}let{provider_token:d,provider_refresh_token:e,access_token:f,refresh_token:g,expires_in:h,expires_at:i,token_type:j}=a;if(!f||!h||!g||!j)throw new dJ("No session defined in URL");let k=Math.round(Date.now()/1e3),l=parseInt(h),m=k+l;i&&(m=parseInt(i));let n=m-k;1e3*n<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${n}s, should have been closer to ${l}s`);let o=m-l;k-o>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",o,m,k):k-o<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",o,m,k);let{data:p,error:q}=await this._getUser(f);if(q)throw q;let r={provider_token:d,provider_refresh_token:e,access_token:f,expires_in:l,expires_at:m,refresh_token:g,token_type:j,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:r,redirectType:a.type},error:null})}catch(a){if(dA(a))return this._returnResult({data:{session:null,redirectType:null},error:a});throw a}}_isImplicitGrantCallback(a){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),a):!!(a.access_token||a.error||a.error_description||a.error_code)}async _isPKCECallback(a){if(!a.code)return!1;let b=ee(a[dy]);return!!(b&&await d5(this.storage,ef(this.storageKey,b)))||!!await d5(this.storage,`${this.storageKey}-code-verifier`)}async signOut(a={scope:"global"}){return(await this.initializePromise,null!=this.lock)?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(a)):await this._signOut(a)}async _signOut({scope:a}={scope:"global"}){return await this._useSession(async b=>{var c;let d=async()=>{await this._removeSession()},{data:e,error:f}=b;if(f&&!dG(f))return this._returnResult({error:f});let g=null==(c=e.session)?void 0:c.access_token;if(g){let{error:b}=await this.admin.signOut(g,a);if(b&&!(dC(b)&&(404===b.status||401===b.status||403===b.status)||dG(b)))return"others"!==a&&await d(),this._returnResult({error:b})}return"others"!==a&&await d(),this._returnResult({error:null})})}onAuthStateChange(a){let b=Symbol("auth-callback"),c={id:b,callback:a,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",b),this.stateChangeEmitters.delete(b)}};return this._debug("#onAuthStateChange()","registered callback with id",b),this.stateChangeEmitters.set(b,c),(async()=>{await this.initializePromise,null!=this.lock?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(b)}):await this._emitInitialSession(b)})(),{data:{subscription:c}}}async _emitInitialSession(a){return await this._useSession(async b=>{var c,d;try{let{data:{session:d},error:e}=b;if(e)throw e;await (null==(c=this.stateChangeEmitters.get(a))?void 0:c.callback("INITIAL_SESSION",d)),this._debug("INITIAL_SESSION","callback id",a,"session",d)}catch(b){if(await (null==(d=this.stateChangeEmitters.get(a))?void 0:d.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",a,"error",b),dP(b))return;dG(b)||dN(b)||dC(b)&&("refresh_token_not_found"===b.code||"refresh_token_already_used"===b.code||"session_expired"===b.code)?console.warn(b):console.error(b)}})}async resetPasswordForEmail(a,b={}){let c=null,d=null,e=null;"pkce"===this.flowType&&([c,d,e]=await this._getCodeChallengeAndMethod(!0));try{return await ew(this.fetch,"POST",`${this.url}/recover`,{body:{email:a,code_challenge:c,code_challenge_method:d,gotrue_meta_security:{captcha_token:b.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(b.redirectTo,e)})}catch(a){if(await ek(this.storage,this.storageKey,e),dA(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var a;try{let{data:b,error:c}=await this.getUser();if(c)throw c;return this._returnResult({data:{identities:null!=(a=b.user.identities)?a:[]},error:null})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async linkIdentity(a){return"token"in a?this.linkIdentityIdToken(a):this.linkIdentityOAuth(a)}async linkIdentityOAuth(a){var b;let c=null;try{let{data:d,error:e}=await this._useSession(async b=>{var d,e,f,g,h;let{data:i,error:j}=b;if(j)throw j;let{url:k,flowId:l}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,a.provider,{redirectTo:null==(d=a.options)?void 0:d.redirectTo,scopes:null==(e=a.options)?void 0:e.scopes,queryParams:null==(f=a.options)?void 0:f.queryParams,skipBrowserRedirect:!0});return c=l,await ew(this.fetch,"GET",k,{headers:this.headers,jwt:null!=(h=null==(g=i.session)?void 0:g.access_token)?h:void 0})});if(e)throw e;return!d_()||(null==(b=a.options)?void 0:b.skipBrowserRedirect)||window.location.assign(null==d?void 0:d.url),this._returnResult({data:{provider:a.provider,url:null==d?void 0:d.url,flowId:c},error:null})}catch(b){if(dA(b))return this._returnResult({data:{provider:a.provider,url:null,flowId:c},error:b});throw b}}async linkIdentityIdToken(a){return await this._useSession(async b=>{var c;try{let{error:d,data:{session:e}}=b;if(d)throw d;let{options:f,provider:g,token:h,access_token:i,nonce:j}=a,{data:k,error:l}=await ew(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!=(c=null==e?void 0:e.access_token)?c:void 0,body:{provider:g,id_token:h,access_token:i,nonce:j,link_identity:!0,gotrue_meta_security:{captcha_token:null==f?void 0:f.captchaToken}},xform:ey});if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!k||!k.session||!k.user)return this._returnResult({data:{user:null,session:null},error:new dH});return k.session&&(await this._saveSession(k.session),await this._notifyAllSubscribers("USER_UPDATED",k.session)),this._returnResult({data:k,error:l})}catch(a){if(await ek(this.storage,this.storageKey,null),dA(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}})}async unlinkIdentity(a){try{return await this._useSession(async b=>{var c,d;let{data:e,error:f}=b;if(f)throw f;return await ew(this.fetch,"DELETE",`${this.url}/user/identities/${a.identity_id}`,{headers:this.headers,jwt:null!=(d=null==(c=e.session)?void 0:c.access_token)?d:void 0})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _refreshAccessToken(a){let b="#_refreshAccessToken()";this._debug(b,"begin");try{var c,d;let e=Date.now();return await (c=async c=>(c>0&&await d9(200*Math.pow(2,c-1)),this._debug(b,"refreshing attempt",c),await ew(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:a},headers:this.headers,xform:ey})),d=(a,b)=>{let c=200*Math.pow(2,a);return b&&dN(b)&&Date.now()+c-e<3e4},new Promise((a,b)=>{(async()=>{for(let e=0;e<1/0;e++)try{let b=await c(e);if(!d(e,null,b))return void a(b)}catch(a){if(!d(e,a))return void b(a)}})()}))}catch(a){if(this._debug(b,"error",a),dA(a))return this._returnResult({data:{session:null,user:null},error:a});throw a}finally{this._debug(b,"end")}}_isValidSession(a){return"object"==typeof a&&null!==a&&"access_token"in a&&"refresh_token"in a&&"expires_at"in a}async _handleProviderSignIn(a,b){let{url:c,flowId:d}=await this._getUrlForProvider(`${this.url}/authorize`,a,{redirectTo:b.redirectTo,scopes:b.scopes,queryParams:b.queryParams});return this._debug("#_handleProviderSignIn()","provider",a,"options",b,"url",c),d_()&&!b.skipBrowserRedirect&&window.location.assign(c),{data:{provider:a,url:c,flowId:d},error:null}}async _recoverAndRefresh(){var a,b;let c="#_recoverAndRefresh()";this._debug(c,"begin");try{let d=await d5(this.storage,this.storageKey);if(d&&this.userStorage){let b=await d5(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!b&&(b={user:d.user},await d4(this.userStorage,this.storageKey+"-user",b)),d.user=null!=(a=null==b?void 0:b.user)?a:er()}else if(d&&!d.user&&!d.user){let a=await d5(this.storage,this.storageKey+"-user");a&&(null==a?void 0:a.user)?(d.user=a.user,await d6(this.storage,this.storageKey+"-user"),await d4(this.storage,this.storageKey,d)):d.user=er()}if(this._debug(c,"session from storage",d),!this._isValidSession(d)){this._debug(c,"session is not valid"),null!==d&&await this._removeSession();return}let e=(null!=(b=d.expires_at)?b:1/0)*1e3-Date.now()<9e4;if(this._debug(c,`session has${e?"":" not"} expired with margin of 90000s`),e){if(this.autoRefreshToken&&d.refresh_token){let{error:a}=await this._callRefreshToken(d.refresh_token);a&&(dP(a)?this._debug(c,"refresh discarded by commit guard",a):this._debug(c,"refresh failed",a))}}else if(d.user&&!0===d.user.__isUserNotAvailableProxy)try{let{data:a,error:b}=await this._getUser(d.access_token);!b&&(null==a?void 0:a.user)?(d.user=a.user,await this._saveSession(d),await this._notifyAllSubscribers("SIGNED_IN",d)):this._debug(c,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(c,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",d)}catch(a){this._debug(c,"error",a),dN(a)?console.warn(a):console.error(a);return}finally{this._debug(c,"end")}}async _callRefreshToken(a){var b,c;if(!a)throw new dF;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===a&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning cached failure (cooldown active)"),this.lastRefreshFailure.result;let d="#_callRefreshToken()";this._debug(d,"begin");try{this.refreshingDeferred=new d7,this.refreshingDeferred.promise.then(void 0,()=>{});let b=await d5(this.storage,this.storageKey),{data:c,error:e}=await this._refreshAccessToken(a);if(e)throw e;if(!c.session)throw new dF;let f=await d5(this.storage,this.storageKey);if(null!==b&&(null===f||f.refresh_token!==b.refresh_token)){this._debug(d,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:f?"replaced":"cleared"});let a={data:null,error:new dO};return this.refreshingDeferred.resolve(a),a}let g=this._sessionRemovalEpoch;if(await this._saveSession(c.session),this._sessionRemovalEpoch!==g){this._debug(d,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await d6(this.storage,this.storageKey),this.userStorage&&await d6(this.userStorage,this.storageKey+"-user");let a={data:null,error:new dO};return this.refreshingDeferred.resolve(a),a}await this._notifyAllSubscribers("TOKEN_REFRESHED",c.session);let h={data:c.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(e){if(this._debug(d,"error",e),dA(e)){let c={data:null,error:e};if(!dN(e)){let a=await d5(this.storage,this.storageKey);(null==a?void 0:a.expires_at)&&1e3*a.expires_at>Date.now()?this._debug(d,"proactive refresh failed, access token still valid — preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:a,result:c,expiresAt:Date.now()+6e4},null==(b=this.refreshingDeferred)||b.resolve(c),c}throw null==(c=this.refreshingDeferred)||c.reject(e),e}finally{this.refreshingDeferred=null,this._debug(d,"end")}}async _notifyAllSubscribers(a,b,c=!0){if(null!==this._pendingInitNotifications&&c)return void this._pendingInitNotifications.push({event:a,session:b,broadcast:c});let d=`#_notifyAllSubscribers(${a})`;this._debug(d,"begin",b,`broadcast = ${c}`);try{this.broadcastChannel&&c&&this.broadcastChannel.postMessage({event:a,session:b});let d=[],e=Array.from(this.stateChangeEmitters.values()).map(async c=>{try{await c.callback(a,b)}catch(a){d.push(a)}});if(await Promise.all(e),d.length>0){for(let a=0;a<d.length;a+=1)console.error(d[a]);throw d[0]}}finally{this._debug(d,"end")}}async _saveSession(a){this._debug("#_saveSession()",a),this.suppressGetSessionWarning=!0;let b=Object.assign({},a),c=b.user&&!0===b.user.__isUserNotAvailableProxy;if(this.userStorage){!c&&b.user&&await d4(this.userStorage,this.storageKey+"-user",{user:b.user});let a=Object.assign({},b);delete a.user;let d=es(a);await d4(this.storage,this.storageKey,d)}else{let a=es(b);await d4(this.storage,this.storageKey,a)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await d6(this.storage,this.storageKey),await el(this.storage,this.storageKey),await d6(this.storage,this.storageKey+"-user"),this.userStorage&&await d6(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let a=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{a&&d_()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",a)}catch(a){console.error("removing visibilitychange callback failed",a)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let a=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=a,a&&"object"==typeof a&&"function"==typeof a.unref?a.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(a);let b=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=b,b&&"object"==typeof b&&"function"==typeof b.unref?b.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(b)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let a=this.autoRefreshTicker;this.autoRefreshTicker=null,a&&clearInterval(a);let b=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,b&&clearTimeout(b)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var a;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),null==(a=this.broadcastChannel)||a.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),null!=this.lock){try{await this._acquireLock(0,async()=>{try{let a=Date.now();try{return await this._useSession(async b=>{let{data:{session:c}}=b;if(!c||!c.refresh_token||!c.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let d=Math.floor((1e3*c.expires_at-a)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${d} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),d<=3&&await this._callRefreshToken(c.refresh_token)})}catch(a){console.error("Auto refresh tick failed with error. This is likely a transient error.",a)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(a){if(a instanceof eH)this._debug("auto refresh token tick lock not available");else throw a}return}if(null!==this.refreshingDeferred)return void this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");try{let a=Date.now();try{await this._useSession(async b=>{let{data:{session:c}}=b;if(!c||!c.refresh_token||!c.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let d=Math.floor((1e3*c.expires_at-a)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${d} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),d<=3&&await this._callRefreshToken(c.refresh_token)})}catch(a){console.error("Auto refresh tick failed with error. This is likely a transient error.",a)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!d_()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(a){this._debug("#visibilityChangedCallback","error",a)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(a){console.error("_handleVisibilityChange",a)}}async _onVisibilityChanged(a){let b=`#_onVisibilityChanged(${a})`;if(this._debug(b,"visibilityState",document.visibilityState),"visible"===document.visibilityState){if(this.autoRefreshToken&&this._startAutoRefresh(),!a)if(await this.initializePromise,null!=this.lock)await this._acquireLock(this.lockAcquireTimeout,async()=>{if("visible"!==document.visibilityState)return void this._debug(b,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");await this._recoverAndRefresh()});else{if("visible"!==document.visibilityState)return void this._debug(b,"visibilityState is no longer visible, skipping recovery");await this._recoverAndRefresh()}}else"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(a,b,c){let d=null==c?void 0:c.redirectTo,e=null,f=null,g=null;"pkce"===this.flowType&&([e,f,g]=await this._getCodeChallengeAndMethod(),d=this._maybeAppendFlowIdToRedirect(d,g));let h=[`provider=${encodeURIComponent(b)}`];if(d&&h.push(`redirect_to=${encodeURIComponent(d)}`),(null==c?void 0:c.scopes)&&h.push(`scopes=${encodeURIComponent(c.scopes)}`),null!=e&&null!=f){let a=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(f)}`});h.push(a.toString())}if(null==c?void 0:c.queryParams){let a=new URLSearchParams(c.queryParams);h.push(a.toString())}return(null==c?void 0:c.skipBrowserRedirect)&&h.push(`skip_http_redirect=${c.skipBrowserRedirect}`),{url:`${a}?${h.join("&")}`,flowId:g}}_maybeAppendFlowIdToRedirect(a,b){return a&&b&&this.experimental.appendPkceFlowIdToRedirects?function(a,b){let c=a.indexOf("#"),d=-1===c?a:a.slice(0,c),e=-1===c?"":a.slice(c),f=d.indexOf("?");if(-1!==f){let a=d.slice(0,f),b=d.slice(f+1).split("&").filter(a=>""!==a&&a!==dy&&!a.startsWith(`${dy}=`));d=b.length>0?`${a}?${b.join("&")}`:a}let g=d.includes("?")?"&":"?";return`${d}${g}${dy}=${encodeURIComponent(b)}${e}`}(a,b):null!=a?a:void 0}async _getCodeChallengeAndMethod(a=!1){return em(this.storage,this.storageKey,a,a=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",a))}async _unenroll(a){try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;return e?this._returnResult({data:null,error:e}):await ew(this.fetch,"DELETE",`${this.url}/factors/${a.factorId}`,{headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _enroll(a){try{return await this._useSession(async b=>{var c,d;let{data:e,error:f}=b;if(f)return this._returnResult({data:null,error:f});let g=Object.assign({friendly_name:a.friendlyName,factor_type:a.factorType},"phone"===a.factorType?{phone:a.phone}:"totp"===a.factorType?{issuer:a.issuer}:{}),{data:h,error:i}=await ew(this.fetch,"POST",`${this.url}/factors`,{body:g,headers:this.headers,jwt:null==(c=null==e?void 0:e.session)?void 0:c.access_token});return i?this._returnResult({data:null,error:i}):("totp"===a.factorType&&"totp"===h.type&&(null==(d=null==h?void 0:h.totp)?void 0:d.qr_code)&&(h.totp.qr_code=`data:image/svg+xml;utf-8,${h.totp.qr_code}`),this._returnResult({data:h,error:null}))})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _verify(a){let b=async()=>{try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let f=Object.assign({challenge_id:a.challengeId},"webauthn"in a?{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_response:"create"===a.webauthn.type?eP(a.webauthn.credential_response):eQ(a.webauthn.credential_response)})}:{code:a.code}),{data:g,error:h}=await ew(this.fetch,"POST",`${this.url}/factors/${a.factorId}/verify`,{body:f,headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});return h?this._returnResult({data:null,error:h}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+g.expires_in},g)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",g),this._returnResult({data:g,error:h}))})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,b):b()}async _challenge(a){let b=async()=>{try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let f=await ew(this.fetch,"POST",`${this.url}/factors/${a.factorId}/challenge`,{body:a,headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});if(f.error)return f;let{data:g}=f;if("webauthn"!==g.type)return{data:g,error:null};switch(g.webauthn.type){case"create":return{data:Object.assign(Object.assign({},g),{webauthn:Object.assign(Object.assign({},g.webauthn),{credential_options:Object.assign(Object.assign({},g.webauthn.credential_options),{publicKey:eN(g.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},g),{webauthn:Object.assign(Object.assign({},g.webauthn),{credential_options:Object.assign(Object.assign({},g.webauthn.credential_options),{publicKey:eO(g.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,b):b()}async _challengeAndVerify(a){let{data:b,error:c}=await this._challenge({factorId:a.factorId});return c?this._returnResult({data:null,error:c}):await this._verify({factorId:a.factorId,challengeId:b.id,code:a.code})}async _listFactors(){var a;let{data:{user:b},error:c}=await this.getUser();if(c)return{data:null,error:c};let d={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let c of null!=(a=null==b?void 0:b.factors)?a:[])d.all.push(c),"verified"===c.status&&c.factor_type in d&&Array.isArray(d[c.factor_type])&&d[c.factor_type].push(c);return{data:d,error:null}}async _getAuthenticatorAssuranceLevel(a){var b,c,d,e;if(a)try{let{payload:d}=d8(a),e=null;d.aal&&(e=d.aal);let f=e,{data:{user:g},error:h}=await this.getUser(a);if(h)return this._returnResult({data:null,error:h});(null!=(c=null==(b=null==g?void 0:g.factors)?void 0:b.filter(a=>"verified"===a.status))?c:[]).length>0&&(f="aal2");let i=d.amr||[];return{data:{currentLevel:e,nextLevel:f,currentAuthenticationMethods:i},error:null}}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}let{data:{session:f},error:g}=await this.getSession();if(g)return this._returnResult({data:null,error:g});if(!f)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:h}=d8(f.access_token),i=null;h.aal&&(i=h.aal);let j=i;return(null!=(e=null==(d=f.user.factors)?void 0:d.filter(a=>"verified"===a.status))?e:[]).length>0&&(j="aal2"),{data:{currentLevel:i,nextLevel:j,currentAuthenticationMethods:h.amr||[]},error:null}}async _getRecoveryCodesStatus(){eq(this.experimental);try{return await this._useSession(async a=>{var b;let{data:c,error:d}=a;if(d)return this._returnResult({data:null,error:d});let{data:e,error:f}=await ew(this.fetch,"GET",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:null==(b=null==c?void 0:c.session)?void 0:b.access_token});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _generateRecoveryCodes(a){eq(this.experimental);try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let{data:f,error:g}=await ew(this.fetch,"POST",`${this.url}/factors/recovery-codes`,{body:(null==a?void 0:a.friendlyName)?{friendly_name:a.friendlyName}:void 0,headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});return g?this._returnResult({data:null,error:g}):this._returnResult({data:f,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _verifyRecoveryCode(a){eq(this.experimental);let b=async()=>{try{return await this._useSession(async b=>{var c;let{data:d,error:e}=b;if(e)return this._returnResult({data:null,error:e});let{data:f,error:g}=await ew(this.fetch,"POST",`${this.url}/factors/recovery-codes/verify`,{body:{code:a.code},headers:this.headers,jwt:null==(c=null==d?void 0:d.session)?void 0:c.access_token});if(g)return this._returnResult({data:null,error:g});let h=Object.assign({expires_at:d$(f.expires_in)},f);return await this._saveSession(h),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",h),this._returnResult({data:f,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}};return null!=this.lock?this._acquireLock(this.lockAcquireTimeout,b):b()}async _regenerateRecoveryCodes(){eq(this.experimental);try{return await this._useSession(async a=>{var b;let{data:c,error:d}=a;if(d)return this._returnResult({data:null,error:d});let{data:e,error:f}=await ew(this.fetch,"POST",`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:null==(b=null==c?void 0:c.session)?void 0:b.access_token});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _unenrollRecoveryCodes(){eq(this.experimental);try{return await this._useSession(async a=>{var b;let{data:c,error:d}=a;if(d)return this._returnResult({data:null,error:d});let{data:e,error:f}=await ew(this.fetch,"DELETE",`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:null==(b=null==c?void 0:c.session)?void 0:b.access_token});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _getAuthorizationDetails(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;return d?this._returnResult({data:null,error:d}):c?await ew(this.fetch,"GET",`${this.url}/oauth/authorizations/${a}`,{headers:this.headers,jwt:c.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new dF})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _approveAuthorization(a,b){try{return await this._useSession(async c=>{let{data:{session:d},error:e}=c;if(e)return this._returnResult({data:null,error:e});if(!d)return this._returnResult({data:null,error:new dF});let f=await ew(this.fetch,"POST",`${this.url}/oauth/authorizations/${a}/consent`,{headers:this.headers,jwt:d.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return f.data&&f.data.redirect_url&&d_()&&!(null==b?void 0:b.skipBrowserRedirect)&&window.location.assign(f.data.redirect_url),f})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(a,b){try{return await this._useSession(async c=>{let{data:{session:d},error:e}=c;if(e)return this._returnResult({data:null,error:e});if(!d)return this._returnResult({data:null,error:new dF});let f=await ew(this.fetch,"POST",`${this.url}/oauth/authorizations/${a}/consent`,{headers:this.headers,jwt:d.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return f.data&&f.data.redirect_url&&d_()&&!(null==b?void 0:b.skipBrowserRedirect)&&window.location.assign(f.data.redirect_url),f})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;return c?this._returnResult({data:null,error:c}):b?await ew(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:b.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new dF})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _revokeOAuthGrant(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;return d?this._returnResult({data:null,error:d}):c?(await ew(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:c.access_token,query:{client_id:a.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new dF})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async fetchJwk(a,b={keys:[]}){let c=b.keys.find(b=>b.kid===a);if(c)return c;let d=Date.now();if((c=this.jwks.keys.find(b=>b.kid===a))&&this.jwks_cached_at+6e5>d)return c;let{data:e,error:f}=await ew(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(f)throw f;return e.keys&&0!==e.keys.length&&(this.jwks=e,this.jwks_cached_at=d,c=e.keys.find(b=>b.kid===a))?c:null}async getClaims(a,b={}){try{let d=a;if(!d){let{data:a,error:b}=await this.getSession();if(b||!a.session)return this._returnResult({data:null,error:b});d=a.session.access_token}let{header:e,payload:f,signature:g,raw:{header:h,payload:i}}=d8(d);if(!(null==b?void 0:b.allowExpired))try{var c=f.exp;if(!c)throw Error("Missing exp claim");if(c<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}catch(a){throw new dR(a instanceof Error?a.message:"JWT validation failed")}let j=!e.alg||e.alg.startsWith("HS")||!e.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(e.kid,(null==b?void 0:b.keys)?{keys:b.keys}:null==b?void 0:b.jwks);if(!j){let{error:a}=await this.getUser(d);if(a)throw a;return{data:{claims:f,header:e,signature:g},error:null}}let k=function(a){switch(a){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(e.alg),l=await crypto.subtle.importKey("jwk",j,k,!0,["verify"]);if(!await crypto.subtle.verify(k,l,g,function(a){let b=[];return!function(a,b){for(let c=0;c<a.length;c+=1){let d=a.charCodeAt(c);if(d>55295&&d<=56319){let b=(d-55296)*1024&65535;d=(a.charCodeAt(c+1)-56320&65535|b)+65536,c+=1}!function(a,b){if(a<=127)return b(a);if(a<=2047){b(192|a>>6),b(128|63&a);return}if(a<=65535){b(224|a>>12),b(128|a>>6&63),b(128|63&a);return}if(a<=1114111){b(240|a>>18),b(128|a>>12&63),b(128|a>>6&63),b(128|63&a);return}throw Error(`Unrecognized Unicode codepoint: ${a.toString(16)}`)}(d,b)}}(a,a=>b.push(a)),new Uint8Array(b)}(`${h}.${i}`)))throw new dR("Invalid JWT signature");return{data:{claims:f,header:e,signature:g},error:null}}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(a){var b,c,d,e;try{if(!eS())return this._returnResult({data:null,error:new dD("Browser does not support WebAuthn",null)});let{data:f,error:g}=await this._startPasskeyAuthentication({options:{captchaToken:null==(b=null==a?void 0:a.options)?void 0:b.captchaToken}});if(g||!f)return this._returnResult({data:null,error:g});let h=eO(f.options),i=null!=(d=null==(c=null==a?void 0:a.options)?void 0:c.signal)?d:eM.createNewAbortSignal(),{data:j,error:k}=await eU({publicKey:h,signal:i,mediation:null==(e=null==a?void 0:a.options)?void 0:e.mediation});if(k||!j)return this._returnResult({data:null,error:null!=k?k:new dD("WebAuthn ceremony failed",null)});let l=eQ(j);return this._verifyPasskeyAuthentication({challengeId:f.challenge_id,credential:l})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(a){var b,c;try{if(!eS())return this._returnResult({data:null,error:new dD("Browser does not support WebAuthn",null)});let{data:d,error:e}=await this._startPasskeyRegistration();if(e||!d)return this._returnResult({data:null,error:e});let f=eN(d.options),g=null!=(c=null==(b=null==a?void 0:a.options)?void 0:b.signal)?c:eM.createNewAbortSignal(),{data:h,error:i}=await eT({publicKey:f,signal:g});if(i||!h)return this._returnResult({data:null,error:null!=i?i:new dD("WebAuthn ceremony failed",null)});let j=eP(h);return this._verifyPasskeyRegistration({challengeId:d.challenge_id,credential:j})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _startPasskeyRegistration(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!b)return this._returnResult({data:null,error:new dF});let{data:d,error:e}=await ew(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:b.access_token,body:{}});return e?this._returnResult({data:null,error:e}):this._returnResult({data:d,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyRegistration(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new dF});let{data:e,error:f}=await ew(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:c.access_token,body:{challenge_id:a.challengeId,credential:a.credential}});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _startPasskeyAuthentication(a){var b;try{let{data:c,error:d}=await ew(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:null==(b=null==a?void 0:a.options)?void 0:b.captchaToken}}});if(d)return this._returnResult({data:null,error:d});return this._returnResult({data:c,error:null})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(a){try{let{data:b,error:c}=await ew(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:a.challengeId,credential:a.credential},xform:ey});if(c)return this._returnResult({data:null,error:c});return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:b,error:null})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _listPasskeys(){try{return await this._useSession(async a=>{let{data:{session:b},error:c}=a;if(c)return this._returnResult({data:null,error:c});if(!b)return this._returnResult({data:null,error:new dF});let{data:d,error:e}=await ew(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:b.access_token,xform:a=>({data:a,error:null})});return e?this._returnResult({data:null,error:e}):this._returnResult({data:d,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _updatePasskey(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new dF});let{data:e,error:f}=await ew(this.fetch,"PATCH",`${this.url}/passkeys/${a.passkeyId}`,{headers:this.headers,jwt:c.access_token,body:{friendly_name:a.friendlyName}});return f?this._returnResult({data:null,error:f}):this._returnResult({data:e,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}async _deletePasskey(a){try{return await this._useSession(async b=>{let{data:{session:c},error:d}=b;if(d)return this._returnResult({data:null,error:d});if(!c)return this._returnResult({data:null,error:new dF});let{error:e}=await ew(this.fetch,"DELETE",`${this.url}/passkeys/${a.passkeyId}`,{headers:this.headers,jwt:c.access_token,noResolveJson:!0});return e?this._returnResult({data:null,error:e}):this._returnResult({data:null,error:null})})}catch(a){if(dA(a))return this._returnResult({data:null,error:a});throw a}}}e0.nextInstanceID={};let e1=e0,e2="";if("undefined"!=typeof Deno)e2="deno",g=null==(n=Deno.version)?void 0:n.deno;else if("undefined"!=typeof document)e2="web";else if("undefined"!=typeof navigator&&"ReactNative"===navigator.product)e2="react-native";else{e2="node";let a=globalThis.process;g=null==a||null==(o=a.version)?void 0:o.replace(/^v/,"")}let e3=[`runtime=${e2}`];g&&e3.push(`runtime-version=${g}`);let e4={headers:{"X-Client-Info":`supabase-js/2.117.2; ${e3.join("; ")}`}},e5={schema:"public"},e6={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},e7={},e8={enabled:!1,respectSamplingDecision:!0};function e9(a){return(e9="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function fa(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function fb(a){for(var b=1;b<arguments.length;b++){var c=null!=arguments[b]?arguments[b]:{};b%2?fa(Object(c),!0).forEach(function(b){!function(a,b,c){var d;(d=function(a,b){if("object"!=e9(a)||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=e9(d))return d;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}(b,"string"),(b="symbol"==e9(d)?d:d+"")in a)?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c}(a,b,c[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(c)):fa(Object(c)).forEach(function(b){Object.defineProperty(a,b,Object.getOwnPropertyDescriptor(c,b))})}return a}let fc=a=>a.startsWith("sb_publishable_")||a.startsWith("sb_secret_"),fd=new Set,fe=(a,b,c,d,e,f)=>{let g=(a=>a?(...b)=>a(...b):(...a)=>fetch(...a))(d),h=Headers,i=(null==e?void 0:e.enabled)===!0,j=(null==e?void 0:e.respectSamplingDecision)!==!1,k=i?function(a){let b=[];try{let c=new URL(a);b.push(c.hostname)}catch(a){}return b.push("*.supabase.co","*.supabase.in"),b.push("localhost","127.0.0.1","[::1]"),b}(b):null,l=!((null==f?void 0:f.omitApiKeyAsBearer)&&fc(a));return async(b,d)=>{let e=await c(),f=new h(null==d?void 0:d.headers);if(f.has("apikey")||f.set("apikey",a),!f.has("Authorization")){let b=null!=e?e:l?a:null;b&&f.set("Authorization",`Bearer ${b}`)}if(k){let a=function(a,b,c){let d=globalThis[bG];if(!d)return ff||(ff=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!function(a,b){let c;if(!a||!b||0===b.length)return!1;if(a instanceof URL)c=a;else try{c=new URL(a)}catch(a){return!1}for(let a of b)try{if("string"==typeof a){if(function(a,b){if(b===a)return!0;if(b.startsWith("*.")){let c=b.slice(2);if(a.endsWith(c)&&(a===c||a.endsWith("."+c)))return!0}return!1}(c.hostname,a))return!0}else if(a instanceof RegExp){if(a.test(c.hostname))return!0}else if("function"==typeof a&&a(c))return!0}catch(a){continue}return!1}("string"==typeof a||a instanceof URL?a:a.url,b))return null;let e=d();if(!e||!e.traceparent){var f;if((null==e||null==(f=e.carrierKeys)?void 0:f.length)&&!fg){fg=!0;let a=e.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${e.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+a)}return null}if(c){let a=function(a){if(!a||"string"!=typeof a)return null;let b=a.split("-");if(4!==b.length)return null;let[c,d,e,f]=b;if(2!==c.length||32!==d.length||16!==e.length||2!==f.length)return null;let g=/^[0-9a-f]+$/i;return g.test(c)&&g.test(d)&&g.test(e)&&g.test(f)&&"00000000000000000000000000000000"!==d&&"0000000000000000"!==e?{version:c,traceId:d,parentId:e,traceFlags:f,isSampled:(1&parseInt(f,16))==1}:null}(e.traceparent);if(a&&!a.isSampled)return{traceparent:e.traceparent}}return e}(b,k,j);a&&(a.traceparent&&!f.has("traceparent")&&f.set("traceparent",a.traceparent),a.tracestate&&!f.has("tracestate")&&f.set("tracestate",a.tracestate),a.baggage&&!f.has("baggage")&&f.set("baggage",a.baggage))}return g(b,fb(fb({},d),{},{headers:f}))}},ff=!1,fg=!1;function fh(a){return"boolean"==typeof a?{enabled:a}:a}let fi=!1;var fj=class extends e1{constructor(a){super(a)}},fk=class{constructor(a,b,c){var d,e,f;this.supabaseUrl=a,this.supabaseKey=b;let g=function(a){let b=null==a?void 0:a.trim();if(!b)throw Error("supabaseUrl is required.");if(!b.match(/^https?:\/\//i))throw Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(b.endsWith("/")?b:b+"/")}catch(a){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}(a);if(!b)throw Error("supabaseKey is required.");(a=>{var b,c;if(!a.startsWith("sb_")||fc(a)||a.startsWith("sb_temp_"))return;let d=null!=(b=null==(c=a.match(/^sb_[a-zA-Z0-9]+_/))?void 0:c[0])?b:"unknown";fd.has(d)||(fd.add(d),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))})(b),function(a){!fi&&"object"==typeof a&&null!==a&&"schema"in a&&void 0!==a.schema&&(fi=!0,console.warn('@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: \'myschema\' } }). A top-level "schema" is ignored and queries go to the default schema.'))}(c),this.realtimeUrl=new URL("realtime/v1",g),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",g),this.storageUrl=new URL("storage/v1",g),this.functionsUrl=new URL("functions/v1",g);let h=`sb-${g.hostname.split(".")[0]}-auth-token`,i=function(a,b){var c,d,e,f,g,h;let{db:i,auth:j,realtime:k,global:l}=a,{db:m,auth:n,realtime:o,global:p}=b,q=fh(a.tracePropagation),r=fh(b.tracePropagation),s={db:fb(fb({},m),i),auth:fb(fb({},n),j),realtime:fb(fb({},o),k),storage:{},global:fb(fb(fb({},p),l),{},{headers:fb(fb({},null!=(c=null==p?void 0:p.headers)?c:{}),null!=(d=null==l?void 0:l.headers)?d:{})}),tracePropagation:{enabled:null!=(e=null!=(f=null==q?void 0:q.enabled)?f:null==r?void 0:r.enabled)&&e,respectSamplingDecision:null==(g=null!=(h=null==q?void 0:q.respectSamplingDecision)?h:null==r?void 0:r.respectSamplingDecision)||g},accessToken:async()=>""};return a.accessToken?s.accessToken=a.accessToken:delete s.accessToken,s}(null!=c?c:{},{db:e5,realtime:e7,auth:fb(fb({},e6),{},{storageKey:h}),global:e4,tracePropagation:e8});this.settings=i,this.storageKey=null!=(d=i.auth.storageKey)?d:"",this.headers=null!=(e=i.global.headers)?e:{},i.accessToken?(this.accessToken=i.accessToken,this.auth=new Proxy({},{get:(a,b)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(b)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!=(f=i.auth)?f:{},this.headers,i.global.fetch),this.fetch=fe(b,a,this._getSessionToken.bind(this),i.global.fetch,i.tracePropagation),this.functionsFetch=fe(b,a,this._getSessionToken.bind(this),i.global.fetch,i.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(fb({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},i.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(a=>this.realtime.setAuth(a)).catch(a=>console.warn("Failed to set initial Realtime auth token:",a)),this.rest=new b0(new URL("rest/v1",g).href,{headers:this.headers,schema:i.db.schema,fetch:this.fetch,timeout:i.db.timeout,urlLengthLimit:i.db.urlLengthLimit,retry:i.db.retry}),this.storage=new ds(this.storageUrl.href,this.headers,this.fetch,null==c?void 0:c.storage),i.accessToken||this._listenForAuthEvents()}get functions(){return new bM(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(a){return this.rest.from(a)}schema(a){return this.rest.schema(a)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(a,b={},c={head:!1,get:!1,count:void 0}){return this.rest.rpc(a,b,c)}channel(a,b={config:{}}){return this.realtime.channel(a,b)}getChannels(){return this.realtime.getChannels()}removeChannel(a){return this.realtime.removeChannel(a)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var a,b;if(this.accessToken)return await this.accessToken();let{data:c}=await this.auth.getSession();return null!=(a=null==(b=c.session)?void 0:b.access_token)?a:null}async _getAccessToken(){var a;return null!=(a=await this._getSessionToken())?a:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:a,persistSession:b,detectSessionInUrl:c,storage:d,userStorage:e,storageKey:f,flowType:g,lock:h,debug:i,throwOnError:j,experimental:k,lockAcquireTimeout:l,skipAutoInitialize:m},n,o){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new fj({url:this.authUrl.href,headers:fb(fb({},p),n),storageKey:f,autoRefreshToken:a,persistSession:b,detectSessionInUrl:c,storage:d,userStorage:e,flowType:g,lock:h,debug:i,throwOnError:j,experimental:k,fetch:o,lockAcquireTimeout:l,skipAutoInitialize:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(a=>"authorization"===a.toLowerCase())})}_initRealtimeClient(a){return new cL(this.realtimeUrl.href,fb(fb({},a),{},{params:fb(fb({},{apikey:this.supabaseKey}),null==a?void 0:a.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((a,b)=>{this._handleTokenChanged(a,"CLIENT",null==b?void 0:b.access_token)})}_handleTokenChanged(a,b,c){("TOKEN_REFRESHED"===a||"SIGNED_IN"===a||"INITIAL_SESSION"===a)&&this.changedAccessToken!==c?(this.changedAccessToken=c,this.realtime.setAuth(c)):"SIGNED_OUT"===a&&(this.realtime.setAuth(),"STORAGE"==b&&this.auth.signOut(),this.changedAccessToken=void 0)}};(function(){if("undefined"!=typeof window||void 0!==globalThis.Deno)return!1;let a=globalThis.process;if(!a)return!1;let b=a.version;if(null==b)return!1;let c=b.match(/^v(\d+)\./);return!!c&&20>=parseInt(c[1],10)})()&&console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715"),c(55),"undefined"==typeof URLPattern||URLPattern;var fl=c(40);if(new WeakMap,fl.unstable_postpone,!1===function(a){return a.includes("needs to bail out of prerendering at this point because it used")&&a.includes("Learn more: https://nextjs.org/docs/messages/ppr-caught-error")}("Route %%% needs to bail out of prerendering at this point because it used ^^^. React throws this special object to indicate where. It should not be caught by your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error"))throw Object.defineProperty(Error("Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js"),"__NEXT_ERROR_CODE",{value:"E296",enumerable:!1,configurable:!0});RegExp(`\\n\\s+at Suspense \\(<anonymous>\\)(?:(?!\\n\\s+at (?:body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6) \\(<anonymous>\\))[\\s\\S])*?\\n\\s+at __next_root_layout_boundary__ \\([^\\n]*\\)`),RegExp(`\\n\\s+at __next_metadata_boundary__[\\n\\s]`),RegExp(`\\n\\s+at __next_viewport_boundary__[\\n\\s]`),RegExp(`\\n\\s+at __next_outlet_boundary__[\\n\\s]`),al();let{env:fm,stdout:fn}=(null==(p=globalThis)?void 0:p.process)??{},fo=fm&&!fm.NO_COLOR&&(fm.FORCE_COLOR||(null==fn?void 0:fn.isTTY)&&!fm.CI&&"dumb"!==fm.TERM),fp=(a,b,c,d)=>{let e=a.substring(0,d)+c,f=a.substring(d+b.length),g=f.indexOf(b);return~g?e+fp(f,b,c,g):e+f},fq=(a,b,c=a)=>fo?d=>{let e=""+d,f=e.indexOf(b,a.length);return~f?a+fp(e,b,c,f)+b:a+e+b}:String,fr=fq("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m");fq("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),fq("\x1b[3m","\x1b[23m"),fq("\x1b[4m","\x1b[24m"),fq("\x1b[7m","\x1b[27m"),fq("\x1b[8m","\x1b[28m"),fq("\x1b[9m","\x1b[29m"),fq("\x1b[30m","\x1b[39m");let fs=fq("\x1b[31m","\x1b[39m"),ft=fq("\x1b[32m","\x1b[39m"),fu=fq("\x1b[33m","\x1b[39m");fq("\x1b[34m","\x1b[39m");let fv=fq("\x1b[35m","\x1b[39m");fq("\x1b[38;2;173;127;168m","\x1b[39m"),fq("\x1b[36m","\x1b[39m");let fw=fq("\x1b[37m","\x1b[39m");function fx(a){if(a)return a}async function fy(a){let b=ab.next({request:a}),c=fx(process.env.SUPABASE_SERVER_URL??"http://127.0.0.1:54321"),d=fx("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0");if(!c||!d)return b;let e=function(a,b,c){if(!a||!b)throw Error(`Your project's URL and Key are required to create a Supabase client!
37
+
38
+ Check your Supabase project's API settings to find these values
39
+
40
+ https://supabase.com/dashboard/project/_/settings/api`);let{storage:d,getAll:e,setAll:f,setItems:g,removedItems:h}=function(a,b){let c,d,e=a.cookies??null,f=a.cookieEncoding,g={},h={};if(e)if("get"in e){let a=async a=>{let b=a.flatMap(a=>[a,...Array.from({length:5}).map((b,c)=>`${a}.${c}`)]),c=[];for(let a=0;a<b.length;a+=1){let d=await e.get(b[a]);(d||"string"==typeof d)&&c.push({name:b[a],value:d})}return c};if(c=async b=>await a(b),"set"in e&&"remove"in e)d=async a=>{for(let b=0;b<a.length;b+=1){let{name:c,value:d,options:f}=a[b];d?await e.set(c,d,f):await e.remove(c,f)}};else if(b)d=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in e)if(c=async()=>await e.getAll(),"setAll"in e)d=e.setAll;else if(b)d=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw Error(`@supabase/ssr: ${b?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${bs()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!b&&bs())c=()=>(()=>{let a=(0,bD.qg)(document.cookie);return Object.keys(a).map(b=>({name:b,value:a[b]??""}))})(),d=a=>{a.forEach(({name:a,value:b,options:c})=>{document.cookie=(0,bD.lK)(a,b,c)})};else if(b)throw Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");else c=()=>[],d=()=>{throw Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")};return b?{getAll:c,setAll:d,setItems:g,removedItems:h,storage:{isServer:!0,getItem:async a=>{if("string"==typeof g[a])return g[a];if(h[a])return null;let b=await c([a]),d=await bx(a,async a=>{let c=b?.find(({name:b})=>b===a)||null;return c?c.value:null});if(!d)return null;let e=d;return"string"==typeof d&&d.startsWith(bE)&&(e=bC(d.substring(bE.length))),e},setItem:async(b,e)=>{b.endsWith("-code-verifier")&&await bF({getAll:c,setAll:d,setItems:{[b]:e},removedItems:{}},{cookieOptions:a?.cookieOptions??null,cookieEncoding:f}),g[b]=e,delete h[b]},removeItem:async a=>{delete g[a],h[a]=!0}}}:{getAll:c,setAll:d,setItems:g,removedItems:h,storage:{isServer:!1,getItem:async a=>{let b=await c([a]),d=await bx(a,async a=>{let c=b?.find(({name:b})=>b===a)||null;return c?c.value:null});if(!d)return null;let e=d;return d.startsWith(bE)&&(e=bC(d.substring(bE.length))),e},setItem:async(b,e)=>{let g=await c([b]),h=new Set((g?.map(({name:a})=>a)||[]).filter(a=>bv(a,b))),i=e;"base64url"===f&&(i=bE+bB(e));let j=bw(b,i);j.forEach(({name:a})=>{h.delete(a)});let k={...bt,...a?.cookieOptions,maxAge:0},l={...bt,...a?.cookieOptions,maxAge:bt.maxAge};delete k.name,delete l.name;let m=[...[...h].map(a=>({name:a,value:"",options:k})),...j.map(({name:a,value:b})=>({name:a,value:b,options:l}))];m.length>0&&await d(m)},removeItem:async b=>{let e=await c([b]),f=(e?.map(({name:a})=>a)||[]).filter(a=>bv(a,b)),g={...bt,...a?.cookieOptions,maxAge:0};delete g.name,f.length>0&&await d(f.map(a=>({name:a,value:"",options:g})))}}}}({...c,cookieEncoding:c?.cookieEncoding??"base64url"},!0),i=new fk(a,b,{...c,global:{...c?.global,headers:{...c?.global?.headers,"X-Client-Info":"supabase-ssr/0.7.0 createServerClient"}},auth:{...c?.cookieOptions?.name?{storageKey:c.cookieOptions.name}:null,...c?.auth,flowType:"pkce",autoRefreshToken:!1,detectSessionInUrl:!1,persistSession:!0,storage:d}});return i.auth.onAuthStateChange(async a=>{(Object.keys(g).length>0||Object.keys(h).length>0)&&("SIGNED_IN"===a||"TOKEN_REFRESHED"===a||"USER_UPDATED"===a||"PASSWORD_RECOVERY"===a||"SIGNED_OUT"===a||"MFA_CHALLENGE_VERIFIED"===a)&&await bF({getAll:e,setAll:f,setItems:g,removedItems:h},{cookieOptions:c?.cookieOptions??null,cookieEncoding:c?.cookieEncoding??"base64url"})}),i}(c,d,{cookies:{getAll:()=>a.cookies.getAll(),setAll(c){for(let b of c)a.cookies.set(b.name,b.value);for(let d of(b=ab.next({request:a}),c))b.cookies.set(d.name,d.value,d.options)}}});return await e.auth.getUser(),b}fq("\x1b[90m","\x1b[39m"),fq("\x1b[40m","\x1b[49m"),fq("\x1b[41m","\x1b[49m"),fq("\x1b[42m","\x1b[49m"),fq("\x1b[43m","\x1b[49m"),fq("\x1b[44m","\x1b[49m"),fq("\x1b[45m","\x1b[49m"),fq("\x1b[46m","\x1b[49m"),fq("\x1b[47m","\x1b[49m"),fw(fr("○")),fs(fr("⨯")),fu(fr("⚠")),fw(fr(" ")),ft(fr("✓")),fv(fr("\xbb")),new a3(1e4,a=>a.length),new WeakMap;let fz={matcher:["/((?!_next/static|_next/image|favicon.ico).*)"]};Object.values({NOT_FOUND:404,FORBIDDEN:403,UNAUTHORIZED:401});let fA={...q},fB=fA.middleware||fA.default,fC="/src/middleware";if("function"!=typeof fB)throw Object.defineProperty(Error(`The Middleware "${fC}" must export a \`middleware\` or a \`default\` function`),"__NEXT_ERROR_CODE",{value:"E120",enumerable:!1,configurable:!0});function fD(a){return br({...a,page:fC,handler:async(...a)=>{try{return await fB(...a)}catch(e){let b=a[0],c=new URL(b.url),d=c.pathname+c.search;throw await u(e,{path:d,method:b.method,headers:Object.fromEntries(b.headers.entries())},{routerKind:"Pages Router",routePath:"/middleware",routeType:"middleware",revalidateReason:void 0}),e}}})}},251:(a,b,c)=>{"use strict";var d=c(356).Buffer;Object.defineProperty(b,"__esModule",{value:!0}),!function(a,b){for(var c in b)Object.defineProperty(a,c,{enumerable:!0,get:b[c]})}(b,{handleFetch:function(){return h},interceptFetch:function(){return i},reader:function(){return f}});let e=c(122),f={url:a=>a.url,header:(a,b)=>a.headers.get(b)};async function g(a,b){let{url:c,method:e,headers:f,body:g,cache:h,credentials:i,integrity:j,mode:k,redirect:l,referrer:m,referrerPolicy:n}=b;return{testData:a,api:"fetch",request:{url:c,method:e,headers:[...Array.from(f),["next-test-stack",function(){let a=(Error().stack??"").split("\n");for(let b=1;b<a.length;b++)if(a[b].length>0){a=a.slice(b);break}return(a=(a=(a=a.filter(a=>!a.includes("/next/dist/"))).slice(0,5)).map(a=>a.replace("webpack-internal:///(rsc)/","").trim())).join(" ")}()]],body:g?d.from(await b.arrayBuffer()).toString("base64"):null,cache:h,credentials:i,integrity:j,mode:k,redirect:l,referrer:m,referrerPolicy:n}}}async function h(a,b){let c=(0,e.getTestReqInfo)(b,f);if(!c)return a(b);let{testData:h,proxyPort:i}=c,j=await g(h,b),k=await a(`http://localhost:${i}`,{method:"POST",body:JSON.stringify(j),next:{internal:!0}});if(!k.ok)throw Object.defineProperty(Error(`Proxy request failed: ${k.status}`),"__NEXT_ERROR_CODE",{value:"E146",enumerable:!1,configurable:!0});let l=await k.json(),{api:m}=l;switch(m){case"continue":return a(b);case"abort":case"unhandled":throw Object.defineProperty(Error(`Proxy request aborted [${b.method} ${b.url}]`),"__NEXT_ERROR_CODE",{value:"E145",enumerable:!1,configurable:!0});case"fetch":let{status:n,headers:o,body:p}=l.response;return new Response(p?d.from(p,"base64"):null,{status:n,headers:new Headers(o)});default:return m}}function i(a){return c.g.fetch=function(b,c){var d;return(null==c||null==(d=c.next)?void 0:d.internal)?a(b,c):h(a,new Request(b,c))},()=>{c.g.fetch=a}}},310:(a,b)=>{"use strict";Symbol.for("react.transitional.element"),Symbol.for("react.portal"),Symbol.for("react.fragment"),Symbol.for("react.strict_mode"),Symbol.for("react.profiler"),Symbol.for("react.forward_ref"),Symbol.for("react.suspense"),Symbol.for("react.memo"),Symbol.for("react.lazy"),Symbol.iterator;Object.prototype.hasOwnProperty,Object.assign},356:a=>{"use strict";a.exports=require("node:buffer")},429:a=>{"use strict";var b=Object.defineProperty,c=Object.getOwnPropertyDescriptor,d=Object.getOwnPropertyNames,e=Object.prototype.hasOwnProperty,f={};function g(a){var b;let c=["path"in a&&a.path&&`Path=${a.path}`,"expires"in a&&(a.expires||0===a.expires)&&`Expires=${("number"==typeof a.expires?new Date(a.expires):a.expires).toUTCString()}`,"maxAge"in a&&"number"==typeof a.maxAge&&`Max-Age=${a.maxAge}`,"domain"in a&&a.domain&&`Domain=${a.domain}`,"secure"in a&&a.secure&&"Secure","httpOnly"in a&&a.httpOnly&&"HttpOnly","sameSite"in a&&a.sameSite&&`SameSite=${a.sameSite}`,"partitioned"in a&&a.partitioned&&"Partitioned","priority"in a&&a.priority&&`Priority=${a.priority}`].filter(Boolean),d=`${a.name}=${encodeURIComponent(null!=(b=a.value)?b:"")}`;return 0===c.length?d:`${d}; ${c.join("; ")}`}function h(a){let b=new Map;for(let c of a.split(/; */)){if(!c)continue;let a=c.indexOf("=");if(-1===a){b.set(c,"true");continue}let[d,e]=[c.slice(0,a),c.slice(a+1)];try{b.set(d,decodeURIComponent(null!=e?e:"true"))}catch{}}return b}function i(a){if(!a)return;let[[b,c],...d]=h(a),{domain:e,expires:f,httponly:g,maxage:i,path:l,samesite:m,secure:n,partitioned:o,priority:p}=Object.fromEntries(d.map(([a,b])=>[a.toLowerCase().replace(/-/g,""),b]));{var q,r,s={name:b,value:decodeURIComponent(c),domain:e,...f&&{expires:new Date(f)},...g&&{httpOnly:!0},..."string"==typeof i&&{maxAge:Number(i)},path:l,...m&&{sameSite:j.includes(q=(q=m).toLowerCase())?q:void 0},...n&&{secure:!0},...p&&{priority:k.includes(r=(r=p).toLowerCase())?r:void 0},...o&&{partitioned:!0}};let a={};for(let b in s)s[b]&&(a[b]=s[b]);return a}}((a,c)=>{for(var d in c)b(a,d,{get:c[d],enumerable:!0})})(f,{RequestCookies:()=>l,ResponseCookies:()=>m,parseCookie:()=>h,parseSetCookie:()=>i,stringifyCookie:()=>g}),a.exports=((a,f,g,h)=>{if(f&&"object"==typeof f||"function"==typeof f)for(let i of d(f))e.call(a,i)||i===g||b(a,i,{get:()=>f[i],enumerable:!(h=c(f,i))||h.enumerable});return a})(b({},"__esModule",{value:!0}),f);var j=["strict","lax","none"],k=["low","medium","high"],l=class{constructor(a){this._parsed=new Map,this._headers=a;let b=a.get("cookie");if(b)for(let[a,c]of h(b))this._parsed.set(a,{name:a,value:c})}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...a){let b="string"==typeof a[0]?a[0]:a[0].name;return this._parsed.get(b)}getAll(...a){var b;let c=Array.from(this._parsed);if(!a.length)return c.map(([a,b])=>b);let d="string"==typeof a[0]?a[0]:null==(b=a[0])?void 0:b.name;return c.filter(([a])=>a===d).map(([a,b])=>b)}has(a){return this._parsed.has(a)}set(...a){let[b,c]=1===a.length?[a[0].name,a[0].value]:a,d=this._parsed;return d.set(b,{name:b,value:c}),this._headers.set("cookie",Array.from(d).map(([a,b])=>g(b)).join("; ")),this}delete(a){let b=this._parsed,c=Array.isArray(a)?a.map(a=>b.delete(a)):b.delete(a);return this._headers.set("cookie",Array.from(b).map(([a,b])=>g(b)).join("; ")),c}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(a=>`${a.name}=${encodeURIComponent(a.value)}`).join("; ")}},m=class{constructor(a){var b,c,d;this._parsed=new Map,this._headers=a;let e=null!=(d=null!=(c=null==(b=a.getSetCookie)?void 0:b.call(a))?c:a.get("set-cookie"))?d:[];for(let a of Array.isArray(e)?e:function(a){if(!a)return[];var b,c,d,e,f,g=[],h=0;function i(){for(;h<a.length&&/\s/.test(a.charAt(h));)h+=1;return h<a.length}for(;h<a.length;){for(b=h,f=!1;i();)if(","===(c=a.charAt(h))){for(d=h,h+=1,i(),e=h;h<a.length&&"="!==(c=a.charAt(h))&&";"!==c&&","!==c;)h+=1;h<a.length&&"="===a.charAt(h)?(f=!0,h=e,g.push(a.substring(b,d)),b=h):h=d+1}else h+=1;(!f||h>=a.length)&&g.push(a.substring(b,a.length))}return g}(e)){let b=i(a);b&&this._parsed.set(b.name,b)}}get(...a){let b="string"==typeof a[0]?a[0]:a[0].name;return this._parsed.get(b)}getAll(...a){var b;let c=Array.from(this._parsed.values());if(!a.length)return c;let d="string"==typeof a[0]?a[0]:null==(b=a[0])?void 0:b.name;return c.filter(a=>a.name===d)}has(a){return this._parsed.has(a)}set(...a){let[b,c,d]=1===a.length?[a[0].name,a[0].value,a[0]]:a,e=this._parsed;return e.set(b,function(a={name:"",value:""}){return"number"==typeof a.expires&&(a.expires=new Date(a.expires)),a.maxAge&&(a.expires=new Date(Date.now()+1e3*a.maxAge)),(null===a.path||void 0===a.path)&&(a.path="/"),a}({name:b,value:c,...d})),function(a,b){for(let[,c]of(b.delete("set-cookie"),a)){let a=g(c);b.append("set-cookie",a)}}(e,this._headers),this}delete(...a){let[b,c]="string"==typeof a[0]?[a[0]]:[a[0].name,a[0]];return this.set({...c,name:b,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(g).join("; ")}}},521:a=>{"use strict";a.exports=require("node:async_hooks")},608:(a,b)=>{"use strict";b.qg=function(a,b){let c=new h,d=a.length;if(d<2)return c;let e=b?.decode||k,f=0;do{let b=function(a,b,c){let d=a.indexOf("=",b);return d<c?d:-1}(a,f,d);if(-1===b)break;let g=function(a,b,c){let d=a.indexOf(";",b);return -1===d?c:d}(a,f,d);if(b>g){f=a.lastIndexOf(";",b-1)+1;continue}let h=j(a,f,b);void 0===c[h]&&(c[h]=e(j(a,b+1,g))),f=g+1}while(f<d);return c},b.lK=i,b.lK=i;let c=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,d=/^[\u0021-\u003A\u003C-\u007E]*$/,e=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,f=/^[\u0020-\u003A\u003D-\u007E]*$/,g=Object.prototype.toString,h=(()=>{let a=function(){};return a.prototype=Object.create(null),a})();function i(a,b,h){let i="object"==typeof a?a:{...h,name:a,value:String(b)},j=("object"==typeof b?b:h)?.encode||encodeURIComponent;if(!c.test(i.name))throw TypeError(`argument name is invalid: ${i.name}`);let k=i.value?j(i.value):"";if(!d.test(k))throw TypeError(`argument val is invalid: ${i.value}`);let l=i.name+"="+k;if(void 0!==i.maxAge){if(!Number.isInteger(i.maxAge))throw TypeError(`option maxAge is invalid: ${i.maxAge}`);l+="; Max-Age="+i.maxAge}if(i.domain){if(!e.test(i.domain))throw TypeError(`option domain is invalid: ${i.domain}`);l+="; Domain="+i.domain}if(i.path){if(!f.test(i.path))throw TypeError(`option path is invalid: ${i.path}`);l+="; Path="+i.path}if(i.expires){var m;if(m=i.expires,"[object Date]"!==g.call(m)||!Number.isFinite(i.expires.valueOf()))throw TypeError(`option expires is invalid: ${i.expires}`);l+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(l+="; HttpOnly"),i.secure&&(l+="; Secure"),i.partitioned&&(l+="; Partitioned"),i.priority)switch("string"==typeof i.priority?i.priority.toLowerCase():void 0){case"low":l+="; Priority=Low";break;case"medium":l+="; Priority=Medium";break;case"high":l+="; Priority=High";break;default:throw TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch("string"==typeof i.sameSite?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError(`option sameSite is invalid: ${i.sameSite}`)}return l}function j(a,b,c){let d=b,e=c;do{let b=a.charCodeAt(d);if(32!==b&&9!==b)break}while(++d<e);for(;e>d;){let b=a.charCodeAt(e-1);if(32!==b&&9!==b)break;e--}return a.slice(d,e)}function k(a){if(-1===a.indexOf("%"))return a;try{return decodeURIComponent(a)}catch(b){return a}}},681:a=>{(()=>{"use strict";"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab="//");var b={};(()=>{b.parse=function(b,c){if("string"!=typeof b)throw TypeError("argument str must be a string");for(var e={},f=b.split(d),g=(c||{}).decode||a,h=0;h<f.length;h++){var i=f[h],j=i.indexOf("=");if(!(j<0)){var k=i.substr(0,j).trim(),l=i.substr(++j,i.length).trim();'"'==l[0]&&(l=l.slice(1,-1)),void 0==e[k]&&(e[k]=function(a,b){try{return b(a)}catch(b){return a}}(l,g))}}return e},b.serialize=function(a,b,d){var f=d||{},g=f.encode||c;if("function"!=typeof g)throw TypeError("option encode is invalid");if(!e.test(a))throw TypeError("argument name is invalid");var h=g(b);if(h&&!e.test(h))throw TypeError("argument val is invalid");var i=a+"="+h;if(null!=f.maxAge){var j=f.maxAge-0;if(isNaN(j)||!isFinite(j))throw TypeError("option maxAge is invalid");i+="; Max-Age="+Math.floor(j)}if(f.domain){if(!e.test(f.domain))throw TypeError("option domain is invalid");i+="; Domain="+f.domain}if(f.path){if(!e.test(f.path))throw TypeError("option path is invalid");i+="; Path="+f.path}if(f.expires){if("function"!=typeof f.expires.toUTCString)throw TypeError("option expires is invalid");i+="; Expires="+f.expires.toUTCString()}if(f.httpOnly&&(i+="; HttpOnly"),f.secure&&(i+="; Secure"),f.sameSite)switch("string"==typeof f.sameSite?f.sameSite.toLowerCase():f.sameSite){case!0:case"strict":i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"none":i+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return i};var a=decodeURIComponent,c=encodeURIComponent,d=/; */,e=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/})(),a.exports=b})()},812:(a,b,c)=>{"use strict";var d,e,f,g,h,i;c.r(b),c.d(b,{DiagConsoleLogger:()=>F,DiagLogLevel:()=>d,INVALID_SPANID:()=>ad,INVALID_SPAN_CONTEXT:()=>af,INVALID_TRACEID:()=>ae,ProxyTracer:()=>ax,ProxyTracerProvider:()=>aA,ROOT_CONTEXT:()=>C,SamplingDecision:()=>g,SpanKind:()=>h,SpanStatusCode:()=>i,TraceFlags:()=>f,ValueType:()=>e,baggageEntryMetadataFromString:()=>z,context:()=>aJ,createContextKey:()=>A,createNoopMeter:()=>Y,createTraceState:()=>aI,default:()=>a1,defaultTextMapGetter:()=>Z,defaultTextMapSetter:()=>$,diag:()=>aK,isSpanContextValid:()=>as,isValidSpanId:()=>ar,isValidTraceId:()=>aq,metrics:()=>aP,propagation:()=>aZ,trace:()=>a0});let j="1.9.1",k=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/,l=function(a){let b=new Set([a]),c=new Set,d=a.match(k);if(!d)return()=>!1;let e={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};if(null!=e.prerelease)return function(b){return b===a};function f(a){return c.add(a),!1}return function(a){if(b.has(a))return!0;if(c.has(a))return!1;let d=a.match(k);if(!d)return f(a);let g={major:+d[1],minor:+d[2],patch:+d[3],prerelease:d[4]};if(null!=g.prerelease||e.major!==g.major)return f(a);if(0===e.major)return e.minor===g.minor&&e.patch<=g.patch?(b.add(a),!0):f(a);return e.minor<=g.minor?(b.add(a),!0):f(a)}}(j),m=j.split(".")[0],n=Symbol.for(`opentelemetry.js.api.${m}`),o="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof c.g?c.g:{};function p(a,b,c,d=!1){var e;let f=o[n]=null!=(e=o[n])?e:{version:j};if(!d&&f[a]){let b=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${a}`);return c.error(b.stack||b.message),!1}if(f.version!==j){let b=Error(`@opentelemetry/api: Registration of version v${f.version} for ${a} does not match previously registered API v${j}`);return c.error(b.stack||b.message),!1}return f[a]=b,c.debug(`@opentelemetry/api: Registered a global for ${a} v${j}.`),!0}function q(a){var b,c;let d=null==(b=o[n])?void 0:b.version;if(d&&l(d))return null==(c=o[n])?void 0:c[a]}function r(a,b){b.debug(`@opentelemetry/api: Unregistering a global for ${a} v${j}.`);let c=o[n];c&&delete c[a]}class s{constructor(a){this._namespace=a.namespace||"DiagComponentLogger"}debug(...a){return t("debug",this._namespace,a)}error(...a){return t("error",this._namespace,a)}info(...a){return t("info",this._namespace,a)}warn(...a){return t("warn",this._namespace,a)}verbose(...a){return t("verbose",this._namespace,a)}}function t(a,b,c){let d=q("diag");if(d)return d[a](b,...c)}!function(a){a[a.NONE=0]="NONE",a[a.ERROR=30]="ERROR",a[a.WARN=50]="WARN",a[a.INFO=60]="INFO",a[a.DEBUG=70]="DEBUG",a[a.VERBOSE=80]="VERBOSE",a[a.ALL=9999]="ALL"}(d||(d={}));class u{static instance(){return this._instance||(this._instance=new u),this._instance}constructor(){function a(a){return function(...b){let c=q("diag");if(c)return c[a](...b)}}let b=this,c=(a,c={logLevel:d.INFO})=>{var e,f,g;if(a===b){let a=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return b.error(null!=(e=a.stack)?e:a.message),!1}"number"==typeof c&&(c={logLevel:c});let h=q("diag"),i=function(a,b){function c(c,d){let e=b[c];return"function"==typeof e&&a>=d?e.bind(b):function(){}}return a<d.NONE?a=d.NONE:a>d.ALL&&(a=d.ALL),b=b||{},{error:c("error",d.ERROR),warn:c("warn",d.WARN),info:c("info",d.INFO),debug:c("debug",d.DEBUG),verbose:c("verbose",d.VERBOSE)}}(null!=(f=c.logLevel)?f:d.INFO,a);if(h&&!c.suppressOverrideMessage){let a=null!=(g=Error().stack)?g:"<failed to generate stacktrace>";h.warn(`Current logger will be overwritten from ${a}`),i.warn(`Current logger will overwrite one already registered from ${a}`)}return p("diag",i,b,!0)};b.setLogger=c,b.disable=()=>{r("diag",b)},b.createComponentLogger=a=>new s(a),b.verbose=a("verbose"),b.debug=a("debug"),b.info=a("info"),b.warn=a("warn"),b.error=a("error")}}class v{constructor(a){this._entries=a?new Map(a):new Map}getEntry(a){let b=this._entries.get(a);if(b)return Object.assign({},b)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(a,b){let c=new v(this._entries);return c._entries.set(a,b),c}removeEntry(a){let b=new v(this._entries);return b._entries.delete(a),b}removeEntries(...a){let b=new v(this._entries);for(let c of a)b._entries.delete(c);return b}clear(){return new v}}let w=Symbol("BaggageEntryMetadata"),x=u.instance();function y(a={}){return new v(new Map(Object.entries(a)))}function z(a){return"string"!=typeof a&&(x.error(`Cannot create baggage metadata from unknown type: ${typeof a}`),a=""),{__TYPE__:w,toString:()=>a}}function A(a){return Symbol.for(a)}class B{constructor(a){let b=this;b._currentContext=a?new Map(a):new Map,b.getValue=a=>b._currentContext.get(a),b.setValue=(a,c)=>{let d=new B(b._currentContext);return d._currentContext.set(a,c),d},b.deleteValue=a=>{let c=new B(b._currentContext);return c._currentContext.delete(a),c}}}let C=new B,D=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],E={};if("undefined"!=typeof console)for(let a of["error","warn","info","debug","trace","log"])"function"==typeof console[a]&&(E[a]=console[a]);class F{constructor(){for(let a=0;a<D.length;a++)this[D[a].n]=function(a){return function(...b){let c=E[a];if("function"!=typeof c&&(c=E.log),"function"!=typeof c&&console&&"function"!=typeof(c=console[a])&&(c=console.log),"function"==typeof c)return c.apply(console,b)}}(D[a].c)}}class G{constructor(){}createGauge(a,b){return S}createHistogram(a,b){return T}createCounter(a,b){return R}createUpDownCounter(a,b){return U}createObservableGauge(a,b){return W}createObservableCounter(a,b){return V}createObservableUpDownCounter(a,b){return X}addBatchObservableCallback(a,b){}removeBatchObservableCallback(a){}}class H{}class I extends H{add(a,b){}}class J extends H{add(a,b){}}class K extends H{record(a,b){}}class L extends H{record(a,b){}}class M{addCallback(a){}removeCallback(a){}}class N extends M{}class O extends M{}class P extends M{}let Q=new G,R=new I,S=new K,T=new L,U=new J,V=new N,W=new O,X=new P;function Y(){return Q}!function(a){a[a.INT=0]="INT",a[a.DOUBLE=1]="DOUBLE"}(e||(e={}));let Z={get(a,b){if(null!=a)return a[b]},keys:a=>null==a?[]:Object.keys(a)},$={set(a,b,c){null!=a&&(a[b]=c)}};class _{active(){return C}with(a,b,c,...d){return b.call(c,...d)}bind(a,b){return b}enable(){return this}disable(){return this}}let aa="context",ab=new _;class ac{constructor(){}static getInstance(){return this._instance||(this._instance=new ac),this._instance}setGlobalContextManager(a){return p(aa,a,u.instance())}active(){return this._getContextManager().active()}with(a,b,c,...d){return this._getContextManager().with(a,b,c,...d)}bind(a,b){return this._getContextManager().bind(a,b)}_getContextManager(){return q(aa)||ab}disable(){this._getContextManager().disable(),r(aa,u.instance())}}!function(a){a[a.NONE=0]="NONE",a[a.SAMPLED=1]="SAMPLED"}(f||(f={}));let ad="0000000000000000",ae="00000000000000000000000000000000",af={traceId:ae,spanId:ad,traceFlags:f.NONE};class ag{constructor(a=af){this._spanContext=a}spanContext(){return this._spanContext}setAttribute(a,b){return this}setAttributes(a){return this}addEvent(a,b){return this}addLink(a){return this}addLinks(a){return this}setStatus(a){return this}updateName(a){return this}end(a){}isRecording(){return!1}recordException(a,b){}}let ah=A("OpenTelemetry Context Key SPAN");function ai(a){return a.getValue(ah)||void 0}function aj(){return ai(ac.getInstance().active())}function ak(a,b){return a.setValue(ah,b)}function al(a){return a.deleteValue(ah)}function am(a,b){return ak(a,new ag(b))}function an(a){var b;return null==(b=ai(a))?void 0:b.spanContext()}let ao=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function ap(a,b){if("string"!=typeof a||a.length!==b)return!1;let c=0;for(let b=0;b<a.length;b+=4)c+=(0|ao[a.charCodeAt(b)])+(0|ao[a.charCodeAt(b+1)])+(0|ao[a.charCodeAt(b+2)])+(0|ao[a.charCodeAt(b+3)]);return c===b}function aq(a){return ap(a,32)&&a!==ae}function ar(a){return ap(a,16)&&a!==ad}function as(a){return aq(a.traceId)&&ar(a.spanId)}function at(a){return new ag(a)}let au=ac.getInstance();class av{startSpan(a,b,c=au.active()){var d;if(null==b?void 0:b.root)return new ag;let e=c&&an(c);return null!==(d=e)&&"object"==typeof d&&"spanId"in d&&"string"==typeof d.spanId&&"traceId"in d&&"string"==typeof d.traceId&&"traceFlags"in d&&"number"==typeof d.traceFlags&&as(e)?new ag(e):new ag}startActiveSpan(a,b,c,d){let e,f,g;if(arguments.length<2)return;2==arguments.length?g=b:3==arguments.length?(e=b,g=c):(e=b,f=c,g=d);let h=null!=f?f:au.active(),i=this.startSpan(a,e,h),j=ak(h,i);return au.with(j,g,void 0,i)}}let aw=new av;class ax{constructor(a,b,c,d){this._provider=a,this.name=b,this.version=c,this.options=d}startSpan(a,b,c){return this._getTracer().startSpan(a,b,c)}startActiveSpan(a,b,c,d){let e=this._getTracer();return Reflect.apply(e.startActiveSpan,e,arguments)}_getTracer(){if(this._delegate)return this._delegate;let a=this._provider.getDelegateTracer(this.name,this.version,this.options);return a?(this._delegate=a,this._delegate):aw}}class ay{getTracer(a,b,c){return new av}}let az=new ay;class aA{getTracer(a,b,c){var d;return null!=(d=this.getDelegateTracer(a,b,c))?d:new ax(this,a,b,c)}getDelegate(){var a;return null!=(a=this._delegate)?a:az}setDelegate(a){this._delegate=a}getDelegateTracer(a,b,c){var d;return null==(d=this._delegate)?void 0:d.getTracer(a,b,c)}}!function(a){a[a.NOT_RECORD=0]="NOT_RECORD",a[a.RECORD=1]="RECORD",a[a.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(g||(g={})),function(a){a[a.INTERNAL=0]="INTERNAL",a[a.SERVER=1]="SERVER",a[a.CLIENT=2]="CLIENT",a[a.PRODUCER=3]="PRODUCER",a[a.CONSUMER=4]="CONSUMER"}(h||(h={})),function(a){a[a.UNSET=0]="UNSET",a[a.OK=1]="OK",a[a.ERROR=2]="ERROR"}(i||(i={}));let aB="[_0-9a-z-*/]",aC=`[a-z]${aB}{0,255}`,aD=`[a-z0-9]${aB}{0,240}@[a-z]${aB}{0,13}`,aE=RegExp(`^(?:${aC}|${aD})$`),aF=/^[ -~]{0,255}[!-~]$/,aG=/,|=/;class aH{constructor(a){this._internalState=new Map,a&&this._parse(a)}set(a,b){let c=this._clone();return c._internalState.has(a)&&c._internalState.delete(a),c._internalState.set(a,b),c}unset(a){let b=this._clone();return b._internalState.delete(a),b}get(a){return this._internalState.get(a)}serialize(){return Array.from(this._internalState.keys()).reduceRight((a,b)=>(a.push(b+"="+this.get(b)),a),[]).join(",")}_parse(a){!(a.length>512)&&(this._internalState=a.split(",").reduceRight((a,b)=>{let c=b.trim(),d=c.indexOf("=");if(-1!==d){let e=c.slice(0,d),f=c.slice(d+1,b.length);aE.test(e)&&aF.test(f)&&!aG.test(f)&&a.set(e,f)}return a},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let a=new aH;return a._internalState=new Map(this._internalState),a}}function aI(a){return new aH(a)}let aJ=ac.getInstance(),aK=u.instance();class aL{getMeter(a,b,c){return Q}}let aM=new aL,aN="metrics";class aO{constructor(){}static getInstance(){return this._instance||(this._instance=new aO),this._instance}setGlobalMeterProvider(a){return p(aN,a,u.instance())}getMeterProvider(){return q(aN)||aM}getMeter(a,b,c){return this.getMeterProvider().getMeter(a,b,c)}disable(){r(aN,u.instance())}}let aP=aO.getInstance();class aQ{inject(a,b){}extract(a,b){return a}fields(){return[]}}let aR=A("OpenTelemetry Baggage Key");function aS(a){return a.getValue(aR)||void 0}function aT(){return aS(ac.getInstance().active())}function aU(a,b){return a.setValue(aR,b)}function aV(a){return a.deleteValue(aR)}let aW="propagation",aX=new aQ;class aY{constructor(){this.createBaggage=y,this.getBaggage=aS,this.getActiveBaggage=aT,this.setBaggage=aU,this.deleteBaggage=aV}static getInstance(){return this._instance||(this._instance=new aY),this._instance}setGlobalPropagator(a){return p(aW,a,u.instance())}inject(a,b,c=$){return this._getGlobalPropagator().inject(a,b,c)}extract(a,b,c=Z){return this._getGlobalPropagator().extract(a,b,c)}fields(){return this._getGlobalPropagator().fields()}disable(){r(aW,u.instance())}_getGlobalPropagator(){return q(aW)||aX}}let aZ=aY.getInstance(),a$="trace";class a_{constructor(){this._proxyTracerProvider=new aA,this.wrapSpanContext=at,this.isSpanContextValid=as,this.deleteSpan=al,this.getSpan=ai,this.getActiveSpan=aj,this.getSpanContext=an,this.setSpan=ak,this.setSpanContext=am}static getInstance(){return this._instance||(this._instance=new a_),this._instance}setGlobalTracerProvider(a){let b=p(a$,this._proxyTracerProvider,u.instance());return b&&this._proxyTracerProvider.setDelegate(a),b}getTracerProvider(){return q(a$)||this._proxyTracerProvider}getTracer(a,b){return this.getTracerProvider().getTracer(a,b)}disable(){r(a$,u.instance()),this._proxyTracerProvider=new aA}}let a0=a_.getInstance(),a1={context:aJ,diag:aK,metrics:aP,propagation:aZ,trace:a0}}},a=>{var b=a(a.s=240);(_ENTRIES="undefined"==typeof _ENTRIES?{}:_ENTRIES)["middleware_src/middleware"]=b}]);
41
+ //# sourceMappingURL=middleware.js.map