conformtools 0.6.19 → 0.6.21

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 (88) hide show
  1. package/dist/{account-KSE6H6DJ.js → account-VD3EE5UT.js} +1 -1
  2. package/dist/{agent-hook-setup-SHZOVJYL.js → agent-hook-setup-D2QNHA3V.js} +1 -1
  3. package/dist/{analysis-engine-KUGSWNQB.js → analysis-engine-VNGF3DE4.js} +1 -1
  4. package/dist/{bridge-REYIYXUU.js → bridge-GW2VQP2I.js} +1 -1
  5. package/dist/browser/timeline_core_bg.wasm +0 -0
  6. package/dist/{chunk-NHVH373D.js → chunk-26ZNWQLT.js} +1 -1
  7. package/dist/{chunk-2GRXBIJB.js → chunk-2WD3MDPB.js} +1 -1
  8. package/dist/{chunk-HKHEL4MZ.js → chunk-2WNNDPVR.js} +1 -1
  9. package/dist/chunk-2XQ42O7E.js +7 -0
  10. package/dist/{chunk-GTN62ZQV.js → chunk-3WJSWOCS.js} +1 -1
  11. package/dist/{chunk-4KMSOMLG.js → chunk-5WL2ZPPB.js} +207 -196
  12. package/dist/chunk-5XJVAA6N.js +10 -0
  13. package/dist/chunk-5YCUHHZO.js +5 -0
  14. package/dist/chunk-AY72AUHE.js +162 -0
  15. package/dist/chunk-BUOYYO22.js +3 -0
  16. package/dist/{chunk-ND2YUUUH.js → chunk-CXOK4SF6.js} +1 -1
  17. package/dist/{chunk-2DEUYEQD.js → chunk-I6WBZBGN.js} +1 -1
  18. package/dist/{chunk-567IWIX6.js → chunk-JCNKPRYY.js} +1 -1
  19. package/dist/{chunk-L2RTMZCN.js → chunk-LKX3HCRN.js} +1 -1
  20. package/dist/chunk-M545OKDZ.js +6 -0
  21. package/dist/{chunk-3DYCTUSQ.js → chunk-M56WEBZY.js} +1 -1
  22. package/dist/chunk-MU5AGXSH.js +3 -0
  23. package/dist/{chunk-EWW5KWAO.js → chunk-OR6IMPAS.js} +1 -1
  24. package/dist/{chunk-WNDA7QSY.js → chunk-P6MSAFNR.js} +1 -1
  25. package/dist/{chunk-ATEWMIY5.js → chunk-PENDVYIL.js} +1 -1
  26. package/dist/{chunk-BD54PRSN.js → chunk-QJPOC4SW.js} +1 -1
  27. package/dist/{chunk-WM7ESQLY.js → chunk-SQCGMF6W.js} +1 -1
  28. package/dist/{chunk-3J2FARFO.js → chunk-VG73BE6N.js} +1 -1
  29. package/dist/{chunk-TD3ZHREE.js → chunk-WW6XAQKM.js} +1 -1
  30. package/dist/chunk-X7C4YS2J.js +6 -0
  31. package/dist/chunk-XAUMTGJZ.js +9 -0
  32. package/dist/{chunk-LUKA7UUJ.js → chunk-Z42CP7YT.js} +1 -1
  33. package/dist/chunk-ZAL7Y5VZ.js +7 -0
  34. package/dist/{claude-setup-ZOEQ5NXE.js → claude-setup-AI4WXN2V.js} +1 -1
  35. package/dist/cli.js +2 -2
  36. package/dist/{cr3-wasm-DIWL7CPH.js → cr3-wasm-CVZ2A7HA.js} +1 -1
  37. package/dist/{demo-engine-ZX24TAXA.js → demo-engine-MOHHYVGV.js} +1 -1
  38. package/dist/{dng-wasm-PE463PG2.js → dng-wasm-TN64FKIN.js} +1 -1
  39. package/dist/{dpx-wasm-DKE3LJ6Z.js → dpx-wasm-BO2NDGTA.js} +1 -1
  40. package/dist/{engine-K6QYU5KJ.js → engine-WMOJ3HRU.js} +2 -2
  41. package/dist/{exr-wasm-HAFH3YA5.js → exr-wasm-W4K6W6JZ.js} +1 -1
  42. package/dist/flame/hook/conformtools_flame/verbs.py +21 -4
  43. package/dist/framing-GOLRVBBJ.js +3 -0
  44. package/dist/gfx-worker.js +1 -1
  45. package/dist/{h264-YX5KP63E.js → h264-LC27KFZT.js} +1 -1
  46. package/dist/{h264-mxf-VAHIJCA7.js → h264-mxf-GQCFBTTP.js} +1 -1
  47. package/dist/hook.js +3 -3
  48. package/dist/host-relink-BYLBYTPH.js +10 -0
  49. package/dist/hosted-ASNIPMSH.js +3 -0
  50. package/dist/hosts-EYVK23A3.js +3 -0
  51. package/dist/http.js +2 -2
  52. package/dist/{inspect-QRHOFMC2.js → inspect-63MCOFOQ.js} +16 -16
  53. package/dist/isobmff-IMEN2G3B.js +3 -0
  54. package/dist/{mc-video-CHBOYPI5.js → mc-video-G4KNAHGG.js} +1 -1
  55. package/dist/mcp.js +1 -1
  56. package/dist/{media-TPGEESEU.js → media-Z23SL7RZ.js} +1 -1
  57. package/dist/{media_core-XOKN7UUF.js → media_core-KHSB6EFN.js} +2 -2
  58. package/dist/{mxf-R2ONKSYU.js → mxf-ZEM6EEZU.js} +1 -1
  59. package/dist/{ops-MKDFWWPG.js → ops-T6ZV7RAM.js} +1 -1
  60. package/dist/{probe-CHT266NN.js → probe-YOYK7HR5.js} +1 -1
  61. package/dist/{r3d-EKISZSKU.js → r3d-6P6K47AH.js} +1 -1
  62. package/dist/{r3d-F4OWLQE2.js → r3d-ISLQ6I3S.js} +1 -1
  63. package/dist/{sequence-patch-6FSMBG7O.js → sequence-patch-5MFTY52Q.js} +1 -1
  64. package/dist/{still-IDLCMQRD.js → still-DMZJUM7M.js} +1 -1
  65. package/dist/{still-wasm-54HEDTRX.js → still-wasm-ZLP224QL.js} +1 -1
  66. package/dist/{store-CFQHKBGL.js → store-6XN5Q6UG.js} +1 -1
  67. package/dist/{tiff-wasm-O7XUGXIO.js → tiff-wasm-TAEKNO4Q.js} +1 -1
  68. package/dist/timeline-P4GJT36O.js +3 -0
  69. package/dist/wasm/media_core_bg.wasm +0 -0
  70. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  71. package/dist/{wav-OLA3QYFJ.js → wav-BNOX5U7S.js} +1 -1
  72. package/package.json +5 -5
  73. package/dist/chunk-4PV2UTKG.js +0 -10
  74. package/dist/chunk-BZQAUU3D.js +0 -6
  75. package/dist/chunk-CUZVK2JJ.js +0 -6
  76. package/dist/chunk-HZG55H3B.js +0 -3
  77. package/dist/chunk-MJKISVPS.js +0 -7
  78. package/dist/chunk-NQD6H7SY.js +0 -7
  79. package/dist/chunk-PY6HS3EP.js +0 -10
  80. package/dist/chunk-UWEM5YEM.js +0 -161
  81. package/dist/chunk-XQON6ASI.js +0 -5
  82. package/dist/chunk-Y7PFSVRX.js +0 -3
  83. package/dist/framing-B6LP7MS2.js +0 -3
  84. package/dist/host-relink-VYEOE3NE.js +0 -10
  85. package/dist/hosted-NLYSTYYN.js +0 -3
  86. package/dist/hosts-47EW33NY.js +0 -3
  87. package/dist/isobmff-RHP3N5K2.js +0 -3
  88. package/dist/timeline-MZ6A3PQX.js +0 -3
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
3
- import{a as ti}from"./chunk-3DYCTUSQ.js";import"./chunk-IN6XVTUS.js";import"./chunk-3PVQ5QP4.js";import"./chunk-VFXMP7IF.js";import"./chunk-BBCQMZQN.js";import"./chunk-ND2YUUUH.js";import{a as Vr,b as Zs,d as ei}from"./chunk-Y7PFSVRX.js";import"./chunk-C2ESM27Z.js";import{b as Tu,c as $,d as Qs,e as k,f as ze,g as Se}from"./chunk-PSANHDZM.js";var _e={};Qs(_e,{__addDisposableResource:()=>Oi,__assign:()=>Ft,__asyncDelegator:()=>wi,__asyncGenerator:()=>vi,__asyncValues:()=>bi,__await:()=>Ge,__awaiter:()=>fi,__classPrivateFieldGet:()=>Ai,__classPrivateFieldIn:()=>ki,__classPrivateFieldSet:()=>Ri,__createBinding:()=>qt,__decorate:()=>oi,__disposeResources:()=>Ci,__esDecorate:()=>ui,__exportStar:()=>mi,__extends:()=>si,__generator:()=>pi,__importDefault:()=>Ti,__importStar:()=>Si,__makeTemplateObject:()=>Ei,__metadata:()=>hi,__param:()=>ai,__propKey:()=>ci,__read:()=>Gr,__rest:()=>ii,__rewriteRelativeImportExtension:()=>Pi,__runInitializers:()=>li,__setFunctionName:()=>di,__spread:()=>_i,__spreadArray:()=>yi,__spreadArrays:()=>gi,__values:()=>Bt,default:()=>Cu});function si(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Kr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function ii(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function oi(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function ai(t,e){return function(r,n){e(r,n,t)}}function ui(t,e,r,n,s,i){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var a=n.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?n.static?t:t.prototype:null,h=e||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),m,_=!1,f=r.length-1;f>=0;f--){var y={};for(var v in n)y[v]=v==="access"?{}:n[v];for(var v in n.access)y.access[v]=n.access[v];y.addInitializer=function(T){if(_)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(T||null))};var w=(0,r[f])(a==="accessor"?{get:h.get,set:h.set}:h[l],y);if(a==="accessor"){if(w===void 0)continue;if(w===null||typeof w!="object")throw new TypeError("Object expected");(m=o(w.get))&&(h.get=m),(m=o(w.set))&&(h.set=m),(m=o(w.init))&&s.unshift(m)}else(m=o(w))&&(a==="field"?s.unshift(m):h[l]=m)}c&&Object.defineProperty(c,n.name,h),_=!0}function li(t,e,r){for(var n=arguments.length>2,s=0;s<e.length;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function ci(t){return typeof t=="symbol"?t:"".concat(t)}function di(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function hi(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function fi(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(h){try{c(n.next(h))}catch(m){o(m)}}function l(h){try{c(n.throw(h))}catch(m){o(m)}}function c(h){h.done?i(h.value):s(h.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function pi(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(n=1,s&&(i=c[0]&2?s.return:c[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,c[1])).done)return i;switch(s=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,s=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){r.label=c[1];break}if(c[0]===6&&r.label<i[1]){r.label=i[1],i=c;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(c);break}i[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(h){c=[6,h],s=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function mi(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&qt(e,t,r)}function Bt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gr(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function _i(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gr(arguments[e]));return t}function gi(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function yi(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Ge(t){return this instanceof Ge?(this.v=t,this):new Ge(t)}function vi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(f){return function(y){return Promise.resolve(y).then(f,m)}}function a(f,y){n[f]&&(s[f]=function(v){return new Promise(function(w,T){i.push([f,v,w,T])>1||l(f,v)})},y&&(s[f]=y(s[f])))}function l(f,y){try{c(n[f](y))}catch(v){_(i[0][3],v)}}function c(f){f.value instanceof Ge?Promise.resolve(f.value.v).then(h,m):_(i[0][2],f)}function h(f){l("next",f)}function m(f){l("throw",f)}function _(f,y){f(y),i.shift(),i.length&&l(i[0][0],i[0][1])}}function wi(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:Ge(t[s](o)),done:!1}:i?i(o):o}:i}}function bi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Bt=="function"?Bt(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),s(a,l,o.done,o.value)})}}function s(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function Ei(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Si(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=zr(t),n=0;n<r.length;n++)r[n]!=="default"&&qt(e,t,r[n]);return ku(e,t),e}function Ti(t){return t&&t.__esModule?t:{default:t}}function Ai(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function Ri(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function ki(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function Oi(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(s=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function Ci(t){function e(i){t.error=t.hasError?new Ou(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;function s(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else n|=1}catch(o){e(o)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function Pi(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,i,o){return n?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):t}var Kr,Ft,qt,ku,zr,Ou,Cu,ge=Tu(()=>{Kr=function(t,e){return Kr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])},Kr(t,e)};Ft=function(){return Ft=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ft.apply(this,arguments)};qt=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});ku=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},zr=function(t){return zr=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},zr(t)};Ou=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Cu={__extends:si,__assign:Ft,__rest:ii,__decorate:oi,__param:ai,__esDecorate:ui,__runInitializers:li,__propKey:ci,__setFunctionName:di,__metadata:hi,__awaiter:fi,__generator:pi,__createBinding:qt,__exportStar:mi,__values:Bt,__read:Gr,__spread:_i,__spreadArrays:gi,__spreadArray:yi,__await:Ge,__asyncGenerator:vi,__asyncDelegator:wi,__asyncValues:bi,__makeTemplateObject:Ei,__importStar:Si,__importDefault:Ti,__classPrivateFieldGet:Ai,__classPrivateFieldSet:Ri,__classPrivateFieldIn:ki,__addDisposableResource:Oi,__disposeResources:Ci,__rewriteRelativeImportExtension:Pi}});var Ii=$(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.resolveFetch=void 0;var Pu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Mt.resolveFetch=Pu});var Qr=$(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FunctionRegion=ye.FunctionsHttpError=ye.FunctionsRelayError=ye.FunctionsFetchError=ye.FunctionsError=void 0;var Je=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}};ye.FunctionsError=Je;var Jr=class extends Je{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};ye.FunctionsFetchError=Jr;var Yr=class extends Je{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};ye.FunctionsRelayError=Yr;var Xr=class extends Je{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};ye.FunctionsHttpError=Xr;var xi;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(xi||(ye.FunctionRegion=xi={}))});var Ni=$(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.FunctionsClient=void 0;var Iu=(ge(),Se(_e)),xu=Ii(),Ye=Qr(),Zr=class{constructor(e,{headers:r={},customFetch:n,region:s=Ye.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=s,this.fetch=(0,xu.resolveFetch)(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Iu.__awaiter(this,arguments,void 0,function*(r,n={}){var s;let i,o;try{let{headers:a,method:l,body:c,signal:h,timeout:m}=n,_={},{region:f}=n;f||(f=this.region);let y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(_["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let v;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(_["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(_["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(_["Content-Type"]="application/json",v=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?v=JSON.stringify(c):v=c;let w=h;m&&(o=new AbortController,i=setTimeout(()=>o.abort(),m),h?(w=o.signal,h.addEventListener("abort",()=>o.abort())):w=o.signal);let T=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},_),this.headers),a),body:v,signal:w}).catch(Z=>{throw new Ye.FunctionsFetchError(Z)}),O=T.headers.get("x-relay-error");if(O&&O==="true")throw new Ye.FunctionsRelayError(T);if(!T.ok)throw new Ye.FunctionsHttpError(T);let E=((s=T.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),x;return E==="application/json"?x=yield T.json():E==="application/octet-stream"||E==="application/pdf"?x=yield T.blob():E==="text/event-stream"?x=T:E==="multipart/form-data"?x=yield T.formData():x=yield T.text(),{data:x,error:null,response:T}}catch(a){return{data:null,error:a,response:a instanceof Ye.FunctionsHttpError||a instanceof Ye.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Wt.FunctionsClient=Zr});var ji=$(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.FunctionRegion=fe.FunctionsRelayError=fe.FunctionsHttpError=fe.FunctionsFetchError=fe.FunctionsError=fe.FunctionsClient=void 0;var Nu=Ni();Object.defineProperty(fe,"FunctionsClient",{enumerable:!0,get:function(){return Nu.FunctionsClient}});var lt=Qr();Object.defineProperty(fe,"FunctionsError",{enumerable:!0,get:function(){return lt.FunctionsError}});Object.defineProperty(fe,"FunctionsFetchError",{enumerable:!0,get:function(){return lt.FunctionsFetchError}});Object.defineProperty(fe,"FunctionsHttpError",{enumerable:!0,get:function(){return lt.FunctionsHttpError}});Object.defineProperty(fe,"FunctionsRelayError",{enumerable:!0,get:function(){return lt.FunctionsRelayError}});Object.defineProperty(fe,"FunctionRegion",{enumerable:!0,get:function(){return lt.FunctionRegion}})});var tn=$(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.WebSocketFactory=void 0;var Ht=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.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 r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
3
+ import{a as ti}from"./chunk-M56WEBZY.js";import"./chunk-IN6XVTUS.js";import"./chunk-3PVQ5QP4.js";import"./chunk-VFXMP7IF.js";import"./chunk-BBCQMZQN.js";import"./chunk-CXOK4SF6.js";import{a as Vr,b as Zs,d as ei}from"./chunk-BUOYYO22.js";import"./chunk-C2ESM27Z.js";import{b as Au,c as $,d as Qs,e as k,f as ze,g as Se}from"./chunk-PSANHDZM.js";var _e={};Qs(_e,{__addDisposableResource:()=>Oi,__assign:()=>Ft,__asyncDelegator:()=>wi,__asyncGenerator:()=>vi,__asyncValues:()=>bi,__await:()=>Ge,__awaiter:()=>fi,__classPrivateFieldGet:()=>Ai,__classPrivateFieldIn:()=>ki,__classPrivateFieldSet:()=>Ri,__createBinding:()=>qt,__decorate:()=>oi,__disposeResources:()=>Ci,__esDecorate:()=>ui,__exportStar:()=>mi,__extends:()=>si,__generator:()=>pi,__importDefault:()=>Ti,__importStar:()=>Si,__makeTemplateObject:()=>Ei,__metadata:()=>hi,__param:()=>ai,__propKey:()=>ci,__read:()=>Gr,__rest:()=>ii,__rewriteRelativeImportExtension:()=>Pi,__runInitializers:()=>li,__setFunctionName:()=>di,__spread:()=>_i,__spreadArray:()=>yi,__spreadArrays:()=>gi,__values:()=>Bt,default:()=>Pu});function si(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Kr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function ii(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function oi(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function ai(t,e){return function(r,n){e(r,n,t)}}function ui(t,e,r,n,s,i){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var a=n.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?n.static?t:t.prototype:null,h=e||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),m,_=!1,f=r.length-1;f>=0;f--){var y={};for(var v in n)y[v]=v==="access"?{}:n[v];for(var v in n.access)y.access[v]=n.access[v];y.addInitializer=function(T){if(_)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(T||null))};var w=(0,r[f])(a==="accessor"?{get:h.get,set:h.set}:h[l],y);if(a==="accessor"){if(w===void 0)continue;if(w===null||typeof w!="object")throw new TypeError("Object expected");(m=o(w.get))&&(h.get=m),(m=o(w.set))&&(h.set=m),(m=o(w.init))&&s.unshift(m)}else(m=o(w))&&(a==="field"?s.unshift(m):h[l]=m)}c&&Object.defineProperty(c,n.name,h),_=!0}function li(t,e,r){for(var n=arguments.length>2,s=0;s<e.length;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function ci(t){return typeof t=="symbol"?t:"".concat(t)}function di(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function hi(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function fi(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(h){try{c(n.next(h))}catch(m){o(m)}}function l(h){try{c(n.throw(h))}catch(m){o(m)}}function c(h){h.done?i(h.value):s(h.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function pi(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(n=1,s&&(i=c[0]&2?s.return:c[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,c[1])).done)return i;switch(s=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,s=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){r.label=c[1];break}if(c[0]===6&&r.label<i[1]){r.label=i[1],i=c;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(c);break}i[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(h){c=[6,h],s=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function mi(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&qt(e,t,r)}function Bt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gr(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function _i(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gr(arguments[e]));return t}function gi(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function yi(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Ge(t){return this instanceof Ge?(this.v=t,this):new Ge(t)}function vi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(f){return function(y){return Promise.resolve(y).then(f,m)}}function a(f,y){n[f]&&(s[f]=function(v){return new Promise(function(w,T){i.push([f,v,w,T])>1||l(f,v)})},y&&(s[f]=y(s[f])))}function l(f,y){try{c(n[f](y))}catch(v){_(i[0][3],v)}}function c(f){f.value instanceof Ge?Promise.resolve(f.value.v).then(h,m):_(i[0][2],f)}function h(f){l("next",f)}function m(f){l("throw",f)}function _(f,y){f(y),i.shift(),i.length&&l(i[0][0],i[0][1])}}function wi(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:Ge(t[s](o)),done:!1}:i?i(o):o}:i}}function bi(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Bt=="function"?Bt(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),s(a,l,o.done,o.value)})}}function s(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function Ei(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Si(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=zr(t),n=0;n<r.length;n++)r[n]!=="default"&&qt(e,t,r[n]);return Ou(e,t),e}function Ti(t){return t&&t.__esModule?t:{default:t}}function Ai(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function Ri(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function ki(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function Oi(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(s=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function Ci(t){function e(i){t.error=t.hasError?new Cu(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;function s(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else n|=1}catch(o){e(o)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function Pi(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,i,o){return n?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):t}var Kr,Ft,qt,Ou,zr,Cu,Pu,ge=Au(()=>{Kr=function(t,e){return Kr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])},Kr(t,e)};Ft=function(){return Ft=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ft.apply(this,arguments)};qt=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});Ou=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},zr=function(t){return zr=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},zr(t)};Cu=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Pu={__extends:si,__assign:Ft,__rest:ii,__decorate:oi,__param:ai,__esDecorate:ui,__runInitializers:li,__propKey:ci,__setFunctionName:di,__metadata:hi,__awaiter:fi,__generator:pi,__createBinding:qt,__exportStar:mi,__values:Bt,__read:Gr,__spread:_i,__spreadArrays:gi,__spreadArray:yi,__await:Ge,__asyncGenerator:vi,__asyncDelegator:wi,__asyncValues:bi,__makeTemplateObject:Ei,__importStar:Si,__importDefault:Ti,__classPrivateFieldGet:Ai,__classPrivateFieldSet:Ri,__classPrivateFieldIn:ki,__addDisposableResource:Oi,__disposeResources:Ci,__rewriteRelativeImportExtension:Pi}});var Ii=$(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.resolveFetch=void 0;var Iu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Mt.resolveFetch=Iu});var Qr=$(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FunctionRegion=ye.FunctionsHttpError=ye.FunctionsRelayError=ye.FunctionsFetchError=ye.FunctionsError=void 0;var Je=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}};ye.FunctionsError=Je;var Jr=class extends Je{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};ye.FunctionsFetchError=Jr;var Yr=class extends Je{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};ye.FunctionsRelayError=Yr;var Xr=class extends Je{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};ye.FunctionsHttpError=Xr;var xi;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(xi||(ye.FunctionRegion=xi={}))});var Ni=$(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.FunctionsClient=void 0;var xu=(ge(),Se(_e)),Nu=Ii(),Ye=Qr(),Zr=class{constructor(e,{headers:r={},customFetch:n,region:s=Ye.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=s,this.fetch=(0,Nu.resolveFetch)(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return xu.__awaiter(this,arguments,void 0,function*(r,n={}){var s;let i,o;try{let{headers:a,method:l,body:c,signal:h,timeout:m}=n,_={},{region:f}=n;f||(f=this.region);let y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(_["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let v;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(_["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(_["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(_["Content-Type"]="application/json",v=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?v=JSON.stringify(c):v=c;let w=h;m&&(o=new AbortController,i=setTimeout(()=>o.abort(),m),h?(w=o.signal,h.addEventListener("abort",()=>o.abort())):w=o.signal);let T=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},_),this.headers),a),body:v,signal:w}).catch(Z=>{throw new Ye.FunctionsFetchError(Z)}),O=T.headers.get("x-relay-error");if(O&&O==="true")throw new Ye.FunctionsRelayError(T);if(!T.ok)throw new Ye.FunctionsHttpError(T);let E=((s=T.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),x;return E==="application/json"?x=yield T.json():E==="application/octet-stream"||E==="application/pdf"?x=yield T.blob():E==="text/event-stream"?x=T:E==="multipart/form-data"?x=yield T.formData():x=yield T.text(),{data:x,error:null,response:T}}catch(a){return{data:null,error:a,response:a instanceof Ye.FunctionsHttpError||a instanceof Ye.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Wt.FunctionsClient=Zr});var ji=$(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.FunctionRegion=fe.FunctionsRelayError=fe.FunctionsHttpError=fe.FunctionsFetchError=fe.FunctionsError=fe.FunctionsClient=void 0;var ju=Ni();Object.defineProperty(fe,"FunctionsClient",{enumerable:!0,get:function(){return ju.FunctionsClient}});var lt=Qr();Object.defineProperty(fe,"FunctionsError",{enumerable:!0,get:function(){return lt.FunctionsError}});Object.defineProperty(fe,"FunctionsFetchError",{enumerable:!0,get:function(){return lt.FunctionsFetchError}});Object.defineProperty(fe,"FunctionsHttpError",{enumerable:!0,get:function(){return lt.FunctionsHttpError}});Object.defineProperty(fe,"FunctionsRelayError",{enumerable:!0,get:function(){return lt.FunctionsRelayError}});Object.defineProperty(fe,"FunctionRegion",{enumerable:!0,get:function(){return lt.FunctionRegion}})});var tn=$(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.WebSocketFactory=void 0;var Ht=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.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 r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
4
4
  import ws from "ws"
5
5
  new RealtimeClient(url, { transport: ws })`}}}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 e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
6
6
 
7
- Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){let n=this.getWebSocketConstructor();return new n(e,r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}};dt.WebSocketFactory=Ht;dt.default=Ht});var Fi=$(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.version=void 0;Kt.version="2.97.0"});var zt=$(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.CONNECTION_STATE=H.TRANSPORTS=H.CHANNEL_EVENTS=H.CHANNEL_STATES=H.SOCKET_STATES=H.MAX_PUSH_BUFFER_SIZE=H.WS_CLOSE_NORMAL=H.DEFAULT_TIMEOUT=H.VERSION=H.DEFAULT_VSN=H.VSN_2_0_0=H.VSN_1_0_0=H.DEFAULT_VERSION=void 0;var Hi=Fi();H.DEFAULT_VERSION=`realtime-js/${Hi.version}`;H.VSN_1_0_0="1.0.0";H.VSN_2_0_0="2.0.0";H.DEFAULT_VSN=H.VSN_2_0_0;H.VERSION=Hi.version;H.DEFAULT_TIMEOUT=1e4;H.WS_CLOSE_NORMAL=1e3;H.MAX_PUSH_BUFFER_SIZE=100;var Bi;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Bi||(H.SOCKET_STATES=Bi={}));var qi;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(qi||(H.CHANNEL_STATES=qi={}));var Mi;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Mi||(H.CHANNEL_EVENTS=Mi={}));var Wi;(function(t){t.websocket="websocket"})(Wi||(H.TRANSPORTS=Wi={}));var Vi;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Vi||(H.CONNECTION_STATE=Vi={}))});var Ki=$(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});var rn=class{constructor(e){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=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var s,i;let o=e.topic,a=(s=e.ref)!==null&&s!==void 0?s:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},m=Object.keys(h).length===0?"":JSON.stringify(h);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(m.length>255)throw new Error(`metadata length ${m.length} exceeds maximum of 255`);let _=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+m.length,f=new ArrayBuffer(this.HEADER_LENGTH+_),y=new DataView(f),v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,l.length),y.setUint8(v++,a.length),y.setUint8(v++,o.length),y.setUint8(v++,c.length),y.setUint8(v++,m.length),y.setUint8(v++,r),Array.from(l,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(a,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(o,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(c,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(m,T=>y.setUint8(v++,T.charCodeAt(0)));var w=new Uint8Array(f.byteLength+n.byteLength);return w.set(new Uint8Array(f),0),w.set(new Uint8Array(n),f.byteLength),w.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,a,l]=n;return r({join_ref:s,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,s)}}_decodeUserBroadcast(e,r,n){let s=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+s));l=l+s;let h=n.decode(e.slice(l,l+i));l=l+i;let m=n.decode(e.slice(l,l+o));l=l+o;let _=e.slice(l,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(_)):_,y={type:this.BROADCAST_EVENT,event:h,payload:f};return o>0&&(y.meta=JSON.parse(m)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};nn.default=rn});var an=$(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});var sn=class{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};on.default=sn});var Gt=$(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.httpEndpointURL=V.toTimestampString=V.toArray=V.toJson=V.toNumber=V.toBoolean=V.convertCell=V.convertColumn=V.convertChangeData=V.PostgresTypes=void 0;var G;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(G||(V.PostgresTypes=G={}));var Bu=(t,e,r={})=>{var n;let s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=(0,V.convertColumn)(o,t,e,s),i),{}):{}};V.convertChangeData=Bu;var qu=(t,e,r,n)=>{let s=e.find(a=>a.name===t),i=s?.type,o=r[t];return i&&!n.includes(i)?(0,V.convertCell)(i,o):un(o)};V.convertColumn=qu;var Mu=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return(0,V.toArray)(e,r)}switch(t){case G.bool:return(0,V.toBoolean)(e);case G.float4:case G.float8:case G.int2:case G.int4:case G.int8:case G.numeric:case G.oid:return(0,V.toNumber)(e);case G.json:case G.jsonb:return(0,V.toJson)(e);case G.timestamp:return(0,V.toTimestampString)(e);case G.abstime:case G.date:case G.daterange:case G.int4range:case G.int8range:case G.money:case G.reltime:case G.text:case G.time:case G.timestamptz:case G.timetz:case G.tsrange:case G.tstzrange:return un(e);default:return un(e)}};V.convertCell=Mu;var un=t=>t,Wu=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}};V.toBoolean=Wu;var Vu=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t};V.toNumber=Vu;var Hu=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t};V.toJson=Hu;var Ku=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>(0,V.convertCell)(e,a))}return t};V.toArray=Ku;var zu=t=>typeof t=="string"?t.replace(" ","T"):t;V.toTimestampString=zu;var Gu=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};V.httpEndpointURL=Gu});var zi=$(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});var Ju=zt(),ln=class{constructor(e,r,n={},s=Ju.DEFAULT_TIMEOUT){this.channel=e,this.event=r,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};cn.default=ln});var hn=$(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;var Gi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Gi||(ht.REALTIME_PRESENCE_LISTEN_EVENTS=Gi={}));var dn=class t{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=t.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=t.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=t.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,s){let i=this.cloneDeep(e),o=this.transformState(r),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{let m=i[c];if(m){let _=h.map(w=>w.presence_ref),f=m.map(w=>w.presence_ref),y=h.filter(w=>f.indexOf(w.presence_ref)<0),v=m.filter(w=>_.indexOf(w.presence_ref)<0);y.length>0&&(a[c]=y),v.length>0&&(l[c]=v)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},n,s)}static syncDiff(e,r,n,s){let{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var c;let h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){let m=e[a].map(f=>f.presence_ref),_=h.filter(f=>m.indexOf(f.presence_ref)<0);e[a].unshift(..._)}n(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let h=l.map(m=>m.presence_ref);c=c.filter(m=>h.indexOf(m.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let s=e[n];return"metas"in s?r[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=s,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};ht.default=dn});var mn=$(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.REALTIME_CHANNEL_STATES=Te.REALTIME_SUBSCRIBE_STATES=Te.REALTIME_LISTEN_TYPES=Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=void 0;var Jt=(ge(),Se(_e)),J=zt(),fn=Jt.__importDefault(zi()),Yu=Jt.__importDefault(an()),Xu=Jt.__importDefault(hn()),Ji=Jt.__importStar(Gt()),Qu=Gt(),Yi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Yi||(Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=Yi={}));var ft;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ft||(Te.REALTIME_LISTEN_TYPES=ft={}));var xe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(xe||(Te.REALTIME_SUBSCRIBE_STATES=xe={}));Te.REALTIME_CHANNEL_STATES=J.CHANNEL_STATES;var pn=class t{constructor(e,r={config:{}},n){var s,i;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=J.CHANNEL_STATES.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new fn.default(this,J.CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new Yu.default(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=J.CHANNEL_STATES.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=J.CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(J.CHANNEL_EVENTS.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new Xu.default(this),this.broadcastEndpointURL=(0,Qu.httpEndpointURL)(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==J.CHANNEL_STATES.closed){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[ft.PRESENCE]&&this.bindings[ft.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},_={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(xe.CHANNEL_ERROR,f)),this._onClose(()=>e?.(xe.CLOSED)),this.updateJoinPayload(Object.assign({config:_},m)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(xe.SUBSCRIBED);return}else{let v=this.bindings.postgres_changes,w=(y=v?.length)!==null&&y!==void 0?y:0,T=[];for(let O=0;O<w;O++){let E=v[O],{filter:{event:x,schema:Z,table:W,filter:re}}=E,ke=f&&f[O];if(ke&&ke.event===x&&t.isFilterValueEqual(ke.schema,Z)&&t.isFilterValueEqual(ke.table,W)&&t.isFilterValueEqual(ke.filter,re))T.push(Object.assign(Object.assign({},E),{id:ke.id}));else{this.unsubscribe(),this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=T,e&&e(xe.SUBSCRIBED);return}}).receive("error",f=>{this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(xe.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this.state===J.CHANNEL_STATES.joined&&e===ft.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,n)}async httpSend(e,r,n={}){var s;if(r==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;let c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=J.CHANNEL_STATES.leaving;let r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(J.CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new fn.default(this,J.CHANNEL_EVENTS.leave,{},e),n.receive("ok",()=>{r(),s("ok")}).receive("timeout",()=>{r(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=J.CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout(e,r,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new fn.default(this,e,r,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>J.MAX_PUSH_BUFFER_SIZE){let r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var s,i;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=J.CHANNEL_EVENTS;if(n&&[a,l,c,h].indexOf(o)>=0&&n!==this._joinRef())return;let _=this._onMessage(o,r,n);if(r&&!_)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var y,v,w;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((w=(v=f.filter)===null||v===void 0?void 0:v.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(f=>f.callback(_,n)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var y,v,w,T,O,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,Z=(y=f.filter)===null||y===void 0?void 0:y.event;return x&&((v=r.ids)===null||v===void 0?void 0:v.includes(x))&&(Z==="*"||Z?.toLocaleLowerCase()===((w=r.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let x=(O=(T=f?.filter)===null||T===void 0?void 0:T.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return x==="*"||x===((E=r?.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof _=="object"&&"ids"in _){let y=_.data,{schema:v,table:w,commit_timestamp:T,type:O,errors:E}=y;_=Object.assign(Object.assign({},{schema:v,table:w,commit_timestamp:T,eventType:O,new:{},old:{},errors:E}),this._getPayloadRecords(y))}f.callback(_,n)})}_isClosed(){return this.state===J.CHANNEL_STATES.closed}_isJoined(){return this.state===J.CHANNEL_STATES.joined}_isJoining(){return this.state===J.CHANNEL_STATES.joining}_isLeaving(){return this.state===J.CHANNEL_STATES.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){let s=e.toLocaleLowerCase(),i={type:s,filter:r,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,r){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&t.isEqual(s.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(let n in e)if(e[n]!==r[n])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(J.CHANNEL_EVENTS.close,{},e)}_onError(e){this._on(J.CHANNEL_EVENTS.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=J.CHANNEL_STATES.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ji.convertChangeData(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ji.convertChangeData(e.columns,e.old_record)),r}};Te.default=pn});var Xi=$(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});var Xt=(ge(),Se(_e)),Zu=Xt.__importDefault(tn()),ne=zt(),el=Xt.__importDefault(Ki()),tl=Xt.__importDefault(an()),rl=Gt(),nl=Xt.__importDefault(mn()),_n=()=>{},Yt={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},sl=[1e3,2e3,5e3,1e4],il=1e4,ol=`
7
+ Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){let n=this.getWebSocketConstructor();return new n(e,r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}};dt.WebSocketFactory=Ht;dt.default=Ht});var Fi=$(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.version=void 0;Kt.version="2.97.0"});var zt=$(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.CONNECTION_STATE=H.TRANSPORTS=H.CHANNEL_EVENTS=H.CHANNEL_STATES=H.SOCKET_STATES=H.MAX_PUSH_BUFFER_SIZE=H.WS_CLOSE_NORMAL=H.DEFAULT_TIMEOUT=H.VERSION=H.DEFAULT_VSN=H.VSN_2_0_0=H.VSN_1_0_0=H.DEFAULT_VERSION=void 0;var Hi=Fi();H.DEFAULT_VERSION=`realtime-js/${Hi.version}`;H.VSN_1_0_0="1.0.0";H.VSN_2_0_0="2.0.0";H.DEFAULT_VSN=H.VSN_2_0_0;H.VERSION=Hi.version;H.DEFAULT_TIMEOUT=1e4;H.WS_CLOSE_NORMAL=1e3;H.MAX_PUSH_BUFFER_SIZE=100;var Bi;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(Bi||(H.SOCKET_STATES=Bi={}));var qi;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(qi||(H.CHANNEL_STATES=qi={}));var Mi;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Mi||(H.CHANNEL_EVENTS=Mi={}));var Wi;(function(t){t.websocket="websocket"})(Wi||(H.TRANSPORTS=Wi={}));var Vi;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Vi||(H.CONNECTION_STATE=Vi={}))});var Ki=$(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});var rn=class{constructor(e){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=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var s,i;let o=e.topic,a=(s=e.ref)!==null&&s!==void 0?s:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},m=Object.keys(h).length===0?"":JSON.stringify(h);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(m.length>255)throw new Error(`metadata length ${m.length} exceeds maximum of 255`);let _=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+m.length,f=new ArrayBuffer(this.HEADER_LENGTH+_),y=new DataView(f),v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,l.length),y.setUint8(v++,a.length),y.setUint8(v++,o.length),y.setUint8(v++,c.length),y.setUint8(v++,m.length),y.setUint8(v++,r),Array.from(l,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(a,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(o,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(c,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(m,T=>y.setUint8(v++,T.charCodeAt(0)));var w=new Uint8Array(f.byteLength+n.byteLength);return w.set(new Uint8Array(f),0),w.set(new Uint8Array(n),f.byteLength),w.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,a,l]=n;return r({join_ref:s,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,s)}}_decodeUserBroadcast(e,r,n){let s=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+s));l=l+s;let h=n.decode(e.slice(l,l+i));l=l+i;let m=n.decode(e.slice(l,l+o));l=l+o;let _=e.slice(l,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(_)):_,y={type:this.BROADCAST_EVENT,event:h,payload:f};return o>0&&(y.meta=JSON.parse(m)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};nn.default=rn});var an=$(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});var sn=class{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}};on.default=sn});var Gt=$(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.httpEndpointURL=V.toTimestampString=V.toArray=V.toJson=V.toNumber=V.toBoolean=V.convertCell=V.convertColumn=V.convertChangeData=V.PostgresTypes=void 0;var G;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(G||(V.PostgresTypes=G={}));var qu=(t,e,r={})=>{var n;let s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=(0,V.convertColumn)(o,t,e,s),i),{}):{}};V.convertChangeData=qu;var Mu=(t,e,r,n)=>{let s=e.find(a=>a.name===t),i=s?.type,o=r[t];return i&&!n.includes(i)?(0,V.convertCell)(i,o):un(o)};V.convertColumn=Mu;var Wu=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return(0,V.toArray)(e,r)}switch(t){case G.bool:return(0,V.toBoolean)(e);case G.float4:case G.float8:case G.int2:case G.int4:case G.int8:case G.numeric:case G.oid:return(0,V.toNumber)(e);case G.json:case G.jsonb:return(0,V.toJson)(e);case G.timestamp:return(0,V.toTimestampString)(e);case G.abstime:case G.date:case G.daterange:case G.int4range:case G.int8range:case G.money:case G.reltime:case G.text:case G.time:case G.timestamptz:case G.timetz:case G.tsrange:case G.tstzrange:return un(e);default:return un(e)}};V.convertCell=Wu;var un=t=>t,Vu=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}};V.toBoolean=Vu;var Hu=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t};V.toNumber=Hu;var Ku=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t};V.toJson=Ku;var zu=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>(0,V.convertCell)(e,a))}return t};V.toArray=zu;var Gu=t=>typeof t=="string"?t.replace(" ","T"):t;V.toTimestampString=Gu;var Ju=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};V.httpEndpointURL=Ju});var zi=$(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});var Yu=zt(),ln=class{constructor(e,r,n={},s=Yu.DEFAULT_TIMEOUT){this.channel=e,this.event=r,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,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()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};cn.default=ln});var hn=$(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;var Gi;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Gi||(ht.REALTIME_PRESENCE_LISTEN_EVENTS=Gi={}));var dn=class t{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=t.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=t.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=t.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,s){let i=this.cloneDeep(e),o=this.transformState(r),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{let m=i[c];if(m){let _=h.map(w=>w.presence_ref),f=m.map(w=>w.presence_ref),y=h.filter(w=>f.indexOf(w.presence_ref)<0),v=m.filter(w=>_.indexOf(w.presence_ref)<0);y.length>0&&(a[c]=y),v.length>0&&(l[c]=v)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},n,s)}static syncDiff(e,r,n,s){let{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var c;let h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){let m=e[a].map(f=>f.presence_ref),_=h.filter(f=>m.indexOf(f.presence_ref)<0);e[a].unshift(..._)}n(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let h=l.map(m=>m.presence_ref);c=c.filter(m=>h.indexOf(m.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let s=e[n];return"metas"in s?r[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=s,r},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}};ht.default=dn});var mn=$(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.REALTIME_CHANNEL_STATES=Te.REALTIME_SUBSCRIBE_STATES=Te.REALTIME_LISTEN_TYPES=Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=void 0;var Jt=(ge(),Se(_e)),J=zt(),fn=Jt.__importDefault(zi()),Xu=Jt.__importDefault(an()),Qu=Jt.__importDefault(hn()),Ji=Jt.__importStar(Gt()),Zu=Gt(),Yi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Yi||(Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=Yi={}));var ft;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ft||(Te.REALTIME_LISTEN_TYPES=ft={}));var xe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(xe||(Te.REALTIME_SUBSCRIBE_STATES=xe={}));Te.REALTIME_CHANNEL_STATES=J.CHANNEL_STATES;var pn=class t{constructor(e,r={config:{}},n){var s,i;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=J.CHANNEL_STATES.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.timeout=this.socket.timeout,this.joinPush=new fn.default(this,J.CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new Xu.default(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=J.CHANNEL_STATES.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=J.CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(J.CHANNEL_EVENTS.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new Qu.default(this),this.broadcastEndpointURL=(0,Zu.httpEndpointURL)(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==J.CHANNEL_STATES.closed){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[ft.PRESENCE]&&this.bindings[ft.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},_={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(xe.CHANNEL_ERROR,f)),this._onClose(()=>e?.(xe.CLOSED)),this.updateJoinPayload(Object.assign({config:_},m)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(xe.SUBSCRIBED);return}else{let v=this.bindings.postgres_changes,w=(y=v?.length)!==null&&y!==void 0?y:0,T=[];for(let O=0;O<w;O++){let E=v[O],{filter:{event:x,schema:Z,table:W,filter:re}}=E,ke=f&&f[O];if(ke&&ke.event===x&&t.isFilterValueEqual(ke.schema,Z)&&t.isFilterValueEqual(ke.table,W)&&t.isFilterValueEqual(ke.filter,re))T.push(Object.assign(Object.assign({},E),{id:ke.id}));else{this.unsubscribe(),this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=T,e&&e(xe.SUBSCRIBED);return}}).receive("error",f=>{this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(xe.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this.state===J.CHANNEL_STATES.joined&&e===ft.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,n)}async httpSend(e,r,n={}){var s;if(r==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;let c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=J.CHANNEL_STATES.leaving;let r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(J.CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new fn.default(this,J.CHANNEL_EVENTS.leave,{},e),n.receive("ok",()=>{r(),s("ok")}).receive("timeout",()=>{r(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=J.CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout(e,r,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new fn.default(this,e,r,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>J.MAX_PUSH_BUFFER_SIZE){let r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var s,i;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=J.CHANNEL_EVENTS;if(n&&[a,l,c,h].indexOf(o)>=0&&n!==this._joinRef())return;let _=this._onMessage(o,r,n);if(r&&!_)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var y,v,w;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((w=(v=f.filter)===null||v===void 0?void 0:v.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(f=>f.callback(_,n)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var y,v,w,T,O,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,Z=(y=f.filter)===null||y===void 0?void 0:y.event;return x&&((v=r.ids)===null||v===void 0?void 0:v.includes(x))&&(Z==="*"||Z?.toLocaleLowerCase()===((w=r.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let x=(O=(T=f?.filter)===null||T===void 0?void 0:T.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return x==="*"||x===((E=r?.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof _=="object"&&"ids"in _){let y=_.data,{schema:v,table:w,commit_timestamp:T,type:O,errors:E}=y;_=Object.assign(Object.assign({},{schema:v,table:w,commit_timestamp:T,eventType:O,new:{},old:{},errors:E}),this._getPayloadRecords(y))}f.callback(_,n)})}_isClosed(){return this.state===J.CHANNEL_STATES.closed}_isJoined(){return this.state===J.CHANNEL_STATES.joined}_isJoining(){return this.state===J.CHANNEL_STATES.joining}_isLeaving(){return this.state===J.CHANNEL_STATES.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){let s=e.toLocaleLowerCase(),i={type:s,filter:r,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,r){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&t.isEqual(s.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(let n in e)if(e[n]!==r[n])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(J.CHANNEL_EVENTS.close,{},e)}_onError(e){this._on(J.CHANNEL_EVENTS.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=J.CHANNEL_STATES.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ji.convertChangeData(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ji.convertChangeData(e.columns,e.old_record)),r}};Te.default=pn});var Xi=$(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});var Xt=(ge(),Se(_e)),el=Xt.__importDefault(tn()),ne=zt(),tl=Xt.__importDefault(Ki()),rl=Xt.__importDefault(an()),nl=Gt(),sl=Xt.__importDefault(mn()),_n=()=>{},Yt={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},il=[1e3,2e3,5e3,1e4],ol=1e4,al=`
8
8
  addEventListener("message", (e) => {
9
9
  if (e.data.event === "start") {
10
10
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
11
11
  }
12
- });`,gn=class{constructor(e,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ne.DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=Yt.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=_n,this.ref=0,this.reconnectTimer=null,this.vsn=ne.DEFAULT_VSN,this.logger=_n,this.conn=null,this.sendBuffer=[],this.serializer=new el.default,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${ne.TRANSPORTS.websocket}`,this.httpEndpoint=(0,rl.httpEndpointURL)(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Zu.default.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let r=e.message;throw r.includes("Node.js")?new Error(`${r}
12
+ });`,gn=class{constructor(e,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ne.DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=Yt.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=_n,this.ref=0,this.reconnectTimer=null,this.vsn=ne.DEFAULT_VSN,this.logger=_n,this.conn=null,this.sendBuffer=[],this.serializer=new tl.default,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${ne.TRANSPORTS.websocket}`,this.httpEndpoint=(0,nl.httpEndpointURL)(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=el.default.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let r=e.message;throw r.includes("Node.js")?new Error(`${r}
13
13
 
14
14
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
15
15
 
@@ -22,8 +22,8 @@ Option 2: Install and provide the "ws" package:
22
22
  const client = new RealtimeClient(url, {
23
23
  ...options,
24
24
  transport: ws
25
- })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ne.SOCKET_STATES.connecting:return ne.CONNECTION_STATE.Connecting;case ne.SOCKET_STATES.open:return ne.CONNECTION_STATE.Open;case ne.SOCKET_STATES.closing:return ne.CONNECTION_STATE.Closing;default:return ne.CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===ne.CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new nl.default(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){let{topic:r,event:n,payload:s,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${r} ${n} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(ne.WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Yt.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){let c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",c)}catch(h){this.log("error","error in heartbeat callback",h)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=r,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${n} ${s} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(n)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ne.SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ne.SOCKET_STATES.open||this.conn.readyState===ne.SOCKET_STATES.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&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)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(ne.CHANNEL_EVENTS.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(r);return`${e}${n}${s}`}_workerObjectUrl(e){let r;if(e)r=e;else{let n=new Blob([ol],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(s=>{let i={access_token:r,version:ne.DEFAULT_VERSION};r&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ne.CHANNEL_EVENTS.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(r)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new tl.default(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Yt.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,n,s,i,o,a,l,c,h,m,_,f;switch(this.transport=(r=e?.transport)!==null&&r!==void 0?r:null,this.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ne.DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Yt.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:_n,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:ne.DEFAULT_VSN,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(y=>sl[y-1]||il),this.vsn){case ne.VSN_1_0_0:this.encode=(h=e?.encode)!==null&&h!==void 0?h:((y,v)=>v(JSON.stringify(y))),this.decode=(m=e?.decode)!==null&&m!==void 0?m:((y,v)=>v(JSON.parse(y)));break;case ne.VSN_2_0_0:this.encode=(_=e?.encode)!==null&&_!==void 0?_:this.serializer.encode.bind(this.serializer),this.decode=(f=e?.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}};yn.default=gn});var vn=$(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.WebSocketFactory=oe.REALTIME_CHANNEL_STATES=oe.REALTIME_SUBSCRIBE_STATES=oe.REALTIME_PRESENCE_LISTEN_EVENTS=oe.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=oe.REALTIME_LISTEN_TYPES=oe.RealtimeClient=oe.RealtimeChannel=oe.RealtimePresence=void 0;var Qt=(ge(),Se(_e)),al=Qt.__importDefault(Xi());oe.RealtimeClient=al.default;var pt=Qt.__importStar(mn());oe.RealtimeChannel=pt.default;Object.defineProperty(oe,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return pt.REALTIME_LISTEN_TYPES}});Object.defineProperty(oe,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return pt.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}});Object.defineProperty(oe,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return pt.REALTIME_SUBSCRIBE_STATES}});Object.defineProperty(oe,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return pt.REALTIME_CHANNEL_STATES}});var Qi=Qt.__importStar(hn());oe.RealtimePresence=Qi.default;Object.defineProperty(oe,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return Qi.REALTIME_PRESENCE_LISTEN_EVENTS}});var ul=Qt.__importDefault(tn());oe.WebSocketFactory=ul.default});var Sn=$(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.version=void 0;nr.version="2.97.0"});var sr=$(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.JWKS_TTL=K.BASE64URL_REGEX=K.API_VERSIONS=K.API_VERSION_HEADER_NAME=K.NETWORK_FAILURE=K.DEFAULT_HEADERS=K.AUDIENCE=K.STORAGE_KEY=K.GOTRUE_URL=K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD=K.AUTO_REFRESH_TICK_DURATION_MS=void 0;var $l=Sn();K.AUTO_REFRESH_TICK_DURATION_MS=30*1e3;K.AUTO_REFRESH_TICK_THRESHOLD=3;K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD*K.AUTO_REFRESH_TICK_DURATION_MS;K.GOTRUE_URL="http://localhost:9999";K.STORAGE_KEY="supabase.auth.token";K.AUDIENCE="";K.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${$l.version}`};K.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2};K.API_VERSION_HEADER_NAME="X-Supabase-Api-Version";K.API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};K.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;K.JWKS_TTL=600*1e3});var De=$(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.AuthInvalidJwtError=F.AuthWeakPasswordError=F.AuthRetryableFetchError=F.AuthPKCECodeVerifierMissingError=F.AuthPKCEGrantCodeExchangeError=F.AuthImplicitGrantRedirectError=F.AuthInvalidCredentialsError=F.AuthInvalidTokenResponseError=F.AuthSessionMissingError=F.CustomAuthError=F.AuthUnknownError=F.AuthApiError=F.AuthError=void 0;F.isAuthError=$e;F.isAuthApiError=Dl;F.isAuthSessionMissingError=Fl;F.isAuthImplicitGrantRedirectError=Bl;F.isAuthPKCECodeVerifierMissingError=ql;F.isAuthRetryableFetchError=Ml;F.isAuthWeakPasswordError=Wl;var et=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};F.AuthError=et;function $e(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Tn=class extends et{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};F.AuthApiError=Tn;function Dl(t){return $e(t)&&t.name==="AuthApiError"}var An=class extends et{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}};F.AuthUnknownError=An;var ve=class extends et{constructor(e,r,n,s){super(e,n,s),this.name=r,this.status=n}};F.CustomAuthError=ve;var Rn=class extends ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};F.AuthSessionMissingError=Rn;function Fl(t){return $e(t)&&t.name==="AuthSessionMissingError"}var kn=class extends ve{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}};F.AuthInvalidTokenResponseError=kn;var On=class extends ve{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}};F.AuthInvalidCredentialsError=On;var Cn=class extends ve{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthImplicitGrantRedirectError=Cn;function Bl(t){return $e(t)&&t.name==="AuthImplicitGrantRedirectError"}var Pn=class extends ve{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthPKCEGrantCodeExchangeError=Pn;var In=class extends ve{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")}};F.AuthPKCECodeVerifierMissingError=In;function ql(t){return $e(t)&&t.name==="AuthPKCECodeVerifierMissingError"}var xn=class extends ve{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};F.AuthRetryableFetchError=xn;function Ml(t){return $e(t)&&t.name==="AuthRetryableFetchError"}var Nn=class extends ve{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};F.AuthWeakPasswordError=Nn;function Wl(t){return $e(t)&&t.name==="AuthWeakPasswordError"}var jn=class extends ve{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};F.AuthInvalidJwtError=jn});var or=$(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.byteToBase64URL=wt;we.byteFromBase64URL=Un;we.stringToBase64URL=Hl;we.stringFromBase64URL=Kl;we.codepointToUTF8=uo;we.stringToUTF8=Ln;we.stringFromUTF8=lo;we.base64UrlToUint8Array=zl;we.stringToUint8Array=Gl;we.bytesToBase64URL=Jl;var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ao=`
26
- \r=`.split(""),Vl=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ao.length;e+=1)t[ao[e].charCodeAt(0)]=-2;for(let e=0;e<ir.length;e+=1)t[ir[e].charCodeAt(0)]=e;return t})();function wt(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}}function Un(t,e,r){let n=Vl[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Hl(t){let e=[],r=s=>{e.push(s)},n={queue:0,queuedBits:0};return Ln(t,s=>{wt(s,n,r)}),wt(null,n,r),e.join("")}function Kl(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{lo(o,n,r)};for(let o=0;o<t.length;o+=1)Un(t.charCodeAt(o),s,i);return e.join("")}function uo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Ln(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}uo(n,e)}}function lo(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function zl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<t.length;s+=1)Un(t.charCodeAt(s),r,n);return new Uint8Array(e)}function Gl(t){let e=[];return Ln(t,r=>e.push(r)),new Uint8Array(e)}function Jl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};return t.forEach(s=>wt(s,r,n)),wt(null,r,n),e.join("")}});var tt=$(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.Deferred=D.removeItemAsync=D.getItemAsync=D.setItemAsync=D.looksLikeFetchResponse=D.resolveFetch=D.supportsLocalStorage=D.isBrowser=void 0;D.expiresAt=Yl;D.generateCallbackId=Xl;D.parseParametersFromURL=ec;D.decodeJWT=oc;D.sleep=ac;D.retryable=uc;D.generatePKCEVerifier=fo;D.generatePKCEChallenge=po;D.getCodeChallengeAndMethod=dc;D.parseResponseAPIVersion=fc;D.validateExp=pc;D.getAlgorithm=mc;D.validateUUID=gc;D.userNotAvailableProxy=yc;D.insecureUserWarningProxy=vc;D.deepClone=wc;var ho=sr(),co=De(),$n=or();function Yl(t){return Math.round(Date.now()/1e3)+t}function Xl(){return Symbol("auth-callback")}var Ql=()=>typeof window<"u"&&typeof document<"u";D.isBrowser=Ql;var Fe={tested:!1,writable:!1},Zl=()=>{if(!(0,D.isBrowser)())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Fe.tested)return Fe.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Fe.tested=!0,Fe.writable=!0}catch{Fe.tested=!0,Fe.writable=!1}return Fe.writable};D.supportsLocalStorage=Zl;function ec(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return r.searchParams.forEach((n,s)=>{e[s]=n}),e}var tc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);D.resolveFetch=tc;var rc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function";D.looksLikeFetchResponse=rc;var nc=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))};D.setItemAsync=nc;var sc=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}};D.getItemAsync=sc;var ic=async(t,e)=>{await t.removeItem(e)};D.removeItemAsync=ic;var ar=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};D.Deferred=ar;ar.promiseConstructor=Promise;function oc(t){let e=t.split(".");if(e.length!==3)throw new co.AuthInvalidJwtError("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!ho.BASE64URL_REGEX.test(e[n]))throw new co.AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse((0,$n.stringFromBase64URL)(e[0])),payload:JSON.parse((0,$n.stringFromBase64URL)(e[1])),signature:(0,$n.base64UrlToUint8Array)(e[2]),raw:{header:e[0],payload:e[1]}}}async function ac(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function uc(t,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function lc(t){return("0"+t.toString(16)).substr(-2)}function fo(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,lc).join("")}async function cc(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function po(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await cc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function dc(t,e,r=!1){let n=fo(),s=n;r&&(s+="/PASSWORD_RECOVERY"),await(0,D.setItemAsync)(t,`${e}-code-verifier`,s);let i=await po(n);return[i,n===i?"plain":"s256"]}var hc=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function fc(t){let e=t.headers.get(ho.API_VERSION_HEADER_NAME);if(!e||!e.match(hc))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function pc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function mc(t){switch(t){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 new Error("Invalid alg claim")}}var _c=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function gc(t){if(!_c.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function yc(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function vc(t,e){return new Proxy(t,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!e.value&&typeof n=="string"&&(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."),e.value=!0),Reflect.get(r,n,s)}})}function wc(t){return JSON.parse(JSON.stringify(t))}});var Bn=$(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.handleError=Fn;Oe._request=Tc;Oe._sessionResponse=mo;Oe._sessionResponsePassword=Rc;Oe._userResponse=kc;Oe._ssoResponse=Oc;Oe._generateLinkResponse=Cc;Oe._noResolveJsonResponse=Pc;var bc=(ge(),Se(_e)),ur=sr(),Dn=tt(),Ue=De(),Be=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Ec=[502,503,504];async function Fn(t){var e;if(!(0,Dn.looksLikeFetchResponse)(t))throw new Ue.AuthRetryableFetchError(Be(t),0);if(Ec.includes(t.status))throw new Ue.AuthRetryableFetchError(Be(t),t.status);let r;try{r=await t.json()}catch(i){throw new Ue.AuthUnknownError(Be(i),i)}let n,s=(0,Dn.parseResponseAPIVersion)(t);if(s&&s.getTime()>=ur.API_VERSIONS["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Ue.AuthWeakPasswordError(Be(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ue.AuthSessionMissingError}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Ue.AuthWeakPasswordError(Be(r),t.status,r.weak_password.reasons);throw new Ue.AuthApiError(Be(r),t.status||500,n)}var Sc=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function Tc(t,e,r,n){var s;let i=Object.assign({},n?.headers);i[ur.API_VERSION_HEADER_NAME]||(i[ur.API_VERSION_HEADER_NAME]=ur.API_VERSIONS["2024-01-01"].name),n?.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n?.query)!==null&&s!==void 0?s:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Ac(t,e,r+a,{headers:i,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Ac(t,e,r,n,s,i){let o=Sc(e,n,s,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Ue.AuthRetryableFetchError(Be(l),0)}if(a.ok||await Fn(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Fn(l)}}function mo(t){var e;let r=null;Ic(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=(0,Dn.expiresAt)(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function Rc(t){let e=mo(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function kc(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Oc(t){return{data:t,error:null}}function Cc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=t,o=bc.__rest(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Pc(t){return t}function Ic(t){return t.access_token&&t.refresh_token&&t.expires_in}});var qn=$(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.SIGN_OUT_SCOPES=void 0;lr.SIGN_OUT_SCOPES=["global","local","others"]});var cr=$(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});var xc=(ge(),Se(_e)),Q=Bn(),qe=tt(),Mn=qn(),ce=De(),Wn=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=(0,qe.resolveFetch)(n),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)}}async signOut(e,r=Mn.SIGN_OUT_SCOPES[0]){if(Mn.SIGN_OUT_SCOPES.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Mn.SIGN_OUT_SCOPES.join(", ")}`);try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=xc.__rest(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=n?.newEmail,delete s.newEmail),await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Q._generateLinkResponse,redirectTo:r?.redirectTo})}catch(r){if((0,ce.isAuthError)(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){(0,qe.validateUUID)(e.userId);try{let{data:r,error:n}=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:r,error:n}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _deleteFactor(e){(0,qe.validateUUID)(e.userId),(0,qe.validateUUID)(e.id);try{return{data:await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}};Vn.default=Wn});var _o=$(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.memoryLocalStorageAdapter=Nc;function Nc(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}});var Kn=$(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.ProcessLockAcquireTimeoutError=ue.NavigatorLockAcquireTimeoutError=ue.LockAcquireTimeoutError=ue.internals=void 0;ue.navigatorLock=Uc;ue.processLock=Lc;var jc=tt();ue.internals={debug:!!(globalThis&&(0,jc.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};var bt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};ue.LockAcquireTimeoutError=bt;var Et=class extends bt{};ue.NavigatorLockAcquireTimeoutError=Et;var dr=class extends bt{};ue.ProcessLockAcquireTimeoutError=dr;async function Uc(t,e,r){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(ue.internals.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}})}catch(s){throw s?.name==="AbortError"?new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" timed out waiting ${e}ms`):s}}var go={};async function Lc(t,e,r){var n;let s=(n=go[t])!==null&&n!==void 0?n:Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),o=(async()=>{let a=null;try{let l=e>=0?new Promise((c,h)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),h(new dr(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([i,l].filter(c=>c)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return go[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await s}catch{}return null}throw a}})(),await o}});var yo=$(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.polyfillGlobalThis=$c;function $c(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}});var wo=$(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getAddress=vo;rt.fromHex=Dc;rt.toHex=Fc;rt.createSiweMessage=Bc;function vo(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Dc(t){return parseInt(t,16)}function Fc(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function Bc(t){var e;let{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:m,version:_}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!m)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(_!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${_}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
25
+ })`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ne.SOCKET_STATES.connecting:return ne.CONNECTION_STATE.Connecting;case ne.SOCKET_STATES.open:return ne.CONNECTION_STATE.Open;case ne.SOCKET_STATES.closing:return ne.CONNECTION_STATE.Closing;default:return ne.CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===ne.CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new sl.default(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){let{topic:r,event:n,payload:s,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${r} ${n} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(ne.WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Yt.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){let c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",c)}catch(h){this.log("error","error in heartbeat callback",h)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=r,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${n} ${s} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(n)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ne.SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ne.SOCKET_STATES.open||this.conn.readyState===ne.SOCKET_STATES.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&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)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(ne.CHANNEL_EVENTS.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(r);return`${e}${n}${s}`}_workerObjectUrl(e){let r;if(e)r=e;else{let n=new Blob([al],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(s=>{let i={access_token:r,version:ne.DEFAULT_VERSION};r&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ne.CHANNEL_EVENTS.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(r)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new rl.default(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Yt.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,n,s,i,o,a,l,c,h,m,_,f;switch(this.transport=(r=e?.transport)!==null&&r!==void 0?r:null,this.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ne.DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Yt.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:_n,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:ne.DEFAULT_VSN,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(y=>il[y-1]||ol),this.vsn){case ne.VSN_1_0_0:this.encode=(h=e?.encode)!==null&&h!==void 0?h:((y,v)=>v(JSON.stringify(y))),this.decode=(m=e?.decode)!==null&&m!==void 0?m:((y,v)=>v(JSON.parse(y)));break;case ne.VSN_2_0_0:this.encode=(_=e?.encode)!==null&&_!==void 0?_:this.serializer.encode.bind(this.serializer),this.decode=(f=e?.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}};yn.default=gn});var vn=$(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.WebSocketFactory=oe.REALTIME_CHANNEL_STATES=oe.REALTIME_SUBSCRIBE_STATES=oe.REALTIME_PRESENCE_LISTEN_EVENTS=oe.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=oe.REALTIME_LISTEN_TYPES=oe.RealtimeClient=oe.RealtimeChannel=oe.RealtimePresence=void 0;var Qt=(ge(),Se(_e)),ul=Qt.__importDefault(Xi());oe.RealtimeClient=ul.default;var pt=Qt.__importStar(mn());oe.RealtimeChannel=pt.default;Object.defineProperty(oe,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return pt.REALTIME_LISTEN_TYPES}});Object.defineProperty(oe,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return pt.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}});Object.defineProperty(oe,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return pt.REALTIME_SUBSCRIBE_STATES}});Object.defineProperty(oe,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return pt.REALTIME_CHANNEL_STATES}});var Qi=Qt.__importStar(hn());oe.RealtimePresence=Qi.default;Object.defineProperty(oe,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return Qi.REALTIME_PRESENCE_LISTEN_EVENTS}});var ll=Qt.__importDefault(tn());oe.WebSocketFactory=ll.default});var Sn=$(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.version=void 0;nr.version="2.97.0"});var sr=$(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.JWKS_TTL=K.BASE64URL_REGEX=K.API_VERSIONS=K.API_VERSION_HEADER_NAME=K.NETWORK_FAILURE=K.DEFAULT_HEADERS=K.AUDIENCE=K.STORAGE_KEY=K.GOTRUE_URL=K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD=K.AUTO_REFRESH_TICK_DURATION_MS=void 0;var Dl=Sn();K.AUTO_REFRESH_TICK_DURATION_MS=30*1e3;K.AUTO_REFRESH_TICK_THRESHOLD=3;K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD*K.AUTO_REFRESH_TICK_DURATION_MS;K.GOTRUE_URL="http://localhost:9999";K.STORAGE_KEY="supabase.auth.token";K.AUDIENCE="";K.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${Dl.version}`};K.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2};K.API_VERSION_HEADER_NAME="X-Supabase-Api-Version";K.API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};K.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;K.JWKS_TTL=600*1e3});var De=$(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.AuthInvalidJwtError=F.AuthWeakPasswordError=F.AuthRetryableFetchError=F.AuthPKCECodeVerifierMissingError=F.AuthPKCEGrantCodeExchangeError=F.AuthImplicitGrantRedirectError=F.AuthInvalidCredentialsError=F.AuthInvalidTokenResponseError=F.AuthSessionMissingError=F.CustomAuthError=F.AuthUnknownError=F.AuthApiError=F.AuthError=void 0;F.isAuthError=$e;F.isAuthApiError=Fl;F.isAuthSessionMissingError=Bl;F.isAuthImplicitGrantRedirectError=ql;F.isAuthPKCECodeVerifierMissingError=Ml;F.isAuthRetryableFetchError=Wl;F.isAuthWeakPasswordError=Vl;var et=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};F.AuthError=et;function $e(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Tn=class extends et{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};F.AuthApiError=Tn;function Fl(t){return $e(t)&&t.name==="AuthApiError"}var An=class extends et{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}};F.AuthUnknownError=An;var ve=class extends et{constructor(e,r,n,s){super(e,n,s),this.name=r,this.status=n}};F.CustomAuthError=ve;var Rn=class extends ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};F.AuthSessionMissingError=Rn;function Bl(t){return $e(t)&&t.name==="AuthSessionMissingError"}var kn=class extends ve{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}};F.AuthInvalidTokenResponseError=kn;var On=class extends ve{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}};F.AuthInvalidCredentialsError=On;var Cn=class extends ve{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthImplicitGrantRedirectError=Cn;function ql(t){return $e(t)&&t.name==="AuthImplicitGrantRedirectError"}var Pn=class extends ve{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthPKCEGrantCodeExchangeError=Pn;var In=class extends ve{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")}};F.AuthPKCECodeVerifierMissingError=In;function Ml(t){return $e(t)&&t.name==="AuthPKCECodeVerifierMissingError"}var xn=class extends ve{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};F.AuthRetryableFetchError=xn;function Wl(t){return $e(t)&&t.name==="AuthRetryableFetchError"}var Nn=class extends ve{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};F.AuthWeakPasswordError=Nn;function Vl(t){return $e(t)&&t.name==="AuthWeakPasswordError"}var jn=class extends ve{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};F.AuthInvalidJwtError=jn});var or=$(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.byteToBase64URL=wt;we.byteFromBase64URL=Ln;we.stringToBase64URL=Kl;we.stringFromBase64URL=zl;we.codepointToUTF8=uo;we.stringToUTF8=Un;we.stringFromUTF8=lo;we.base64UrlToUint8Array=Gl;we.stringToUint8Array=Jl;we.bytesToBase64URL=Yl;var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ao=`
26
+ \r=`.split(""),Hl=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<ao.length;e+=1)t[ao[e].charCodeAt(0)]=-2;for(let e=0;e<ir.length;e+=1)t[ir[e].charCodeAt(0)]=e;return t})();function wt(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}}function Ln(t,e,r){let n=Hl[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Kl(t){let e=[],r=s=>{e.push(s)},n={queue:0,queuedBits:0};return Un(t,s=>{wt(s,n,r)}),wt(null,n,r),e.join("")}function zl(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{lo(o,n,r)};for(let o=0;o<t.length;o+=1)Ln(t.charCodeAt(o),s,i);return e.join("")}function uo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Un(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}uo(n,e)}}function lo(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Gl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<t.length;s+=1)Ln(t.charCodeAt(s),r,n);return new Uint8Array(e)}function Jl(t){let e=[];return Un(t,r=>e.push(r)),new Uint8Array(e)}function Yl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};return t.forEach(s=>wt(s,r,n)),wt(null,r,n),e.join("")}});var tt=$(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.Deferred=D.removeItemAsync=D.getItemAsync=D.setItemAsync=D.looksLikeFetchResponse=D.resolveFetch=D.supportsLocalStorage=D.isBrowser=void 0;D.expiresAt=Xl;D.generateCallbackId=Ql;D.parseParametersFromURL=tc;D.decodeJWT=ac;D.sleep=uc;D.retryable=lc;D.generatePKCEVerifier=fo;D.generatePKCEChallenge=po;D.getCodeChallengeAndMethod=hc;D.parseResponseAPIVersion=pc;D.validateExp=mc;D.getAlgorithm=_c;D.validateUUID=yc;D.userNotAvailableProxy=vc;D.insecureUserWarningProxy=wc;D.deepClone=bc;var ho=sr(),co=De(),$n=or();function Xl(t){return Math.round(Date.now()/1e3)+t}function Ql(){return Symbol("auth-callback")}var Zl=()=>typeof window<"u"&&typeof document<"u";D.isBrowser=Zl;var Fe={tested:!1,writable:!1},ec=()=>{if(!(0,D.isBrowser)())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Fe.tested)return Fe.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Fe.tested=!0,Fe.writable=!0}catch{Fe.tested=!0,Fe.writable=!1}return Fe.writable};D.supportsLocalStorage=ec;function tc(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return r.searchParams.forEach((n,s)=>{e[s]=n}),e}var rc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);D.resolveFetch=rc;var nc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function";D.looksLikeFetchResponse=nc;var sc=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))};D.setItemAsync=sc;var ic=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}};D.getItemAsync=ic;var oc=async(t,e)=>{await t.removeItem(e)};D.removeItemAsync=oc;var ar=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};D.Deferred=ar;ar.promiseConstructor=Promise;function ac(t){let e=t.split(".");if(e.length!==3)throw new co.AuthInvalidJwtError("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!ho.BASE64URL_REGEX.test(e[n]))throw new co.AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse((0,$n.stringFromBase64URL)(e[0])),payload:JSON.parse((0,$n.stringFromBase64URL)(e[1])),signature:(0,$n.base64UrlToUint8Array)(e[2]),raw:{header:e[0],payload:e[1]}}}async function uc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function lc(t,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function cc(t){return("0"+t.toString(16)).substr(-2)}function fo(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,cc).join("")}async function dc(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function po(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await dc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function hc(t,e,r=!1){let n=fo(),s=n;r&&(s+="/PASSWORD_RECOVERY"),await(0,D.setItemAsync)(t,`${e}-code-verifier`,s);let i=await po(n);return[i,n===i?"plain":"s256"]}var fc=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function pc(t){let e=t.headers.get(ho.API_VERSION_HEADER_NAME);if(!e||!e.match(fc))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function mc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function _c(t){switch(t){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 new Error("Invalid alg claim")}}var gc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function yc(t){if(!gc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function vc(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function wc(t,e){return new Proxy(t,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!e.value&&typeof n=="string"&&(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."),e.value=!0),Reflect.get(r,n,s)}})}function bc(t){return JSON.parse(JSON.stringify(t))}});var Bn=$(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.handleError=Fn;Oe._request=Ac;Oe._sessionResponse=mo;Oe._sessionResponsePassword=kc;Oe._userResponse=Oc;Oe._ssoResponse=Cc;Oe._generateLinkResponse=Pc;Oe._noResolveJsonResponse=Ic;var Ec=(ge(),Se(_e)),ur=sr(),Dn=tt(),Le=De(),Be=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Sc=[502,503,504];async function Fn(t){var e;if(!(0,Dn.looksLikeFetchResponse)(t))throw new Le.AuthRetryableFetchError(Be(t),0);if(Sc.includes(t.status))throw new Le.AuthRetryableFetchError(Be(t),t.status);let r;try{r=await t.json()}catch(i){throw new Le.AuthUnknownError(Be(i),i)}let n,s=(0,Dn.parseResponseAPIVersion)(t);if(s&&s.getTime()>=ur.API_VERSIONS["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Le.AuthWeakPasswordError(Be(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Le.AuthSessionMissingError}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Le.AuthWeakPasswordError(Be(r),t.status,r.weak_password.reasons);throw new Le.AuthApiError(Be(r),t.status||500,n)}var Tc=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function Ac(t,e,r,n){var s;let i=Object.assign({},n?.headers);i[ur.API_VERSION_HEADER_NAME]||(i[ur.API_VERSION_HEADER_NAME]=ur.API_VERSIONS["2024-01-01"].name),n?.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n?.query)!==null&&s!==void 0?s:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Rc(t,e,r+a,{headers:i,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Rc(t,e,r,n,s,i){let o=Tc(e,n,s,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Le.AuthRetryableFetchError(Be(l),0)}if(a.ok||await Fn(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Fn(l)}}function mo(t){var e;let r=null;xc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=(0,Dn.expiresAt)(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function kc(t){let e=mo(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Oc(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Cc(t){return{data:t,error:null}}function Pc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=t,o=Ec.__rest(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Ic(t){return t}function xc(t){return t.access_token&&t.refresh_token&&t.expires_in}});var qn=$(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.SIGN_OUT_SCOPES=void 0;lr.SIGN_OUT_SCOPES=["global","local","others"]});var cr=$(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});var Nc=(ge(),Se(_e)),Q=Bn(),qe=tt(),Mn=qn(),ce=De(),Wn=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=(0,qe.resolveFetch)(n),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)}}async signOut(e,r=Mn.SIGN_OUT_SCOPES[0]){if(Mn.SIGN_OUT_SCOPES.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Mn.SIGN_OUT_SCOPES.join(", ")}`);try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=Nc.__rest(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=n?.newEmail,delete s.newEmail),await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Q._generateLinkResponse,redirectTo:r?.redirectTo})}catch(r){if((0,ce.isAuthError)(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){(0,qe.validateUUID)(e.userId);try{let{data:r,error:n}=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:r,error:n}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _deleteFactor(e){(0,qe.validateUUID)(e.userId),(0,qe.validateUUID)(e.id);try{return{data:await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}};Vn.default=Wn});var _o=$(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.memoryLocalStorageAdapter=jc;function jc(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}});var Kn=$(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.ProcessLockAcquireTimeoutError=ue.NavigatorLockAcquireTimeoutError=ue.LockAcquireTimeoutError=ue.internals=void 0;ue.navigatorLock=Uc;ue.processLock=$c;var Lc=tt();ue.internals={debug:!!(globalThis&&(0,Lc.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};var bt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};ue.LockAcquireTimeoutError=bt;var Et=class extends bt{};ue.NavigatorLockAcquireTimeoutError=Et;var dr=class extends bt{};ue.ProcessLockAcquireTimeoutError=dr;async function Uc(t,e,r){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(ue.internals.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}})}catch(s){throw s?.name==="AbortError"?new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" timed out waiting ${e}ms`):s}}var go={};async function $c(t,e,r){var n;let s=(n=go[t])!==null&&n!==void 0?n:Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),o=(async()=>{let a=null;try{let l=e>=0?new Promise((c,h)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),h(new dr(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([i,l].filter(c=>c)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return go[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await s}catch{}return null}throw a}})(),await o}});var yo=$(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.polyfillGlobalThis=Dc;function Dc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}});var wo=$(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getAddress=vo;rt.fromHex=Fc;rt.toHex=Bc;rt.createSiweMessage=qc;function vo(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Fc(t){return parseInt(t,16)}function Bc(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function qc(t){var e;let{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:m,version:_}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!m)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(_!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${_}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
27
27
  `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let f=vo(t.address),y=h?`${h}://${n}`:n,v=t.statement?`${t.statement}
28
28
  `:"",w=`${y} wants you to sign in with your Ethereum account:
29
29
  ${f}
@@ -38,8 +38,8 @@ Not Before: ${a.toISOString()}`),l&&(T+=`
38
38
  Request ID: ${l}`),c){let O=`
39
39
  Resources:`;for(let E of c){if(!E||typeof E!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${E}`);O+=`
40
40
  - ${E}`}T+=O}return`${w}
41
- ${T}`}});var Eo=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebAuthnUnknownError=Ne.WebAuthnError=void 0;Ne.isWebAuthnError=qc;Ne.identifyRegistrationError=Mc;Ne.identifyAuthenticationError=Wc;var bo=Jn(),te=class extends Error{constructor({message:e,code:r,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s??(n instanceof Error?n.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};Ne.WebAuthnError=te;var Gn=class extends te{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};Ne.WebAuthnUnknownError=Gn;function qc(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Mc({error:t,options:e}){var r,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new te({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new te({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new te({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new te({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new te({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new te({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if((0,bo.isValidDomain)(o)){if(i.rp.id!==o)return new te({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new te({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Wc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if((0,bo.isValidDomain)(n)){if(r.rpId!==n)return new te({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Jn=$(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.WebAuthnApi=M.DEFAULT_REQUEST_OPTIONS=M.DEFAULT_CREATION_OPTIONS=M.webAuthnAbortService=M.WebAuthnAbortService=M.identifyAuthenticationError=M.identifyRegistrationError=M.isWebAuthnError=M.WebAuthnError=void 0;M.deserializeCredentialCreationOptions=Hc;M.deserializeCredentialRequestOptions=Kc;M.serializeCredentialCreationResponse=zc;M.serializeCredentialRequestResponse=Gc;M.isValidDomain=Jc;M.createCredential=Ao;M.getCredential=Ro;M.mergeCredentialCreationOptions=ko;M.mergeCredentialRequestOptions=Oo;var To=(ge(),Se(_e)),Re=or(),Ce=De(),Vc=tt(),Pe=Eo();Object.defineProperty(M,"identifyAuthenticationError",{enumerable:!0,get:function(){return Pe.identifyAuthenticationError}});Object.defineProperty(M,"identifyRegistrationError",{enumerable:!0,get:function(){return Pe.identifyRegistrationError}});Object.defineProperty(M,"isWebAuthnError",{enumerable:!0,get:function(){return Pe.isWebAuthnError}});Object.defineProperty(M,"WebAuthnError",{enumerable:!0,get:function(){return Pe.WebAuthnError}});var hr=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};M.WebAuthnAbortService=hr;M.webAuthnAbortService=new hr;function Hc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,s=To.__rest(t,["challenge","user","excludeCredentials"]),i=(0,Re.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,Re.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,Re.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function Kc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=To.__rest(t,["challenge","allowCredentials"]),s=(0,Re.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:(0,Re.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function zc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Gc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,Re.bytesToBase64URL)(new Uint8Array(s.authenticatorData)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(s.clientDataJSON)),signature:(0,Re.bytesToBase64URL)(new Uint8Array(s.signature)),userHandle:s.userHandle?(0,Re.bytesToBase64URL)(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Jc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function So(){var t,e;return!!((0,Vc.isBrowser)()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Ao(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyRegistrationError)({error:e,options:t})}}}async function Ro(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyAuthenticationError)({error:e,options:t})}}}M.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};M.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function fr(...t){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of t)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(r(o))n[i]=o;else if(e(o)){let a=n[i];e(a)?n[i]=fr(a,o):n[i]=fr(o)}else n[i]=o}return n}function ko(t,e){return fr(M.DEFAULT_CREATION_OPTIONS,t,e||{})}function Oo(t,e){return fr(M.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Yn=class{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:s},i){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let c=s??M.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:h}=a.webauthn.credential_options.publicKey;if(!h.name){let m=n;if(m)h.name=`${h.id}:${m}`;else{let f=(await this.client.getUser()).data.user,y=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";h.name=`${h.id}:${y}`}}h.displayName||(h.displayName=h.name)}switch(a.webauthn.type){case"create":{let h=ko(a.webauthn.credential_options.publicKey,i?.create),{data:m,error:_}=await Ao({publicKey:h,signal:c});return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}case"request":{let h=Oo(a.webauthn.credential_options.publicKey,i?.request),{data:m,error:_}=await Ro(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:h,signal:c}));return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}}}catch(a){return(0,Ce.isAuthError)(a)?{data:null,error:a}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn authentication")};try{if(!So())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn registration")};try{if(!So())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var m;return(m=h.data)===null||m===void 0?void 0:m.all.find(_=>_.factor_type==="webauthn"&&_.friendly_name===e&&_.status!=="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in register",o)}}}};M.WebAuthnApi=Yn});var Qn=$(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});var Yc=(ge(),Se(_e)),Xc=Yc.__importDefault(cr()),pe=sr(),S=De(),I=Bn(),A=tt(),Co=_o(),Po=Kn(),Qc=yo(),Zc=Sn(),Io=or(),pr=wo(),St=Jn();(0,Qc.polyfillGlobalThis)();var ed={url:pe.GOTRUE_URL,storageKey:pe.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:pe.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function xo(t,e,r){return await r()}var nt={},mr=class t{get jwks(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},ed),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&(0,A.isBrowser)()){let o=`${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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Xc.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,A.resolveFetch)(i.fetch),this.lock=i.lock||xo,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&(0,A.isBrowser)()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Po.navigatorLock:this.lock=xo,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 St.WebAuthnApi(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.persistSession?(i.storage?this.storage=i.storage:(0,A.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),(0,A.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Zc.version}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if((0,A.isBrowser)()&&(r=(0,A.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),(0,A.isBrowser)()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,S.isAuthImplicitGrantRedirectError)(i)){let l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return(0,S.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new S.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,s;try{let i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:I._sessionResponse}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if((0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,n,s;try{let i;if("email"in e){let{email:h,password:m,options:_}=e,f=null,y=null;this.flowType==="pkce"&&([f,y]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:_?.emailRedirectTo,body:{email:h,password:m,data:(r=_?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:_?.captchaToken},code_challenge:f,code_challenge_method:y},xform:I._sessionResponse})}else if("phone"in e){let{phone:h,password:m,options:_}=e;i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=_?.data)!==null&&n!==void 0?n:{},channel:(s=_?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:_?.captchaToken}},xform:I._sessionResponse})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,s,i,o,a,l,c,h,m,_;let f,y;if("message"in e)f=e.message,y=e.signature;else{let{chain:v,wallet:w,statement:T,options:O}=e,E;if((0,A.isBrowser)())if(typeof w=="object")E=w;else{let Ee=window;if("ethereum"in Ee&&typeof Ee.ethereum=="object"&&"request"in Ee.ethereum&&typeof Ee.ethereum.request=="function")E=Ee.ethereum;else throw new 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(typeof w!="object"||!O?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=w}let x=new URL((r=O?.url)!==null&&r!==void 0?r:window.location.href),Z=await E.request({method:"eth_requestAccounts"}).then(Ee=>Ee).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let W=(0,pr.getAddress)(Z[0]),re=(n=O?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!re){let Ee=await E.request({method:"eth_chainId"});re=(0,pr.fromHex)(Ee)}let ke={domain:x.host,address:W,statement:T,uri:x.href,version:"1",chainId:re,nonce:(s=O?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=O?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=O?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=O?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=O?.signInWithEthereum)===null||h===void 0?void 0:h.resources};f=(0,pr.createSiweMessage)(ke),y=await E.request({method:"personal_sign",params:[(0,pr.toHex)(f),W]})}try{let{data:v,error:w}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:I._sessionResponse});if(w)throw w;if(!v||!v.session||!v.user){let T=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:T})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:w})}catch(v){if((0,S.isAuthError)(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,s,i,o,a,l,c,h,m,_,f;let y,v;if("message"in e)y=e.message,v=e.signature;else{let{chain:w,wallet:T,statement:O,options:E}=e,x;if((0,A.isBrowser)())if(typeof T=="object")x=T;else{let W=window;if("solana"in W&&typeof W.solana=="object"&&("signIn"in W.solana&&typeof W.solana.signIn=="function"||"signMessage"in W.solana&&typeof W.solana.signMessage=="function"))x=W.solana;else throw new 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(typeof T!="object"||!E?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=T}let Z=new URL((r=E?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){let W=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},E?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),O?{statement:O}:null)),re;if(Array.isArray(W)&&W[0]&&typeof W[0]=="object")re=W[0];else if(W&&typeof W=="object"&&"signedMessage"in W&&"signature"in W)re=W;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in re&&"signature"in re&&(typeof re.signedMessage=="string"||re.signedMessage instanceof Uint8Array)&&re.signature instanceof Uint8Array)y=typeof re.signedMessage=="string"?re.signedMessage:new TextDecoder().decode(re.signedMessage),v=re.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${Z.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(s=(n=E?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=E?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${E.signInWithSolana.notBefore}`]:[],...!((o=E?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${E.signInWithSolana.expirationTime}`]:[],...!((a=E?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${E.signInWithSolana.chainId}`]:[],...!((l=E?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${E.signInWithSolana.nonce}`]:[],...!((c=E?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${E.signInWithSolana.requestId}`]:[],...!((m=(h=E?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||m===void 0)&&m.length?["Resources",...E.signInWithSolana.resources.map(re=>`- ${re}`)]:[]].join(`
42
- `);let W=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{let{data:w,error:T}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:(0,Io.bytesToBase64URL)(v)},!((_=e.options)===null||_===void 0)&&_.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:I._sessionResponse});if(T)throw T;if(!w||!w.session||!w.user){let O=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:O})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:T})}catch(w){if((0,S.isAuthError)(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async _exchangeCodeForSession(e){let r=await(0,A.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new S.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:I._sessionResponse});if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:n,token:s,access_token:i,nonce:o}=e,a=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:I._sessionResponse}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let h=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:h})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,s,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,h=null;this.flowType==="pkce"&&([c,h]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:m}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:m})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:h}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:h})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let s,i;"options"in e&&(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await(0,I._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:I._sessionResponse});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if((0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var r,n,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,I._request)(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:I._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,A.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new S.AuthSessionMissingError;let{error:s}=await(0,I._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:a}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await(0,A.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<pe.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await(0,A.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,A.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,A.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:I._userResponse}):await this._useSession(async r=>{var n,s,i;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new S.AuthSessionMissingError}:await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:I._userResponse})})}catch(r){if((0,S.isAuthError)(r))return(0,S.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new S.AuthSessionMissingError;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:h}=await(0,I._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:I._userResponse});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S.AuthSessionMissingError;let r=Date.now()/1e3,n=r,s=!0,i=null,{payload:o}=(0,A.decodeJWT)(e.access_token);if(o.exp&&(n=o.exp,s=n<=r),s){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new S.AuthSessionMissingError;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,A.isBrowser)())throw new S.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new S.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new S.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new S.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new S.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:O,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new S.AuthImplicitGrantRedirectError("No session defined in URL");let h=Math.round(Date.now()/1e3),m=parseInt(a),_=h+m;l&&(_=parseInt(l));let f=_-h;f*1e3<=pe.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${m}s`);let y=_-m;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,_,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,_,h);let{data:v,error:w}=await this._getUser(i);if(w)throw w;let T={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:_,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:T,redirectType:e.type},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await(0,A.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i&&!(0,S.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,S.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,S.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,A.generateCallbackId)(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,s;try{let{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,I._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:s}=await this._useSession(async i=>{var o,a,l,c,h;let{data:m,error:_}=i;if(_)throw _;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await(0,I._request)(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=m.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(s)throw s;return(0,A.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:s,data:{session:i}}=r;if(s)throw s;let{options:o,provider:a,token:l,access_token:c,nonce:h}=e,m=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:I._sessionResponse}),{data:_,error:f}=m;return f?this._returnResult({data:{user:null,session:null},error:f}):!_||!_.session||!_.user?this._returnResult({data:{user:null,session:null},error:new S.AuthInvalidTokenResponseError}):(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("USER_UPDATED",_.session)),this._returnResult({data:_,error:f}))}catch(s){if(await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)throw o;return await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await(0,A.retryable)(async s=>(s>0&&await(0,A.sleep)(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I._sessionResponse})),(s,i)=>{let o=200*Math.pow(2,s);return i&&(0,S.isAuthRetryableFetchError)(i)&&Date.now()+o-n<pe.AUTO_REFRESH_TICK_DURATION_MS})}catch(n){if(this._debug(r,"error",n),(0,S.isAuthError)(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),(0,A.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await(0,A.getItemAsync)(this.storage,this.storageKey);if(s&&this.userStorage){let o=await(0,A.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await(0,A.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:(0,A.userNotAvailableProxy)()}else if(s&&!s.user&&!s.user){let o=await(0,A.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await(0,A.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,A.setItemAsync)(this.storage,this.storageKey,s)):s.user=(0,A.userNotAvailableProxy)()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((r=s.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<pe.EXPIRY_MARGIN_MS;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${pe.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),(0,S.isAuthRetryableFetchError)(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new S.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new A.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new S.AuthSessionMissingError;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(s,"error",i),(0,S.isAuthError)(i)){let o={data:null,error:i};return(0,S.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,r,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,A.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await(0,A.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let s=Object.assign({},r);delete s.user;let i=(0,A.deepClone)(s);await(0,A.setItemAsync)(this.storage,this.storageKey,i)}else{let s=(0,A.deepClone)(r);await(0,A.setItemAsync)(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,A.removeItemAsync)(this.storage,this.storageKey),await(0,A.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,A.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,A.removeItemAsync)(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&(0,A.isBrowser)()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),pe.AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/pe.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${pe.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${pe.AUTO_REFRESH_TICK_THRESHOLD} ticks`),s<=pe.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Po.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,A.isBrowser)()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let s=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,A.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(n?.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,I._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,St.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,St.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialCreationOptions)(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,s,i;if(e)try{let{payload:f}=(0,A.decodeJWT)(e),y=null;f.aal&&(y=f.aal);let v=y,{data:{user:w},error:T}=await this.getUser(e);if(T)return this._returnResult({data:null,error:T});((n=(r=w?.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(v="aal2");let E=f.amr||[];return{data:{currentLevel:y,nextLevel:v,currentAuthenticationMethods:E},error:null}}catch(f){if((0,S.isAuthError)(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=(0,A.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let h=c;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let _=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:_},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await(0,I._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,A.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,A.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await(0,I._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+pe.JWKS_TTL>s)return n;let{data:i,error:o}=await(0,I._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});n=f.session.access_token}let{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=(0,A.decodeJWT)(n);r?.allowExpired||(0,A.validateExp)(i.exp);let c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}let h=(0,A.getAlgorithm)(s.alg),m=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,o,(0,Io.stringToUint8Array)(`${a}.${l}`)))throw new S.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}};mr.nextInstanceID={};Xn.default=mr});var No=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var td=(ge(),Se(_e)),rd=td.__importDefault(cr()),nd=rd.default;Zn.default=nd});var jo=$(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var sd=(ge(),Se(_e)),id=sd.__importDefault(Qn()),od=id.default;es.default=od});var ts=$(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.processLock=ae.lockInternals=ae.NavigatorLockAcquireTimeoutError=ae.navigatorLock=ae.AuthClient=ae.AuthAdminApi=ae.GoTrueClient=ae.GoTrueAdminApi=void 0;var st=(ge(),Se(_e)),ad=st.__importDefault(cr());ae.GoTrueAdminApi=ad.default;var ud=st.__importDefault(Qn());ae.GoTrueClient=ud.default;var ld=st.__importDefault(No());ae.AuthAdminApi=ld.default;var cd=st.__importDefault(jo());ae.AuthClient=cd.default;st.__exportStar(qn(),ae);st.__exportStar(De(),ae);var _r=Kn();Object.defineProperty(ae,"navigatorLock",{enumerable:!0,get:function(){return _r.navigatorLock}});Object.defineProperty(ae,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return _r.NavigatorLockAcquireTimeoutError}});Object.defineProperty(ae,"lockInternals",{enumerable:!0,get:function(){return _r.internals}});Object.defineProperty(ae,"processLock",{enumerable:!0,get:function(){return _r.processLock}})});var aa=$(U=>{"use strict";var kt=Symbol.for("react.element"),$d=Symbol.for("react.portal"),Dd=Symbol.for("react.fragment"),Fd=Symbol.for("react.strict_mode"),Bd=Symbol.for("react.profiler"),qd=Symbol.for("react.provider"),Md=Symbol.for("react.context"),Wd=Symbol.for("react.forward_ref"),Vd=Symbol.for("react.suspense"),Hd=Symbol.for("react.memo"),Kd=Symbol.for("react.lazy"),Yo=Symbol.iterator;function zd(t){return t===null||typeof t!="object"?null:(t=Yo&&t[Yo]||t["@@iterator"],typeof t=="function"?t:null)}var Zo={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ea=Object.assign,ta={};function it(t,e,r){this.props=t,this.context=e,this.refs=ta,this.updater=r||Zo}it.prototype.isReactComponent={};it.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};it.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function ra(){}ra.prototype=it.prototype;function os(t,e,r){this.props=t,this.context=e,this.refs=ta,this.updater=r||Zo}var as=os.prototype=new ra;as.constructor=os;ea(as,it.prototype);as.isPureReactComponent=!0;var Xo=Array.isArray,na=Object.prototype.hasOwnProperty,us={current:null},sa={key:!0,ref:!0,__self:!0,__source:!0};function ia(t,e,r){var n,s={},i=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)na.call(e,n)&&!sa.hasOwnProperty(n)&&(s[n]=e[n]);var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];s.children=l}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)s[n]===void 0&&(s[n]=a[n]);return{$$typeof:kt,type:t,key:i,ref:o,props:s,_owner:us.current}}function Gd(t,e){return{$$typeof:kt,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function ls(t){return typeof t=="object"&&t!==null&&t.$$typeof===kt}function Jd(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Qo=/\/+/g;function is(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Jd(""+t.key):e.toString(36)}function Er(t,e,r,n,s){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(i){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case kt:case $d:o=!0}}if(o)return o=t,s=s(o),t=n===""?"."+is(o,0):n,Xo(s)?(r="",t!=null&&(r=t.replace(Qo,"$&/")+"/"),Er(s,e,r,"",function(c){return c})):s!=null&&(ls(s)&&(s=Gd(s,r+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(Qo,"$&/")+"/")+t)),e.push(s)),1;if(o=0,n=n===""?".":n+":",Xo(t))for(var a=0;a<t.length;a++){i=t[a];var l=n+is(i,a);o+=Er(i,e,r,l,s)}else if(l=zd(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=n+is(i,a++),o+=Er(i,e,r,l,s);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return o}function br(t,e,r){if(t==null)return t;var n=[],s=0;return Er(t,n,"","",function(i){return e.call(r,i,s++)}),n}function Yd(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var he={current:null},Sr={transition:null},Xd={ReactCurrentDispatcher:he,ReactCurrentBatchConfig:Sr,ReactCurrentOwner:us};function oa(){throw Error("act(...) is not supported in production builds of React.")}U.Children={map:br,forEach:function(t,e,r){br(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return br(t,function(){e++}),e},toArray:function(t){return br(t,function(e){return e})||[]},only:function(t){if(!ls(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};U.Component=it;U.Fragment=Dd;U.Profiler=Bd;U.PureComponent=os;U.StrictMode=Fd;U.Suspense=Vd;U.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Xd;U.act=oa;U.cloneElement=function(t,e,r){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var n=ea({},t.props),s=t.key,i=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,o=us.current),e.key!==void 0&&(s=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)na.call(e,l)&&!sa.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:kt,type:t.type,key:s,ref:i,props:n,_owner:o}};U.createContext=function(t){return t={$$typeof:Md,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:qd,_context:t},t.Consumer=t};U.createElement=ia;U.createFactory=function(t){var e=ia.bind(null,t);return e.type=t,e};U.createRef=function(){return{current:null}};U.forwardRef=function(t){return{$$typeof:Wd,render:t}};U.isValidElement=ls;U.lazy=function(t){return{$$typeof:Kd,_payload:{_status:-1,_result:t},_init:Yd}};U.memo=function(t,e){return{$$typeof:Hd,type:t,compare:e===void 0?null:e}};U.startTransition=function(t){var e=Sr.transition;Sr.transition={};try{t()}finally{Sr.transition=e}};U.unstable_act=oa;U.useCallback=function(t,e){return he.current.useCallback(t,e)};U.useContext=function(t){return he.current.useContext(t)};U.useDebugValue=function(){};U.useDeferredValue=function(t){return he.current.useDeferredValue(t)};U.useEffect=function(t,e){return he.current.useEffect(t,e)};U.useId=function(){return he.current.useId()};U.useImperativeHandle=function(t,e,r){return he.current.useImperativeHandle(t,e,r)};U.useInsertionEffect=function(t,e){return he.current.useInsertionEffect(t,e)};U.useLayoutEffect=function(t,e){return he.current.useLayoutEffect(t,e)};U.useMemo=function(t,e){return he.current.useMemo(t,e)};U.useReducer=function(t,e,r){return he.current.useReducer(t,e,r)};U.useRef=function(t){return he.current.useRef(t)};U.useState=function(t){return he.current.useState(t)};U.useSyncExternalStore=function(t,e,r){return he.current.useSyncExternalStore(t,e,r)};U.useTransition=function(){return he.current.useTransition()};U.version="18.3.1"});var ua=$((L,Tr)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",e=Symbol.for("react.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,v="@@iterator";function w(u){if(u===null||typeof u!="object")return null;var d=y&&u[y]||u[v];return typeof d=="function"?d:null}var T={current:null},O={transition:null},E={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},x={current:null},Z={},W=null;function re(u){W=u}Z.setExtraStackFrame=function(u){W=u},Z.getCurrentStack=null,Z.getStackAddendum=function(){var u="";W&&(u+=W);var d=Z.getCurrentStack;return d&&(u+=d()||""),u};var ke=!1,Ee=!1,pa=!1,ma=!1,_a=!1,Me={ReactCurrentDispatcher:T,ReactCurrentBatchConfig:O,ReactCurrentOwner:x};Me.ReactDebugCurrentFrame=Z,Me.ReactCurrentActQueue=E;function We(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("warn",u,p)}}function q(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("error",u,p)}}function ds(u,d,p){{var g=Me.ReactDebugCurrentFrame,b=g.getStackAddendum();b!==""&&(d+="%s",p=p.concat([b]));var N=p.map(function(C){return String(C)});N.unshift("Warning: "+d),Function.prototype.apply.call(console[u],console,N)}}var hs={};function Rr(u,d){{var p=u.constructor,g=p&&(p.displayName||p.name)||"ReactClass",b=g+"."+d;if(hs[b])return;q("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",d,g),hs[b]=!0}}var fs={isMounted:function(u){return!1},enqueueForceUpdate:function(u,d,p){Rr(u,"forceUpdate")},enqueueReplaceState:function(u,d,p,g){Rr(u,"replaceState")},enqueueSetState:function(u,d,p,g){Rr(u,"setState")}},Ie=Object.assign,kr={};Object.freeze(kr);function Le(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}Le.prototype.isReactComponent={},Le.prototype.setState=function(u,d){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,d,"setState")},Le.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};{var Or={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},ga=function(u,d){Object.defineProperty(Le.prototype,u,{get:function(){We("%s(...) is deprecated in plain JavaScript React classes. %s",d[0],d[1])}})};for(var Cr in Or)Or.hasOwnProperty(Cr)&&ga(Cr,Or[Cr])}function ps(){}ps.prototype=Le.prototype;function Pr(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}var Ir=Pr.prototype=new ps;Ir.constructor=Pr,Ie(Ir,Le.prototype),Ir.isPureReactComponent=!0;function ya(){var u={current:null};return Object.seal(u),u}var va=Array.isArray;function Ot(u){return va(u)}function wa(u){{var d=typeof Symbol=="function"&&Symbol.toStringTag,p=d&&u[Symbol.toStringTag]||u.constructor.name||"Object";return p}}function ba(u){try{return ms(u),!1}catch{return!0}}function ms(u){return""+u}function Ct(u){if(ba(u))return q("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",wa(u)),ms(u)}function Ea(u,d,p){var g=u.displayName;if(g)return g;var b=d.displayName||d.name||"";return b!==""?p+"("+b+")":p}function _s(u){return u.displayName||"Context"}function je(u){if(u==null)return null;if(typeof u.tag=="number"&&q("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case n:return"Fragment";case r:return"Portal";case i:return"Profiler";case s:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case a:var d=u;return _s(d)+".Consumer";case o:var p=u;return _s(p._context)+".Provider";case l:return Ea(u,u.render,"ForwardRef");case m:var g=u.displayName||null;return g!==null?g:je(u.type)||"Memo";case _:{var b=u,N=b._payload,C=b._init;try{return je(C(N))}catch{return null}}}return null}var ot=Object.prototype.hasOwnProperty,gs={key:!0,ref:!0,__self:!0,__source:!0},ys,vs,xr;xr={};function ws(u){if(ot.call(u,"ref")){var d=Object.getOwnPropertyDescriptor(u,"ref").get;if(d&&d.isReactWarning)return!1}return u.ref!==void 0}function bs(u){if(ot.call(u,"key")){var d=Object.getOwnPropertyDescriptor(u,"key").get;if(d&&d.isReactWarning)return!1}return u.key!==void 0}function Sa(u,d){var p=function(){ys||(ys=!0,q("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"key",{get:p,configurable:!0})}function Ta(u,d){var p=function(){vs||(vs=!0,q("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"ref",{get:p,configurable:!0})}function Aa(u){if(typeof u.ref=="string"&&x.current&&u.__self&&x.current.stateNode!==u.__self){var d=je(x.current.type);xr[d]||(q('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',d,u.ref),xr[d]=!0)}}var Nr=function(u,d,p,g,b,N,C){var j={$$typeof:e,type:u,key:d,ref:p,props:C,_owner:N};return j._store={},Object.defineProperty(j._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(j,"_self",{configurable:!1,enumerable:!1,writable:!1,value:g}),Object.defineProperty(j,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(j.props),Object.freeze(j)),j};function Ra(u,d,p){var g,b={},N=null,C=null,j=null,B=null;if(d!=null){ws(d)&&(C=d.ref,Aa(d)),bs(d)&&(Ct(d.key),N=""+d.key),j=d.__self===void 0?null:d.__self,B=d.__source===void 0?null:d.__source;for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(b[g]=d[g])}var z=arguments.length-2;if(z===1)b.children=p;else if(z>1){for(var Y=Array(z),X=0;X<z;X++)Y[X]=arguments[X+2];Object.freeze&&Object.freeze(Y),b.children=Y}if(u&&u.defaultProps){var ee=u.defaultProps;for(g in ee)b[g]===void 0&&(b[g]=ee[g])}if(N||C){var ie=typeof u=="function"?u.displayName||u.name||"Unknown":u;N&&Sa(b,ie),C&&Ta(b,ie)}return Nr(u,N,C,j,B,x.current,b)}function ka(u,d){var p=Nr(u.type,d,u.ref,u._self,u._source,u._owner,u.props);return p}function Oa(u,d,p){if(u==null)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+u+".");var g,b=Ie({},u.props),N=u.key,C=u.ref,j=u._self,B=u._source,z=u._owner;if(d!=null){ws(d)&&(C=d.ref,z=x.current),bs(d)&&(Ct(d.key),N=""+d.key);var Y;u.type&&u.type.defaultProps&&(Y=u.type.defaultProps);for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(d[g]===void 0&&Y!==void 0?b[g]=Y[g]:b[g]=d[g])}var X=arguments.length-2;if(X===1)b.children=p;else if(X>1){for(var ee=Array(X),ie=0;ie<X;ie++)ee[ie]=arguments[ie+2];b.children=ee}return Nr(u.type,N,C,j,B,z,b)}function Ve(u){return typeof u=="object"&&u!==null&&u.$$typeof===e}var Es=".",Ca=":";function Pa(u){var d=/[=:]/g,p={"=":"=0",":":"=2"},g=u.replace(d,function(b){return p[b]});return"$"+g}var Ss=!1,Ia=/\/+/g;function Ts(u){return u.replace(Ia,"$&/")}function jr(u,d){return typeof u=="object"&&u!==null&&u.key!=null?(Ct(u.key),Pa(""+u.key)):d.toString(36)}function Pt(u,d,p,g,b){var N=typeof u;(N==="undefined"||N==="boolean")&&(u=null);var C=!1;if(u===null)C=!0;else switch(N){case"string":case"number":C=!0;break;case"object":switch(u.$$typeof){case e:case r:C=!0}}if(C){var j=u,B=b(j),z=g===""?Es+jr(j,0):g;if(Ot(B)){var Y="";z!=null&&(Y=Ts(z)+"/"),Pt(B,d,Y,"",function(Su){return Su})}else B!=null&&(Ve(B)&&(B.key&&(!j||j.key!==B.key)&&Ct(B.key),B=ka(B,p+(B.key&&(!j||j.key!==B.key)?Ts(""+B.key)+"/":"")+z)),d.push(B));return 1}var X,ee,ie=0,le=g===""?Es:g+Ca;if(Ot(u))for(var Dt=0;Dt<u.length;Dt++)X=u[Dt],ee=le+jr(X,Dt),ie+=Pt(X,d,p,ee,b);else{var Wr=w(u);if(typeof Wr=="function"){var Js=u;Wr===Js.entries&&(Ss||We("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ss=!0);for(var bu=Wr.call(Js),Ys,Eu=0;!(Ys=bu.next()).done;)X=Ys.value,ee=le+jr(X,Eu++),ie+=Pt(X,d,p,ee,b)}else if(N==="object"){var Xs=String(u);throw new Error("Objects are not valid as a React child (found: "+(Xs==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":Xs)+"). If you meant to render a collection of children, use an array instead.")}}return ie}function It(u,d,p){if(u==null)return u;var g=[],b=0;return Pt(u,g,"","",function(N){return d.call(p,N,b++)}),g}function xa(u){var d=0;return It(u,function(){d++}),d}function Na(u,d,p){It(u,function(){d.apply(this,arguments)},p)}function ja(u){return It(u,function(d){return d})||[]}function Ua(u){if(!Ve(u))throw new Error("React.Children.only expected to receive a single React element child.");return u}function La(u){var d={$$typeof:a,_currentValue:u,_currentValue2:u,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};d.Provider={$$typeof:o,_context:d};var p=!1,g=!1,b=!1;{var N={$$typeof:a,_context:d};Object.defineProperties(N,{Provider:{get:function(){return g||(g=!0,q("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),d.Provider},set:function(C){d.Provider=C}},_currentValue:{get:function(){return d._currentValue},set:function(C){d._currentValue=C}},_currentValue2:{get:function(){return d._currentValue2},set:function(C){d._currentValue2=C}},_threadCount:{get:function(){return d._threadCount},set:function(C){d._threadCount=C}},Consumer:{get:function(){return p||(p=!0,q("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),d.Consumer}},displayName:{get:function(){return d.displayName},set:function(C){b||(We("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",C),b=!0)}}}),d.Consumer=N}return d._currentRenderer=null,d._currentRenderer2=null,d}var at=-1,Ur=0,As=1,$a=2;function Da(u){if(u._status===at){var d=u._result,p=d();if(p.then(function(N){if(u._status===Ur||u._status===at){var C=u;C._status=As,C._result=N}},function(N){if(u._status===Ur||u._status===at){var C=u;C._status=$a,C._result=N}}),u._status===at){var g=u;g._status=Ur,g._result=p}}if(u._status===As){var b=u._result;return b===void 0&&q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
41
+ ${T}`}});var Eo=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebAuthnUnknownError=Ne.WebAuthnError=void 0;Ne.isWebAuthnError=Mc;Ne.identifyRegistrationError=Wc;Ne.identifyAuthenticationError=Vc;var bo=Jn(),te=class extends Error{constructor({message:e,code:r,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s??(n instanceof Error?n.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};Ne.WebAuthnError=te;var Gn=class extends te{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};Ne.WebAuthnUnknownError=Gn;function Mc(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Wc({error:t,options:e}){var r,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new te({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new te({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new te({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new te({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new te({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new te({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if((0,bo.isValidDomain)(o)){if(i.rp.id!==o)return new te({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new te({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Vc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if((0,bo.isValidDomain)(n)){if(r.rpId!==n)return new te({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Jn=$(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.WebAuthnApi=M.DEFAULT_REQUEST_OPTIONS=M.DEFAULT_CREATION_OPTIONS=M.webAuthnAbortService=M.WebAuthnAbortService=M.identifyAuthenticationError=M.identifyRegistrationError=M.isWebAuthnError=M.WebAuthnError=void 0;M.deserializeCredentialCreationOptions=Kc;M.deserializeCredentialRequestOptions=zc;M.serializeCredentialCreationResponse=Gc;M.serializeCredentialRequestResponse=Jc;M.isValidDomain=Yc;M.createCredential=Ao;M.getCredential=Ro;M.mergeCredentialCreationOptions=ko;M.mergeCredentialRequestOptions=Oo;var To=(ge(),Se(_e)),Re=or(),Ce=De(),Hc=tt(),Pe=Eo();Object.defineProperty(M,"identifyAuthenticationError",{enumerable:!0,get:function(){return Pe.identifyAuthenticationError}});Object.defineProperty(M,"identifyRegistrationError",{enumerable:!0,get:function(){return Pe.identifyRegistrationError}});Object.defineProperty(M,"isWebAuthnError",{enumerable:!0,get:function(){return Pe.isWebAuthnError}});Object.defineProperty(M,"WebAuthnError",{enumerable:!0,get:function(){return Pe.WebAuthnError}});var hr=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};M.WebAuthnAbortService=hr;M.webAuthnAbortService=new hr;function Kc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,s=To.__rest(t,["challenge","user","excludeCredentials"]),i=(0,Re.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,Re.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,Re.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function zc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=To.__rest(t,["challenge","allowCredentials"]),s=(0,Re.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:(0,Re.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function Gc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Jc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,Re.bytesToBase64URL)(new Uint8Array(s.authenticatorData)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(s.clientDataJSON)),signature:(0,Re.bytesToBase64URL)(new Uint8Array(s.signature)),userHandle:s.userHandle?(0,Re.bytesToBase64URL)(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Yc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function So(){var t,e;return!!((0,Hc.isBrowser)()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Ao(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyRegistrationError)({error:e,options:t})}}}async function Ro(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyAuthenticationError)({error:e,options:t})}}}M.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};M.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function fr(...t){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of t)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(r(o))n[i]=o;else if(e(o)){let a=n[i];e(a)?n[i]=fr(a,o):n[i]=fr(o)}else n[i]=o}return n}function ko(t,e){return fr(M.DEFAULT_CREATION_OPTIONS,t,e||{})}function Oo(t,e){return fr(M.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Yn=class{constructor(e){this.client=e,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(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:s},i){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let c=s??M.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:h}=a.webauthn.credential_options.publicKey;if(!h.name){let m=n;if(m)h.name=`${h.id}:${m}`;else{let f=(await this.client.getUser()).data.user,y=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";h.name=`${h.id}:${y}`}}h.displayName||(h.displayName=h.name)}switch(a.webauthn.type){case"create":{let h=ko(a.webauthn.credential_options.publicKey,i?.create),{data:m,error:_}=await Ao({publicKey:h,signal:c});return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}case"request":{let h=Oo(a.webauthn.credential_options.publicKey,i?.request),{data:m,error:_}=await Ro(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:h,signal:c}));return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}}}catch(a){return(0,Ce.isAuthError)(a)?{data:null,error:a}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn authentication")};try{if(!So())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn registration")};try{if(!So())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var m;return(m=h.data)===null||m===void 0?void 0:m.all.find(_=>_.factor_type==="webauthn"&&_.friendly_name===e&&_.status!=="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in register",o)}}}};M.WebAuthnApi=Yn});var Qn=$(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});var Xc=(ge(),Se(_e)),Qc=Xc.__importDefault(cr()),pe=sr(),S=De(),I=Bn(),R=tt(),Co=_o(),Po=Kn(),Zc=yo(),ed=Sn(),Io=or(),pr=wo(),St=Jn();(0,Zc.polyfillGlobalThis)();var td={url:pe.GOTRUE_URL,storageKey:pe.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:pe.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function xo(t,e,r){return await r()}var nt={},mr=class t{get jwks(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},td),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&(0,R.isBrowser)()){let o=`${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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Qc.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,R.resolveFetch)(i.fetch),this.lock=i.lock||xo,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&(0,R.isBrowser)()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Po.navigatorLock:this.lock=xo,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 St.WebAuthnApi(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.persistSession?(i.storage?this.storage=i.storage:(0,R.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),(0,R.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ed.version}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if((0,R.isBrowser)()&&(r=(0,R.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),(0,R.isBrowser)()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,S.isAuthImplicitGrantRedirectError)(i)){let l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return(0,S.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new S.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,s;try{let i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:I._sessionResponse}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if((0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,n,s;try{let i;if("email"in e){let{email:h,password:m,options:_}=e,f=null,y=null;this.flowType==="pkce"&&([f,y]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:_?.emailRedirectTo,body:{email:h,password:m,data:(r=_?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:_?.captchaToken},code_challenge:f,code_challenge_method:y},xform:I._sessionResponse})}else if("phone"in e){let{phone:h,password:m,options:_}=e;i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=_?.data)!==null&&n!==void 0?n:{},channel:(s=_?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:_?.captchaToken}},xform:I._sessionResponse})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,s,i,o,a,l,c,h,m,_;let f,y;if("message"in e)f=e.message,y=e.signature;else{let{chain:v,wallet:w,statement:T,options:O}=e,E;if((0,R.isBrowser)())if(typeof w=="object")E=w;else{let Ee=window;if("ethereum"in Ee&&typeof Ee.ethereum=="object"&&"request"in Ee.ethereum&&typeof Ee.ethereum.request=="function")E=Ee.ethereum;else throw new 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(typeof w!="object"||!O?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=w}let x=new URL((r=O?.url)!==null&&r!==void 0?r:window.location.href),Z=await E.request({method:"eth_requestAccounts"}).then(Ee=>Ee).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let W=(0,pr.getAddress)(Z[0]),re=(n=O?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!re){let Ee=await E.request({method:"eth_chainId"});re=(0,pr.fromHex)(Ee)}let ke={domain:x.host,address:W,statement:T,uri:x.href,version:"1",chainId:re,nonce:(s=O?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=O?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=O?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=O?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=O?.signInWithEthereum)===null||h===void 0?void 0:h.resources};f=(0,pr.createSiweMessage)(ke),y=await E.request({method:"personal_sign",params:[(0,pr.toHex)(f),W]})}try{let{data:v,error:w}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:I._sessionResponse});if(w)throw w;if(!v||!v.session||!v.user){let T=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:T})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:w})}catch(v){if((0,S.isAuthError)(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,s,i,o,a,l,c,h,m,_,f;let y,v;if("message"in e)y=e.message,v=e.signature;else{let{chain:w,wallet:T,statement:O,options:E}=e,x;if((0,R.isBrowser)())if(typeof T=="object")x=T;else{let W=window;if("solana"in W&&typeof W.solana=="object"&&("signIn"in W.solana&&typeof W.solana.signIn=="function"||"signMessage"in W.solana&&typeof W.solana.signMessage=="function"))x=W.solana;else throw new 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(typeof T!="object"||!E?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=T}let Z=new URL((r=E?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){let W=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},E?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),O?{statement:O}:null)),re;if(Array.isArray(W)&&W[0]&&typeof W[0]=="object")re=W[0];else if(W&&typeof W=="object"&&"signedMessage"in W&&"signature"in W)re=W;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in re&&"signature"in re&&(typeof re.signedMessage=="string"||re.signedMessage instanceof Uint8Array)&&re.signature instanceof Uint8Array)y=typeof re.signedMessage=="string"?re.signedMessage:new TextDecoder().decode(re.signedMessage),v=re.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${Z.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(s=(n=E?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=E?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${E.signInWithSolana.notBefore}`]:[],...!((o=E?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${E.signInWithSolana.expirationTime}`]:[],...!((a=E?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${E.signInWithSolana.chainId}`]:[],...!((l=E?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${E.signInWithSolana.nonce}`]:[],...!((c=E?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${E.signInWithSolana.requestId}`]:[],...!((m=(h=E?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||m===void 0)&&m.length?["Resources",...E.signInWithSolana.resources.map(re=>`- ${re}`)]:[]].join(`
42
+ `);let W=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{let{data:w,error:T}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:(0,Io.bytesToBase64URL)(v)},!((_=e.options)===null||_===void 0)&&_.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:I._sessionResponse});if(T)throw T;if(!w||!w.session||!w.user){let O=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:O})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:T})}catch(w){if((0,S.isAuthError)(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async _exchangeCodeForSession(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new S.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:I._sessionResponse});if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:n,token:s,access_token:i,nonce:o}=e,a=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:I._sessionResponse}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let h=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:h})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,s,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,h=null;this.flowType==="pkce"&&([c,h]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:m}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:m})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:h}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:h})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let s,i;"options"in e&&(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await(0,I._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:I._sessionResponse});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if((0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var r,n,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,I._request)(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:I._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,R.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new S.AuthSessionMissingError;let{error:s}=await(0,I._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:a}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await(0,R.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<pe.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,R.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,R.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:I._userResponse}):await this._useSession(async r=>{var n,s,i;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new S.AuthSessionMissingError}:await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:I._userResponse})})}catch(r){if((0,S.isAuthError)(r))return(0,S.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new S.AuthSessionMissingError;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:h}=await(0,I._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:I._userResponse});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S.AuthSessionMissingError;let r=Date.now()/1e3,n=r,s=!0,i=null,{payload:o}=(0,R.decodeJWT)(e.access_token);if(o.exp&&(n=o.exp,s=n<=r),s){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new S.AuthSessionMissingError;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,R.isBrowser)())throw new S.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new S.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new S.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new S.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new S.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:O,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new S.AuthImplicitGrantRedirectError("No session defined in URL");let h=Math.round(Date.now()/1e3),m=parseInt(a),_=h+m;l&&(_=parseInt(l));let f=_-h;f*1e3<=pe.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${m}s`);let y=_-m;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,_,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,_,h);let{data:v,error:w}=await this._getUser(i);if(w)throw w;let T={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:_,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:T,redirectType:e.type},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i&&!(0,S.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,S.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,S.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,R.generateCallbackId)(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,s;try{let{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,I._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:s}=await this._useSession(async i=>{var o,a,l,c,h;let{data:m,error:_}=i;if(_)throw _;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await(0,I._request)(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=m.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(s)throw s;return(0,R.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:s,data:{session:i}}=r;if(s)throw s;let{options:o,provider:a,token:l,access_token:c,nonce:h}=e,m=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:I._sessionResponse}),{data:_,error:f}=m;return f?this._returnResult({data:{user:null,session:null},error:f}):!_||!_.session||!_.user?this._returnResult({data:{user:null,session:null},error:new S.AuthInvalidTokenResponseError}):(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("USER_UPDATED",_.session)),this._returnResult({data:_,error:f}))}catch(s){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)throw o;return await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await(0,R.retryable)(async s=>(s>0&&await(0,R.sleep)(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I._sessionResponse})),(s,i)=>{let o=200*Math.pow(2,s);return i&&(0,S.isAuthRetryableFetchError)(i)&&Date.now()+o-n<pe.AUTO_REFRESH_TICK_DURATION_MS})}catch(n){if(this._debug(r,"error",n),(0,S.isAuthError)(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),(0,R.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await(0,R.getItemAsync)(this.storage,this.storageKey);if(s&&this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:(0,R.userNotAvailableProxy)()}else if(s&&!s.user&&!s.user){let o=await(0,R.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,R.setItemAsync)(this.storage,this.storageKey,s)):s.user=(0,R.userNotAvailableProxy)()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((r=s.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<pe.EXPIRY_MARGIN_MS;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${pe.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),(0,S.isAuthRetryableFetchError)(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new S.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new R.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new S.AuthSessionMissingError;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(s,"error",i),(0,S.isAuthError)(i)){let o={data:null,error:i};return(0,S.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,r,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let s=Object.assign({},r);delete s.user;let i=(0,R.deepClone)(s);await(0,R.setItemAsync)(this.storage,this.storageKey,i)}else{let s=(0,R.deepClone)(r);await(0,R.setItemAsync)(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,R.removeItemAsync)(this.storage,this.storageKey),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,R.removeItemAsync)(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&(0,R.isBrowser)()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),pe.AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/pe.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${pe.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${pe.AUTO_REFRESH_TICK_THRESHOLD} ticks`),s<=pe.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Po.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,R.isBrowser)()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let s=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(n?.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,I._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,St.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,St.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialCreationOptions)(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,s,i;if(e)try{let{payload:f}=(0,R.decodeJWT)(e),y=null;f.aal&&(y=f.aal);let v=y,{data:{user:w},error:T}=await this.getUser(e);if(T)return this._returnResult({data:null,error:T});((n=(r=w?.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(v="aal2");let E=f.amr||[];return{data:{currentLevel:y,nextLevel:v,currentAuthenticationMethods:E},error:null}}catch(f){if((0,S.isAuthError)(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=(0,R.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let h=c;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let _=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:_},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await(0,I._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await(0,I._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+pe.JWKS_TTL>s)return n;let{data:i,error:o}=await(0,I._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});n=f.session.access_token}let{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=(0,R.decodeJWT)(n);r?.allowExpired||(0,R.validateExp)(i.exp);let c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}let h=(0,R.getAlgorithm)(s.alg),m=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,o,(0,Io.stringToUint8Array)(`${a}.${l}`)))throw new S.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}};mr.nextInstanceID={};Xn.default=mr});var No=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var rd=(ge(),Se(_e)),nd=rd.__importDefault(cr()),sd=nd.default;Zn.default=sd});var jo=$(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var id=(ge(),Se(_e)),od=id.__importDefault(Qn()),ad=od.default;es.default=ad});var ts=$(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.processLock=ae.lockInternals=ae.NavigatorLockAcquireTimeoutError=ae.navigatorLock=ae.AuthClient=ae.AuthAdminApi=ae.GoTrueClient=ae.GoTrueAdminApi=void 0;var st=(ge(),Se(_e)),ud=st.__importDefault(cr());ae.GoTrueAdminApi=ud.default;var ld=st.__importDefault(Qn());ae.GoTrueClient=ld.default;var cd=st.__importDefault(No());ae.AuthAdminApi=cd.default;var dd=st.__importDefault(jo());ae.AuthClient=dd.default;st.__exportStar(qn(),ae);st.__exportStar(De(),ae);var _r=Kn();Object.defineProperty(ae,"navigatorLock",{enumerable:!0,get:function(){return _r.navigatorLock}});Object.defineProperty(ae,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return _r.NavigatorLockAcquireTimeoutError}});Object.defineProperty(ae,"lockInternals",{enumerable:!0,get:function(){return _r.internals}});Object.defineProperty(ae,"processLock",{enumerable:!0,get:function(){return _r.processLock}})});var ua=$(L=>{"use strict";var kt=Symbol.for("react.element"),Dd=Symbol.for("react.portal"),Fd=Symbol.for("react.fragment"),Bd=Symbol.for("react.strict_mode"),qd=Symbol.for("react.profiler"),Md=Symbol.for("react.provider"),Wd=Symbol.for("react.context"),Vd=Symbol.for("react.forward_ref"),Hd=Symbol.for("react.suspense"),Kd=Symbol.for("react.memo"),zd=Symbol.for("react.lazy"),Xo=Symbol.iterator;function Gd(t){return t===null||typeof t!="object"?null:(t=Xo&&t[Xo]||t["@@iterator"],typeof t=="function"?t:null)}var ea={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ta=Object.assign,ra={};function it(t,e,r){this.props=t,this.context=e,this.refs=ra,this.updater=r||ea}it.prototype.isReactComponent={};it.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};it.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function na(){}na.prototype=it.prototype;function os(t,e,r){this.props=t,this.context=e,this.refs=ra,this.updater=r||ea}var as=os.prototype=new na;as.constructor=os;ta(as,it.prototype);as.isPureReactComponent=!0;var Qo=Array.isArray,sa=Object.prototype.hasOwnProperty,us={current:null},ia={key:!0,ref:!0,__self:!0,__source:!0};function oa(t,e,r){var n,s={},i=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)sa.call(e,n)&&!ia.hasOwnProperty(n)&&(s[n]=e[n]);var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];s.children=l}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)s[n]===void 0&&(s[n]=a[n]);return{$$typeof:kt,type:t,key:i,ref:o,props:s,_owner:us.current}}function Jd(t,e){return{$$typeof:kt,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function ls(t){return typeof t=="object"&&t!==null&&t.$$typeof===kt}function Yd(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var Zo=/\/+/g;function is(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Yd(""+t.key):e.toString(36)}function Er(t,e,r,n,s){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(i){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case kt:case Dd:o=!0}}if(o)return o=t,s=s(o),t=n===""?"."+is(o,0):n,Qo(s)?(r="",t!=null&&(r=t.replace(Zo,"$&/")+"/"),Er(s,e,r,"",function(c){return c})):s!=null&&(ls(s)&&(s=Jd(s,r+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(Zo,"$&/")+"/")+t)),e.push(s)),1;if(o=0,n=n===""?".":n+":",Qo(t))for(var a=0;a<t.length;a++){i=t[a];var l=n+is(i,a);o+=Er(i,e,r,l,s)}else if(l=Gd(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=n+is(i,a++),o+=Er(i,e,r,l,s);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return o}function br(t,e,r){if(t==null)return t;var n=[],s=0;return Er(t,n,"","",function(i){return e.call(r,i,s++)}),n}function Xd(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var he={current:null},Sr={transition:null},Qd={ReactCurrentDispatcher:he,ReactCurrentBatchConfig:Sr,ReactCurrentOwner:us};function aa(){throw Error("act(...) is not supported in production builds of React.")}L.Children={map:br,forEach:function(t,e,r){br(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return br(t,function(){e++}),e},toArray:function(t){return br(t,function(e){return e})||[]},only:function(t){if(!ls(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};L.Component=it;L.Fragment=Fd;L.Profiler=qd;L.PureComponent=os;L.StrictMode=Bd;L.Suspense=Hd;L.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Qd;L.act=aa;L.cloneElement=function(t,e,r){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var n=ta({},t.props),s=t.key,i=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,o=us.current),e.key!==void 0&&(s=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)sa.call(e,l)&&!ia.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:kt,type:t.type,key:s,ref:i,props:n,_owner:o}};L.createContext=function(t){return t={$$typeof:Wd,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:Md,_context:t},t.Consumer=t};L.createElement=oa;L.createFactory=function(t){var e=oa.bind(null,t);return e.type=t,e};L.createRef=function(){return{current:null}};L.forwardRef=function(t){return{$$typeof:Vd,render:t}};L.isValidElement=ls;L.lazy=function(t){return{$$typeof:zd,_payload:{_status:-1,_result:t},_init:Xd}};L.memo=function(t,e){return{$$typeof:Kd,type:t,compare:e===void 0?null:e}};L.startTransition=function(t){var e=Sr.transition;Sr.transition={};try{t()}finally{Sr.transition=e}};L.unstable_act=aa;L.useCallback=function(t,e){return he.current.useCallback(t,e)};L.useContext=function(t){return he.current.useContext(t)};L.useDebugValue=function(){};L.useDeferredValue=function(t){return he.current.useDeferredValue(t)};L.useEffect=function(t,e){return he.current.useEffect(t,e)};L.useId=function(){return he.current.useId()};L.useImperativeHandle=function(t,e,r){return he.current.useImperativeHandle(t,e,r)};L.useInsertionEffect=function(t,e){return he.current.useInsertionEffect(t,e)};L.useLayoutEffect=function(t,e){return he.current.useLayoutEffect(t,e)};L.useMemo=function(t,e){return he.current.useMemo(t,e)};L.useReducer=function(t,e,r){return he.current.useReducer(t,e,r)};L.useRef=function(t){return he.current.useRef(t)};L.useState=function(t){return he.current.useState(t)};L.useSyncExternalStore=function(t,e,r){return he.current.useSyncExternalStore(t,e,r)};L.useTransition=function(){return he.current.useTransition()};L.version="18.3.1"});var la=$((U,Tr)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",e=Symbol.for("react.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,v="@@iterator";function w(u){if(u===null||typeof u!="object")return null;var d=y&&u[y]||u[v];return typeof d=="function"?d:null}var T={current:null},O={transition:null},E={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},x={current:null},Z={},W=null;function re(u){W=u}Z.setExtraStackFrame=function(u){W=u},Z.getCurrentStack=null,Z.getStackAddendum=function(){var u="";W&&(u+=W);var d=Z.getCurrentStack;return d&&(u+=d()||""),u};var ke=!1,Ee=!1,ma=!1,_a=!1,ga=!1,Me={ReactCurrentDispatcher:T,ReactCurrentBatchConfig:O,ReactCurrentOwner:x};Me.ReactDebugCurrentFrame=Z,Me.ReactCurrentActQueue=E;function We(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("warn",u,p)}}function q(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("error",u,p)}}function ds(u,d,p){{var g=Me.ReactDebugCurrentFrame,b=g.getStackAddendum();b!==""&&(d+="%s",p=p.concat([b]));var N=p.map(function(C){return String(C)});N.unshift("Warning: "+d),Function.prototype.apply.call(console[u],console,N)}}var hs={};function Rr(u,d){{var p=u.constructor,g=p&&(p.displayName||p.name)||"ReactClass",b=g+"."+d;if(hs[b])return;q("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",d,g),hs[b]=!0}}var fs={isMounted:function(u){return!1},enqueueForceUpdate:function(u,d,p){Rr(u,"forceUpdate")},enqueueReplaceState:function(u,d,p,g){Rr(u,"replaceState")},enqueueSetState:function(u,d,p,g){Rr(u,"setState")}},Ie=Object.assign,kr={};Object.freeze(kr);function Ue(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}Ue.prototype.isReactComponent={},Ue.prototype.setState=function(u,d){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,d,"setState")},Ue.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};{var Or={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},ya=function(u,d){Object.defineProperty(Ue.prototype,u,{get:function(){We("%s(...) is deprecated in plain JavaScript React classes. %s",d[0],d[1])}})};for(var Cr in Or)Or.hasOwnProperty(Cr)&&ya(Cr,Or[Cr])}function ps(){}ps.prototype=Ue.prototype;function Pr(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}var Ir=Pr.prototype=new ps;Ir.constructor=Pr,Ie(Ir,Ue.prototype),Ir.isPureReactComponent=!0;function va(){var u={current:null};return Object.seal(u),u}var wa=Array.isArray;function Ot(u){return wa(u)}function ba(u){{var d=typeof Symbol=="function"&&Symbol.toStringTag,p=d&&u[Symbol.toStringTag]||u.constructor.name||"Object";return p}}function Ea(u){try{return ms(u),!1}catch{return!0}}function ms(u){return""+u}function Ct(u){if(Ea(u))return q("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ba(u)),ms(u)}function Sa(u,d,p){var g=u.displayName;if(g)return g;var b=d.displayName||d.name||"";return b!==""?p+"("+b+")":p}function _s(u){return u.displayName||"Context"}function je(u){if(u==null)return null;if(typeof u.tag=="number"&&q("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case n:return"Fragment";case r:return"Portal";case i:return"Profiler";case s:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case a:var d=u;return _s(d)+".Consumer";case o:var p=u;return _s(p._context)+".Provider";case l:return Sa(u,u.render,"ForwardRef");case m:var g=u.displayName||null;return g!==null?g:je(u.type)||"Memo";case _:{var b=u,N=b._payload,C=b._init;try{return je(C(N))}catch{return null}}}return null}var ot=Object.prototype.hasOwnProperty,gs={key:!0,ref:!0,__self:!0,__source:!0},ys,vs,xr;xr={};function ws(u){if(ot.call(u,"ref")){var d=Object.getOwnPropertyDescriptor(u,"ref").get;if(d&&d.isReactWarning)return!1}return u.ref!==void 0}function bs(u){if(ot.call(u,"key")){var d=Object.getOwnPropertyDescriptor(u,"key").get;if(d&&d.isReactWarning)return!1}return u.key!==void 0}function Ta(u,d){var p=function(){ys||(ys=!0,q("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"key",{get:p,configurable:!0})}function Aa(u,d){var p=function(){vs||(vs=!0,q("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"ref",{get:p,configurable:!0})}function Ra(u){if(typeof u.ref=="string"&&x.current&&u.__self&&x.current.stateNode!==u.__self){var d=je(x.current.type);xr[d]||(q('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',d,u.ref),xr[d]=!0)}}var Nr=function(u,d,p,g,b,N,C){var j={$$typeof:e,type:u,key:d,ref:p,props:C,_owner:N};return j._store={},Object.defineProperty(j._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(j,"_self",{configurable:!1,enumerable:!1,writable:!1,value:g}),Object.defineProperty(j,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(j.props),Object.freeze(j)),j};function ka(u,d,p){var g,b={},N=null,C=null,j=null,B=null;if(d!=null){ws(d)&&(C=d.ref,Ra(d)),bs(d)&&(Ct(d.key),N=""+d.key),j=d.__self===void 0?null:d.__self,B=d.__source===void 0?null:d.__source;for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(b[g]=d[g])}var z=arguments.length-2;if(z===1)b.children=p;else if(z>1){for(var Y=Array(z),X=0;X<z;X++)Y[X]=arguments[X+2];Object.freeze&&Object.freeze(Y),b.children=Y}if(u&&u.defaultProps){var ee=u.defaultProps;for(g in ee)b[g]===void 0&&(b[g]=ee[g])}if(N||C){var ie=typeof u=="function"?u.displayName||u.name||"Unknown":u;N&&Ta(b,ie),C&&Aa(b,ie)}return Nr(u,N,C,j,B,x.current,b)}function Oa(u,d){var p=Nr(u.type,d,u.ref,u._self,u._source,u._owner,u.props);return p}function Ca(u,d,p){if(u==null)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+u+".");var g,b=Ie({},u.props),N=u.key,C=u.ref,j=u._self,B=u._source,z=u._owner;if(d!=null){ws(d)&&(C=d.ref,z=x.current),bs(d)&&(Ct(d.key),N=""+d.key);var Y;u.type&&u.type.defaultProps&&(Y=u.type.defaultProps);for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(d[g]===void 0&&Y!==void 0?b[g]=Y[g]:b[g]=d[g])}var X=arguments.length-2;if(X===1)b.children=p;else if(X>1){for(var ee=Array(X),ie=0;ie<X;ie++)ee[ie]=arguments[ie+2];b.children=ee}return Nr(u.type,N,C,j,B,z,b)}function Ve(u){return typeof u=="object"&&u!==null&&u.$$typeof===e}var Es=".",Pa=":";function Ia(u){var d=/[=:]/g,p={"=":"=0",":":"=2"},g=u.replace(d,function(b){return p[b]});return"$"+g}var Ss=!1,xa=/\/+/g;function Ts(u){return u.replace(xa,"$&/")}function jr(u,d){return typeof u=="object"&&u!==null&&u.key!=null?(Ct(u.key),Ia(""+u.key)):d.toString(36)}function Pt(u,d,p,g,b){var N=typeof u;(N==="undefined"||N==="boolean")&&(u=null);var C=!1;if(u===null)C=!0;else switch(N){case"string":case"number":C=!0;break;case"object":switch(u.$$typeof){case e:case r:C=!0}}if(C){var j=u,B=b(j),z=g===""?Es+jr(j,0):g;if(Ot(B)){var Y="";z!=null&&(Y=Ts(z)+"/"),Pt(B,d,Y,"",function(Tu){return Tu})}else B!=null&&(Ve(B)&&(B.key&&(!j||j.key!==B.key)&&Ct(B.key),B=Oa(B,p+(B.key&&(!j||j.key!==B.key)?Ts(""+B.key)+"/":"")+z)),d.push(B));return 1}var X,ee,ie=0,le=g===""?Es:g+Pa;if(Ot(u))for(var Dt=0;Dt<u.length;Dt++)X=u[Dt],ee=le+jr(X,Dt),ie+=Pt(X,d,p,ee,b);else{var Wr=w(u);if(typeof Wr=="function"){var Js=u;Wr===Js.entries&&(Ss||We("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ss=!0);for(var Eu=Wr.call(Js),Ys,Su=0;!(Ys=Eu.next()).done;)X=Ys.value,ee=le+jr(X,Su++),ie+=Pt(X,d,p,ee,b)}else if(N==="object"){var Xs=String(u);throw new Error("Objects are not valid as a React child (found: "+(Xs==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":Xs)+"). If you meant to render a collection of children, use an array instead.")}}return ie}function It(u,d,p){if(u==null)return u;var g=[],b=0;return Pt(u,g,"","",function(N){return d.call(p,N,b++)}),g}function Na(u){var d=0;return It(u,function(){d++}),d}function ja(u,d,p){It(u,function(){d.apply(this,arguments)},p)}function La(u){return It(u,function(d){return d})||[]}function Ua(u){if(!Ve(u))throw new Error("React.Children.only expected to receive a single React element child.");return u}function $a(u){var d={$$typeof:a,_currentValue:u,_currentValue2:u,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};d.Provider={$$typeof:o,_context:d};var p=!1,g=!1,b=!1;{var N={$$typeof:a,_context:d};Object.defineProperties(N,{Provider:{get:function(){return g||(g=!0,q("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),d.Provider},set:function(C){d.Provider=C}},_currentValue:{get:function(){return d._currentValue},set:function(C){d._currentValue=C}},_currentValue2:{get:function(){return d._currentValue2},set:function(C){d._currentValue2=C}},_threadCount:{get:function(){return d._threadCount},set:function(C){d._threadCount=C}},Consumer:{get:function(){return p||(p=!0,q("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),d.Consumer}},displayName:{get:function(){return d.displayName},set:function(C){b||(We("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",C),b=!0)}}}),d.Consumer=N}return d._currentRenderer=null,d._currentRenderer2=null,d}var at=-1,Lr=0,As=1,Da=2;function Fa(u){if(u._status===at){var d=u._result,p=d();if(p.then(function(N){if(u._status===Lr||u._status===at){var C=u;C._status=As,C._result=N}},function(N){if(u._status===Lr||u._status===at){var C=u;C._status=Da,C._result=N}}),u._status===at){var g=u;g._status=Lr,g._result=p}}if(u._status===As){var b=u._result;return b===void 0&&q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
43
43
 
44
44
  Your code should look like:
45
45
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -47,22 +47,22 @@ Your code should look like:
47
47
  Did you accidentally put curly braces around the import?`,b),"default"in b||q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
48
48
 
49
49
  Your code should look like:
50
- const MyComponent = lazy(() => import('./MyComponent'))`,b),b.default}else throw u._result}function Fa(u){var d={_status:at,_result:u},p={$$typeof:_,_payload:d,_init:Da};{var g,b;Object.defineProperties(p,{defaultProps:{configurable:!0,get:function(){return g},set:function(N){q("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),g=N,Object.defineProperty(p,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return b},set:function(N){q("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),b=N,Object.defineProperty(p,"propTypes",{enumerable:!0})}}})}return p}function Ba(u){u!=null&&u.$$typeof===m?q("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof u!="function"?q("forwardRef requires a render function but was given %s.",u===null?"null":typeof u):u.length!==0&&u.length!==2&&q("forwardRef render functions accept exactly two parameters: props and ref. %s",u.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),u!=null&&(u.defaultProps!=null||u.propTypes!=null)&&q("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var d={$$typeof:l,render:u};{var p;Object.defineProperty(d,"displayName",{enumerable:!1,configurable:!0,get:function(){return p},set:function(g){p=g,!u.name&&!u.displayName&&(u.displayName=g)}})}return d}var Rs;Rs=Symbol.for("react.module.reference");function ks(u){return!!(typeof u=="string"||typeof u=="function"||u===n||u===i||_a||u===s||u===c||u===h||ma||u===f||ke||Ee||pa||typeof u=="object"&&u!==null&&(u.$$typeof===_||u.$$typeof===m||u.$$typeof===o||u.$$typeof===a||u.$$typeof===l||u.$$typeof===Rs||u.getModuleId!==void 0))}function qa(u,d){ks(u)||q("memo: The first argument must be a component. Instead received: %s",u===null?"null":typeof u);var p={$$typeof:m,type:u,compare:d===void 0?null:d};{var g;Object.defineProperty(p,"displayName",{enumerable:!1,configurable:!0,get:function(){return g},set:function(b){g=b,!u.name&&!u.displayName&&(u.displayName=b)}})}return p}function de(){var u=T.current;return u===null&&q(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
50
+ const MyComponent = lazy(() => import('./MyComponent'))`,b),b.default}else throw u._result}function Ba(u){var d={_status:at,_result:u},p={$$typeof:_,_payload:d,_init:Fa};{var g,b;Object.defineProperties(p,{defaultProps:{configurable:!0,get:function(){return g},set:function(N){q("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),g=N,Object.defineProperty(p,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return b},set:function(N){q("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),b=N,Object.defineProperty(p,"propTypes",{enumerable:!0})}}})}return p}function qa(u){u!=null&&u.$$typeof===m?q("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof u!="function"?q("forwardRef requires a render function but was given %s.",u===null?"null":typeof u):u.length!==0&&u.length!==2&&q("forwardRef render functions accept exactly two parameters: props and ref. %s",u.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),u!=null&&(u.defaultProps!=null||u.propTypes!=null)&&q("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var d={$$typeof:l,render:u};{var p;Object.defineProperty(d,"displayName",{enumerable:!1,configurable:!0,get:function(){return p},set:function(g){p=g,!u.name&&!u.displayName&&(u.displayName=g)}})}return d}var Rs;Rs=Symbol.for("react.module.reference");function ks(u){return!!(typeof u=="string"||typeof u=="function"||u===n||u===i||ga||u===s||u===c||u===h||_a||u===f||ke||Ee||ma||typeof u=="object"&&u!==null&&(u.$$typeof===_||u.$$typeof===m||u.$$typeof===o||u.$$typeof===a||u.$$typeof===l||u.$$typeof===Rs||u.getModuleId!==void 0))}function Ma(u,d){ks(u)||q("memo: The first argument must be a component. Instead received: %s",u===null?"null":typeof u);var p={$$typeof:m,type:u,compare:d===void 0?null:d};{var g;Object.defineProperty(p,"displayName",{enumerable:!1,configurable:!0,get:function(){return g},set:function(b){g=b,!u.name&&!u.displayName&&(u.displayName=b)}})}return p}function de(){var u=T.current;return u===null&&q(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
51
51
  1. You might have mismatching versions of React and the renderer (such as React DOM)
52
52
  2. You might be breaking the Rules of Hooks
53
53
  3. You might have more than one copy of React in the same app
54
- See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),u}function Ma(u){var d=de();if(u._context!==void 0){var p=u._context;p.Consumer===u?q("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):p.Provider===u&&q("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return d.useContext(u)}function Wa(u){var d=de();return d.useState(u)}function Va(u,d,p){var g=de();return g.useReducer(u,d,p)}function Ha(u){var d=de();return d.useRef(u)}function Ka(u,d){var p=de();return p.useEffect(u,d)}function za(u,d){var p=de();return p.useInsertionEffect(u,d)}function Ga(u,d){var p=de();return p.useLayoutEffect(u,d)}function Ja(u,d){var p=de();return p.useCallback(u,d)}function Ya(u,d){var p=de();return p.useMemo(u,d)}function Xa(u,d,p){var g=de();return g.useImperativeHandle(u,d,p)}function Qa(u,d){{var p=de();return p.useDebugValue(u,d)}}function Za(){var u=de();return u.useTransition()}function eu(u){var d=de();return d.useDeferredValue(u)}function tu(){var u=de();return u.useId()}function ru(u,d,p){var g=de();return g.useSyncExternalStore(u,d,p)}var ut=0,Os,Cs,Ps,Is,xs,Ns,js;function Us(){}Us.__reactDisabledLog=!0;function nu(){{if(ut===0){Os=console.log,Cs=console.info,Ps=console.warn,Is=console.error,xs=console.group,Ns=console.groupCollapsed,js=console.groupEnd;var u={configurable:!0,enumerable:!0,value:Us,writable:!0};Object.defineProperties(console,{info:u,log:u,warn:u,error:u,group:u,groupCollapsed:u,groupEnd:u})}ut++}}function su(){{if(ut--,ut===0){var u={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:Ie({},u,{value:Os}),info:Ie({},u,{value:Cs}),warn:Ie({},u,{value:Ps}),error:Ie({},u,{value:Is}),group:Ie({},u,{value:xs}),groupCollapsed:Ie({},u,{value:Ns}),groupEnd:Ie({},u,{value:js})})}ut<0&&q("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Lr=Me.ReactCurrentDispatcher,$r;function xt(u,d,p){{if($r===void 0)try{throw Error()}catch(b){var g=b.stack.trim().match(/\n( *(at )?)/);$r=g&&g[1]||""}return`
55
- `+$r+u}}var Dr=!1,Nt;{var iu=typeof WeakMap=="function"?WeakMap:Map;Nt=new iu}function Ls(u,d){if(!u||Dr)return"";{var p=Nt.get(u);if(p!==void 0)return p}var g;Dr=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var N;N=Lr.current,Lr.current=null,nu();try{if(d){var C=function(){throw Error()};if(Object.defineProperty(C.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(C,[])}catch(le){g=le}Reflect.construct(u,[],C)}else{try{C.call()}catch(le){g=le}u.call(C.prototype)}}else{try{throw Error()}catch(le){g=le}u()}}catch(le){if(le&&g&&typeof le.stack=="string"){for(var j=le.stack.split(`
54
+ See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),u}function Wa(u){var d=de();if(u._context!==void 0){var p=u._context;p.Consumer===u?q("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):p.Provider===u&&q("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return d.useContext(u)}function Va(u){var d=de();return d.useState(u)}function Ha(u,d,p){var g=de();return g.useReducer(u,d,p)}function Ka(u){var d=de();return d.useRef(u)}function za(u,d){var p=de();return p.useEffect(u,d)}function Ga(u,d){var p=de();return p.useInsertionEffect(u,d)}function Ja(u,d){var p=de();return p.useLayoutEffect(u,d)}function Ya(u,d){var p=de();return p.useCallback(u,d)}function Xa(u,d){var p=de();return p.useMemo(u,d)}function Qa(u,d,p){var g=de();return g.useImperativeHandle(u,d,p)}function Za(u,d){{var p=de();return p.useDebugValue(u,d)}}function eu(){var u=de();return u.useTransition()}function tu(u){var d=de();return d.useDeferredValue(u)}function ru(){var u=de();return u.useId()}function nu(u,d,p){var g=de();return g.useSyncExternalStore(u,d,p)}var ut=0,Os,Cs,Ps,Is,xs,Ns,js;function Ls(){}Ls.__reactDisabledLog=!0;function su(){{if(ut===0){Os=console.log,Cs=console.info,Ps=console.warn,Is=console.error,xs=console.group,Ns=console.groupCollapsed,js=console.groupEnd;var u={configurable:!0,enumerable:!0,value:Ls,writable:!0};Object.defineProperties(console,{info:u,log:u,warn:u,error:u,group:u,groupCollapsed:u,groupEnd:u})}ut++}}function iu(){{if(ut--,ut===0){var u={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:Ie({},u,{value:Os}),info:Ie({},u,{value:Cs}),warn:Ie({},u,{value:Ps}),error:Ie({},u,{value:Is}),group:Ie({},u,{value:xs}),groupCollapsed:Ie({},u,{value:Ns}),groupEnd:Ie({},u,{value:js})})}ut<0&&q("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Ur=Me.ReactCurrentDispatcher,$r;function xt(u,d,p){{if($r===void 0)try{throw Error()}catch(b){var g=b.stack.trim().match(/\n( *(at )?)/);$r=g&&g[1]||""}return`
55
+ `+$r+u}}var Dr=!1,Nt;{var ou=typeof WeakMap=="function"?WeakMap:Map;Nt=new ou}function Us(u,d){if(!u||Dr)return"";{var p=Nt.get(u);if(p!==void 0)return p}var g;Dr=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var N;N=Ur.current,Ur.current=null,su();try{if(d){var C=function(){throw Error()};if(Object.defineProperty(C.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(C,[])}catch(le){g=le}Reflect.construct(u,[],C)}else{try{C.call()}catch(le){g=le}u.call(C.prototype)}}else{try{throw Error()}catch(le){g=le}u()}}catch(le){if(le&&g&&typeof le.stack=="string"){for(var j=le.stack.split(`
56
56
  `),B=g.stack.split(`
57
57
  `),z=j.length-1,Y=B.length-1;z>=1&&Y>=0&&j[z]!==B[Y];)Y--;for(;z>=1&&Y>=0;z--,Y--)if(j[z]!==B[Y]){if(z!==1||Y!==1)do if(z--,Y--,Y<0||j[z]!==B[Y]){var X=`
58
- `+j[z].replace(" at new "," at ");return u.displayName&&X.includes("<anonymous>")&&(X=X.replace("<anonymous>",u.displayName)),typeof u=="function"&&Nt.set(u,X),X}while(z>=1&&Y>=0);break}}}finally{Dr=!1,Lr.current=N,su(),Error.prepareStackTrace=b}var ee=u?u.displayName||u.name:"",ie=ee?xt(ee):"";return typeof u=="function"&&Nt.set(u,ie),ie}function ou(u,d,p){return Ls(u,!1)}function au(u){var d=u.prototype;return!!(d&&d.isReactComponent)}function jt(u,d,p){if(u==null)return"";if(typeof u=="function")return Ls(u,au(u));if(typeof u=="string")return xt(u);switch(u){case c:return xt("Suspense");case h:return xt("SuspenseList")}if(typeof u=="object")switch(u.$$typeof){case l:return ou(u.render);case m:return jt(u.type,d,p);case _:{var g=u,b=g._payload,N=g._init;try{return jt(N(b),d,p)}catch{}}}return""}var $s={},Ds=Me.ReactDebugCurrentFrame;function Ut(u){if(u){var d=u._owner,p=jt(u.type,u._source,d?d.type:null);Ds.setExtraStackFrame(p)}else Ds.setExtraStackFrame(null)}function uu(u,d,p,g,b){{var N=Function.call.bind(ot);for(var C in u)if(N(u,C)){var j=void 0;try{if(typeof u[C]!="function"){var B=Error((g||"React class")+": "+p+" type `"+C+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof u[C]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw B.name="Invariant Violation",B}j=u[C](d,C,g,p,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(z){j=z}j&&!(j instanceof Error)&&(Ut(b),q("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",g||"React class",p,C,typeof j),Ut(null)),j instanceof Error&&!(j.message in $s)&&($s[j.message]=!0,Ut(b),q("Failed %s type: %s",p,j.message),Ut(null))}}}function He(u){if(u){var d=u._owner,p=jt(u.type,u._source,d?d.type:null);re(p)}else re(null)}var Fr;Fr=!1;function Fs(){if(x.current){var u=je(x.current.type);if(u)return`
58
+ `+j[z].replace(" at new "," at ");return u.displayName&&X.includes("<anonymous>")&&(X=X.replace("<anonymous>",u.displayName)),typeof u=="function"&&Nt.set(u,X),X}while(z>=1&&Y>=0);break}}}finally{Dr=!1,Ur.current=N,iu(),Error.prepareStackTrace=b}var ee=u?u.displayName||u.name:"",ie=ee?xt(ee):"";return typeof u=="function"&&Nt.set(u,ie),ie}function au(u,d,p){return Us(u,!1)}function uu(u){var d=u.prototype;return!!(d&&d.isReactComponent)}function jt(u,d,p){if(u==null)return"";if(typeof u=="function")return Us(u,uu(u));if(typeof u=="string")return xt(u);switch(u){case c:return xt("Suspense");case h:return xt("SuspenseList")}if(typeof u=="object")switch(u.$$typeof){case l:return au(u.render);case m:return jt(u.type,d,p);case _:{var g=u,b=g._payload,N=g._init;try{return jt(N(b),d,p)}catch{}}}return""}var $s={},Ds=Me.ReactDebugCurrentFrame;function Lt(u){if(u){var d=u._owner,p=jt(u.type,u._source,d?d.type:null);Ds.setExtraStackFrame(p)}else Ds.setExtraStackFrame(null)}function lu(u,d,p,g,b){{var N=Function.call.bind(ot);for(var C in u)if(N(u,C)){var j=void 0;try{if(typeof u[C]!="function"){var B=Error((g||"React class")+": "+p+" type `"+C+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof u[C]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw B.name="Invariant Violation",B}j=u[C](d,C,g,p,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(z){j=z}j&&!(j instanceof Error)&&(Lt(b),q("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",g||"React class",p,C,typeof j),Lt(null)),j instanceof Error&&!(j.message in $s)&&($s[j.message]=!0,Lt(b),q("Failed %s type: %s",p,j.message),Lt(null))}}}function He(u){if(u){var d=u._owner,p=jt(u.type,u._source,d?d.type:null);re(p)}else re(null)}var Fr;Fr=!1;function Fs(){if(x.current){var u=je(x.current.type);if(u)return`
59
59
 
60
- Check the render method of \``+u+"`."}return""}function lu(u){if(u!==void 0){var d=u.fileName.replace(/^.*[\\\/]/,""),p=u.lineNumber;return`
60
+ Check the render method of \``+u+"`."}return""}function cu(u){if(u!==void 0){var d=u.fileName.replace(/^.*[\\\/]/,""),p=u.lineNumber;return`
61
61
 
62
- Check your code at `+d+":"+p+"."}return""}function cu(u){return u!=null?lu(u.__source):""}var Bs={};function du(u){var d=Fs();if(!d){var p=typeof u=="string"?u:u.displayName||u.name;p&&(d=`
62
+ Check your code at `+d+":"+p+"."}return""}function du(u){return u!=null?cu(u.__source):""}var Bs={};function hu(u){var d=Fs();if(!d){var p=typeof u=="string"?u:u.displayName||u.name;p&&(d=`
63
63
 
64
- Check the top-level render call using <`+p+">.")}return d}function qs(u,d){if(!(!u._store||u._store.validated||u.key!=null)){u._store.validated=!0;var p=du(d);if(!Bs[p]){Bs[p]=!0;var g="";u&&u._owner&&u._owner!==x.current&&(g=" It was passed a child from "+je(u._owner.type)+"."),He(u),q('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',p,g),He(null)}}}function Ms(u,d){if(typeof u=="object"){if(Ot(u))for(var p=0;p<u.length;p++){var g=u[p];Ve(g)&&qs(g,d)}else if(Ve(u))u._store&&(u._store.validated=!0);else if(u){var b=w(u);if(typeof b=="function"&&b!==u.entries)for(var N=b.call(u),C;!(C=N.next()).done;)Ve(C.value)&&qs(C.value,d)}}}function Ws(u){{var d=u.type;if(d==null||typeof d=="string")return;var p;if(typeof d=="function")p=d.propTypes;else if(typeof d=="object"&&(d.$$typeof===l||d.$$typeof===m))p=d.propTypes;else return;if(p){var g=je(d);uu(p,u.props,"prop",g,u)}else if(d.PropTypes!==void 0&&!Fr){Fr=!0;var b=je(d);q("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof d.getDefaultProps=="function"&&!d.getDefaultProps.isReactClassApproved&&q("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function hu(u){{for(var d=Object.keys(u.props),p=0;p<d.length;p++){var g=d[p];if(g!=="children"&&g!=="key"){He(u),q("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",g),He(null);break}}u.ref!==null&&(He(u),q("Invalid attribute `ref` supplied to `React.Fragment`."),He(null))}}function Vs(u,d,p){var g=ks(u);if(!g){var b="";(u===void 0||typeof u=="object"&&u!==null&&Object.keys(u).length===0)&&(b+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var N=cu(d);N?b+=N:b+=Fs();var C;u===null?C="null":Ot(u)?C="array":u!==void 0&&u.$$typeof===e?(C="<"+(je(u.type)||"Unknown")+" />",b=" Did you accidentally export a JSX literal instead of a component?"):C=typeof u,q("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",C,b)}var j=Ra.apply(this,arguments);if(j==null)return j;if(g)for(var B=2;B<arguments.length;B++)Ms(arguments[B],u);return u===n?hu(j):Ws(j),j}var Hs=!1;function fu(u){var d=Vs.bind(null,u);return d.type=u,Hs||(Hs=!0,We("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(d,"type",{enumerable:!1,get:function(){return We("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:u}),u}}),d}function pu(u,d,p){for(var g=Oa.apply(this,arguments),b=2;b<arguments.length;b++)Ms(arguments[b],g.type);return Ws(g),g}function mu(u,d){var p=O.transition;O.transition={};var g=O.transition;O.transition._updatedFibers=new Set;try{u()}finally{if(O.transition=p,p===null&&g._updatedFibers){var b=g._updatedFibers.size;b>10&&We("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),g._updatedFibers.clear()}}}var Ks=!1,Lt=null;function _u(u){if(Lt===null)try{var d=("require"+Math.random()).slice(0,7),p=Tr&&Tr[d];Lt=p.call(Tr,"timers").setImmediate}catch{Lt=function(b){Ks===!1&&(Ks=!0,typeof MessageChannel>"u"&&q("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var N=new MessageChannel;N.port1.onmessage=b,N.port2.postMessage(void 0)}}return Lt(u)}var Ke=0,zs=!1;function Gs(u){{var d=Ke;Ke++,E.current===null&&(E.current=[]);var p=E.isBatchingLegacy,g;try{if(E.isBatchingLegacy=!0,g=u(),!p&&E.didScheduleLegacyUpdate){var b=E.current;b!==null&&(E.didScheduleLegacyUpdate=!1,Mr(b))}}catch(ee){throw $t(d),ee}finally{E.isBatchingLegacy=p}if(g!==null&&typeof g=="object"&&typeof g.then=="function"){var N=g,C=!1,j={then:function(ee,ie){C=!0,N.then(function(le){$t(d),Ke===0?Br(le,ee,ie):ee(le)},function(le){$t(d),ie(le)})}};return!zs&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){C||(zs=!0,q("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),j}else{var B=g;if($t(d),Ke===0){var z=E.current;z!==null&&(Mr(z),E.current=null);var Y={then:function(ee,ie){E.current===null?(E.current=[],Br(B,ee,ie)):ee(B)}};return Y}else{var X={then:function(ee,ie){ee(B)}};return X}}}}function $t(u){u!==Ke-1&&q("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ke=u}function Br(u,d,p){{var g=E.current;if(g!==null)try{Mr(g),_u(function(){g.length===0?(E.current=null,d(u)):Br(u,d,p)})}catch(b){p(b)}else d(u)}}var qr=!1;function Mr(u){if(!qr){qr=!0;var d=0;try{for(;d<u.length;d++){var p=u[d];do p=p(!0);while(p!==null)}u.length=0}catch(g){throw u=u.slice(d+1),g}finally{qr=!1}}}var gu=Vs,yu=pu,vu=fu,wu={map:It,forEach:Na,count:xa,toArray:ja,only:Ua};L.Children=wu,L.Component=Le,L.Fragment=n,L.Profiler=i,L.PureComponent=Pr,L.StrictMode=s,L.Suspense=c,L.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Me,L.act=Gs,L.cloneElement=yu,L.createContext=La,L.createElement=gu,L.createFactory=vu,L.createRef=ya,L.forwardRef=Ba,L.isValidElement=Ve,L.lazy=Fa,L.memo=qa,L.startTransition=mu,L.unstable_act=Gs,L.useCallback=Ja,L.useContext=Ma,L.useDebugValue=Qa,L.useDeferredValue=eu,L.useEffect=Ka,L.useId=tu,L.useImperativeHandle=Xa,L.useInsertionEffect=za,L.useLayoutEffect=Ga,L.useMemo=Ya,L.useReducer=Va,L.useRef=Ha,L.useState=Wa,L.useSyncExternalStore=ru,L.useTransition=Za,L.version=t,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)})()});var la=$((Mf,cs)=>{"use strict";process.env.NODE_ENV==="production"?cs.exports=aa():cs.exports=ua()});var ni=[{canonical:"prproj",aliases:["prproj"],extensions:["prproj"],label:"Premiere Pro Project",short_label:"Premiere Project",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"prproj"},{canonical:"premiere-xml",aliases:["premiere-xml"],extensions:["xml"],label:"Premiere Pro XML",short_label:"Premiere XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"xmeml"},{canonical:"resolve-xml",aliases:["resolve-xml"],extensions:["xml"],label:"DaVinci Resolve XML",short_label:"Resolve XML",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"resolve-fcpxml",aliases:["resolve-fcpxml"],extensions:["fcpxml"],label:"DaVinci Resolve FCPXML",short_label:"Resolve FCPXML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"finalcut-fcpxml",aliases:["finalcut-fcpxml","fcpxmld"],extensions:["fcpxmld","fcpxml"],label:"Apple Final Cut Pro (.fcpxmld)",short_label:"Final Cut",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"resolve-drt",aliases:["resolve-drt"],extensions:["drt"],label:"DaVinci Resolve Timeline (.drt)",short_label:"Resolve DRT",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"drt"},{canonical:"fcp-xml",aliases:["fcp-xml"],extensions:["xml"],label:"Final Cut Pro 7 XML",short_label:"FCP XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"aaf",aliases:["aaf"],extensions:["aaf"],label:"Avid AAF",short_label:"AAF",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"aaf"},{canonical:"avb",aliases:["avb"],extensions:["avb"],label:"Avid Bin",short_label:"Avid Bin",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"avb"},{canonical:"flame-archive",aliases:["flame-archive","flame"],extensions:[],label:"Autodesk Flame Archive",short_label:"Flame Archive",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"flame-archive"},{canonical:"otio",aliases:["otio"],extensions:["otio","otioz"],label:"OpenTimelineIO",short_label:"OTIO",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"otio"},{canonical:"baselight-blscene",aliases:["baselight-blscene","blscene","baselight"],extensions:["blscene"],label:"Baselight Scene",short_label:"Baselight",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"blscene"},{canonical:"capcut",aliases:["capcut","jianying"],extensions:[],label:"CapCut Project",short_label:"CapCut",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"capcut"}],Au=new Map,ri=new Map;for(let t of ni){for(let e of t.aliases)Au.set(e.toLowerCase(),t);for(let e of t.extensions){let r=ri.get(e.toLowerCase())??[];r.push(t),ri.set(e.toLowerCase(),r)}}var nh=new Set(ni.map(t=>t.canonical));async function Hr(t){let e=t.name.toLowerCase();if(e.endsWith(".prproj"))return{format:"prproj",confidence:"high",details:"Premiere Pro project file (.prproj)"};if(e.endsWith(".aaf"))return{format:"aaf",confidence:"high",details:"Advanced Authoring Format (.aaf)"};if(e.endsWith(".avb"))return{format:"avb",confidence:"high",details:"Avid Bin file (.avb)"};if(e.endsWith(".otio"))return{format:"otio",confidence:"high",details:"OpenTimelineIO file (.otio)"};if(e.endsWith(".blscene"))return{format:"baselight-blscene",confidence:"high",details:"Baselight scene (.blscene)"};if(e.endsWith(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxmld"))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro bundle (.fcpxmld)"};if(e.endsWith(".fcpxml")){try{let r=await t.slice(0,65536).text();if(/<library\b/.test(r)||/<fcpxml\s+version="1\.1\d"/.test(r))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro FCPXML export (.fcpxml)"}}catch{}return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve export"}}if(e.endsWith(".json")){if(/(^|\/)draft_(content|info)\.json$/.test(e))return{format:"capcut",confidence:"high",details:"CapCut project (draft JSON)"};try{let r=await t.slice(0,262144).text();if(/"canvas_config"\s*:/.test(r)&&/"materials"\s*:/.test(r))return{format:"capcut",confidence:"medium",details:"CapCut project (draft JSON)"}}catch{}}if(e.endsWith(".xml"))return await Ru(t);if(e.endsWith(".flame-archive.zip"))return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (.flame-archive.zip)"};{let r=new Uint8Array(await t.slice(0,4).arrayBuffer());if(r[0]===128&&r[1]===130&&r[2]===167&&r[3]===214)return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (bare TOC header)"};if(r[0]===80&&r[1]===75)try{let{unzipSync:n}=await import("./esm-SFFBP7PS.js"),s=n(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(s)){let a=o;if(/_\d+\.seg$/.test(i)||a.length>=4&&a[0]===128&&a[1]===130&&a[2]===167&&a[3]===214)return{format:"flame-archive",confidence:"medium",details:"Autodesk Flame archive (zip-wrapped TOC + segs)"}}}catch{}}return{format:"unknown",confidence:"high",details:`Unsupported file extension: ${e.split(".").pop()||"none"}`}}async function Ru(t){try{let e=await t.text(),n=new DOMParser().parseFromString(e,"text/xml");if(n.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(n.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(n.querySelector("xmeml")){let a=n.querySelectorAll("sequence > name, bin > name");for(let l of a)if(l.textContent?.includes("(Resolve)"))return{format:"resolve-xml",confidence:"high",details:'Found "(Resolve)" marker in sequence/bin name'};return{format:"fcp-xml",confidence:"medium",details:"XMEML format without Premiere/Resolve markers - likely Final Cut Pro"}}return{format:"unknown",confidence:"high",details:"No recognized XML format markers found"}}catch(e){return{format:"unknown",confidence:"high",details:`Failed to parse XML: ${e}`}}}var R={};Qs(R,{FunctionRegion:()=>be.FunctionRegion,FunctionsError:()=>be.FunctionsError,FunctionsFetchError:()=>be.FunctionsFetchError,FunctionsHttpError:()=>be.FunctionsHttpError,FunctionsRelayError:()=>be.FunctionsRelayError,PostgrestError:()=>en,SupabaseClient:()=>Do,createClient:()=>rs});var be=ze(ji(),1);var en=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ju=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,c=i.status,h=i.statusText;if(i.ok){var m,_;if(r.method!=="HEAD"){var f;let T=await i.text();T===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=T:a=JSON.parse(T))}let v=(m=r.headers.get("Prefer"))===null||m===void 0?void 0:m.match(/count=(exact|planned|estimated)/),w=(_=i.headers.get("content-range"))===null||_===void 0?void 0:_.split("/");v&&w&&w.length>1&&(l=parseInt(w[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,h="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var y;let v=await i.text();try{o=JSON.parse(v),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,h="OK")}catch{i.status===404&&v===""?(c=204,h="No Content"):o={message:v}}if(o&&r.isMaybeSingle&&(!(o==null||(y=o.details)===null||y===void 0)&&y.includes("0 rows"))&&(o=null,c=200,h="OK"),o&&r.shouldThrowOnError)throw new en(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",c="",h=i?.cause;if(h){var m,_,f,y;let T=(m=h?.message)!==null&&m!==void 0?m:"",O=(_=h?.code)!==null&&_!==void 0?_:"";a=`${(f=i?.name)!==null&&f!==void 0?f:"FetchError"}: ${i?.message}`,a+=`
64
+ Check the top-level render call using <`+p+">.")}return d}function qs(u,d){if(!(!u._store||u._store.validated||u.key!=null)){u._store.validated=!0;var p=hu(d);if(!Bs[p]){Bs[p]=!0;var g="";u&&u._owner&&u._owner!==x.current&&(g=" It was passed a child from "+je(u._owner.type)+"."),He(u),q('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',p,g),He(null)}}}function Ms(u,d){if(typeof u=="object"){if(Ot(u))for(var p=0;p<u.length;p++){var g=u[p];Ve(g)&&qs(g,d)}else if(Ve(u))u._store&&(u._store.validated=!0);else if(u){var b=w(u);if(typeof b=="function"&&b!==u.entries)for(var N=b.call(u),C;!(C=N.next()).done;)Ve(C.value)&&qs(C.value,d)}}}function Ws(u){{var d=u.type;if(d==null||typeof d=="string")return;var p;if(typeof d=="function")p=d.propTypes;else if(typeof d=="object"&&(d.$$typeof===l||d.$$typeof===m))p=d.propTypes;else return;if(p){var g=je(d);lu(p,u.props,"prop",g,u)}else if(d.PropTypes!==void 0&&!Fr){Fr=!0;var b=je(d);q("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof d.getDefaultProps=="function"&&!d.getDefaultProps.isReactClassApproved&&q("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function fu(u){{for(var d=Object.keys(u.props),p=0;p<d.length;p++){var g=d[p];if(g!=="children"&&g!=="key"){He(u),q("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",g),He(null);break}}u.ref!==null&&(He(u),q("Invalid attribute `ref` supplied to `React.Fragment`."),He(null))}}function Vs(u,d,p){var g=ks(u);if(!g){var b="";(u===void 0||typeof u=="object"&&u!==null&&Object.keys(u).length===0)&&(b+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var N=du(d);N?b+=N:b+=Fs();var C;u===null?C="null":Ot(u)?C="array":u!==void 0&&u.$$typeof===e?(C="<"+(je(u.type)||"Unknown")+" />",b=" Did you accidentally export a JSX literal instead of a component?"):C=typeof u,q("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",C,b)}var j=ka.apply(this,arguments);if(j==null)return j;if(g)for(var B=2;B<arguments.length;B++)Ms(arguments[B],u);return u===n?fu(j):Ws(j),j}var Hs=!1;function pu(u){var d=Vs.bind(null,u);return d.type=u,Hs||(Hs=!0,We("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(d,"type",{enumerable:!1,get:function(){return We("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:u}),u}}),d}function mu(u,d,p){for(var g=Ca.apply(this,arguments),b=2;b<arguments.length;b++)Ms(arguments[b],g.type);return Ws(g),g}function _u(u,d){var p=O.transition;O.transition={};var g=O.transition;O.transition._updatedFibers=new Set;try{u()}finally{if(O.transition=p,p===null&&g._updatedFibers){var b=g._updatedFibers.size;b>10&&We("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),g._updatedFibers.clear()}}}var Ks=!1,Ut=null;function gu(u){if(Ut===null)try{var d=("require"+Math.random()).slice(0,7),p=Tr&&Tr[d];Ut=p.call(Tr,"timers").setImmediate}catch{Ut=function(b){Ks===!1&&(Ks=!0,typeof MessageChannel>"u"&&q("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var N=new MessageChannel;N.port1.onmessage=b,N.port2.postMessage(void 0)}}return Ut(u)}var Ke=0,zs=!1;function Gs(u){{var d=Ke;Ke++,E.current===null&&(E.current=[]);var p=E.isBatchingLegacy,g;try{if(E.isBatchingLegacy=!0,g=u(),!p&&E.didScheduleLegacyUpdate){var b=E.current;b!==null&&(E.didScheduleLegacyUpdate=!1,Mr(b))}}catch(ee){throw $t(d),ee}finally{E.isBatchingLegacy=p}if(g!==null&&typeof g=="object"&&typeof g.then=="function"){var N=g,C=!1,j={then:function(ee,ie){C=!0,N.then(function(le){$t(d),Ke===0?Br(le,ee,ie):ee(le)},function(le){$t(d),ie(le)})}};return!zs&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){C||(zs=!0,q("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),j}else{var B=g;if($t(d),Ke===0){var z=E.current;z!==null&&(Mr(z),E.current=null);var Y={then:function(ee,ie){E.current===null?(E.current=[],Br(B,ee,ie)):ee(B)}};return Y}else{var X={then:function(ee,ie){ee(B)}};return X}}}}function $t(u){u!==Ke-1&&q("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ke=u}function Br(u,d,p){{var g=E.current;if(g!==null)try{Mr(g),gu(function(){g.length===0?(E.current=null,d(u)):Br(u,d,p)})}catch(b){p(b)}else d(u)}}var qr=!1;function Mr(u){if(!qr){qr=!0;var d=0;try{for(;d<u.length;d++){var p=u[d];do p=p(!0);while(p!==null)}u.length=0}catch(g){throw u=u.slice(d+1),g}finally{qr=!1}}}var yu=Vs,vu=mu,wu=pu,bu={map:It,forEach:ja,count:Na,toArray:La,only:Ua};U.Children=bu,U.Component=Ue,U.Fragment=n,U.Profiler=i,U.PureComponent=Pr,U.StrictMode=s,U.Suspense=c,U.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Me,U.act=Gs,U.cloneElement=vu,U.createContext=$a,U.createElement=yu,U.createFactory=wu,U.createRef=va,U.forwardRef=qa,U.isValidElement=Ve,U.lazy=Ba,U.memo=Ma,U.startTransition=_u,U.unstable_act=Gs,U.useCallback=Ya,U.useContext=Wa,U.useDebugValue=Za,U.useDeferredValue=tu,U.useEffect=za,U.useId=ru,U.useImperativeHandle=Qa,U.useInsertionEffect=Ga,U.useLayoutEffect=Ja,U.useMemo=Xa,U.useReducer=Ha,U.useRef=Ka,U.useState=Va,U.useSyncExternalStore=nu,U.useTransition=eu,U.version=t,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)})()});var ca=$((Kf,cs)=>{"use strict";process.env.NODE_ENV==="production"?cs.exports=ua():cs.exports=la()});var ni=[{canonical:"prproj",aliases:["prproj"],extensions:["prproj"],label:"Premiere Pro Project",short_label:"Premiere Project",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"prproj"},{canonical:"premiere-xml",aliases:["premiere-xml"],extensions:["xml"],label:"Premiere Pro XML",short_label:"Premiere XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"xmeml"},{canonical:"resolve-xml",aliases:["resolve-xml"],extensions:["xml"],label:"DaVinci Resolve XML",short_label:"Resolve XML",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"resolve-fcpxml",aliases:["resolve-fcpxml"],extensions:["fcpxml"],label:"DaVinci Resolve FCPXML",short_label:"Resolve FCPXML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"finalcut-fcpxml",aliases:["finalcut-fcpxml","fcpxmld"],extensions:["fcpxmld","fcpxml"],label:"Apple Final Cut Pro (.fcpxmld)",short_label:"Final Cut",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"resolve-drt",aliases:["resolve-drt"],extensions:["drt"],label:"DaVinci Resolve Timeline (.drt)",short_label:"Resolve DRT",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"drt"},{canonical:"fcp-xml",aliases:["fcp-xml"],extensions:["xml"],label:"Final Cut Pro 7 XML",short_label:"FCP XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"aaf",aliases:["aaf"],extensions:["aaf"],label:"Avid AAF",short_label:"AAF",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"aaf"},{canonical:"avb",aliases:["avb"],extensions:["avb"],label:"Avid Bin",short_label:"Avid Bin",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"avb"},{canonical:"flame-archive",aliases:["flame-archive","flame"],extensions:[],label:"Autodesk Flame Archive",short_label:"Flame Archive",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"flame-archive"},{canonical:"otio",aliases:["otio"],extensions:["otio","otioz"],label:"OpenTimelineIO",short_label:"OTIO",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"otio"},{canonical:"baselight-blscene",aliases:["baselight-blscene","blscene","baselight"],extensions:["blscene"],label:"Baselight Scene",short_label:"Baselight",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"blscene"},{canonical:"capcut",aliases:["capcut","jianying"],extensions:[],label:"CapCut Project",short_label:"CapCut",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"capcut"}],Ru=new Map,ri=new Map;for(let t of ni){for(let e of t.aliases)Ru.set(e.toLowerCase(),t);for(let e of t.extensions){let r=ri.get(e.toLowerCase())??[];r.push(t),ri.set(e.toLowerCase(),r)}}var ih=new Set(ni.map(t=>t.canonical));async function Hr(t){let e=t.name.toLowerCase();if(e.endsWith(".prproj"))return{format:"prproj",confidence:"high",details:"Premiere Pro project file (.prproj)"};if(e.endsWith(".aaf"))return{format:"aaf",confidence:"high",details:"Advanced Authoring Format (.aaf)"};if(e.endsWith(".avb"))return{format:"avb",confidence:"high",details:"Avid Bin file (.avb)"};if(e.endsWith(".otio"))return{format:"otio",confidence:"high",details:"OpenTimelineIO file (.otio)"};if(e.endsWith(".blscene"))return{format:"baselight-blscene",confidence:"high",details:"Baselight scene (.blscene)"};if(e.endsWith(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxmld"))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro bundle (.fcpxmld)"};if(e.endsWith(".fcpxml")){try{let r=await t.slice(0,65536).text();if(/<library\b/.test(r)||/<fcpxml\s+version="1\.1\d"/.test(r))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro FCPXML export (.fcpxml)"}}catch{}return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve export"}}if(e.endsWith(".json")){if(/(^|\/)draft_(content|info)\.json$/.test(e))return{format:"capcut",confidence:"high",details:"CapCut project (draft JSON)"};try{let r=await t.slice(0,262144).text();if(/"canvas_config"\s*:/.test(r)&&/"materials"\s*:/.test(r))return{format:"capcut",confidence:"medium",details:"CapCut project (draft JSON)"}}catch{}}if(e.endsWith(".xml"))return await ku(t);if(e.endsWith(".flame-archive.zip"))return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (.flame-archive.zip)"};{let r=new Uint8Array(await t.slice(0,4).arrayBuffer());if(r[0]===128&&r[1]===130&&r[2]===167&&r[3]===214)return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (bare TOC header)"};if(r[0]===80&&r[1]===75)try{let{unzipSync:n}=await import("./esm-SFFBP7PS.js"),s=n(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(s)){let a=o;if(/_\d+\.seg$/.test(i)||a.length>=4&&a[0]===128&&a[1]===130&&a[2]===167&&a[3]===214)return{format:"flame-archive",confidence:"medium",details:"Autodesk Flame archive (zip-wrapped TOC + segs)"}}}catch{}}return{format:"unknown",confidence:"high",details:`Unsupported file extension: ${e.split(".").pop()||"none"}`}}async function ku(t){try{let e=await t.text(),n=new DOMParser().parseFromString(e,"text/xml");if(n.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(n.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(n.querySelector("xmeml")){let a=n.querySelectorAll("sequence > name, bin > name");for(let l of a)if(l.textContent?.includes("(Resolve)"))return{format:"resolve-xml",confidence:"high",details:'Found "(Resolve)" marker in sequence/bin name'};return{format:"fcp-xml",confidence:"medium",details:"XMEML format without Premiere/Resolve markers - likely Final Cut Pro"}}return{format:"unknown",confidence:"high",details:"No recognized XML format markers found"}}catch(e){return{format:"unknown",confidence:"high",details:`Failed to parse XML: ${e}`}}}var A={};Qs(A,{FunctionRegion:()=>be.FunctionRegion,FunctionsError:()=>be.FunctionsError,FunctionsFetchError:()=>be.FunctionsFetchError,FunctionsHttpError:()=>be.FunctionsHttpError,FunctionsRelayError:()=>be.FunctionsRelayError,PostgrestError:()=>en,SupabaseClient:()=>Do,createClient:()=>rs});var be=ze(ji(),1);var en=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Lu=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,c=i.status,h=i.statusText;if(i.ok){var m,_;if(r.method!=="HEAD"){var f;let T=await i.text();T===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=T:a=JSON.parse(T))}let v=(m=r.headers.get("Prefer"))===null||m===void 0?void 0:m.match(/count=(exact|planned|estimated)/),w=(_=i.headers.get("content-range"))===null||_===void 0?void 0:_.split("/");v&&w&&w.length>1&&(l=parseInt(w[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,c=406,h="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var y;let v=await i.text();try{o=JSON.parse(v),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,h="OK")}catch{i.status===404&&v===""?(c=204,h="No Content"):o={message:v}}if(o&&r.isMaybeSingle&&(!(o==null||(y=o.details)===null||y===void 0)&&y.includes("0 rows"))&&(o=null,c=200,h="OK"),o&&r.shouldThrowOnError)throw new en(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",c="",h=i?.cause;if(h){var m,_,f,y;let T=(m=h?.message)!==null&&m!==void 0?m:"",O=(_=h?.code)!==null&&_!==void 0?_:"";a=`${(f=i?.name)!==null&&f!==void 0?f:"FetchError"}: ${i?.message}`,a+=`
65
65
 
66
66
  Caused by: ${(y=h?.name)!==null&&y!==void 0?y:"Error"}: ${T}`,O&&(a+=` (${O})`),h?.stack&&(a+=`
67
- ${h.stack}`)}else{var v;a=(v=i?.stack)!==null&&v!==void 0?v:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} 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.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} 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.`)),{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:a,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},Uu=class extends ju{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let s=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),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:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Ui=new RegExp("[,()]"),Xe=class extends Uu{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${i}.${e}`),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Lu=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:s=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},s=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Xe({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new Xe({method:s,url:i,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),s||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((h,m)=>h.concat(Object.keys(m)),[]);if(c.length>0){let h=[...new Set(c)].map(m=>`"${m}"`);a.searchParams.set("columns",h.join(","))}}return new Xe({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Xe({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new Xe({method:r,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ct(t){"@babel/helpers - typeof";return ct=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ct(t)}function $u(t,e){if(ct(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ct(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Du(t){var e=$u(t,"string");return ct(e)=="symbol"?e:e+""}function Fu(t,e,r){return(e=Du(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Li(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function Vt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Li(Object(r),!0).forEach(function(n){Fu(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Li(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var $i=class Di{constructor(e,{headers:r={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let h=new AbortController,m=setTimeout(()=>h.abort(),i),_=c?.signal;if(_){if(_.aborted)return clearTimeout(m),a(l,c);let f=()=>{clearTimeout(m),h.abort()};return _.addEventListener("abort",f,{once:!0}),a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(m),_.removeEventListener("abort",f)})}return a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>clearTimeout(m))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Lu(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Di(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:s=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,h=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(h)),m=n&&Object.values(r).some(h);m?(a="POST",c=r):n||s?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{l.searchParams.append(f,y)})):(a="POST",c=r);let _=new Headers(this.headers);return m?_.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&_.set("Prefer",`count=${i}`),new Xe({method:a,url:l,headers:_,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var Lo=ze(vn(),1);var mt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function ll(t,e,r){let n=new URL(e,t);if(r)for(let[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function cl(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function dl(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){let a=ll(t.baseUrl,n,s),l=await cl(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),m=(c.headers.get("content-type")||"").includes("application/json"),_=m&&h?JSON.parse(h):h;if(!c.ok){let f=m?_:void 0,y=f?.error;throw new mt(y?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:y?.type,icebergCode:y?.code,details:f})}return{status:c.status,headers:c.headers,data:_}}}}function Zt(t){return t.join("")}var hl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Zt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`}),!0}catch(e){if(e instanceof mt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof mt&&r.status===409)return;throw r}}};function Qe(t){return t.join("")}var fl=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof mt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof mt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Zi=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=dl({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new hl(this.client,e),this.tableOps=new fl(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var tr=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function rr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var er=class extends tr{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},no=class extends tr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var pl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),ml=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},wn=t=>{if(Array.isArray(t))return t.map(r=>wn(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=wn(n)}),e},_l=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function gt(t){"@babel/helpers - typeof";return gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gt(t)}function gl(t,e){if(gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(gt(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yl(t){var e=gl(t,"string");return gt(e)=="symbol"?e:e+""}function vl(t,e,r){return(e=yl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function eo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?eo(Object(r),!0).forEach(function(n){vl(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):eo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var to=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},wl=async(t,e,r,n)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let s=t,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new er(to(o),i,a,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new no(to(t),t,n))},bl=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?P(P({},s),r):(ml(n)?(s.headers=P({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(n)):s.body=n,e?.duplex&&(s.duplex=e.duplex),P(P({},s),r))};async function _t(t,e,r,n,s,i,o){return new Promise((a,l)=>{t(r,bl(e,n,s,i)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>wl(c,l,n,o))})}function so(t="storage"){return{get:async(e,r,n,s)=>_t(e,"GET",r,n,s,void 0,t),post:async(e,r,n,s,i)=>_t(e,"POST",r,s,i,n,t),put:async(e,r,n,s,i)=>_t(e,"PUT",r,s,i,n,t),head:async(e,r,n,s)=>_t(e,"HEAD",r,P(P({},n),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,r,n,s,i)=>_t(e,"DELETE",r,s,i,n,t)}}var El=so("storage"),{get:yt,post:Ae,put:bn,head:Sl,remove:En}=El,me=so("vectors"),Ze=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=pl(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=P(P({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(rr(r))return{data:null,error:r};throw r}}},Tl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},io;io=Symbol.toStringTag;var Al=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[io]="BlobDownloadBuilder",this.promise=null}asStream(){return new Tl(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},Rl={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ro={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},kl=class extends Ze{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var s=this;return s.handleOperation(async()=>{let i,o=P(P({},ro),n),a=P(P({},s.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=P(P({},a),n.headers));let c=s._removeEmptyFolders(e),h=s._getFinalPath(c),m=await(t=="PUT"?bn:Ae)(s.fetch,`${s.url}/object/${h}`,i,P({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:m.Id,fullPath:m.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var s=this;let i=s._removeEmptyFolders(t),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),s.handleOperation(async()=>{let l,c=P({upsert:ro.upsert},n),h=P(P({},s.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType),{path:i,fullPath:(await bn(s.fetch,a.toString(),l,{headers:h})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),s=P({},r.headers);e?.upsert&&(s["x-upsert"]="true");let i=await Ae(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new tr("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Ae(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Ae(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(t),i=await Ae(n.fetch,`${n.url}/object/sign/${s}`,P({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:n.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let s=await Ae(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return s.map(o=>P(P({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString(e?.transform||{}),i=s?`?${s}`:"",o=this._getFinalPath(t),a=()=>yt(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Al(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>wn(await yt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Sl(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(rr(n)&&n instanceof no){let s=n.originalError;if([400,404].includes(s?.status))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],s=e?.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let s=P(P(P({},Rl),e),{},{prefix:t||""});return await Ae(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=P({},t);return await Ae(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},Ol="2.97.0",vt={"X-Client-Info":`storage-js/${Ol}`},Cl=class extends Ze{constructor(t,e={},r,n){let s=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=P(P({},vt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await yt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Ae(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await bn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Pl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),e);super(n,s,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await yt(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!_l(t))throw new tr("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 r=new Zi({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},Il=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},xl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Nl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},jl=class extends Nl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Ul(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Ul=class extends Il{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Ll(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Ll=class extends xl{constructor(t,e,r,n,s){super(t,e,s),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},oo=class extends Cl{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new kl(this.url,this.headers,t,this.fetch)}get vectors(){return new jl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Pl(this.url+"/iceberg",this.headers,this.fetch)}};var $o=ze(ts(),1);k(R,ze(vn(),1));k(R,ze(ts(),1));var dd="2.97.0",Tt="";typeof Deno<"u"?Tt="deno":typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":Tt="node";var hd={"X-Client-Info":`supabase-js-${Tt}/${dd}`},fd={headers:hd},pd={schema:"public"},md={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},_d={};function At(t){"@babel/helpers - typeof";return At=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},At(t)}function gd(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(At(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yd(t){var e=gd(t,"string");return At(e)=="symbol"?e:e+""}function vd(t,e,r){return(e=yd(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Uo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function se(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(r),!0).forEach(function(n){vd(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Uo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var wd=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),bd=()=>Headers,Ed=(t,e,r)=>{let n=wd(r),s=bd();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new s(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(i,se(se({},o),{},{headers:c}))}};function Sd(t){return t.endsWith("/")?t:t+"/"}function Td(t,e){var r,n;let{db:s,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:h,global:m}=e,_={db:se(se({},l),s),auth:se(se({},c),i),realtime:se(se({},h),o),storage:{},global:se(se(se({},m),a),{},{headers:se(se({},(r=m?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Ad(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Sd(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Rd=class extends $o.AuthClient{constructor(t){super(t)}},Do=class{constructor(t,e,r){var n,s;this.supabaseUrl=t,this.supabaseKey=e;let i=Ad(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:pd,realtime:_d,auth:se(se({},md),{},{storageKey:o}),global:fd},l=Td(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,m)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=Ed(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(se({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new $i(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new oo(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new be.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,m){let _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rd({url:this.authUrl.href,headers:se(se({},_),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Lo.RealtimeClient(this.realtimeUrl.href,se(se({},t),{},{params:se(se({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},rs=(t,e,r)=>new Do(t,e,r);function kd(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}kd()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");var Rt=typeof window<"u"&&!!window.__CONFORM_ENGINE__,Fo=Rt?"http://127.0.0.1:9":import.meta.env.VITE_SUPABASE_URL,Bo=Rt?"offline":import.meta.env.VITE_SUPABASE_ANON_KEY;if(!Fo)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!Bo)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var gr=rs(Fo,Bo,{auth:{autoRefreshToken:!Rt,persistSession:!Rt,detectSessionInUrl:!Rt}});var Od=typeof __BUILD_SHA__<"u"?`web-${__BUILD_SHA__}`:"web-dev",Cd=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/v1-me/v1/engine/telemetry`,Pd=1e4,Id=crypto.randomUUID(),yr=0,xd=0,vr=[],qo=null;function Mo(){yr++,ss=!1,Wo=Date.now()}var ss=!1,Wo=0;function Vo(){return ss}function wr(t,e={}){yr||(yr=1),vr.push({kind:"outcome",verb:t,ok:e.ok??!0,code:e.ok===!1?e.code??"error":void 0,error:e.ok===!1?e.error:void 0,duration_ms:Math.max(0,Math.round(e.ms??0)),counts:e.counts,fields:e.fields,session_id:e.session_id,version:Od,run_id:Id,seq:++xd,req:yr,event_id:crypto.randomUUID(),run_at:new Date().toISOString(),client:"web",author:"user"}),qo??=setTimeout(()=>void Ko(),Pd)}var ns=null;async function Ho(t,e,r=()=>({})){let n=performance.now();ns=null;try{let s=await e(),i=ns;return ns=null,wr(t,i?{ok:!1,...i,ms:performance.now()-n}:{...r(s),ok:!0,ms:performance.now()-n}),s}catch(s){throw wr(t,{ok:!1,code:s?.code,error:s instanceof Error?s.message:String(s),ms:performance.now()-n}),s}}async function Ko(){if(qo=null,!vr.length)return;let t=vr;vr=[];try{let{data:{session:e}}=await gr.auth.getSession();if(!e?.access_token)return;await fetch(Cd,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${e.access_token}`,apikey:import.meta.env.VITE_SUPABASE_ANON_KEY},body:JSON.stringify({events:t})})}catch{}}typeof window<"u"&&window.addEventListener("pagehide",()=>{ss&&wr("page_leave",{counts:{seconds:Math.round((Date.now()-Wo)/1e3)}}),Ko()});var Nd=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`;async function jd(t){let{data:{session:e}}=await gr.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,n=JSON.stringify({format:t.format,source_filename:t.sourceFilename,persist:t.persist,session_id:t.sessionId,selected_sequence_names:t.selectedSequenceNames,previously_selected_names:t.previouslySelectedNames}),s=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),i=n+`
68
- `+s,o=new Set([502,503,504,529,546]),a=null;for(let l=0;;l++){try{a=await fetch(`${Nd}/v1-timeline-canonicalize/v1/timeline-canonicalize`,{method:"POST",headers:{"Content-Type":"application/x-ct-canonicalize-v1",Authorization:`Bearer ${r}`},body:i})}catch(c){if(l>=2)throw c;a=null}if(a&&(a.ok||!o.has(a.status)))break;if(l>=2)throw a?.status===546?new Error("Our conversion server stopped this timeline three times in a row. That is a limit on our side, not a problem with your file. Please try again later; if it keeps failing, converting fewer sequences at a time gets it through, and we'd like to hear about it."):new Error(`The processing server timed out (${a?.status??"network error"}) \u2014 a server hiccup, not a problem with your file. Please try again in a minute.`);await new Promise(c=>setTimeout(c,1500*(l+1)))}if(!a.ok){let l=await a.json().catch(()=>({}));throw new Error(l?.error?.message??`canonicalize failed (${a.status})`)}return await a.json()}async function zo(t){return!t.sessionId&&!Vo()&&Mo(),Ho("timeline_read",()=>jd(t),e=>({fields:[`format=${String(t.format).toLowerCase()}`,...t.selectedSequenceNames?.length?[]:["scope=project"]],counts:{timelines:e.session?.timelines?.length??0},session_id:e.session_id??void 0}))}var Ud=[{ext:"mov",name:"QuickTime",container:"mov",codec:"prores",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"mp4",name:"MPEG-4",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4v",name:"MPEG-4 Video",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4a",name:"MPEG-4 Audio",container:"mov",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mxf",name:"MXF",container:"mxf",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback for XAVC-I NDF/DF. Coordinated 45-patch metadata rewrite (index entries + Duration fields). DNxHD foundation works; mid-clip trim works structurally; awaiting more corpus."},{ext:"r3d",name:"RED RAW",container:"r3d",codec:"r3d",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback (V-Raptor 6K). Trim/prepare/inspect run client-side as opaque WASM (mediaOp) \u2014 browser sees no algorithm; WS bridge retired. DRAGON era + Komodo + 8K need corpus expansion. Run oracle/i2o/cli/r3d-corpus.ts on new fixtures."},{ext:"braw",name:"Blackmagic RAW",container:"mov",codec:"braw",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:'Verified Resolve playback. Standard MP4 container with BRAW codec; reuses structure-preserving MOV walker. The "secret sauce" was knowing BRAW = MP4.'},{ext:"crm",name:"Canon Cinema RAW Light",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"Frame-indexed single file. Canon SDK available."},{ext:"rmf",name:"Canon RAW (legacy)",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"ari",name:"ARRIRAW",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"8KB header + raw Bayer per frame. Sparse = select which .ari files to include."},{ext:"arx",name:"ARRIRAW HDE",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"dpx",name:"DPX",container:"frame-seq",codec:"dpx",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"SMPTE 268M. Image data offset at byte 4. ~25MB per 4K frame."},{ext:"exr",name:"OpenEXR",container:"frame-seq",codec:"exr",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tif",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tiff",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"png",name:"PNG",container:"frame-seq",codec:"png",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpeg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"psd",name:"Photoshop",container:"still",codec:"psd",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tga",name:"Targa",container:"still",codec:"tga",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"bmp",name:"Bitmap",container:"still",codec:"bmp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"gif",name:"GIF",container:"still",codec:"gif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"webp",name:"WebP",container:"still",codec:"webp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"avif",name:"AVIF",container:"still",codec:"avif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"wav",name:"WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"RIFF/WAV trim decoder ships. Poly WAV (8-24ch) could benefit from time-axis chunking."},{ext:"bwf",name:"Broadcast WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"WAV + bext chunk (~602+ bytes) with timecode reference. Same trim decoder as WAV."},{ext:"aif",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aiff",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"mp3",name:"MP3",container:"audio",codec:"mp3",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aac",name:"AAC",container:"audio",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"avi",name:"AVI",container:"avi",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mkv",name:"Matroska",container:"mkv",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"m2ts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"webm",name:"WebM",container:"mkv",codec:"vp9",frameType:"inter",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1}],Go=new Map;for(let t of Ud)Go.set(t.ext,t);function Ld(t){let e=t.split(".").pop()?.toLowerCase();return e?Go.get(e)??null:null}function Jo(t){return Ld(t)!==null}var Zd=ze(la());var Qd=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Ar=class extends Error{constructor(e,r){super(r??"A new version of Conform was released while this page was open, so part of the app could no longer be loaded. Reload the page to continue \u2014 nothing has been sent yet."),this.name="StaleBuildError",this.chunk=e,this.buildSha=Qd}};var ca=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Hf=900*1e3;async function eh(t=fetch,e=ca){if(!e||e==="dev"||e==="unknown")return!1;try{let r=await t(`/build-info.json?t=${Date.now()}`,{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();return typeof n.sha=="string"&&n.sha!==""&&n.sha!=="unknown"&&n.sha!==e}catch{return!1}}async function da(t=fetch,e=ca){if(await eh(t,e))throw new Ar("timeline-read","A new version of Conform was released while this page was open. Reload the page and drop the file again \u2014 nothing has been read or sent yet.")}function ha(){return typeof window<"u"&&!!window.__CONFORM_ENGINE__}async function tp(t){if(Jo(t.name))return await th(t);let e=await Hr(t);if(e.format!=="unknown"&&Vr(e.format)){let{names:r}=await Zs(t,e.format);return{kind:"timeline",format:e.format,name:t.name,observed_bytes:t.size,total_size:t.size,session:{id:null,inline:{timelines:r.map(n=>({name:n}))}},warnings:[],inspector:{layer:"timeline-core/wasm-inspect",version:"1",duration_ms:0}}}return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:`Unrecognized file: ${t.name}`}],inspector:{layer:"inspect/unknown",version:"1",duration_ms:0}}}async function th(t){let e=Date.now(),r=await ti(t);if(!r)return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:"No browser-side probe available (proprietary format or unsupported extension)"}],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}};let n=r.container??"media",s={metadata:{id:t.name,user_id:"",source_format:n,source_filename:t.name,source_file_sha256:null,source_file_bytes:t.size,parser_name:`media:${n}`,parser_version:"1",status:"ready",error_message:null,metadata:{},created_at:new Date().toISOString()},timelines:[],media_references:[r]};return{kind:"media",format:n,name:t.name,observed_bytes:0,total_size:t.size,session:{id:null,inline:s},warnings:[],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}}}var fa=new Map,rh=t=>t.replace(/^[a-z]\d+:/,""),rp=t=>fa.get(rh(t));async function np(t,e={}){if(ha()){let{engine:o}=await import("./engine-K6QYU5KJ.js"),a=await o.canonicalize(t,e.selectedSequenceNames,e.previouslySelectedNames);for(let l of a.session.timelines??[])fa.set(l.id,a.session_id);return{session:a.session,sessionId:a.session_id,persistError:null}}let{format:r}=await Hr(t);if(!Vr(r))throw new Error(`No Rust timeline engine for format '${r}' (${t.name})`);await da();let{fmt:n,extract:s}=await ei(t,r,e.selectedSequenceNames),i=await zo({format:n,extract:s,sourceFilename:t.name,persist:e.persist,sessionId:e.sessionId,selectedSequenceNames:e.selectedSequenceNames,previouslySelectedNames:e.previouslySelectedNames});return{session:i.session,sessionId:i.session_id??i.session?.id??null,persistError:i.persist_error??null}}export{np as canonicalizeTimelineFile,rp as engineSessionFor,rh as engineTimelineId,tp as inspectFile};
67
+ ${h.stack}`)}else{var v;a=(v=i?.stack)!==null&&v!==void 0?v:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} 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.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} 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.`)),{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:a,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},Uu=class extends Lu{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let s=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),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:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Li=new RegExp("[,()]"),Xe=class extends Uu{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Li.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Li.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${i}.${e}`),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},$u=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:s=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},s=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Xe({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new Xe({method:s,url:i,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),s||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((h,m)=>h.concat(Object.keys(m)),[]);if(c.length>0){let h=[...new Set(c)].map(m=>`"${m}"`);a.searchParams.set("columns",h.join(","))}}return new Xe({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Xe({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new Xe({method:r,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ct(t){"@babel/helpers - typeof";return ct=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ct(t)}function Du(t,e){if(ct(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ct(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Fu(t){var e=Du(t,"string");return ct(e)=="symbol"?e:e+""}function Bu(t,e,r){return(e=Fu(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Ui(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function Vt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ui(Object(r),!0).forEach(function(n){Bu(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ui(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var $i=class Di{constructor(e,{headers:r={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let h=new AbortController,m=setTimeout(()=>h.abort(),i),_=c?.signal;if(_){if(_.aborted)return clearTimeout(m),a(l,c);let f=()=>{clearTimeout(m),h.abort()};return _.addEventListener("abort",f,{once:!0}),a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(m),_.removeEventListener("abort",f)})}return a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>clearTimeout(m))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new $u(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Di(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:s=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,h=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(h)),m=n&&Object.values(r).some(h);m?(a="POST",c=r):n||s?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{l.searchParams.append(f,y)})):(a="POST",c=r);let _=new Headers(this.headers);return m?_.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&_.set("Prefer",`count=${i}`),new Xe({method:a,url:l,headers:_,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var Uo=ze(vn(),1);var mt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function cl(t,e,r){let n=new URL(e,t);if(r)for(let[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function dl(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function hl(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){let a=cl(t.baseUrl,n,s),l=await dl(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),m=(c.headers.get("content-type")||"").includes("application/json"),_=m&&h?JSON.parse(h):h;if(!c.ok){let f=m?_:void 0,y=f?.error;throw new mt(y?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:y?.type,icebergCode:y?.code,details:f})}return{status:c.status,headers:c.headers,data:_}}}}function Zt(t){return t.join("")}var fl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Zt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`}),!0}catch(e){if(e instanceof mt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof mt&&r.status===409)return;throw r}}};function Qe(t){return t.join("")}var pl=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof mt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof mt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Zi=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=hl({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new fl(this.client,e),this.tableOps=new pl(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var tr=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function rr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var er=class extends tr{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},no=class extends tr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var ml=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),_l=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},wn=t=>{if(Array.isArray(t))return t.map(r=>wn(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=wn(n)}),e},gl=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function gt(t){"@babel/helpers - typeof";return gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gt(t)}function yl(t,e){if(gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(gt(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vl(t){var e=yl(t,"string");return gt(e)=="symbol"?e:e+""}function wl(t,e,r){return(e=vl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function eo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?eo(Object(r),!0).forEach(function(n){wl(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):eo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var to=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},bl=async(t,e,r,n)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let s=t,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new er(to(o),i,a,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new no(to(t),t,n))},El=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?P(P({},s),r):(_l(n)?(s.headers=P({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(n)):s.body=n,e?.duplex&&(s.duplex=e.duplex),P(P({},s),r))};async function _t(t,e,r,n,s,i,o){return new Promise((a,l)=>{t(r,El(e,n,s,i)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>bl(c,l,n,o))})}function so(t="storage"){return{get:async(e,r,n,s)=>_t(e,"GET",r,n,s,void 0,t),post:async(e,r,n,s,i)=>_t(e,"POST",r,s,i,n,t),put:async(e,r,n,s,i)=>_t(e,"PUT",r,s,i,n,t),head:async(e,r,n,s)=>_t(e,"HEAD",r,P(P({},n),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,r,n,s,i)=>_t(e,"DELETE",r,s,i,n,t)}}var Sl=so("storage"),{get:yt,post:Ae,put:bn,head:Tl,remove:En}=Sl,me=so("vectors"),Ze=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=ml(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=P(P({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(rr(r))return{data:null,error:r};throw r}}},Al=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},io;io=Symbol.toStringTag;var Rl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[io]="BlobDownloadBuilder",this.promise=null}asStream(){return new Al(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},kl={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ro={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Ol=class extends Ze{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var s=this;return s.handleOperation(async()=>{let i,o=P(P({},ro),n),a=P(P({},s.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=P(P({},a),n.headers));let c=s._removeEmptyFolders(e),h=s._getFinalPath(c),m=await(t=="PUT"?bn:Ae)(s.fetch,`${s.url}/object/${h}`,i,P({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:m.Id,fullPath:m.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var s=this;let i=s._removeEmptyFolders(t),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),s.handleOperation(async()=>{let l,c=P({upsert:ro.upsert},n),h=P(P({},s.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType),{path:i,fullPath:(await bn(s.fetch,a.toString(),l,{headers:h})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),s=P({},r.headers);e?.upsert&&(s["x-upsert"]="true");let i=await Ae(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new tr("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Ae(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Ae(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(t),i=await Ae(n.fetch,`${n.url}/object/sign/${s}`,P({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:n.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let s=await Ae(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return s.map(o=>P(P({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString(e?.transform||{}),i=s?`?${s}`:"",o=this._getFinalPath(t),a=()=>yt(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Rl(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>wn(await yt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Tl(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(rr(n)&&n instanceof no){let s=n.originalError;if([400,404].includes(s?.status))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],s=e?.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let s=P(P(P({},kl),e),{},{prefix:t||""});return await Ae(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=P({},t);return await Ae(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},Cl="2.97.0",vt={"X-Client-Info":`storage-js/${Cl}`},Pl=class extends Ze{constructor(t,e={},r,n){let s=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=P(P({},vt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await yt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Ae(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await bn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Il=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),e);super(n,s,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await yt(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!gl(t))throw new tr("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 r=new Zi({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},xl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Nl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},jl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Ll=class extends jl{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Ul(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Ul=class extends xl{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new $l(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},$l=class extends Nl{constructor(t,e,r,n,s){super(t,e,s),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},oo=class extends Pl{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new Ol(this.url,this.headers,t,this.fetch)}get vectors(){return new Ll(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Il(this.url+"/iceberg",this.headers,this.fetch)}};var $o=ze(ts(),1);k(A,ze(vn(),1));k(A,ze(ts(),1));var hd="2.97.0",Tt="";typeof Deno<"u"?Tt="deno":typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":Tt="node";var fd={"X-Client-Info":`supabase-js-${Tt}/${hd}`},pd={headers:fd},md={schema:"public"},_d={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},gd={};function At(t){"@babel/helpers - typeof";return At=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},At(t)}function yd(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(At(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function vd(t){var e=yd(t,"string");return At(e)=="symbol"?e:e+""}function wd(t,e,r){return(e=vd(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Lo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function se(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Lo(Object(r),!0).forEach(function(n){wd(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Lo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var bd=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ed=()=>Headers,Sd=(t,e,r)=>{let n=bd(r),s=Ed();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new s(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(i,se(se({},o),{},{headers:c}))}};function Td(t){return t.endsWith("/")?t:t+"/"}function Ad(t,e){var r,n;let{db:s,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:h,global:m}=e,_={db:se(se({},l),s),auth:se(se({},c),i),realtime:se(se({},h),o),storage:{},global:se(se(se({},m),a),{},{headers:se(se({},(r=m?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Rd(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Td(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var kd=class extends $o.AuthClient{constructor(t){super(t)}},Do=class{constructor(t,e,r){var n,s;this.supabaseUrl=t,this.supabaseKey=e;let i=Rd(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:md,realtime:gd,auth:se(se({},_d),{},{storageKey:o}),global:pd},l=Ad(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,m)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=Sd(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(se({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new $i(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new oo(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new be.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,m){let _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new kd({url:this.authUrl.href,headers:se(se({},_),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Uo.RealtimeClient(this.realtimeUrl.href,se(se({},t),{},{params:se(se({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},rs=(t,e,r)=>new Do(t,e,r);function Od(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Od()&&console.warn("\u26A0\uFE0F Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function Fo(t,e){return async(r,n,s)=>{let i,o=()=>i??=s(),a=l=>i&&l?.name==="AbortError";try{return await t(r,n,o)}catch(l){if(a(l))return i;if(!l?.isAcquireTimeout)throw l;try{return await e(r,o)}catch(c){if(a(c))return i;throw c}}}}var Rt=typeof window<"u"&&!!window.__CONFORM_ENGINE__,Bo=Rt?"http://127.0.0.1:9":import.meta.env.VITE_SUPABASE_URL,qo=Rt?"offline":import.meta.env.VITE_SUPABASE_ANON_KEY;if(!Bo)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!qo)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var gr=rs(Bo,qo,{auth:{autoRefreshToken:!Rt,persistSession:!Rt,detectSessionInUrl:!Rt,...typeof navigator<"u"&&navigator.locks?{lock:Fo(A.navigatorLock,(t,e)=>navigator.locks.request(t,{steal:!0},e))}:{}}});var Cd=typeof __BUILD_SHA__<"u"?`web-${__BUILD_SHA__}`:"web-dev",Pd=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/v1-me/v1/engine/telemetry`,Id=1e4,xd=crypto.randomUUID(),yr=0,Nd=0,vr=[],Mo=null;function Wo(){yr++,ss=!1,Vo=Date.now()}var ss=!1,Vo=0;function Ho(){return ss}function wr(t,e={}){yr||(yr=1),vr.push({kind:"outcome",verb:t,ok:e.ok??!0,code:e.ok===!1?e.code??"error":void 0,error:e.ok===!1?e.error:void 0,duration_ms:Math.max(0,Math.round(e.ms??0)),counts:e.counts,fields:e.fields,session_id:e.session_id,version:Cd,run_id:xd,seq:++Nd,req:yr,event_id:crypto.randomUUID(),run_at:new Date().toISOString(),client:"web",author:"user"}),Mo??=setTimeout(()=>void zo(),Id)}var ns=null;async function Ko(t,e,r=()=>({})){let n=performance.now();ns=null;try{let s=await e(),i=ns;return ns=null,wr(t,i?{ok:!1,...i,ms:performance.now()-n}:{...r(s),ok:!0,ms:performance.now()-n}),s}catch(s){throw wr(t,{ok:!1,code:s?.code,error:s instanceof Error?s.message:String(s),ms:performance.now()-n}),s}}async function zo(){if(Mo=null,!vr.length)return;let t=vr;vr=[];try{let{data:{session:e}}=await gr.auth.getSession();if(!e?.access_token)return;await fetch(Pd,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${e.access_token}`,apikey:import.meta.env.VITE_SUPABASE_ANON_KEY},body:JSON.stringify({events:t})})}catch{}}typeof window<"u"&&window.addEventListener("pagehide",()=>{ss&&wr("page_leave",{counts:{seconds:Math.round((Date.now()-Vo)/1e3)}}),zo()});var jd=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`;async function Ld(t){let{data:{session:e}}=await gr.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,n=JSON.stringify({format:t.format,source_filename:t.sourceFilename,persist:t.persist,session_id:t.sessionId,selected_sequence_names:t.selectedSequenceNames,previously_selected_names:t.previouslySelectedNames}),s=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),i=n+`
68
+ `+s,o=new Set([502,503,504,529,546]),a=null;for(let l=0;;l++){try{a=await fetch(`${jd}/v1-timeline-canonicalize/v1/timeline-canonicalize`,{method:"POST",headers:{"Content-Type":"application/x-ct-canonicalize-v1",Authorization:`Bearer ${r}`},body:i})}catch(c){if(l>=2)throw c;a=null}if(a&&(a.ok||!o.has(a.status)))break;if(l>=2)throw a?.status===546?new Error("Our conversion server stopped this timeline three times in a row. That is a limit on our side, not a problem with your file. Please try again later; if it keeps failing, converting fewer sequences at a time gets it through, and we'd like to hear about it."):new Error(`The processing server timed out (${a?.status??"network error"}) \u2014 a server hiccup, not a problem with your file. Please try again in a minute.`);await new Promise(c=>setTimeout(c,1500*(l+1)))}if(!a.ok){let l=await a.json().catch(()=>({}));throw new Error(l?.error?.message??`canonicalize failed (${a.status})`)}return await a.json()}async function Go(t){return!t.sessionId&&!Ho()&&Wo(),Ko("timeline_read",()=>Ld(t),e=>({fields:[`format=${String(t.format).toLowerCase()}`,...t.selectedSequenceNames?.length?[]:["scope=project"]],counts:{timelines:e.session?.timelines?.length??0},session_id:e.session_id??void 0}))}var Ud=[{ext:"mov",name:"QuickTime",container:"mov",codec:"prores",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"mp4",name:"MPEG-4",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4v",name:"MPEG-4 Video",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4a",name:"MPEG-4 Audio",container:"mov",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mxf",name:"MXF",container:"mxf",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback for XAVC-I NDF/DF. Coordinated 45-patch metadata rewrite (index entries + Duration fields). DNxHD foundation works; mid-clip trim works structurally; awaiting more corpus."},{ext:"r3d",name:"RED RAW",container:"r3d",codec:"r3d",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback (V-Raptor 6K). Trim/prepare/inspect run client-side as opaque WASM (mediaOp) \u2014 browser sees no algorithm; WS bridge retired. DRAGON era + Komodo + 8K need corpus expansion. Run oracle/i2o/cli/r3d-corpus.ts on new fixtures."},{ext:"braw",name:"Blackmagic RAW",container:"mov",codec:"braw",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:'Verified Resolve playback. Standard MP4 container with BRAW codec; reuses structure-preserving MOV walker. The "secret sauce" was knowing BRAW = MP4.'},{ext:"crm",name:"Canon Cinema RAW Light",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"Frame-indexed single file. Canon SDK available."},{ext:"rmf",name:"Canon RAW (legacy)",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"ari",name:"ARRIRAW",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"8KB header + raw Bayer per frame. Sparse = select which .ari files to include."},{ext:"arx",name:"ARRIRAW HDE",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"dpx",name:"DPX",container:"frame-seq",codec:"dpx",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"SMPTE 268M. Image data offset at byte 4. ~25MB per 4K frame."},{ext:"exr",name:"OpenEXR",container:"frame-seq",codec:"exr",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tif",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tiff",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"png",name:"PNG",container:"frame-seq",codec:"png",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpeg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"psd",name:"Photoshop",container:"still",codec:"psd",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tga",name:"Targa",container:"still",codec:"tga",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"bmp",name:"Bitmap",container:"still",codec:"bmp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"gif",name:"GIF",container:"still",codec:"gif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"webp",name:"WebP",container:"still",codec:"webp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"avif",name:"AVIF",container:"still",codec:"avif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"wav",name:"WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"RIFF/WAV trim decoder ships. Poly WAV (8-24ch) could benefit from time-axis chunking."},{ext:"bwf",name:"Broadcast WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"WAV + bext chunk (~602+ bytes) with timecode reference. Same trim decoder as WAV."},{ext:"aif",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aiff",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"mp3",name:"MP3",container:"audio",codec:"mp3",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aac",name:"AAC",container:"audio",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"avi",name:"AVI",container:"avi",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mkv",name:"Matroska",container:"mkv",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"m2ts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"webm",name:"WebM",container:"mkv",codec:"vp9",frameType:"inter",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1}],Jo=new Map;for(let t of Ud)Jo.set(t.ext,t);function $d(t){let e=t.split(".").pop()?.toLowerCase();return e?Jo.get(e)??null:null}function Yo(t){return $d(t)!==null}var eh=ze(ca());var Zd=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Ar=class extends Error{constructor(e,r){super(r??"A new version of Conform was released while this page was open, so part of the app could no longer be loaded. Reload the page to continue \u2014 nothing has been sent yet."),this.name="StaleBuildError",this.chunk=e,this.buildSha=Zd}};var da=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Jf=900*1e3;async function th(t=fetch,e=da){if(!e||e==="dev"||e==="unknown")return!1;try{let r=await t(`/build-info.json?t=${Date.now()}`,{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();return typeof n.sha=="string"&&n.sha!==""&&n.sha!=="unknown"&&n.sha!==e}catch{return!1}}async function ha(t=fetch,e=da){if(await th(t,e))throw new Ar("timeline-read","A new version of Conform was released while this page was open. Reload the page and drop the file again \u2014 nothing has been read or sent yet.")}function fa(){return typeof window<"u"&&!!window.__CONFORM_ENGINE__}async function ip(t){if(Yo(t.name))return await rh(t);let e=await Hr(t);if(e.format!=="unknown"&&Vr(e.format)){let r=e.format==="flame-archive"?(await sh(t)).session.timelines.filter(n=>n.kind!=="compound"&&n.tracks?.some(s=>s.items?.length)).map(n=>n.name??"").filter(Boolean):(await Zs(t,e.format)).names;return{kind:"timeline",format:e.format,name:t.name,observed_bytes:t.size,total_size:t.size,session:{id:null,inline:{timelines:r.map(n=>({name:n}))}},warnings:[],inspector:{layer:"timeline-core/wasm-inspect",version:"1",duration_ms:0}}}return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:`Unrecognized file: ${t.name}`}],inspector:{layer:"inspect/unknown",version:"1",duration_ms:0}}}async function rh(t){let e=Date.now(),r=await ti(t);if(!r)return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:"No browser-side probe available (proprietary format or unsupported extension)"}],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}};let n=r.container??"media",s={metadata:{id:t.name,user_id:"",source_format:n,source_filename:t.name,source_file_sha256:null,source_file_bytes:t.size,parser_name:`media:${n}`,parser_version:"1",status:"ready",error_message:null,metadata:{},created_at:new Date().toISOString()},timelines:[],media_references:[r]};return{kind:"media",format:n,name:t.name,observed_bytes:0,total_size:t.size,session:{id:null,inline:s},warnings:[],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}}}var pa=new Map,nh=t=>t.replace(/^[a-z]\d+:/,""),op=t=>pa.get(nh(t));async function sh(t,e={}){if(fa()){let{engine:o}=await import("./engine-WMOJ3HRU.js"),a=await o.canonicalize(t,e.selectedSequenceNames,e.previouslySelectedNames);for(let l of a.session.timelines??[])pa.set(l.id,a.session_id);return{session:a.session,sessionId:a.session_id,persistError:null}}let{format:r}=await Hr(t);if(!Vr(r))throw new Error(`No Rust timeline engine for format '${r}' (${t.name})`);await ha();let{fmt:n,extract:s}=await ei(t,r,e.selectedSequenceNames),i=await Go({format:n,extract:s,sourceFilename:t.name,persist:e.persist,sessionId:e.sessionId,selectedSequenceNames:e.selectedSequenceNames,previouslySelectedNames:e.previouslySelectedNames});return{session:i.session,sessionId:i.session_id??i.session?.id??null,persistError:i.persist_error??null}}export{sh as canonicalizeTimelineFile,op as engineSessionFor,nh as engineTimelineId,ip as inspectFile};