conformtools 0.5.1 → 0.6.2

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 (93) hide show
  1. package/README.md +69 -6
  2. package/dist/browser/timeline_core_bg.wasm +0 -0
  3. package/dist/chunk-6TM32YIJ.js +7 -0
  4. package/dist/chunk-BTXLTVNK.js +3 -0
  5. package/dist/{chunk-AHNDJFQR.js → chunk-BUEIRRNY.js} +1 -1
  6. package/dist/chunk-BXFVYGFW.js +3 -0
  7. package/dist/chunk-CX3USH6A.js +318 -0
  8. package/dist/chunk-D5DEQ467.js +3 -0
  9. package/dist/{chunk-YPRTUS5W.js → chunk-FNGHTZ5F.js} +1 -1
  10. package/dist/chunk-GXEVALBL.js +3 -0
  11. package/dist/chunk-JH3OLTR6.js +3 -0
  12. package/dist/chunk-KP4C2MFM.js +3 -0
  13. package/dist/chunk-PIEH7J6J.js +3 -0
  14. package/dist/chunk-RUBNBRUK.js +3 -0
  15. package/dist/chunk-RULUDOB7.js +3 -0
  16. package/dist/chunk-Y2BEEOPB.js +3 -0
  17. package/dist/claude-setup-XSNTKEU7.js +5 -0
  18. package/dist/cli.js +11 -5
  19. package/dist/conformtools-decode +0 -0
  20. package/dist/cr3-wasm-YTMVBAFM.js +3 -0
  21. package/dist/dng-wasm-WUUQB7M2.js +3 -0
  22. package/dist/dpx-wasm-XBKO4V4W.js +3 -0
  23. package/dist/exr-wasm-VE2W6MFW.js +3 -0
  24. package/dist/{h264-JHQCJTWP.js → h264-HD7BY5J5.js} +1 -1
  25. package/dist/{h264-mxf-4M63NBQK.js → h264-mxf-6OOODSAK.js} +1 -1
  26. package/dist/http.js +2 -2
  27. package/dist/{inspect-6OM4FTVW.js → inspect-TDZCNXVW.js} +2 -2
  28. package/dist/isobmff-57HSD6O2.js +3 -0
  29. package/dist/mcp.js +10 -9
  30. package/dist/media_core-R5PPN3AY.js +9 -0
  31. package/dist/{media_core_bg-XIM7Y4R3.js → media_core_bg-YBW45HJ2.js} +1 -1
  32. package/dist/mxf-FAXEK4WR.js +3 -0
  33. package/dist/{ops-7HVBBXUQ.js → ops-UPPAG2TI.js} +1 -1
  34. package/dist/premiere-uxp/icons/panel.png +0 -0
  35. package/dist/premiere-uxp/icons/panel@2x.png +0 -0
  36. package/dist/premiere-uxp/icons/plugin.png +0 -0
  37. package/dist/premiere-uxp/icons/plugin@2x.png +0 -0
  38. package/dist/premiere-uxp/index.html +38 -0
  39. package/dist/premiere-uxp/index.js +93 -0
  40. package/dist/premiere-uxp/lib/clipmeta.js +170 -0
  41. package/dist/premiere-uxp/lib/ctx.js +62 -0
  42. package/dist/premiere-uxp/lib/handles.js +57 -0
  43. package/dist/premiere-uxp/lib/markers.js +198 -0
  44. package/dist/premiere-uxp/lib/pairing.js +58 -0
  45. package/dist/premiere-uxp/lib/premiere.js +82 -0
  46. package/dist/premiere-uxp/lib/probe.js +139 -0
  47. package/dist/premiere-uxp/lib/protocol.js +165 -0
  48. package/dist/premiere-uxp/lib/render.js +38 -0
  49. package/dist/premiere-uxp/lib/session.js +85 -0
  50. package/dist/premiere-uxp/lib/sizing.js +312 -0
  51. package/dist/premiere-uxp/lib/time.js +82 -0
  52. package/dist/premiere-uxp/lib/timeline.js +336 -0
  53. package/dist/premiere-uxp/lib/verbs.js +20 -0
  54. package/dist/premiere-uxp/lib/write.js +97 -0
  55. package/dist/premiere-uxp/manifest.json +102 -0
  56. package/dist/{r3d-AT6NNIY3.js → r3d-EY6FEFKM.js} +1 -1
  57. package/dist/r3d-KJVC7T2C.js +3 -0
  58. package/dist/resolve-bridge.py +974 -0
  59. package/dist/resolve-presets/conform.tools.xml +127 -0
  60. package/dist/sscd-embed-DHFTEIOC.js +3 -0
  61. package/dist/sscd-sweep-OYS4XAID.js +3 -0
  62. package/dist/statusline-GMMCFMOA.js +4 -0
  63. package/dist/statusline.js +3 -0
  64. package/dist/{still-E4HLCCST.js → still-WY7MUR7A.js} +1 -1
  65. package/dist/tiff-wasm-T2V2ICZT.js +3 -0
  66. package/dist/wasm/media_core_bg.wasm +0 -0
  67. package/dist/wasm/udf_bg.wasm +0 -0
  68. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  69. package/dist/{wav-DXF73Y56.js → wav-LFS6OZHJ.js} +1 -1
  70. package/package.json +1 -1
  71. package/dist/chunk-35U7WGES.js +0 -3
  72. package/dist/chunk-3XTUTEKJ.js +0 -102
  73. package/dist/chunk-HJXRLQOI.js +0 -3
  74. package/dist/chunk-IDDQR56R.js +0 -7
  75. package/dist/chunk-UUMHVA7R.js +0 -3
  76. package/dist/chunk-WWGQFOB2.js +0 -64
  77. package/dist/cr3-wasm-X6Q4YMUU.js +0 -3
  78. package/dist/dng-wasm-EAB24KDN.js +0 -3
  79. package/dist/dpx-wasm-OX2D24ZB.js +0 -3
  80. package/dist/exr-wasm-Z6BBPJSN.js +0 -3
  81. package/dist/isobmff-XL33CVJR.js +0 -3
  82. package/dist/media_core-VSTO6CS4.js +0 -9
  83. package/dist/mxf-VIANACTI.js +0 -3
  84. package/dist/r3d-2QCFX7UX.js +0 -3
  85. package/dist/sscd-sweep-IXM4OD7O.js +0 -3
  86. package/dist/tiff-wasm-XYTQNL2F.js +0 -3
  87. package/dist/zod-IPSV75LP.js +0 -3
  88. /package/dist/{arriraw-Y5VXHXNX.js → arriraw-BEZILZY3.js} +0 -0
  89. /package/dist/{chunk-NYB4ISL3.js → chunk-NP53ITN6.js} +0 -0
  90. /package/dist/{media_core_bg-BKXQLNFA.js → media_core_bg-5UIQAP7I.js} +0 -0
  91. /package/dist/{prores-TQEZ3KFH.js → prores-BNALPJPS.js} +0 -0
  92. /package/dist/{timeline_core_bg-QEOVAIWP.js → timeline_core_bg-XYT26ZTU.js} +0 -0
  93. /package/dist/{udf_bg-UTQ6BVXX.js → udf_bg-R3JEZJAT.js} +0 -0
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
3
- import{e as kt,f as qr,h as Br,k as Fr}from"./chunk-35U7WGES.js";import"./chunk-P7OVDUA5.js";import"./chunk-UCMNH6Q6.js";import"./chunk-YPRTUS5W.js";import"./chunk-C2ESM27Z.js";import{b as Cn,c as P,d as Dr,e as E,f as Ie,g as re}from"./chunk-PSANHDZM.js";var Y={};Dr(Y,{__addDisposableResource:()=>ps,__assign:()=>ze,__asyncDelegator:()=>os,__asyncGenerator:()=>is,__asyncValues:()=>as,__await:()=>ve,__awaiter:()=>Zr,__classPrivateFieldGet:()=>hs,__classPrivateFieldIn:()=>fs,__classPrivateFieldSet:()=>ds,__createBinding:()=>Ye,__decorate:()=>Kr,__disposeResources:()=>ms,__esDecorate:()=>zr,__exportStar:()=>ts,__extends:()=>Wr,__generator:()=>es,__importDefault:()=>us,__importStar:()=>cs,__makeTemplateObject:()=>ls,__metadata:()=>Qr,__param:()=>Gr,__propKey:()=>Yr,__read:()=>It,__rest:()=>Hr,__rewriteRelativeImportExtension:()=>_s,__runInitializers:()=>Jr,__setFunctionName:()=>Xr,__spread:()=>rs,__spreadArray:()=>ns,__spreadArrays:()=>ss,__values:()=>Je,default:()=>Ln});function Wr(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ot(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Hr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Kr(t,e,r,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,r):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,s);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(n<3?o(i):n>3?o(e,r,i):o(e,r))||i);return n>3&&i&&Object.defineProperty(e,r,i),i}function Gr(t,e){return function(r,s){e(r,s,t)}}function zr(t,e,r,s,n,i){function o(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var a=s.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?s.static?t:t.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,s.name):{}),d,f=!1,h=r.length-1;h>=0;h--){var p={};for(var m in s)p[m]=m==="access"?{}:s[m];for(var m in s.access)p.access[m]=s.access[m];p.addInitializer=function(y){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(y||null))};var _=(0,r[h])(a==="accessor"?{get:u.get,set:u.set}:u[l],p);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(d=o(_.get))&&(u.get=d),(d=o(_.set))&&(u.set=d),(d=o(_.init))&&n.unshift(d)}else(d=o(_))&&(a==="field"?n.unshift(d):u[l]=d)}c&&Object.defineProperty(c,s.name,u),f=!0}function Jr(t,e,r){for(var s=arguments.length>2,n=0;n<e.length;n++)r=s?e[n].call(t,r):e[n].call(t);return s?r:void 0}function Yr(t){return typeof t=="symbol"?t:"".concat(t)}function Xr(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 Qr(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Zr(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(d){o(d)}}function l(u){try{c(s.throw(u))}catch(d){o(d)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,e||[])).next())})}function es(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,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(u){return l([c,u])}}function l(c){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(s=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=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++,n=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(u){c=[6,u],n=0}finally{s=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ts(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ye(e,t,r)}function Je(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function It(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function rs(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(It(arguments[e]));return t}function ss(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var s=Array(t),n=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,n++)s[n]=i[o];return s}function ns(t,e,r){if(r||arguments.length===2)for(var s=0,n=e.length,i;s<n;s++)(i||!(s in e))&&(i||(i=Array.prototype.slice.call(e,0,s)),i[s]=e[s]);return t.concat(i||Array.prototype.slice.call(e))}function ve(t){return this instanceof ve?(this.v=t,this):new ve(t)}function is(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=r.apply(t,e||[]),n,i=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(h){return function(p){return Promise.resolve(p).then(h,d)}}function a(h,p){s[h]&&(n[h]=function(m){return new Promise(function(_,y){i.push([h,m,_,y])>1||l(h,m)})},p&&(n[h]=p(n[h])))}function l(h,p){try{c(s[h](p))}catch(m){f(i[0][3],m)}}function c(h){h.value instanceof ve?Promise.resolve(h.value.v).then(u,d):f(i[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function f(h,p){h(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function os(t){var e,r;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,i){e[n]=t[n]?function(o){return(r=!r)?{value:ve(t[n](o)),done:!1}:i?i(o):o}:i}}function as(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 Je=="function"?Je(t):t[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),n(a,l,o.done,o.value)})}}function n(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function ls(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function cs(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=Pt(t),s=0;s<r.length;s++)r[s]!=="default"&&Ye(e,t,r[s]);return jn(e,t),e}function us(t){return t&&t.__esModule?t:{default:t}}function hs(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}function ds(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function fs(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 ps(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var s,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=e[Symbol.asyncDispose]}if(s===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=e[Symbol.dispose],r&&(n=s)}if(typeof s!="function")throw new TypeError("Object not disposable.");n&&(s=function(){try{n.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:s,async:r})}else r&&t.stack.push({async:!0});return e}function ms(t){function e(i){t.error=t.hasError?new Un(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,s=0;function n(){for(;r=t.stack.pop();)try{if(!r.async&&s===1)return s=0,t.stack.push(r),Promise.resolve().then(n);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(n,function(o){return e(o),n()})}else s|=1}catch(o){e(o)}if(s===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return n()}function _s(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,s,n,i,o){return s?e?".jsx":".js":n&&(!i||!o)?r:n+i+"."+o.toLowerCase()+"js"}):t}var Ot,ze,Ye,jn,Pt,Un,Ln,X=Cn(()=>{Ot=function(t,e){return Ot=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(r[n]=s[n])},Ot(t,e)};ze=function(){return ze=Object.assign||function(e){for(var r,s=1,n=arguments.length;s<n;s++){r=arguments[s];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},ze.apply(this,arguments)};Ye=Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]});jn=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},Pt=function(t){return Pt=Object.getOwnPropertyNames||function(e){var r=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[r.length]=s);return r},Pt(t)};Un=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var s=new Error(r);return s.name="SuppressedError",s.error=t,s.suppressed=e,s};Ln={__extends:Wr,__assign:ze,__rest:Hr,__decorate:Kr,__param:Gr,__esDecorate:zr,__runInitializers:Jr,__propKey:Yr,__setFunctionName:Xr,__metadata:Qr,__awaiter:Zr,__generator:es,__createBinding:Ye,__exportStar:ts,__values:Je,__read:It,__spread:rs,__spreadArrays:ss,__spreadArray:ns,__await:ve,__asyncGenerator:is,__asyncDelegator:os,__asyncValues:as,__makeTemplateObject:ls,__importStar:cs,__importDefault:us,__classPrivateFieldGet:hs,__classPrivateFieldSet:ds,__classPrivateFieldIn:fs,__addDisposableResource:ps,__disposeResources:ms,__rewriteRelativeImportExtension:_s}});var gs=P(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.resolveFetch=void 0;var $n=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Xe.resolveFetch=$n});var jt=P(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.FunctionRegion=Q.FunctionsHttpError=Q.FunctionsRelayError=Q.FunctionsFetchError=Q.FunctionsError=void 0;var we=class extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}};Q.FunctionsError=we;var Ct=class extends we{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};Q.FunctionsFetchError=Ct;var xt=class extends we{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};Q.FunctionsRelayError=xt;var Nt=class extends we{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};Q.FunctionsHttpError=Nt;var ys;(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"})(ys||(Q.FunctionRegion=ys={}))});var vs=P(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.FunctionsClient=void 0;var Dn=(X(),re(Y)),qn=gs(),be=jt(),Ut=class{constructor(e,{headers:r={},customFetch:s,region:n=be.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=(0,qn.resolveFetch)(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Dn.__awaiter(this,arguments,void 0,function*(r,s={}){var n;let i,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=s,f={},{region:h}=s;h||(h=this.region);let p=new URL(`${this.url}/${r}`);h&&h!=="any"&&(f["x-region"]=h,p.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(f["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(f["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,i=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let y=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:m,signal:_}).catch(H=>{throw new be.FunctionsFetchError(H)}),S=y.headers.get("x-relay-error");if(S&&S==="true")throw new be.FunctionsRelayError(y);if(!y.ok)throw new be.FunctionsHttpError(y);let w=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),k;return w==="application/json"?k=yield y.json():w==="application/octet-stream"||w==="application/pdf"?k=yield y.blob():w==="text/event-stream"?k=y:w==="multipart/form-data"?k=yield y.formData():k=yield y.text(),{data:k,error:null,response:y}}catch(a){return{data:null,error:a,response:a instanceof be.FunctionsHttpError||a instanceof be.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Qe.FunctionsClient=Ut});var ws=P(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.FunctionRegion=G.FunctionsRelayError=G.FunctionsHttpError=G.FunctionsFetchError=G.FunctionsError=G.FunctionsClient=void 0;var Bn=vs();Object.defineProperty(G,"FunctionsClient",{enumerable:!0,get:function(){return Bn.FunctionsClient}});var Ce=jt();Object.defineProperty(G,"FunctionsError",{enumerable:!0,get:function(){return Ce.FunctionsError}});Object.defineProperty(G,"FunctionsFetchError",{enumerable:!0,get:function(){return Ce.FunctionsFetchError}});Object.defineProperty(G,"FunctionsHttpError",{enumerable:!0,get:function(){return Ce.FunctionsHttpError}});Object.defineProperty(G,"FunctionsRelayError",{enumerable:!0,get:function(){return Ce.FunctionsRelayError}});Object.defineProperty(G,"FunctionRegion",{enumerable:!0,get:function(){return Ce.FunctionRegion}})});var $t=P(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebSocketFactory=void 0;var et=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 s=r.versions;if(s&&s.node){let n=s.node,i=parseInt(n.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{e as kt,f as qr,h as Br,k as Fr}from"./chunk-JH3OLTR6.js";import"./chunk-C2ESM27Z.js";import"./chunk-P7OVDUA5.js";import"./chunk-UCMNH6Q6.js";import"./chunk-FNGHTZ5F.js";import{b as Cn,c as P,d as Dr,e as E,f as Ie,g as re}from"./chunk-PSANHDZM.js";var Y={};Dr(Y,{__addDisposableResource:()=>ps,__assign:()=>ze,__asyncDelegator:()=>os,__asyncGenerator:()=>is,__asyncValues:()=>as,__await:()=>ve,__awaiter:()=>Zr,__classPrivateFieldGet:()=>hs,__classPrivateFieldIn:()=>fs,__classPrivateFieldSet:()=>ds,__createBinding:()=>Ye,__decorate:()=>Kr,__disposeResources:()=>ms,__esDecorate:()=>zr,__exportStar:()=>ts,__extends:()=>Wr,__generator:()=>es,__importDefault:()=>us,__importStar:()=>cs,__makeTemplateObject:()=>ls,__metadata:()=>Qr,__param:()=>Gr,__propKey:()=>Yr,__read:()=>It,__rest:()=>Hr,__rewriteRelativeImportExtension:()=>_s,__runInitializers:()=>Jr,__setFunctionName:()=>Xr,__spread:()=>rs,__spreadArray:()=>ns,__spreadArrays:()=>ss,__values:()=>Je,default:()=>Ln});function Wr(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ot(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Hr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Kr(t,e,r,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,r):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,s);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(n<3?o(i):n>3?o(e,r,i):o(e,r))||i);return n>3&&i&&Object.defineProperty(e,r,i),i}function Gr(t,e){return function(r,s){e(r,s,t)}}function zr(t,e,r,s,n,i){function o(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var a=s.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?s.static?t:t.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,s.name):{}),d,f=!1,h=r.length-1;h>=0;h--){var p={};for(var m in s)p[m]=m==="access"?{}:s[m];for(var m in s.access)p.access[m]=s.access[m];p.addInitializer=function(y){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(y||null))};var _=(0,r[h])(a==="accessor"?{get:u.get,set:u.set}:u[l],p);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(d=o(_.get))&&(u.get=d),(d=o(_.set))&&(u.set=d),(d=o(_.init))&&n.unshift(d)}else(d=o(_))&&(a==="field"?n.unshift(d):u[l]=d)}c&&Object.defineProperty(c,s.name,u),f=!0}function Jr(t,e,r){for(var s=arguments.length>2,n=0;n<e.length;n++)r=s?e[n].call(t,r):e[n].call(t);return s?r:void 0}function Yr(t){return typeof t=="symbol"?t:"".concat(t)}function Xr(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 Qr(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Zr(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(d){o(d)}}function l(u){try{c(s.throw(u))}catch(d){o(d)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,e||[])).next())})}function es(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,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(u){return l([c,u])}}function l(c){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(s=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=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++,n=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(u){c=[6,u],n=0}finally{s=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ts(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ye(e,t,r)}function Je(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function It(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function rs(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(It(arguments[e]));return t}function ss(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var s=Array(t),n=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,n++)s[n]=i[o];return s}function ns(t,e,r){if(r||arguments.length===2)for(var s=0,n=e.length,i;s<n;s++)(i||!(s in e))&&(i||(i=Array.prototype.slice.call(e,0,s)),i[s]=e[s]);return t.concat(i||Array.prototype.slice.call(e))}function ve(t){return this instanceof ve?(this.v=t,this):new ve(t)}function is(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=r.apply(t,e||[]),n,i=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(h){return function(p){return Promise.resolve(p).then(h,d)}}function a(h,p){s[h]&&(n[h]=function(m){return new Promise(function(_,y){i.push([h,m,_,y])>1||l(h,m)})},p&&(n[h]=p(n[h])))}function l(h,p){try{c(s[h](p))}catch(m){f(i[0][3],m)}}function c(h){h.value instanceof ve?Promise.resolve(h.value.v).then(u,d):f(i[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function f(h,p){h(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function os(t){var e,r;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,i){e[n]=t[n]?function(o){return(r=!r)?{value:ve(t[n](o)),done:!1}:i?i(o):o}:i}}function as(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 Je=="function"?Je(t):t[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),n(a,l,o.done,o.value)})}}function n(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function ls(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function cs(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=Pt(t),s=0;s<r.length;s++)r[s]!=="default"&&Ye(e,t,r[s]);return jn(e,t),e}function us(t){return t&&t.__esModule?t:{default:t}}function hs(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}function ds(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function fs(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 ps(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var s,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=e[Symbol.asyncDispose]}if(s===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=e[Symbol.dispose],r&&(n=s)}if(typeof s!="function")throw new TypeError("Object not disposable.");n&&(s=function(){try{n.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:s,async:r})}else r&&t.stack.push({async:!0});return e}function ms(t){function e(i){t.error=t.hasError?new Un(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,s=0;function n(){for(;r=t.stack.pop();)try{if(!r.async&&s===1)return s=0,t.stack.push(r),Promise.resolve().then(n);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(n,function(o){return e(o),n()})}else s|=1}catch(o){e(o)}if(s===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return n()}function _s(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,s,n,i,o){return s?e?".jsx":".js":n&&(!i||!o)?r:n+i+"."+o.toLowerCase()+"js"}):t}var Ot,ze,Ye,jn,Pt,Un,Ln,X=Cn(()=>{Ot=function(t,e){return Ot=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(r[n]=s[n])},Ot(t,e)};ze=function(){return ze=Object.assign||function(e){for(var r,s=1,n=arguments.length;s<n;s++){r=arguments[s];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},ze.apply(this,arguments)};Ye=Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]});jn=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},Pt=function(t){return Pt=Object.getOwnPropertyNames||function(e){var r=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[r.length]=s);return r},Pt(t)};Un=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var s=new Error(r);return s.name="SuppressedError",s.error=t,s.suppressed=e,s};Ln={__extends:Wr,__assign:ze,__rest:Hr,__decorate:Kr,__param:Gr,__esDecorate:zr,__runInitializers:Jr,__propKey:Yr,__setFunctionName:Xr,__metadata:Qr,__awaiter:Zr,__generator:es,__createBinding:Ye,__exportStar:ts,__values:Je,__read:It,__spread:rs,__spreadArrays:ss,__spreadArray:ns,__await:ve,__asyncGenerator:is,__asyncDelegator:os,__asyncValues:as,__makeTemplateObject:ls,__importStar:cs,__importDefault:us,__classPrivateFieldGet:hs,__classPrivateFieldSet:ds,__classPrivateFieldIn:fs,__addDisposableResource:ps,__disposeResources:ms,__rewriteRelativeImportExtension:_s}});var gs=P(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.resolveFetch=void 0;var $n=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Xe.resolveFetch=$n});var jt=P(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.FunctionRegion=Q.FunctionsHttpError=Q.FunctionsRelayError=Q.FunctionsFetchError=Q.FunctionsError=void 0;var we=class extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}};Q.FunctionsError=we;var Ct=class extends we{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};Q.FunctionsFetchError=Ct;var xt=class extends we{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};Q.FunctionsRelayError=xt;var Nt=class extends we{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};Q.FunctionsHttpError=Nt;var ys;(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"})(ys||(Q.FunctionRegion=ys={}))});var vs=P(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.FunctionsClient=void 0;var Dn=(X(),re(Y)),qn=gs(),be=jt(),Ut=class{constructor(e,{headers:r={},customFetch:s,region:n=be.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=(0,qn.resolveFetch)(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Dn.__awaiter(this,arguments,void 0,function*(r,s={}){var n;let i,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=s,f={},{region:h}=s;h||(h=this.region);let p=new URL(`${this.url}/${r}`);h&&h!=="any"&&(f["x-region"]=h,p.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(f["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(f["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,i=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let y=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:m,signal:_}).catch(H=>{throw new be.FunctionsFetchError(H)}),S=y.headers.get("x-relay-error");if(S&&S==="true")throw new be.FunctionsRelayError(y);if(!y.ok)throw new be.FunctionsHttpError(y);let w=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),k;return w==="application/json"?k=yield y.json():w==="application/octet-stream"||w==="application/pdf"?k=yield y.blob():w==="text/event-stream"?k=y:w==="multipart/form-data"?k=yield y.formData():k=yield y.text(),{data:k,error:null,response:y}}catch(a){return{data:null,error:a,response:a instanceof be.FunctionsHttpError||a instanceof be.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Qe.FunctionsClient=Ut});var ws=P(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.FunctionRegion=G.FunctionsRelayError=G.FunctionsHttpError=G.FunctionsFetchError=G.FunctionsError=G.FunctionsClient=void 0;var Bn=vs();Object.defineProperty(G,"FunctionsClient",{enumerable:!0,get:function(){return Bn.FunctionsClient}});var Ce=jt();Object.defineProperty(G,"FunctionsError",{enumerable:!0,get:function(){return Ce.FunctionsError}});Object.defineProperty(G,"FunctionsFetchError",{enumerable:!0,get:function(){return Ce.FunctionsFetchError}});Object.defineProperty(G,"FunctionsHttpError",{enumerable:!0,get:function(){return Ce.FunctionsHttpError}});Object.defineProperty(G,"FunctionsRelayError",{enumerable:!0,get:function(){return Ce.FunctionsRelayError}});Object.defineProperty(G,"FunctionRegion",{enumerable:!0,get:function(){return Ce.FunctionRegion}})});var $t=P(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebSocketFactory=void 0;var et=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 s=r.versions;if(s&&s.node){let n=s.node,i=parseInt(n.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
 
@@ -39,7 +39,7 @@ Request ID: ${l}`),c){let S=`
39
39
  Resources:`;for(let w of c){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);S+=`
40
40
  - ${w}`}y+=S}return`${_}
41
41
  ${y}`}});var ln=P(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.WebAuthnUnknownError=he.WebAuthnError=void 0;he.isWebAuthnError=Jo;he.identifyRegistrationError=Yo;he.identifyAuthenticationError=Xo;var an=Ir(),D=class extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};he.WebAuthnError=D;var Pr=class extends D{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};he.WebAuthnUnknownError=Pr;function Jo(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Yo({error:t,options:e}){var r,s,n;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 D({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 D({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new D({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new D({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 D({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new D({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 D({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new D({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,an.isValidDomain)(o)){if(i.rp.id!==o)return new D({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new D({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 D({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 D({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 D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Xo({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 D({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new D({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let s=window.location.hostname;if((0,an.isValidDomain)(s)){if(r.rpId!==s)return new D({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new D({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new D({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 D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Ir=P(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.WebAuthnApi=I.DEFAULT_REQUEST_OPTIONS=I.DEFAULT_CREATION_OPTIONS=I.webAuthnAbortService=I.WebAuthnAbortService=I.identifyAuthenticationError=I.identifyRegistrationError=I.isWebAuthnError=I.WebAuthnError=void 0;I.deserializeCredentialCreationOptions=Zo;I.deserializeCredentialRequestOptions=ea;I.serializeCredentialCreationResponse=ta;I.serializeCredentialRequestResponse=ra;I.isValidDomain=sa;I.createCredential=hn;I.getCredential=dn;I.mergeCredentialCreationOptions=fn;I.mergeCredentialRequestOptions=pn;var un=(X(),re(Y)),ie=mt(),ae=me(),Qo=ke(),le=ln();Object.defineProperty(I,"identifyAuthenticationError",{enumerable:!0,get:function(){return le.identifyAuthenticationError}});Object.defineProperty(I,"identifyRegistrationError",{enumerable:!0,get:function(){return le.identifyRegistrationError}});Object.defineProperty(I,"isWebAuthnError",{enumerable:!0,get:function(){return le.isWebAuthnError}});Object.defineProperty(I,"WebAuthnError",{enumerable:!0,get:function(){return le.WebAuthnError}});var bt=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}}};I.WebAuthnAbortService=bt;I.webAuthnAbortService=new bt;function Zo(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:s}=t,n=un.__rest(t,["challenge","user","excludeCredentials"]),i=(0,ie.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,ie.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){let c=s[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,ie.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function ea(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,s=un.__rest(t,["challenge","allowCredentials"]),n=(0,ie.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});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,ie.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function ta(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,ie.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,ie.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ra(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,ie.bytesToBase64URL)(new Uint8Array(n.authenticatorData)),clientDataJSON:(0,ie.bytesToBase64URL)(new Uint8Array(n.clientDataJSON)),signature:(0,ie.bytesToBase64URL)(new Uint8Array(n.signature)),userHandle:n.userHandle?(0,ie.bytesToBase64URL)(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function sa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function cn(){var t,e;return!!((0,Qo.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 hn(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new le.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new le.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,le.identifyRegistrationError)({error:e,options:t})}}}async function dn(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new le.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new le.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,le.identifyAuthenticationError)({error:e,options:t})}}}I.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};I.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Et(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of t)if(n)for(let i in n){let o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){let a=s[i];e(a)?s[i]=Et(a,o):s[i]=Et(o)}else s[i]=o}return s}function fn(t,e){return Et(I.DEFAULT_CREATION_OPTIONS,t,e||{})}function pn(t,e){return Et(I.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Cr=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:s,signal:n},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=n??I.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=s;if(d)u.name=`${u.id}:${d}`;else{let h=(await this.client.getUser()).data.user,p=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=fn(a.webauthn.credential_options.publicKey,i?.create),{data:d,error:f}=await hn({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let u=pn(a.webauthn.credential_options.publicKey,i?.request),{data:d,error:f}=await dn(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return(0,ae.isAuthError)(a)?{data:null,error:a}:{data:null,error:new ae.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ae.AuthError("rpId is required for WebAuthn authentication")};try{if(!cn())return{data:null,error:new ae.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{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:s,credential_response:l.credential_response}})}catch(o){return(0,ae.isAuthError)(o)?{data:null,error:o}:{data:null,error:new ae.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ae.AuthError("rpId is required for WebAuthn registration")};try{if(!cn())return{data:null,error:new ae.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(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.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:s},signal:n},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,ae.isAuthError)(o)?{data:null,error:o}:{data:null,error:new ae.AuthUnknownError("Unexpected error in register",o)}}}};I.WebAuthnApi=Cr});var Nr=P(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var na=(X(),re(Y)),ia=na.__importDefault(vt()),z=ft(),g=me(),T=br(),v=ke(),mn=tn(),_n=Rr(),oa=sn(),aa=nr(),gn=mt(),St=on(),He=Ir();(0,oa.polyfillGlobalThis)();var la={url:z.GOTRUE_URL,storageKey:z.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:z.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function yn(t,e,r){return await r()}var Oe={},At=class t{get jwks(){var e,r;return(r=(e=Oe[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Oe[this.storageKey]=Object.assign(Object.assign({},Oe[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Oe[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Oe[this.storageKey]=Object.assign(Object.assign({},Oe[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;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({},la),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,v.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 ia.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,v.resolveFetch)(i.fetch),this.lock=i.lock||yn,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,v.isBrowser)()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=_n.navigatorLock:this.lock=yn,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 He.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,v.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,mn.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,mn.memoryLocalStorageAdapter)(this.memoryStorage)),(0,v.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)}(n=this.broadcastChannel)===null||n===void 0||n.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} (${aa.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={},s="none";if((0,v.isBrowser)()&&(r=(0,v.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),(0,v.isBrowser)()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,g.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}=n;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,g.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new g.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{let i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:T._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,g.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){let{email:u,password:d,options:f}=e,h=null,p=null;this.flowType==="pkce"&&([h,p]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:h,code_challenge_method:p},xform:T._sessionResponse})}else if("phone"in e){let{phone:u,password:d,options:f}=e;i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:T._sessionResponse})}else throw new g.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,v.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,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.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,T._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:T._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,T._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:T._sessionResponsePassword})}else throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.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,s,n,i,o,a,l,c,u,d,f;let h,p;if("message"in e)h=e.message,p=e.signature;else{let{chain:m,wallet:_,statement:y,options:S}=e,w;if((0,v.isBrowser)())if(typeof _=="object")w=_;else{let ce=window;if("ethereum"in ce&&typeof ce.ethereum=="object"&&"request"in ce.ethereum&&typeof ce.ethereum.request=="function")w=ce.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 _!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=_}let k=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href),H=await w.request({method:"eth_requestAccounts"}).then(ce=>ce).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!H||H.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let j=(0,St.getAddress)(H[0]),V=(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!V){let ce=await w.request({method:"eth_chainId"});V=(0,St.fromHex)(ce)}let de={domain:k.host,address:j,statement:y,uri:k.href,version:"1",chainId:V,nonce:(n=S?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=S?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=S?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=S?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=(0,St.createSiweMessage)(de),p=await w.request({method:"personal_sign",params:[(0,St.toHex)(h),j]})}try{let{data:m,error:_}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:T._sessionResponse});if(_)throw _;if(!m||!m.session||!m.user){let y=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if((0,g.isAuthError)(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,s,n,i,o,a,l,c,u,d,f,h;let p,m;if("message"in e)p=e.message,m=e.signature;else{let{chain:_,wallet:y,statement:S,options:w}=e,k;if((0,v.isBrowser)())if(typeof y=="object")k=y;else{let j=window;if("solana"in j&&typeof j.solana=="object"&&("signIn"in j.solana&&typeof j.solana.signIn=="function"||"signMessage"in j.solana&&typeof j.solana.signMessage=="function"))k=j.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 y!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=y}let H=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in k&&k.signIn){let j=await k.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w?.signInWithSolana),{version:"1",domain:H.host,uri:H.href}),S?{statement:S}:null)),V;if(Array.isArray(j)&&j[0]&&typeof j[0]=="object")V=j[0];else if(j&&typeof j=="object"&&"signedMessage"in j&&"signature"in j)V=j;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in V&&"signature"in V&&(typeof V.signedMessage=="string"||V.signedMessage instanceof Uint8Array)&&V.signature instanceof Uint8Array)p=typeof V.signedMessage=="string"?V.signedMessage:new TextDecoder().decode(V.signedMessage),m=V.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in k)||typeof k.signMessage!="function"||!("publicKey"in k)||typeof k!="object"||!k.publicKey||!("toBase58"in k.publicKey)||typeof k.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${H.host} wants you to sign in with your Solana account:`,k.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${H.href}`,`Issued At: ${(n=(s=w?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=w?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((a=w?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((c=w?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((d=(u=w?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...w.signInWithSolana.resources.map(V=>`- ${V}`)]:[]].join(`
42
- `);let j=await k.signMessage(new TextEncoder().encode(p),"utf8");if(!j||!(j instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=j}}try{let{data:_,error:y}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:(0,gn.bytesToBase64URL)(m)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:T._sessionResponse});if(y)throw y;if(!_||!_.session||!_.user){let S=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:S})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:y})}catch(_){if((0,g.isAuthError)(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await(0,v.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new g.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:T._sessionResponse});if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new g.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:n??null}),error:o})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:T._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 u=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:u})}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,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:d}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},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:u})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await(0,T._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:T._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(n){if((0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,T._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:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.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:T._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,v.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.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:s}=e;if(s)throw s;if(!r)throw new g.AuthSessionMissingError;let{error:n}=await(0,T._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if((0,g.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:s,type:n,options:i}=e,{error:o}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,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:s,type:n,options:i}=e,{data:o,error:a}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,g.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 s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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,v.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 s=e.expires_at?e.expires_at*1e3-Date.now()<z.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,v.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,v.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},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,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:T._userResponse}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new g.AuthSessionMissingError}:await(0,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:T._userResponse})})}catch(r){if((0,g.isAuthError)(r))return(0,g.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,v.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 s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new g.AuthSessionMissingError;let o=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:u}=await(0,T._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:T._userResponse});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(s))return this._returnResult({data:{user:null},error:s});throw s}}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 g.AuthSessionMissingError;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=(0,v.decodeJWT)(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){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:s-r,expires_at:s},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,g.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 s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new g.AuthSessionMissingError;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,v.isBrowser)())throw new g.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new g.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 g.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new g.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 g.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:S,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:S.session,redirectType:null},error:null}}let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new g.AuthImplicitGrantRedirectError("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;l&&(f=parseInt(l));let h=f-u;h*1e3<=z.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let p=f-d;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,f,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,f,u);let{data:m,error:_}=await this._getUser(i);if(_)throw _;let y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_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,v.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 s;let{data:n,error:i}=r;if(i&&!(0,g.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,g.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,g.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,v.generateCallbackId)(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,T._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,g.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:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;let{data:d,error:f}=i;if(f)throw f;let h=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,T._request)(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return(0,v.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:T._sessionResponse}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new g.AuthInvalidTokenResponseError}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if((0,g.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 s=Date.now();return await(0,v.retryable)(async n=>(n>0&&await(0,v.sleep)(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:T._sessionResponse})),(n,i)=>{let o=200*Math.pow(2,n);return i&&(0,g.isAuthRetryableFetchError)(i)&&Date.now()+o-s<z.AUTO_REFRESH_TICK_DURATION_MS})}catch(s){if(this._debug(r,"error",s),(0,g.isAuthError)(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}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 s=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",s),(0,v.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await(0,v.getItemAsync)(this.storage,this.storageKey);if(n&&this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:(0,v.userNotAvailableProxy)()}else if(n&&!n.user&&!n.user){let o=await(0,v.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,v.setItemAsync)(this.storage,this.storageKey,n)):n.user=(0,v.userNotAvailableProxy)()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<z.EXPIRY_MARGIN_MS;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${z.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),(0,g.isAuthRetryableFetchError)(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new g.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new v.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new g.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(n,"error",i),(0,g.isAuthError)(i)){let o={data:null,error:i};return(0,g.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&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(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=(0,v.deepClone)(n);await(0,v.setItemAsync)(this.storage,this.storageKey,i)}else{let n=(0,v.deepClone)(r);await(0,v.setItemAsync)(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,v.removeItemAsync)(this.storage,this.storageKey),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,v.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,v.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(),z.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:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/z.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${z.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${z.AUTO_REFRESH_TICK_THRESHOLD} ticks`),n<=z.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(s.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 _n.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,v.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,s){let n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,T._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;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,T._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.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,g.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 s;let{data:n,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,He.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,He.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,g.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 s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,He.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,He.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:h}=(0,v.decodeJWT)(e),p=null;h.aal&&(p=h.aal);let m=p,{data:{user:_},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=_?.factors)===null||r===void 0?void 0:r.filter(k=>k.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");let w=h.amr||[];return{data:{currentLevel:p,nextLevel:m,currentAuthenticationMethods:w},error:null}}catch(h){if((0,g.isAuthError)(h))return this._returnResult({data:null,error:h});throw h}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,v.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await(0,T._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await(0,T._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(e){if((0,g.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+z.JWKS_TTL>n)return s;let{data:i,error:o}=await(0,T._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=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=(0,v.decodeJWT)(s);r?.allowExpired||(0,v.validateExp)(i.exp);let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}let u=(0,v.getAlgorithm)(n.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,(0,gn.stringToUint8Array)(`${a}.${l}`)))throw new g.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}};At.nextInstanceID={};xr.default=At});var vn=P(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});var ca=(X(),re(Y)),ua=ca.__importDefault(vt()),ha=ua.default;jr.default=ha});var wn=P(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});var da=(X(),re(Y)),fa=da.__importDefault(Nr()),pa=fa.default;Ur.default=pa});var Lr=P(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.processLock=M.lockInternals=M.NavigatorLockAcquireTimeoutError=M.navigatorLock=M.AuthClient=M.AuthAdminApi=M.GoTrueClient=M.GoTrueAdminApi=void 0;var Pe=(X(),re(Y)),ma=Pe.__importDefault(vt());M.GoTrueAdminApi=ma.default;var _a=Pe.__importDefault(Nr());M.GoTrueClient=_a.default;var ga=Pe.__importDefault(vn());M.AuthAdminApi=ga.default;var ya=Pe.__importDefault(wn());M.AuthClient=ya.default;Pe.__exportStar(Er(),M);Pe.__exportStar(me(),M);var Tt=Rr();Object.defineProperty(M,"navigatorLock",{enumerable:!0,get:function(){return Tt.navigatorLock}});Object.defineProperty(M,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return Tt.NavigatorLockAcquireTimeoutError}});Object.defineProperty(M,"lockInternals",{enumerable:!0,get:function(){return Tt.internals}});Object.defineProperty(M,"processLock",{enumerable:!0,get:function(){return Tt.processLock}})});var Vr=[{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:"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"}],xn=new Map,Mr=new Map;for(let t of Vr){for(let e of t.aliases)xn.set(e.toLowerCase(),t);for(let e of t.extensions){let r=Mr.get(e.toLowerCase())??[];r.push(t),Mr.set(e.toLowerCase(),r)}}var Ba=new Set(Vr.map(t=>t.canonical));async function Rt(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(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxml"))return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve or Final Cut Pro X export"};if(e.endsWith(".xml"))return await Nn(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:s}=await import("./esm-SFFBP7PS.js"),n=s(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(n)){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 Nn(t){try{let e=await t.text(),s=new DOMParser().parseFromString(e,"text/xml");if(s.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(s.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(s.querySelector("xmeml")){let a=s.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 b={};Dr(b,{FunctionRegion:()=>te.FunctionRegion,FunctionsError:()=>te.FunctionsError,FunctionsFetchError:()=>te.FunctionsFetchError,FunctionsHttpError:()=>te.FunctionsHttpError,FunctionsRelayError:()=>te.FunctionsRelayError,PostgrestError:()=>Lt,SupabaseClient:()=>An,createClient:()=>$r});var te=Ie(ws(),1);var Lt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Fn=class{constructor(t){var e,r,s;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=(s=t.urlLengthLimit)!==null&&s!==void 0?s: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 s=this.fetch,n=s(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,u=i.statusText;if(i.ok){var d,f;if(r.method!=="HEAD"){var h;let y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((h=r.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let m=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),_=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");m&&_&&_.length>1&&(l=parseInt(_[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,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var p;let m=await i.text();try{o=JSON.parse(m),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,u="OK")}catch{i.status===404&&m===""?(c=204,u="No Content"):o={message:m}}if(o&&r.isMaybeSingle&&(!(o==null||(p=o.details)===null||p===void 0)&&p.includes("0 rows"))&&(o=null,c=200,u="OK"),o&&r.shouldThrowOnError)throw new Lt(o)}return{error:o,data:a,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(n=n.catch(i=>{var o;let a="",l="",c="",u=i?.cause;if(u){var d,f,h,p;let y=(d=u?.message)!==null&&d!==void 0?d:"",S=(f=u?.code)!==null&&f!==void 0?f:"";a=`${(h=i?.name)!==null&&h!==void 0?h:"FetchError"}: ${i?.message}`,a+=`
42
+ `);let j=await k.signMessage(new TextEncoder().encode(p),"utf8");if(!j||!(j instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=j}}try{let{data:_,error:y}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:(0,gn.bytesToBase64URL)(m)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:T._sessionResponse});if(y)throw y;if(!_||!_.session||!_.user){let S=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:S})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:y})}catch(_){if((0,g.isAuthError)(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await(0,v.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new g.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:T._sessionResponse});if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new g.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:n??null}),error:o})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:T._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 u=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:u})}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,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:d}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},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:u})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await(0,T._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:T._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(n){if((0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,T._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:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.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:T._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,v.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.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:s}=e;if(s)throw s;if(!r)throw new g.AuthSessionMissingError;let{error:n}=await(0,T._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if((0,g.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:s,type:n,options:i}=e,{error:o}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,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:s,type:n,options:i}=e,{data:o,error:a}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,g.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 s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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,v.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 s=e.expires_at?e.expires_at*1e3-Date.now()<z.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,v.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,v.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},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,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:T._userResponse}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new g.AuthSessionMissingError}:await(0,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:T._userResponse})})}catch(r){if((0,g.isAuthError)(r))return(0,g.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,v.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 s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new g.AuthSessionMissingError;let o=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:u}=await(0,T._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:T._userResponse});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(s))return this._returnResult({data:{user:null},error:s});throw s}}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 g.AuthSessionMissingError;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=(0,v.decodeJWT)(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){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:s-r,expires_at:s},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,g.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 s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new g.AuthSessionMissingError;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,v.isBrowser)())throw new g.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new g.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 g.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new g.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 g.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:S,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:S.session,redirectType:null},error:null}}let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new g.AuthImplicitGrantRedirectError("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;l&&(f=parseInt(l));let h=f-u;h*1e3<=z.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let p=f-d;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,f,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,f,u);let{data:m,error:_}=await this._getUser(i);if(_)throw _;let y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_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,v.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 s;let{data:n,error:i}=r;if(i&&!(0,g.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,g.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,g.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,v.generateCallbackId)(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,T._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,g.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:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;let{data:d,error:f}=i;if(f)throw f;let h=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,T._request)(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return(0,v.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:T._sessionResponse}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new g.AuthInvalidTokenResponseError}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if((0,g.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 s=Date.now();return await(0,v.retryable)(async n=>(n>0&&await(0,v.sleep)(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:T._sessionResponse})),(n,i)=>{let o=200*Math.pow(2,n);return i&&(0,g.isAuthRetryableFetchError)(i)&&Date.now()+o-s<z.AUTO_REFRESH_TICK_DURATION_MS})}catch(s){if(this._debug(r,"error",s),(0,g.isAuthError)(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}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 s=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",s),(0,v.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await(0,v.getItemAsync)(this.storage,this.storageKey);if(n&&this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:(0,v.userNotAvailableProxy)()}else if(n&&!n.user&&!n.user){let o=await(0,v.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,v.setItemAsync)(this.storage,this.storageKey,n)):n.user=(0,v.userNotAvailableProxy)()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<z.EXPIRY_MARGIN_MS;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${z.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),(0,g.isAuthRetryableFetchError)(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new g.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new v.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new g.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(n,"error",i),(0,g.isAuthError)(i)){let o={data:null,error:i};return(0,g.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&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(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=(0,v.deepClone)(n);await(0,v.setItemAsync)(this.storage,this.storageKey,i)}else{let n=(0,v.deepClone)(r);await(0,v.setItemAsync)(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,v.removeItemAsync)(this.storage,this.storageKey),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,v.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,v.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(),z.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:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/z.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${z.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${z.AUTO_REFRESH_TICK_THRESHOLD} ticks`),n<=z.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(s.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 _n.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,v.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,s){let n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,T._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;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,T._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.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,g.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 s;let{data:n,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,He.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,He.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,g.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 s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,He.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,He.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:h}=(0,v.decodeJWT)(e),p=null;h.aal&&(p=h.aal);let m=p,{data:{user:_},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=_?.factors)===null||r===void 0?void 0:r.filter(k=>k.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");let w=h.amr||[];return{data:{currentLevel:p,nextLevel:m,currentAuthenticationMethods:w},error:null}}catch(h){if((0,g.isAuthError)(h))return this._returnResult({data:null,error:h});throw h}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,v.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await(0,T._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await(0,T._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(e){if((0,g.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+z.JWKS_TTL>n)return s;let{data:i,error:o}=await(0,T._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=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=(0,v.decodeJWT)(s);r?.allowExpired||(0,v.validateExp)(i.exp);let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}let u=(0,v.getAlgorithm)(n.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,(0,gn.stringToUint8Array)(`${a}.${l}`)))throw new g.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}};At.nextInstanceID={};xr.default=At});var vn=P(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});var ca=(X(),re(Y)),ua=ca.__importDefault(vt()),ha=ua.default;jr.default=ha});var wn=P(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});var da=(X(),re(Y)),fa=da.__importDefault(Nr()),pa=fa.default;Ur.default=pa});var Lr=P(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.processLock=M.lockInternals=M.NavigatorLockAcquireTimeoutError=M.navigatorLock=M.AuthClient=M.AuthAdminApi=M.GoTrueClient=M.GoTrueAdminApi=void 0;var Pe=(X(),re(Y)),ma=Pe.__importDefault(vt());M.GoTrueAdminApi=ma.default;var _a=Pe.__importDefault(Nr());M.GoTrueClient=_a.default;var ga=Pe.__importDefault(vn());M.AuthAdminApi=ga.default;var ya=Pe.__importDefault(wn());M.AuthClient=ya.default;Pe.__exportStar(Er(),M);Pe.__exportStar(me(),M);var Tt=Rr();Object.defineProperty(M,"navigatorLock",{enumerable:!0,get:function(){return Tt.navigatorLock}});Object.defineProperty(M,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return Tt.NavigatorLockAcquireTimeoutError}});Object.defineProperty(M,"lockInternals",{enumerable:!0,get:function(){return Tt.internals}});Object.defineProperty(M,"processLock",{enumerable:!0,get:function(){return Tt.processLock}})});var Vr=[{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"}],xn=new Map,Mr=new Map;for(let t of Vr){for(let e of t.aliases)xn.set(e.toLowerCase(),t);for(let e of t.extensions){let r=Mr.get(e.toLowerCase())??[];r.push(t),Mr.set(e.toLowerCase(),r)}}var Ba=new Set(Vr.map(t=>t.canonical));async function Rt(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(".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(".xml"))return await Nn(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:s}=await import("./esm-SFFBP7PS.js"),n=s(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(n)){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 Nn(t){try{let e=await t.text(),s=new DOMParser().parseFromString(e,"text/xml");if(s.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(s.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(s.querySelector("xmeml")){let a=s.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 b={};Dr(b,{FunctionRegion:()=>te.FunctionRegion,FunctionsError:()=>te.FunctionsError,FunctionsFetchError:()=>te.FunctionsFetchError,FunctionsHttpError:()=>te.FunctionsHttpError,FunctionsRelayError:()=>te.FunctionsRelayError,PostgrestError:()=>Lt,SupabaseClient:()=>An,createClient:()=>$r});var te=Ie(ws(),1);var Lt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Fn=class{constructor(t){var e,r,s;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=(s=t.urlLengthLimit)!==null&&s!==void 0?s: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 s=this.fetch,n=s(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,u=i.statusText;if(i.ok){var d,f;if(r.method!=="HEAD"){var h;let y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((h=r.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let m=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),_=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");m&&_&&_.length>1&&(l=parseInt(_[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,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var p;let m=await i.text();try{o=JSON.parse(m),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,u="OK")}catch{i.status===404&&m===""?(c=204,u="No Content"):o={message:m}}if(o&&r.isMaybeSingle&&(!(o==null||(p=o.details)===null||p===void 0)&&p.includes("0 rows"))&&(o=null,c=200,u="OK"),o&&r.shouldThrowOnError)throw new Lt(o)}return{error:o,data:a,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(n=n.catch(i=>{var o;let a="",l="",c="",u=i?.cause;if(u){var d,f,h,p;let y=(d=u?.message)!==null&&d!==void 0?d:"",S=(f=u?.code)!==null&&f!==void 0?f:"";a=`${(h=i?.name)!==null&&h!==void 0?h:"FetchError"}: ${i?.message}`,a+=`
43
43
 
44
44
  Caused by: ${(p=u?.name)!==null&&p!==void 0?p:"Error"}: ${y}`,S&&(a+=` (${S})`),u?.stack&&(a+=`
45
45
  ${u.stack}`)}else{var m;a=(m=i?.stack)!==null&&m!==void 0?m:""}let _=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${_} 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.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(l+=`. Your request URL is ${_} 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:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Mn=class extends Fn{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let i=n?`${n}.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 s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${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:s=!1,wal:n=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"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}},bs=new RegExp("[,()]"),Ee=class extends Mn{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(s=>typeof s=="string"&&bs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&bs.test(s)?`"${s}"`:`${s}`).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:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}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 s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Vn=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},n=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),s&&l.append("Prefer",`count=${s}`),new Ee({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let n="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 Ee({method:n,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!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),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new Ee({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 s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Ee({method:s,url:n,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:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ee({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function xe(t){"@babel/helpers - typeof";return xe=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},xe(t)}function Wn(t,e){if(xe(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(xe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Hn(t){var e=Wn(t,"string");return xe(e)=="symbol"?e:e+""}function Kn(t,e,r){return(e=Hn(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Es(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Ze(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Es(Object(r),!0).forEach(function(s){Kn(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Es(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Ss=class As{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=o;let a=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let u=new AbortController,d=setTimeout(()=>u.abort(),i),f=c?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,c);let h=()=>{clearTimeout(d),u.abort()};return f.addEventListener("abort",h,{once:!0}),a(l,Ze(Ze({},c),{},{signal:u.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",h)})}return a(l,Ze(Ze({},c),{},{signal:u.signal})).finally(()=>clearTimeout(d))}: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 Vn(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new As(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),d=s&&Object.values(r).some(u);d?(a="POST",c=r):s||n?(a=s?"HEAD":"GET",Object.entries(r).filter(([h,p])=>p!==void 0).map(([h,p])=>[h,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([h,p])=>{l.searchParams.append(h,p)})):(a="POST",c=r);let f=new Headers(this.headers);return d?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Ee({method:a,url:l,headers:f,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var En=Ie(er(),1);var $e=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 _i(t,e,r){let s=new URL(e,t);if(r)for(let[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function gi(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 yi(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){let a=_i(t.baseUrl,s,n),l=await gi(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),f=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?f:void 0,p=h?.error;throw new $e(p?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:p?.type,icebergCode:p?.code,details:h})}return{status:c.status,headers:c.headers,data:f}}}}function lt(t){return t.join("")}var vi=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:lt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}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/${lt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${lt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${lt(t.namespace)}`}),!0}catch(e){if(e instanceof $e&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof $e&&r.status===409)return;throw r}}};function Se(t){return t.join("")}var wi=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/${Se(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/${Se(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/${Se(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/${Se(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/${Se(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/${Se(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof $e&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof $e&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},qs=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=yi({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new vi(this.client,e),this.tableOps=new wi(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 ut=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function ht(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ct=class extends ut{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Vs=class extends ut{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var bi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ei=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)},tr=t=>{if(Array.isArray(t))return t.map(r=>tr(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,s])=>{let n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=tr(s)}),e},Si=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function qe(t){"@babel/helpers - typeof";return qe=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},qe(t)}function Ai(t,e){if(qe(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(qe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ti(t){var e=Ai(t,"string");return qe(e)=="symbol"?e:e+""}function ki(t,e,r){return(e=Ti(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Bs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function A(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Bs(Object(r),!0).forEach(function(s){ki(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Bs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Fs=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)},Ri=async(t,e,r,s)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let n=t,i=n.status||500;if(typeof n.json=="function")n.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new ct(Fs(o),i,a,s))}).catch(()=>{if(s==="vectors"){let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}else{let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}});else{let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}}else e(new Vs(Fs(t),t,s))},Oi=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!s?A(A({},n),r):(Ei(s)?(n.headers=A({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s)):n.body=s,e?.duplex&&(n.duplex=e.duplex),A(A({},n),r))};async function De(t,e,r,s,n,i,o){return new Promise((a,l)=>{t(r,Oi(e,s,n,i)).then(c=>{if(!c.ok)throw c;if(s?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!u||!u.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>Ri(c,l,s,o))})}function Ws(t="storage"){return{get:async(e,r,s,n)=>De(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>De(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>De(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>De(e,"HEAD",r,A(A({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>De(e,"DELETE",r,n,i,s,t)}}var Pi=Ws("storage"),{get:Be,post:ne,put:rr,head:Ii,remove:sr}=Pi,J=Ws("vectors"),Ae=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=bi(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=A(A({},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(ht(r))return{data:null,error:r};throw r}}},Ci=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(ht(e))return{data:null,error:e};throw e}}},Hs;Hs=Symbol.toStringTag;var xi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Hs]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ci(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(ht(e))return{data:null,error:e};throw e}}},Ni={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ms={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ji=class extends Ae{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i,o=A(A({},Ms),s),a=A(A({},n.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",n.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",n.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers&&(a=A(A({},a),s.headers));let c=n._removeEmptyFolders(e),u=n._getFinalPath(c),d=await(t=="PUT"?rr:ne)(n.fetch,`${n.url}/object/${u}`,i,A({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;let i=n._removeEmptyFolders(t),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,c=A({upsert:Ms.upsert},s),u=A(A({},n.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,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:i,fullPath:(await rr(n.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t),n=A({},r.headers);e?.upsert&&(n["x-upsert"]="true");let i=await ne(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new ut("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 s=this;return s.handleOperation(async()=>await ne(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await ne(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=await ne(s.fetch,`${s.url}/object/sign/${n}`,A({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:s.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{let n=await ne(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(o=>A(A({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let s=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),i=n?`?${n}`:"",o=this._getFinalPath(t),a=()=>Be(this.fetch,`${this.url}/${s}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new xi(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>tr(await Be(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Ii(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(ht(s)&&s instanceof Vs){let n=s.originalError;if([400,404].includes(n?.status))return{data:!1,error:s}}throw s}}getPublicUrl(t,e){let r=this._getFinalPath(t),s=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&s.push(o);let a=s.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 sr(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{let n=A(A(A({},Ni),e),{},{prefix:t||""});return await ne(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let s=A({},t);return await ne(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{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("&")}},Ui="2.97.0",Fe={"X-Client-Info":`storage-js/${Ui}`},Li=class extends Ae{constructor(t,e={},r,s){let n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let i=n.href.replace(/\/$/,""),o=A(A({},Fe),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Be(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Be(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ne(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 rr(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 ne(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await sr(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():""}},$i=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ne(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 s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Be(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await sr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Si(t))throw new ut("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 qs({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){let o=n[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(n,a),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},Di=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},qi=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,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 J.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await J.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 J.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await J.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 J.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Bi=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Fi=class extends Bi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Mi(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)}},Mi=class extends Di{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,A(A({},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 Vi(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Vi=class extends qi{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Ks=class extends Li{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new ji(this.url,this.headers,t,this.fetch)}get vectors(){return new Fi(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $i(this.url+"/iceberg",this.headers,this.fetch)}};var Sn=Ie(Lr(),1);E(b,Ie(er(),1));E(b,Ie(Lr(),1));var va="2.97.0",Ke="";typeof Deno<"u"?Ke="deno":typeof document<"u"?Ke="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ke="react-native":Ke="node";var wa={"X-Client-Info":`supabase-js-${Ke}/${va}`},ba={headers:wa},Ea={schema:"public"},Sa={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Aa={};function Ge(t){"@babel/helpers - typeof";return Ge=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},Ge(t)}function Ta(t,e){if(Ge(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(Ge(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ka(t){var e=Ta(t,"string");return Ge(e)=="symbol"?e:e+""}function Ra(t,e,r){return(e=ka(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function bn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function B(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?bn(Object(r),!0).forEach(function(s){Ra(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):bn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Oa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Pa=()=>Headers,Ia=(t,e,r)=>{let s=Oa(r),n=Pa();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new n(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,B(B({},o),{},{headers:c}))}};function Ca(t){return t.endsWith("/")?t:t+"/"}function xa(t,e){var r,s;let{db:n,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,f={db:B(B({},l),n),auth:B(B({},c),i),realtime:B(B({},u),o),storage:{},global:B(B(B({},d),a),{},{headers:B(B({},(r=d?.headers)!==null&&r!==void 0?r:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Na(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(Ca(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var ja=class extends Sn.AuthClient{constructor(t){super(t)}},An=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=Na(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:Ea,realtime:Aa,auth:B(B({},Sa),{},{storageKey:o}),global:ba},l=xa(r??{},a);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} 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=Ia(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(B({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Ss(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 Ks(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new te.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:s}=await t.auth.getSession();return(e=(r=s.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:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ja({url:this.authUrl.href,headers:B(B({},f),u),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new En.RealtimeClient(this.realtimeUrl.href,B(B({},t),{},{params:B(B({},{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)}},$r=(t,e,r)=>new An(t,e,r);function Ua(){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}Ua()&&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 Tn=import.meta.env.VITE_SUPABASE_URL,kn=import.meta.env.VITE_SUPABASE_ANON_KEY;if(!Tn)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!kn)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var Rn=$r(Tn,kn,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0}});var La=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`,pc=import.meta.env.VITE_LOCAL_API_URL?.replace(/\/$/,"");async function On(t){let{data:{session:e}}=await Rn.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,s=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}),n=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),i=s+`
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
3
+ import{a as k,b as I}from"./chunk-SP5RGDAM.js";import{a as O,b as T}from"./chunk-AACY2V3L.js";import{b as p,c as H}from"./chunk-BUEIRRNY.js";import{a as N}from"./chunk-TK55FA56.js";import{a as C}from"./chunk-JEMLKBH2.js";import{b as J,c as _}from"./chunk-FNGHTZ5F.js";import{A as x,Ca as s,K as F,L as D,W as f,ca as A,h,j as g,k as v,ka as z,m as w,na as E,u as R,v as S,x as y,y as M,z as P}from"./chunk-PIEH7J6J.js";import"./chunk-PSANHDZM.js";function m(e){return(t,n)=>e.read(t,n)}function L(e){let t=e.toLowerCase().trim();return t==="aprn"||t==="aprh"?"prores_raw":t==="apch"||t==="apcn"||t==="apcs"||t==="apco"||t==="ap4h"||t==="ap4x"?"prores":t==="avdn"?"dnxhd":t==="dnxh"?"dnxhr":t==="avc1"||t==="avc3"?"h264":t==="hev1"||t==="hvc1"?"h265":t==="braw"?"braw":e}var b={apco:"Proxy",apcs:"LT",apcn:"422",apch:"HQ",ap4h:"4444",ap4x:"4444 XQ"},X={1:"bt709",2:"unknown",5:"bt470bg",6:"smpte170m",9:"bt2020",11:"smpte431",12:"smpte432"},q={1:"bt709",2:"unknown",6:"smpte170m",8:"linear",13:"iec61966-2-1",14:"bt2020-10",15:"bt2020-12",16:"smpte2084",18:"arib-std-b67"},K={0:"gbr",1:"bt709",2:"unknown",5:"bt470bg",6:"smpte170m",9:"bt2020nc",10:"bt2020c"};function Y(e,t){return e==="ap4h"||e==="ap4x"?t===32?"yuva444p12le":"yuv444p12le":e in b?"yuv422p10le":void 0}var U={66:"Baseline",77:"Main",88:"Extended",100:"High",110:"High 10",122:"High 4:2:2",244:"High 4:4:4"},V={1:"Main",2:"Main 10",3:"Main Still",4:"Rext"},Z={1270:"DNxHR 444",1271:"DNxHR HQX",1272:"DNxHR HQ",1273:"DNxHR SQ",1274:"DNxHR LB"};function ee(e,t){if(b[e.codec_fourcc])return`ProRes ${b[e.codec_fourcc]}`;if(e.vc3_cid)return Z[e.vc3_cid]??`DNxHD ${e.vc3_cid}`;if(e.video_profile!=null){if(t==="h264"&&U[e.video_profile])return`H.264 ${U[e.video_profile]}`;if(t==="h265"&&V[e.video_profile])return`HEVC ${V[e.video_profile]}`}}function re(e,t){let n=e.video_chroma,r=e.video_bit_depth;if(n==null&&t==="h264"&&[66,77,88].includes(e.video_profile??-1)&&([n,r]=[1,8]),n==null&&e.vc3_cid&&(n=e.vc3_cid===1270||e.vc3_cid===1256?3:2),n==null||r==null)return;let o=["gray","yuv420p","yuv422p","yuv444p"][n];return r>8?`${o}${r}le`:o}function $(e,t){let n=[];for(let r of e){if(r.kind!=="clip"||!r.source_range)continue;let o=r.source_range.start.value,i=r.source_range.duration.value,c=Math.max(0,Math.floor(o)-t),a=Math.floor(o+i-1)+t;a>=c&&n.push({first_frame:c,last_frame:a})}return n}var le={async inspect(e){await s();let t=e.parts[0],n=await f(m(t),t.fileSize,e.format),r=JSON.parse(n);if(!r)return null;let o=r.timecode&&r.timecode.fps_denominator>0?r.timecode.fps_numerator/r.timecode.fps_denominator:null,i=L(r.codec_fourcc),c=[{kind:"video",codec:i,width:r.width??void 0,height:r.height??void 0,rate:o??void 0,bit_depth:p(r.codec_fourcc)??p(i)??H(i,r.video_profile)??r.video_bit_depth??void 0,codec_specific:{fourcc:r.codec_fourcc,profile:ee(r,i),pixel_format:Y(r.codec_fourcc,r.video_depth)??re(r,i),colr:r.colr?{primaries:X[r.colr.primaries]??r.colr.primaries,transfer:q[r.colr.transfer]??r.colr.transfer,matrix:K[r.colr.matrix]??r.colr.matrix}:void 0}}];for(let a of r.audio_tracks??(r.audio?[r.audio]:[]))c.push({kind:"audio",codec:a.codec_fourcc,channels:a.channels??void 0,rate:a.sample_rate??void 0,bit_depth:a.bit_depth??void 0,codec_specific:{fourcc:a.codec_fourcc,channel_layout:a.channel_layout??void 0}});return{id:t.filename,kind:"external",target_url:t.filename,available_range:o&&r.duration_seconds?{start:{value:0,rate:o},duration:{value:Math.round(r.duration_seconds*o),rate:o}}:null,reel_name:null,source_timecode:r.timecode?.display??null,container:e.format==="mov"?"mov":e.format,codec:i,size_bytes:t.fileSize,source_fps:o,source_resolution_w:r.width??null,source_resolution_h:r.height??null,streams:c,decode_provenance:r.decode_provenance??null,vendor_metadata:r.timecode?{drop_frame:r.timecode.drop_frame}:{},binding_state:"unbound",raw_extraction:{mov_probe:r},metadata:{}}},async extract(e){await s();let t=e.parts[0],n=JSON.parse(await A(m(t),t.fileSize,e.format));if(n.length===0)return null;let r=JSON.parse(await f(m(t),t.fileSize,e.format)),o=r?L(r.codec_fourcc):e.format,i=r?.timecode&&r.timecode.fps_denominator>0?r.timecode.fps_numerator/r.timecode.fps_denominator:void 0;return{v:1,container:e.format==="mov"?"mov":e.format,codec:o,width:r?.width??void 0,height:r?.height??void 0,fps:i,frame_count:O(n),timecode:r?.timecode?.display??void 0,granularity:T(n),segments:n}},async sparsify(e,t){await s();let n=e.parts[0],r=$(t.items,t.handles),o=await E(m(n),n.fileSize,JSON.stringify(r),e.format),i=JSON.parse(o);return[{filename:n.filename,fileSize:i.fileSize,structuralRanges:i.structuralRanges,essenceRanges:i.essenceRanges,trimInputs:i.trimInputs}]},async trim(e,t){await s();let n=e.parts[0],r=$(t.items,t.handles);if(r.length===0)throw new Error("isobmff trim: no usable trim ranges in items");let o=C(r),i=[];for(let[c,a]of o.entries()){let l=await z(m(n),n.fileSize,a.first_frame,a.last_frame+1,e.format),u=JSON.parse(l);o.length>1&&(u.output_clip_number=c+1,u.output_clip_count=o.length,u.output_part_number=1),i.push(u)}return i},async decode(e,t,n){await s();let r=n.detail==="coarse",o=e.parts[0];if(e.format==="crm"){let u=await w(m(o),o.fileSize,t,r?"preview":"full");return d(u)}let i=await j(e);if(t<0||t>=i.length)throw new _(t,i.length);let c=i[t],a=await o.read(c.offset,c.size);if(e.format==="braw")return d(r?g(a,0):v(a));if(Q(a))return d(r?y(a,0):M(a));if(B(a))return d(r?F(a,0):D(a));if(r)return d(R(a,0));let l=await te(a);return l||d(x(a))},async decode16(e,t){await s();let n=e.parts[0];if(e.format==="crm")throw new Error("crm: no 16-bit decoder");let r=await j(e);if(t<0||t>=r.length)throw new _(t,r.length);let o=r[t],i=await n.read(o.offset,o.size),c=e.format==="braw"?h(i):Q(i)?S(i):B(i)?(()=>{throw new Error("vc3: no 16-bit decoder")})():P(i);return J(c)}};async function te(e){if(!!0)return null;try{let t=await import("./prores-BNALPJPS.js");if(!await t.proresGpuAvailable())return null;let n=await t.decodeProResRgbaGpu(e);return n?{width:n.width,height:n.height,rgba:n.rgba}:null}catch{return null}}function B(e){return e.length>=4&&e[0]===0&&e[1]===0&&e[2]===2&&e[3]===128}function Q(e){return e.length>=8&&e[4]===112&&e[5]===114&&e[6]===114&&e[7]===102}function d(e){let t=new DataView(e.buffer,e.byteOffset,8);return{width:t.getUint32(0,!0),height:t.getUint32(4,!0),rgba:e.slice(8)}}var G=new WeakMap;async function j(e){let t=G.get(e);if(!t){let n=e.parts[0];t=I(k(await N({fileSize:n.fileSize,read:n.read}))),G.set(e,t)}return t}export{le as isobmffFormat};