@srimandir/dosha-calculator 2.4.2 → 2.4.4

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.
@@ -1,29 +1,30 @@
1
- (function(H,w){typeof exports=="object"&&typeof module<"u"?w(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],w):(H=typeof globalThis<"u"?globalThis:H||self,w(H.DoshaCalculator={},H.React,H.AstrologyCommon))})(this,(function(H,w,q){"use strict";function Kn(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const Ce=Kn(w);var nr={exports:{}},$t={};var as;function Bn(){if(as)return $t;as=1;var r=w,e=Symbol.for("react.element"),t=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(o,c,u){var d,f={},m=null,p=null;u!==void 0&&(m=""+u),c.key!==void 0&&(m=""+c.key),c.ref!==void 0&&(p=c.ref);for(d in c)s.call(c,d)&&!a.hasOwnProperty(d)&&(f[d]=c[d]);if(o&&o.defaultProps)for(d in c=o.defaultProps,c)f[d]===void 0&&(f[d]=c[d]);return{$$typeof:e,type:o,key:m,ref:p,props:f,_owner:n.current}}return $t.Fragment=t,$t.jsx=i,$t.jsxs=i,$t}var Lt={};var is;function Fn(){return is||(is=1,process.env.NODE_ENV!=="production"&&(function(){var r=w,e=Symbol.for("react.element"),t=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),o=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),g=Symbol.iterator,y="@@iterator";function x(h){if(h===null||typeof h!="object")return null;var S=g&&h[g]||h[y];return typeof S=="function"?S:null}var b=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(h){{for(var S=arguments.length,j=new Array(S>1?S-1:0),$=1;$<S;$++)j[$-1]=arguments[$];_("error",h,j)}}function _(h,S,j){{var $=b.ReactDebugCurrentFrame,Y=$.getStackAddendum();Y!==""&&(S+="%s",j=j.concat([Y]));var X=j.map(function(W){return String(W)});X.unshift("Warning: "+S),Function.prototype.apply.call(console[h],console,X)}}var O=!1,A=!1,M=!1,E=!1,N=!1,L;L=Symbol.for("react.module.reference");function De(h){return!!(typeof h=="string"||typeof h=="function"||h===s||h===a||N||h===n||h===u||h===d||E||h===p||O||A||M||typeof h=="object"&&h!==null&&(h.$$typeof===m||h.$$typeof===f||h.$$typeof===i||h.$$typeof===o||h.$$typeof===c||h.$$typeof===L||h.getModuleId!==void 0))}function ye(h,S,j){var $=h.displayName;if($)return $;var Y=S.displayName||S.name||"";return Y!==""?j+"("+Y+")":j}function Ae(h){return h.displayName||"Context"}function ee(h){if(h==null)return null;if(typeof h.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof h=="function")return h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case s:return"Fragment";case t:return"Portal";case a:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof h=="object")switch(h.$$typeof){case o:var S=h;return Ae(S)+".Consumer";case i:var j=h;return Ae(j._context)+".Provider";case c:return ye(h,h.render,"ForwardRef");case f:var $=h.displayName||null;return $!==null?$:ee(h.type)||"Memo";case m:{var Y=h,X=Y._payload,W=Y._init;try{return ee(W(X))}catch{return null}}}return null}var te=Object.assign,he=0,Je,Oe,re,fe,Se,Q,v;function B(){}B.__reactDisabledLog=!0;function z(){{if(he===0){Je=console.log,Oe=console.info,re=console.warn,fe=console.error,Se=console.group,Q=console.groupCollapsed,v=console.groupEnd;var h={configurable:!0,enumerable:!0,value:B,writable:!0};Object.defineProperties(console,{info:h,log:h,warn:h,error:h,group:h,groupCollapsed:h,groupEnd:h})}he++}}function G(){{if(he--,he===0){var h={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:te({},h,{value:Je}),info:te({},h,{value:Oe}),warn:te({},h,{value:re}),error:te({},h,{value:fe}),group:te({},h,{value:Se}),groupCollapsed:te({},h,{value:Q}),groupEnd:te({},h,{value:v})})}he<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var V=b.ReactCurrentDispatcher,K;function U(h,S,j){{if(K===void 0)try{throw Error()}catch(Y){var $=Y.stack.trim().match(/\n( *(at )?)/);K=$&&$[1]||""}return`
2
- `+K+h}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(h,S){if(!h||J)return"";{var j=se.get(h);if(j!==void 0)return j}var $;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(S){var W=function(){throw Error()};if(Object.defineProperty(W.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(W,[])}catch(Re){$=Re}Reflect.construct(h,[],W)}else{try{W.call()}catch(Re){$=Re}h.call(W.prototype)}}else{try{throw Error()}catch(Re){$=Re}h()}}catch(Re){if(Re&&$&&typeof Re.stack=="string"){for(var F=Re.stack.split(`
3
- `),Ee=$.stack.split(`
4
- `),ue=F.length-1,pe=Ee.length-1;ue>=1&&pe>=0&&F[ue]!==Ee[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(F[ue]!==Ee[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||F[ue]!==Ee[pe]){var We=`
5
- `+F[ue].replace(" at new "," at ");return h.displayName&&We.includes("<anonymous>")&&(We=We.replace("<anonymous>",h.displayName)),typeof h=="function"&&se.set(h,We),We}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,G(),Error.prepareStackTrace=Y}var Dt=h?h.displayName||h.name:"",bt=Dt?U(Dt):"";return typeof h=="function"&&se.set(h,bt),bt}function Te(h,S,j){return le(h,!1)}function Nt(h){var S=h.prototype;return!!(S&&S.isReactComponent)}function Fe(h,S,j){if(h==null)return"";if(typeof h=="function")return le(h,Nt(h));if(typeof h=="string")return U(h);switch(h){case u:return U("Suspense");case d:return U("SuspenseList")}if(typeof h=="object")switch(h.$$typeof){case c:return Te(h.render);case f:return Fe(h.type,S,j);case m:{var $=h,Y=$._payload,X=$._init;try{return Fe(X(Y),S,j)}catch{}}}return""}var $e=Object.prototype.hasOwnProperty,yt={},vt=b.ReactDebugCurrentFrame;function et(h){if(h){var S=h._owner,j=Fe(h.type,h._source,S?S.type:null);vt.setExtraStackFrame(j)}else vt.setExtraStackFrame(null)}function Zt(h,S,j,$,Y){{var X=Function.call.bind($e);for(var W in h)if(X(h,W)){var F=void 0;try{if(typeof h[W]!="function"){var Ee=Error(($||"React class")+": "+j+" type `"+W+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof h[W]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ee.name="Invariant Violation",Ee}F=h[W](S,W,$,j,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){F=ue}F&&!(F instanceof Error)&&(et(Y),k("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",$||"React class",j,W,typeof F),et(null)),F instanceof Error&&!(F.message in yt)&&(yt[F.message]=!0,et(Y),k("Failed %s type: %s",j,F.message),et(null))}}}var T=Array.isArray;function D(h){return T(h)}function ie(h){{var S=typeof Symbol=="function"&&Symbol.toStringTag,j=S&&h[Symbol.toStringTag]||h.constructor.name||"Object";return j}}function Ve(h){try{return it(h),!1}catch{return!0}}function it(h){return""+h}function ke(h){if(Ve(h))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ie(h)),it(h)}var ce=b.ReactCurrentOwner,Pe={key:!0,ref:!0,__self:!0,__source:!0},qe,Le;function er(h){if($e.call(h,"ref")){var S=Object.getOwnPropertyDescriptor(h,"ref").get;if(S&&S.isReactWarning)return!1}return h.ref!==void 0}function C(h){if($e.call(h,"key")){var S=Object.getOwnPropertyDescriptor(h,"key").get;if(S&&S.isReactWarning)return!1}return h.key!==void 0}function ne(h,S){typeof h.ref=="string"&&ce.current}function xe(h,S){{var j=function(){qe||(qe=!0,k("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",S))};j.isReactWarning=!0,Object.defineProperty(h,"key",{get:j,configurable:!0})}}function je(h,S){{var j=function(){Le||(Le=!0,k("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",S))};j.isReactWarning=!0,Object.defineProperty(h,"ref",{get:j,configurable:!0})}}var ve=function(h,S,j,$,Y,X,W){var F={$$typeof:e,type:h,key:S,ref:j,props:W,_owner:X};return F._store={},Object.defineProperty(F._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(F,"_self",{configurable:!1,enumerable:!1,writable:!1,value:$}),Object.defineProperty(F,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(F.props),Object.freeze(F)),F};function tr(h,S,j,$,Y){{var X,W={},F=null,Ee=null;j!==void 0&&(ke(j),F=""+j),C(S)&&(ke(S.key),F=""+S.key),er(S)&&(Ee=S.ref,ne(S,Y));for(X in S)$e.call(S,X)&&!Pe.hasOwnProperty(X)&&(W[X]=S[X]);if(h&&h.defaultProps){var ue=h.defaultProps;for(X in ue)W[X]===void 0&&(W[X]=ue[X])}if(F||Ee){var pe=typeof h=="function"?h.displayName||h.name||"Unknown":h;F&&xe(W,pe),Ee&&je(W,pe)}return ve(h,F,Ee,Y,$,ce.current,W)}}var rr=b.ReactCurrentOwner,Pr=b.ReactDebugCurrentFrame;function ot(h){if(h){var S=h._owner,j=Fe(h.type,h._source,S?S.type:null);Pr.setExtraStackFrame(j)}else Pr.setExtraStackFrame(null)}var sr;sr=!1;function Er(h){return typeof h=="object"&&h!==null&&h.$$typeof===e}function Ar(){{if(rr.current){var h=ee(rr.current.type);if(h)return`
1
+ (function(G,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("react"),require("@srimandir/astrology-common")):typeof define=="function"&&define.amd?define(["exports","react","@srimandir/astrology-common"],v):(G=typeof globalThis<"u"?globalThis:G||self,v(G.DoshaCalculator={},G.React,G.AstrologyCommon))})(this,(function(G,v,q){"use strict";function Jn(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const r in t)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,s.get?s:{enumerable:!0,get:()=>t[r]})}}return e.default=t,Object.freeze(e)}const Re=Jn(v);var lr={exports:{}},Ut={};var hs;function Yn(){if(hs)return Ut;hs=1;var t=v,e=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,n=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,a={key:!0,ref:!0,__self:!0,__source:!0};function i(o,l,u){var d,f={},m=null,p=null;u!==void 0&&(m=""+u),l.key!==void 0&&(m=""+l.key),l.ref!==void 0&&(p=l.ref);for(d in l)s.call(l,d)&&!a.hasOwnProperty(d)&&(f[d]=l[d]);if(o&&o.defaultProps)for(d in l=o.defaultProps,l)f[d]===void 0&&(f[d]=l[d]);return{$$typeof:e,type:o,key:m,ref:p,props:f,_owner:n.current}}return Ut.Fragment=r,Ut.jsx=i,Ut.jsxs=i,Ut}var Mt={};var fs;function Qn(){return fs||(fs=1,process.env.NODE_ENV!=="production"&&(function(){var t=v,e=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),n=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.provider"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),g=Symbol.iterator,y="@@iterator";function x(h){if(h===null||typeof h!="object")return null;var w=g&&h[g]||h[y];return typeof w=="function"?w:null}var _=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function S(h){{for(var w=arguments.length,T=new Array(w>1?w-1:0),D=1;D<w;D++)T[D-1]=arguments[D];k("error",h,T)}}function k(h,w,T){{var D=_.ReactDebugCurrentFrame,Y=D.getStackAddendum();Y!==""&&(w+="%s",T=T.concat([Y]));var X=T.map(function(W){return String(W)});X.unshift("Warning: "+w),Function.prototype.apply.call(console[h],console,X)}}var N=!1,O=!1,B=!1,P=!1,U=!1,$;$=Symbol.for("react.module.reference");function De(h){return!!(typeof h=="string"||typeof h=="function"||h===s||h===a||U||h===n||h===u||h===d||P||h===p||N||O||B||typeof h=="object"&&h!==null&&(h.$$typeof===m||h.$$typeof===f||h.$$typeof===i||h.$$typeof===o||h.$$typeof===l||h.$$typeof===$||h.getModuleId!==void 0))}function ge(h,w,T){var D=h.displayName;if(D)return D;var Y=w.displayName||w.name||"";return Y!==""?T+"("+Y+")":T}function Ee(h){return h.displayName||"Context"}function ee(h){if(h==null)return null;if(typeof h.tag=="number"&&S("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof h=="function")return h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case s:return"Fragment";case r:return"Portal";case a:return"Profiler";case n:return"StrictMode";case u:return"Suspense";case d:return"SuspenseList"}if(typeof h=="object")switch(h.$$typeof){case o:var w=h;return Ee(w)+".Consumer";case i:var T=h;return Ee(T._context)+".Provider";case l:return ge(h,h.render,"ForwardRef");case f:var D=h.displayName||null;return D!==null?D:ee(h.type)||"Memo";case m:{var Y=h,X=Y._payload,W=Y._init;try{return ee(W(X))}catch{return null}}}return null}var te=Object.assign,he=0,Qe,Oe,re,fe,ke,Q,b;function K(){}K.__reactDisabledLog=!0;function z(){{if(he===0){Qe=console.log,Oe=console.info,re=console.warn,fe=console.error,ke=console.group,Q=console.groupCollapsed,b=console.groupEnd;var h={configurable:!0,enumerable:!0,value:K,writable:!0};Object.defineProperties(console,{info:h,log:h,warn:h,error:h,group:h,groupCollapsed:h,groupEnd:h})}he++}}function H(){{if(he--,he===0){var h={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:te({},h,{value:Qe}),info:te({},h,{value:Oe}),warn:te({},h,{value:re}),error:te({},h,{value:fe}),group:te({},h,{value:ke}),groupCollapsed:te({},h,{value:Q}),groupEnd:te({},h,{value:b})})}he<0&&S("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var V=_.ReactCurrentDispatcher,M;function L(h,w,T){{if(M===void 0)try{throw Error()}catch(Y){var D=Y.stack.trim().match(/\n( *(at )?)/);M=D&&D[1]||""}return`
2
+ `+M+h}}var J=!1,se;{var me=typeof WeakMap=="function"?WeakMap:Map;se=new me}function le(h,w){if(!h||J)return"";{var T=se.get(h);if(T!==void 0)return T}var D;J=!0;var Y=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var X;X=V.current,V.current=null,z();try{if(w){var W=function(){throw Error()};if(Object.defineProperty(W.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(W,[])}catch(Ce){D=Ce}Reflect.construct(h,[],W)}else{try{W.call()}catch(Ce){D=Ce}h.call(W.prototype)}}else{try{throw Error()}catch(Ce){D=Ce}h()}}catch(Ce){if(Ce&&D&&typeof Ce.stack=="string"){for(var F=Ce.stack.split(`
3
+ `),Ae=D.stack.split(`
4
+ `),ue=F.length-1,pe=Ae.length-1;ue>=1&&pe>=0&&F[ue]!==Ae[pe];)pe--;for(;ue>=1&&pe>=0;ue--,pe--)if(F[ue]!==Ae[pe]){if(ue!==1||pe!==1)do if(ue--,pe--,pe<0||F[ue]!==Ae[pe]){var We=`
5
+ `+F[ue].replace(" at new "," at ");return h.displayName&&We.includes("<anonymous>")&&(We=We.replace("<anonymous>",h.displayName)),typeof h=="function"&&se.set(h,We),We}while(ue>=1&&pe>=0);break}}}finally{J=!1,V.current=X,H(),Error.prepareStackTrace=Y}var Lt=h?h.displayName||h.name:"",wt=Lt?L(Lt):"";return typeof h=="function"&&se.set(h,wt),wt}function Te(h,w,T){return le(h,!1)}function $t(h){var w=h.prototype;return!!(w&&w.isReactComponent)}function Fe(h,w,T){if(h==null)return"";if(typeof h=="function")return le(h,$t(h));if(typeof h=="string")return L(h);switch(h){case u:return L("Suspense");case d:return L("SuspenseList")}if(typeof h=="object")switch(h.$$typeof){case l:return Te(h.render);case f:return Fe(h.type,w,T);case m:{var D=h,Y=D._payload,X=D._init;try{return Fe(X(Y),w,T)}catch{}}}return""}var $e=Object.prototype.hasOwnProperty,bt={},vt=_.ReactDebugCurrentFrame;function rt(h){if(h){var w=h._owner,T=Fe(h.type,h._source,w?w.type:null);vt.setExtraStackFrame(T)}else vt.setExtraStackFrame(null)}function rr(h,w,T,D,Y){{var X=Function.call.bind($e);for(var W in h)if(X(h,W)){var F=void 0;try{if(typeof h[W]!="function"){var Ae=Error((D||"React class")+": "+T+" type `"+W+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof h[W]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ae.name="Invariant Violation",Ae}F=h[W](w,W,D,T,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(ue){F=ue}F&&!(F instanceof Error)&&(rt(Y),S("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",D||"React class",T,W,typeof F),rt(null)),F instanceof Error&&!(F.message in bt)&&(bt[F.message]=!0,rt(Y),S("Failed %s type: %s",T,F.message),rt(null))}}}var j=Array.isArray;function I(h){return j(h)}function ie(h){{var w=typeof Symbol=="function"&&Symbol.toStringTag,T=w&&h[Symbol.toStringTag]||h.constructor.name||"Object";return T}}function ze(h){try{return lt(h),!1}catch{return!0}}function lt(h){return""+h}function _e(h){if(ze(h))return S("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ie(h)),lt(h)}var ce=_.ReactCurrentOwner,je={key:!0,ref:!0,__self:!0,__source:!0},qe,Le;function sr(h){if($e.call(h,"ref")){var w=Object.getOwnPropertyDescriptor(h,"ref").get;if(w&&w.isReactWarning)return!1}return h.ref!==void 0}function C(h){if($e.call(h,"key")){var w=Object.getOwnPropertyDescriptor(h,"key").get;if(w&&w.isReactWarning)return!1}return h.key!==void 0}function ne(h,w){typeof h.ref=="string"&&ce.current}function Se(h,w){{var T=function(){qe||(qe=!0,S("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",w))};T.isReactWarning=!0,Object.defineProperty(h,"key",{get:T,configurable:!0})}}function xe(h,w){{var T=function(){Le||(Le=!0,S("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",w))};T.isReactWarning=!0,Object.defineProperty(h,"ref",{get:T,configurable:!0})}}var ye=function(h,w,T,D,Y,X,W){var F={$$typeof:e,type:h,key:w,ref:T,props:W,_owner:X};return F._store={},Object.defineProperty(F._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(F,"_self",{configurable:!1,enumerable:!1,writable:!1,value:D}),Object.defineProperty(F,"_source",{configurable:!1,enumerable:!1,writable:!1,value:Y}),Object.freeze&&(Object.freeze(F.props),Object.freeze(F)),F};function nr(h,w,T,D,Y){{var X,W={},F=null,Ae=null;T!==void 0&&(_e(T),F=""+T),C(w)&&(_e(w.key),F=""+w.key),sr(w)&&(Ae=w.ref,ne(w,Y));for(X in w)$e.call(w,X)&&!je.hasOwnProperty(X)&&(W[X]=w[X]);if(h&&h.defaultProps){var ue=h.defaultProps;for(X in ue)W[X]===void 0&&(W[X]=ue[X])}if(F||Ae){var pe=typeof h=="function"?h.displayName||h.name||"Unknown":h;F&&Se(W,pe),Ae&&xe(W,pe)}return ye(h,F,Ae,Y,D,ce.current,W)}}var ar=_.ReactCurrentOwner,Ir=_.ReactDebugCurrentFrame;function ct(h){if(h){var w=h._owner,T=Fe(h.type,h._source,w?w.type:null);Ir.setExtraStackFrame(T)}else Ir.setExtraStackFrame(null)}var ir;ir=!1;function Dr(h){return typeof h=="object"&&h!==null&&h.$$typeof===e}function $r(){{if(ar.current){var h=ee(ar.current.type);if(h)return`
6
6
 
7
- Check the render method of \``+h+"`."}return""}}function Pl(h){return""}var Nn={};function El(h){{var S=Ar();if(!S){var j=typeof h=="string"?h:h.displayName||h.name;j&&(S=`
7
+ Check the render method of \``+h+"`."}return""}}function Xl(h){return""}var qn={};function Zl(h){{var w=$r();if(!w){var T=typeof h=="string"?h:h.displayName||h.name;T&&(w=`
8
8
 
9
- Check the top-level render call using <`+j+">.")}return S}}function Dn(h,S){{if(!h._store||h._store.validated||h.key!=null)return;h._store.validated=!0;var j=El(S);if(Nn[j])return;Nn[j]=!0;var $="";h&&h._owner&&h._owner!==rr.current&&($=" It was passed a child from "+ee(h._owner.type)+"."),ot(h),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',j,$),ot(null)}}function $n(h,S){{if(typeof h!="object")return;if(D(h))for(var j=0;j<h.length;j++){var $=h[j];Er($)&&Dn($,S)}else if(Er(h))h._store&&(h._store.validated=!0);else if(h){var Y=x(h);if(typeof Y=="function"&&Y!==h.entries)for(var X=Y.call(h),W;!(W=X.next()).done;)Er(W.value)&&Dn(W.value,S)}}}function Al(h){{var S=h.type;if(S==null||typeof S=="string")return;var j;if(typeof S=="function")j=S.propTypes;else if(typeof S=="object"&&(S.$$typeof===c||S.$$typeof===f))j=S.propTypes;else return;if(j){var $=ee(S);Zt(j,h.props,"prop",$,h)}else if(S.PropTypes!==void 0&&!sr){sr=!0;var Y=ee(S);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof S.getDefaultProps=="function"&&!S.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function Ol(h){{for(var S=Object.keys(h.props),j=0;j<S.length;j++){var $=S[j];if($!=="children"&&$!=="key"){ot(h),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",$),ot(null);break}}h.ref!==null&&(ot(h),k("Invalid attribute `ref` supplied to `React.Fragment`."),ot(null))}}var Ln={};function Un(h,S,j,$,Y,X){{var W=De(h);if(!W){var F="";(h===void 0||typeof h=="object"&&h!==null&&Object.keys(h).length===0)&&(F+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ee=Pl();Ee?F+=Ee:F+=Ar();var ue;h===null?ue="null":D(h)?ue="array":h!==void 0&&h.$$typeof===e?(ue="<"+(ee(h.type)||"Unknown")+" />",F=" Did you accidentally export a JSX literal instead of a component?"):ue=typeof h,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ue,F)}var pe=tr(h,S,j,Y,X);if(pe==null)return pe;if(W){var We=S.children;if(We!==void 0)if($)if(D(We)){for(var Dt=0;Dt<We.length;Dt++)$n(We[Dt],h);Object.freeze&&Object.freeze(We)}else k("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else $n(We,h)}if($e.call(S,"key")){var bt=ee(h),Re=Object.keys(S).filter(function($l){return $l!=="key"}),ns=Re.length>0?"{key: someKey, "+Re.join(": ..., ")+": ...}":"{key: someKey}";if(!Ln[bt+ns]){var Dl=Re.length>0?"{"+Re.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
9
+ Check the top-level render call using <`+T+">.")}return w}}function Wn(h,w){{if(!h._store||h._store.validated||h.key!=null)return;h._store.validated=!0;var T=Zl(w);if(qn[T])return;qn[T]=!0;var D="";h&&h._owner&&h._owner!==ar.current&&(D=" It was passed a child from "+ee(h._owner.type)+"."),ct(h),S('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',T,D),ct(null)}}function Hn(h,w){{if(typeof h!="object")return;if(I(h))for(var T=0;T<h.length;T++){var D=h[T];Dr(D)&&Wn(D,w)}else if(Dr(h))h._store&&(h._store.validated=!0);else if(h){var Y=x(h);if(typeof Y=="function"&&Y!==h.entries)for(var X=Y.call(h),W;!(W=X.next()).done;)Dr(W.value)&&Wn(W.value,w)}}}function ec(h){{var w=h.type;if(w==null||typeof w=="string")return;var T;if(typeof w=="function")T=w.propTypes;else if(typeof w=="object"&&(w.$$typeof===l||w.$$typeof===f))T=w.propTypes;else return;if(T){var D=ee(w);rr(T,h.props,"prop",D,h)}else if(w.PropTypes!==void 0&&!ir){ir=!0;var Y=ee(w);S("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",Y||"Unknown")}typeof w.getDefaultProps=="function"&&!w.getDefaultProps.isReactClassApproved&&S("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function tc(h){{for(var w=Object.keys(h.props),T=0;T<w.length;T++){var D=w[T];if(D!=="children"&&D!=="key"){ct(h),S("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",D),ct(null);break}}h.ref!==null&&(ct(h),S("Invalid attribute `ref` supplied to `React.Fragment`."),ct(null))}}var Gn={};function zn(h,w,T,D,Y,X){{var W=De(h);if(!W){var F="";(h===void 0||typeof h=="object"&&h!==null&&Object.keys(h).length===0)&&(F+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ae=Xl();Ae?F+=Ae:F+=$r();var ue;h===null?ue="null":I(h)?ue="array":h!==void 0&&h.$$typeof===e?(ue="<"+(ee(h.type)||"Unknown")+" />",F=" Did you accidentally export a JSX literal instead of a component?"):ue=typeof h,S("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",ue,F)}var pe=nr(h,w,T,Y,X);if(pe==null)return pe;if(W){var We=w.children;if(We!==void 0)if(D)if(I(We)){for(var Lt=0;Lt<We.length;Lt++)Hn(We[Lt],h);Object.freeze&&Object.freeze(We)}else S("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else Hn(We,h)}if($e.call(w,"key")){var wt=ee(h),Ce=Object.keys(w).filter(function(oc){return oc!=="key"}),ds=Ce.length>0?"{key: someKey, "+Ce.join(": ..., ")+": ...}":"{key: someKey}";if(!Gn[wt+ds]){var ic=Ce.length>0?"{"+Ce.join(": ..., ")+": ...}":"{}";S(`A props object containing a "key" prop is being spread into JSX:
10
10
  let props = %s;
11
11
  <%s {...props} />
12
12
  React keys must be passed directly to JSX without using spread:
13
13
  let props = %s;
14
- <%s key={someKey} {...props} />`,ns,bt,Dl,bt),Ln[bt+ns]=!0}}return h===s?Ol(pe):Al(pe),pe}}function Rl(h,S,j){return Un(h,S,j,!0)}function Cl(h,S,j){return Un(h,S,j,!1)}var Il=Cl,Nl=Rl;Lt.Fragment=s,Lt.jsx=Il,Lt.jsxs=Nl})()),Lt}var os;function qn(){return os||(os=1,process.env.NODE_ENV==="production"?nr.exports=Bn():nr.exports=Fn()),nr.exports}var l=qn();const ar={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"};function ir(r,e){var t={};for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(r);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(r,s[n])&&(t[s[n]]=r[s[n]]);return t}function Wn(r,e,t,s){function n(a){return a instanceof t?a:new t(function(i){i(a)})}return new(t||(t=Promise))(function(a,i){function o(d){try{u(s.next(d))}catch(f){i(f)}}function c(d){try{u(s.throw(d))}catch(f){i(f)}}function u(d){d.done?a(d.value):n(d.value).then(o,c)}u((s=s.apply(r,e||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const Gn=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);class Or extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Hn extends Or{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ls extends Or{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class cs extends Or{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Rr;(function(r){r.Any="any",r.ApNortheast1="ap-northeast-1",r.ApNortheast2="ap-northeast-2",r.ApSouth1="ap-south-1",r.ApSoutheast1="ap-southeast-1",r.ApSoutheast2="ap-southeast-2",r.CaCentral1="ca-central-1",r.EuCentral1="eu-central-1",r.EuWest1="eu-west-1",r.EuWest2="eu-west-2",r.EuWest3="eu-west-3",r.SaEast1="sa-east-1",r.UsEast1="us-east-1",r.UsWest1="us-west-1",r.UsWest2="us-west-2"})(Rr||(Rr={}));class zn{constructor(e,{headers:t={},customFetch:s,region:n=Rr.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Gn(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Wn(this,arguments,void 0,function*(t,s={}){var n;let a,i;try{const{headers:o,method:c,body:u,signal:d,timeout:f}=s;let m={},{region:p}=s;p||(p=this.region);const g=new URL(`${this.url}/${t}`);p&&p!=="any"&&(m["x-region"]=p,g.searchParams.set("forceFunctionRegion",p));let y;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(m["Content-Type"]="application/octet-stream",y=u):typeof u=="string"?(m["Content-Type"]="text/plain",y=u):typeof FormData<"u"&&u instanceof FormData?y=u:(m["Content-Type"]="application/json",y=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?y=JSON.stringify(u):y=u;let x=d;f&&(i=new AbortController,a=setTimeout(()=>i.abort(),f),d?(x=i.signal,d.addEventListener("abort",()=>i.abort())):x=i.signal);const b=yield this.fetch(g.toString(),{method:c||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),o),body:y,signal:x}).catch(A=>{throw new Hn(A)}),k=b.headers.get("x-relay-error");if(k&&k==="true")throw new ls(b);if(!b.ok)throw new cs(b);let _=((n=b.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),O;return _==="application/json"?O=yield b.json():_==="application/octet-stream"||_==="application/pdf"?O=yield b.blob():_==="text/event-stream"?O=b:_==="multipart/form-data"?O=yield b.formData():O=yield b.text(),{data:O,error:null,response:b}}catch(o){return{data:null,error:o,response:o instanceof cs||o instanceof ls?o.context:void 0}}finally{a&&clearTimeout(a)}})}}var Vn=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}},Jn=class{constructor(r){var e,t,s;this.shouldThrowOnError=!1,this.method=r.method,this.url=r.url,this.headers=new Headers(r.headers),this.schema=r.schema,this.body=r.body,this.shouldThrowOnError=(e=r.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=r.signal,this.isMaybeSingle=(t=r.isMaybeSingle)!==null&&t!==void 0?t:!1,this.urlLengthLimit=(s=r.urlLengthLimit)!==null&&s!==void 0?s:8e3,r.fetch?this.fetch=r.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=new Headers(this.headers),this.headers.set(r,e),this}then(r,e){var t=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");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let i=null,o=null,c=null,u=a.status,d=a.statusText;if(a.ok){var f,m;if(t.method!=="HEAD"){var p;const b=await a.text();b===""||(t.headers.get("Accept")==="text/csv"||t.headers.get("Accept")&&(!((p=t.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text"))?o=b:o=JSON.parse(b))}const y=(f=t.headers.get("Prefer"))===null||f===void 0?void 0:f.match(/count=(exact|planned|estimated)/),x=(m=a.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");y&&x&&x.length>1&&(c=parseInt(x[1])),t.isMaybeSingle&&t.method==="GET"&&Array.isArray(o)&&(o.length>1?(i={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,u=406,d="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{var g;const y=await a.text();try{i=JSON.parse(y),Array.isArray(i)&&a.status===404&&(o=[],i=null,u=200,d="OK")}catch{a.status===404&&y===""?(u=204,d="No Content"):i={message:y}}if(i&&t.isMaybeSingle&&(!(i==null||(g=i.details)===null||g===void 0)&&g.includes("0 rows"))&&(i=null,u=200,d="OK"),i&&t.shouldThrowOnError)throw new Vn(i)}return{error:i,data:o,count:c,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(a=>{var i;let o="",c="",u="";const d=a?.cause;if(d){var f,m,p,g;const b=(f=d?.message)!==null&&f!==void 0?f:"",k=(m=d?.code)!==null&&m!==void 0?m:"";o=`${(p=a?.name)!==null&&p!==void 0?p:"FetchError"}: ${a?.message}`,o+=`
14
+ <%s key={someKey} {...props} />`,ds,wt,ic,wt),Gn[wt+ds]=!0}}return h===s?tc(pe):ec(pe),pe}}function rc(h,w,T){return zn(h,w,T,!0)}function sc(h,w,T){return zn(h,w,T,!1)}var nc=sc,ac=rc;Mt.Fragment=s,Mt.jsx=nc,Mt.jsxs=ac})()),Mt}var ms;function Xn(){return ms||(ms=1,process.env.NODE_ENV==="production"?lr.exports=Yn():lr.exports=Qn()),lr.exports}var c=Xn();const cr={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"};function ur(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 Zn(t,e,r,s){function n(a){return a instanceof r?a:new r(function(i){i(a)})}return new(r||(r=Promise))(function(a,i){function o(d){try{u(s.next(d))}catch(f){i(f)}}function l(d){try{u(s.throw(d))}catch(f){i(f)}}function u(d){d.done?a(d.value):n(d.value).then(o,l)}u((s=s.apply(t,e||[])).next())})}typeof SuppressedError=="function"&&SuppressedError;const ea=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Lr extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}}class ta extends Lr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ps extends Lr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class gs extends Lr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Ur;(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"})(Ur||(Ur={}));class ra{constructor(e,{headers:r={},customFetch:s,region:n=Ur.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=ea(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Zn(this,arguments,void 0,function*(r,s={}){var n;let a,i;try{const{headers:o,method:l,body:u,signal:d,timeout:f}=s;let m={},{region:p}=s;p||(p=this.region);const g=new URL(`${this.url}/${r}`);p&&p!=="any"&&(m["x-region"]=p,g.searchParams.set("forceFunctionRegion",p));let y;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(m["Content-Type"]="application/octet-stream",y=u):typeof u=="string"?(m["Content-Type"]="text/plain",y=u):typeof FormData<"u"&&u instanceof FormData?y=u:(m["Content-Type"]="application/json",y=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?y=JSON.stringify(u):y=u;let x=d;f&&(i=new AbortController,a=setTimeout(()=>i.abort(),f),d?(x=i.signal,d.addEventListener("abort",()=>i.abort())):x=i.signal);const _=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},m),this.headers),o),body:y,signal:x}).catch(O=>{throw new ta(O)}),S=_.headers.get("x-relay-error");if(S&&S==="true")throw new ps(_);if(!_.ok)throw new gs(_);let k=((n=_.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),N;return k==="application/json"?N=yield _.json():k==="application/octet-stream"||k==="application/pdf"?N=yield _.blob():k==="text/event-stream"?N=_:k==="multipart/form-data"?N=yield _.formData():N=yield _.text(),{data:N,error:null,response:_}}catch(o){return{data:null,error:o,response:o instanceof gs||o instanceof ps?o.context:void 0}}finally{a&&clearTimeout(a)}})}}var sa=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},na=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");const s=this.fetch;let n=s(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async a=>{let i=null,o=null,l=null,u=a.status,d=a.statusText;if(a.ok){var f,m;if(r.method!=="HEAD"){var p;const _=await a.text();_===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text"))?o=_:o=JSON.parse(_))}const y=(f=r.headers.get("Prefer"))===null||f===void 0?void 0:f.match(/count=(exact|planned|estimated)/),x=(m=a.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");y&&x&&x.length>1&&(l=parseInt(x[1])),r.isMaybeSingle&&r.method==="GET"&&Array.isArray(o)&&(o.length>1?(i={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,u=406,d="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{var g;const y=await a.text();try{i=JSON.parse(y),Array.isArray(i)&&a.status===404&&(o=[],i=null,u=200,d="OK")}catch{a.status===404&&y===""?(u=204,d="No Content"):i={message:y}}if(i&&r.isMaybeSingle&&(!(i==null||(g=i.details)===null||g===void 0)&&g.includes("0 rows"))&&(i=null,u=200,d="OK"),i&&r.shouldThrowOnError)throw new sa(i)}return{error:i,data:o,count:l,status:u,statusText:d}});return this.shouldThrowOnError||(n=n.catch(a=>{var i;let o="",l="",u="";const d=a?.cause;if(d){var f,m,p,g;const _=(f=d?.message)!==null&&f!==void 0?f:"",S=(m=d?.code)!==null&&m!==void 0?m:"";o=`${(p=a?.name)!==null&&p!==void 0?p:"FetchError"}: ${a?.message}`,o+=`
15
15
 
16
- Caused by: ${(g=d?.name)!==null&&g!==void 0?g:"Error"}: ${b}`,k&&(o+=` (${k})`),d?.stack&&(o+=`
17
- ${d.stack}`)}else{var y;o=(y=a?.stack)!==null&&y!==void 0?y:""}const x=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",x>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${x} 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.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",x>this.urlLengthLimit&&(c+=`. Your request URL is ${x} 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:`${(i=a?.name)!==null&&i!==void 0?i:"FetchError"}: ${a?.message}`,details:o,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),n.then(r,e)}returns(){return this}overrideTypes(){return this}},Yn=class extends Jn{select(r){let e=!1;const t=(r??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",t),this.headers.append("Prefer","return=representation"),this}order(r,{ascending:e=!0,nullsFirst:t,foreignTable:s,referencedTable:n=s}={}){const a=n?`${n}.order`:"order",i=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${i?`${i},`:""}${r}.${e?"asc":"desc"}${t===void 0?"":t?".nullsfirst":".nullslast"}`),this}limit(r,{foreignTable:e,referencedTable:t=e}={}){const s=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(s,`${r}`),this}range(r,e,{foreignTable:t,referencedTable:s=t}={}){const n=typeof s>"u"?"offset":`${s}.offset`,a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${r}`),this.url.searchParams.set(a,`${e-r+1}`),this}abortSignal(r){return this.signal=r,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:r=!1,verbose:e=!1,settings:t=!1,buffers:s=!1,wal:n=!1,format:a="text"}={}){var i;const o=[r?"analyze":null,e?"verbose":null,t?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${c}"; options=${o};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(r){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${r}`),this}};const us=new RegExp("[,()]");var wt=class extends Yn{eq(r,e){return this.url.searchParams.append(r,`eq.${e}`),this}neq(r,e){return this.url.searchParams.append(r,`neq.${e}`),this}gt(r,e){return this.url.searchParams.append(r,`gt.${e}`),this}gte(r,e){return this.url.searchParams.append(r,`gte.${e}`),this}lt(r,e){return this.url.searchParams.append(r,`lt.${e}`),this}lte(r,e){return this.url.searchParams.append(r,`lte.${e}`),this}like(r,e){return this.url.searchParams.append(r,`like.${e}`),this}likeAllOf(r,e){return this.url.searchParams.append(r,`like(all).{${e.join(",")}}`),this}likeAnyOf(r,e){return this.url.searchParams.append(r,`like(any).{${e.join(",")}}`),this}ilike(r,e){return this.url.searchParams.append(r,`ilike.${e}`),this}ilikeAllOf(r,e){return this.url.searchParams.append(r,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(r,e){return this.url.searchParams.append(r,`ilike(any).{${e.join(",")}}`),this}regexMatch(r,e){return this.url.searchParams.append(r,`match.${e}`),this}regexIMatch(r,e){return this.url.searchParams.append(r,`imatch.${e}`),this}is(r,e){return this.url.searchParams.append(r,`is.${e}`),this}isDistinct(r,e){return this.url.searchParams.append(r,`isdistinct.${e}`),this}in(r,e){const t=Array.from(new Set(e)).map(s=>typeof s=="string"&&us.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`in.(${t})`),this}notIn(r,e){const t=Array.from(new Set(e)).map(s=>typeof s=="string"&&us.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(r,`not.in.(${t})`),this}contains(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cs.{${e.join(",")}}`):this.url.searchParams.append(r,`cs.${JSON.stringify(e)}`),this}containedBy(r,e){return typeof e=="string"?this.url.searchParams.append(r,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(r,`cd.{${e.join(",")}}`):this.url.searchParams.append(r,`cd.${JSON.stringify(e)}`),this}rangeGt(r,e){return this.url.searchParams.append(r,`sr.${e}`),this}rangeGte(r,e){return this.url.searchParams.append(r,`nxl.${e}`),this}rangeLt(r,e){return this.url.searchParams.append(r,`sl.${e}`),this}rangeLte(r,e){return this.url.searchParams.append(r,`nxr.${e}`),this}rangeAdjacent(r,e){return this.url.searchParams.append(r,`adj.${e}`),this}overlaps(r,e){return typeof e=="string"?this.url.searchParams.append(r,`ov.${e}`):this.url.searchParams.append(r,`ov.{${e.join(",")}}`),this}textSearch(r,e,{config:t,type:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");const a=t===void 0?"":`(${t})`;return this.url.searchParams.append(r,`${n}fts${a}.${e}`),this}match(r){return Object.entries(r).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(r,e,t){return this.url.searchParams.append(r,`not.${e}.${t}`),this}or(r,{foreignTable:e,referencedTable:t=e}={}){const s=t?`${t}.or`:"or";return this.url.searchParams.append(s,`(${r})`),this}filter(r,e,t){return this.url.searchParams.append(r,`${e}.${t}`),this}},Qn=class{constructor(r,{headers:e={},schema:t,fetch:s,urlLengthLimit:n=8e3}){this.url=r,this.headers=new Headers(e),this.schema=t,this.fetch=s,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(r,e){const{head:t=!1,count:s}=e??{},n=t?"HEAD":"GET";let a=!1;const i=(r??"*").split("").map(u=>/\s/.test(u)&&!a?"":(u==='"'&&(a=!a),u)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",i),s&&c.append("Prefer",`count=${s}`),new wt({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(r,{count:e,defaultToNull:t=!0}={}){var s;const n="POST",{url:a,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),t||i.append("Prefer","missing=default"),Array.isArray(r)){const o=r.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(o.length>0){const c=[...new Set(o)].map(u=>`"${u}"`);a.searchParams.set("columns",c.join(","))}}return new wt({method:n,url:a,headers:i,schema:this.schema,body:r,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(r,{onConflict:e,ignoreDuplicates:t=!1,count:s,defaultToNull:n=!0}={}){var a;const i="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${t?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&c.append("Prefer",`count=${s}`),n||c.append("Prefer","missing=default"),Array.isArray(r)){const u=r.reduce((d,f)=>d.concat(Object.keys(f)),[]);if(u.length>0){const d=[...new Set(u)].map(f=>`"${f}"`);o.searchParams.set("columns",d.join(","))}}return new wt({method:i,url:o,headers:c,schema:this.schema,body:r,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(r,{count:e}={}){var t;const s="PATCH",{url:n,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new wt({method:s,url:n,headers:a,schema:this.schema,body:r,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:r}={}){var e;const t="DELETE",{url:s,headers:n}=this.cloneRequestState();return r&&n.append("Prefer",`count=${r}`),new wt({method:t,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Ut(r){"@babel/helpers - typeof";return Ut=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},Ut(r)}function Xn(r,e){if(Ut(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Ut(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Zn(r){var e=Xn(r,"string");return Ut(e)=="symbol"?e:e+""}function ea(r,e,t){return(e=Zn(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function ds(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function or(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ds(Object(t),!0).forEach(function(s){ea(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ds(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}var ta=class Mn{constructor(e,{headers:t={},schema:s,fetch:n,timeout:a,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=s,this.urlLengthLimit=i;const o=n??globalThis.fetch;a!==void 0&&a>0?this.fetch=(c,u)=>{const d=new AbortController,f=setTimeout(()=>d.abort(),a),m=u?.signal;if(m){if(m.aborted)return clearTimeout(f),o(c,u);const p=()=>{clearTimeout(f),d.abort()};return m.addEventListener("abort",p,{once:!0}),o(c,or(or({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(f),m.removeEventListener("abort",p)})}return o(c,or(or({},u),{},{signal:d.signal})).finally(()=>clearTimeout(f))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Qn(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Mn(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:s=!1,get:n=!1,count:a}={}){var i;let o;const c=new URL(`${this.url}/rpc/${e}`);let u;const d=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(d)),f=s&&Object.values(t).some(d);f?(o="POST",u=t):s||n?(o=s?"HEAD":"GET",Object.entries(t).filter(([p,g])=>g!==void 0).map(([p,g])=>[p,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([p,g])=>{c.searchParams.append(p,g)})):(o="POST",u=t);const m=new Headers(this.headers);return f?m.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&m.set("Prefer",`count=${a}`),new wt({method:o,url:c,headers:m,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};class ra{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."};const t=globalThis.process;if(t){const s=t.versions;if(s&&s.node){const n=s.node,a=parseInt(n.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${a} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${a} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
16
+ Caused by: ${(g=d?.name)!==null&&g!==void 0?g:"Error"}: ${_}`,S&&(o+=` (${S})`),d?.stack&&(o+=`
17
+ ${d.stack}`)}else{var y;o=(y=a?.stack)!==null&&y!==void 0?y:""}const x=this.url.toString().length;return a?.name==="AbortError"||a?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",x>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${x} 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.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",x>this.urlLengthLimit&&(l+=`. Your request URL is ${x} 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:`${(i=a?.name)!==null&&i!==void 0?i:"FetchError"}: ${a?.message}`,details:o,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},aa=class extends na{select(t){let e=!1;const 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}={}){const a=n?`${n}.order`:"order",i=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){const n=typeof s>"u"?"offset":`${s}.offset`,a=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(a,`${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:a="text"}={}){var i;const o=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${l}"; options=${o};`),a==="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}};const ys=new RegExp("[,()]");var _t=class extends aa{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){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&ys.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(s=>typeof s=="string"&&ys.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");const a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).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}={}){const 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}},ia=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){const{head:r=!1,count:s}=e??{},n=r?"HEAD":"GET";let a=!1;const i=(t??"*").split("").map(u=>/\s/.test(u)&&!a?"":(u==='"'&&(a=!a),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",i),s&&l.append("Prefer",`count=${s}`),new _t({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;const n="POST",{url:a,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){const o=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){const l=[...new Set(o)].map(u=>`"${u}"`);a.searchParams.set("columns",l.join(","))}}return new _t({method:n,url:a,headers:i,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 a;const i="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){const u=t.reduce((d,f)=>d.concat(Object.keys(f)),[]);if(u.length>0){const d=[...new Set(u)].map(f=>`"${f}"`);o.searchParams.set("columns",d.join(","))}}return new _t({method:i,url:o,headers:l,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;const s="PATCH",{url:n,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new _t({method:s,url:n,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;const r="DELETE",{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new _t({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Bt(t){"@babel/helpers - typeof";return Bt=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},Bt(t)}function oa(t,e){if(Bt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Bt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function la(t){var e=oa(t,"string");return Bt(e)=="symbol"?e:e+""}function ca(t,e,r){return(e=la(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 dr(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){ca(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 ua=class Vn{constructor(e,{headers:r={},schema:s,fetch:n,timeout:a,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=i;const o=n??globalThis.fetch;a!==void 0&&a>0?this.fetch=(l,u)=>{const d=new AbortController,f=setTimeout(()=>d.abort(),a),m=u?.signal;if(m){if(m.aborted)return clearTimeout(f),o(l,u);const p=()=>{clearTimeout(f),d.abort()};return m.addEventListener("abort",p,{once:!0}),o(l,dr(dr({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(f),m.removeEventListener("abort",p)})}return o(l,dr(dr({},u),{},{signal:d.signal})).finally(()=>clearTimeout(f))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ia(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Vn(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:a}={}){var i;let o;const l=new URL(`${this.url}/rpc/${e}`);let u;const d=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(d)),f=s&&Object.values(r).some(d);f?(o="POST",u=r):s||n?(o=s?"HEAD":"GET",Object.entries(r).filter(([p,g])=>g!==void 0).map(([p,g])=>[p,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([p,g])=>{l.searchParams.append(p,g)})):(o="POST",u=r);const m=new Headers(this.headers);return f?m.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&m.set("Prefer",`count=${a}`),new _t({method:o,url:l,headers:m,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};class da{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."};const r=globalThis.process;if(r){const s=r.versions;if(s&&s.node){const n=s.node,a=parseInt(n.replace(/^v/,"").split(".")[0]);return a>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${a} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${a} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
18
18
  import ws from "ws"
19
- 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(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`
19
+ 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(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
20
20
 
21
- Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const s=this.getWebSocketConstructor();return new s(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const sa="realtime-js/2.99.1",na="1.0.0",hs="2.0.0",fs=hs,Cr=1e4,aa=1e3,ia=100;var tt;(function(r){r[r.connecting=0]="connecting",r[r.open=1]="open",r[r.closing=2]="closing",r[r.closed=3]="closed"})(tt||(tt={}));var ge;(function(r){r.closed="closed",r.errored="errored",r.joined="joined",r.joining="joining",r.leaving="leaving"})(ge||(ge={}));var Ge;(function(r){r.close="phx_close",r.error="phx_error",r.join="phx_join",r.reply="phx_reply",r.leave="phx_leave",r.access_token="access_token"})(Ge||(Ge={}));var Ir;(function(r){r.websocket="websocket"})(Ir||(Ir={}));var lt;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(lt||(lt={}));class oa{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return t(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,s;const n=(s=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,s;const n=(s=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&s!==void 0?s:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,s){var n,a;const i=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",c=(a=e.join_ref)!==null&&a!==void 0?a:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=Object.keys(d).length===0?"":JSON.stringify(d);if(c.length>255)throw new Error(`joinRef length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+c.length+o.length+i.length+u.length+f.length,p=new ArrayBuffer(this.HEADER_LENGTH+m);let g=new DataView(p),y=0;g.setUint8(y++,this.KINDS.userBroadcastPush),g.setUint8(y++,c.length),g.setUint8(y++,o.length),g.setUint8(y++,i.length),g.setUint8(y++,u.length),g.setUint8(y++,f.length),g.setUint8(y++,t),Array.from(c,b=>g.setUint8(y++,b.charCodeAt(0))),Array.from(o,b=>g.setUint8(y++,b.charCodeAt(0))),Array.from(i,b=>g.setUint8(y++,b.charCodeAt(0))),Array.from(u,b=>g.setUint8(y++,b.charCodeAt(0))),Array.from(f,b=>g.setUint8(y++,b.charCodeAt(0)));var x=new Uint8Array(p.byteLength+s.byteLength);return x.set(new Uint8Array(p),0),x.set(new Uint8Array(s),p.byteLength),x.buffer}decode(e,t){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return t(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,a,i,o,c]=s;return t({join_ref:n,ref:a,topic:i,event:o,payload:c})}return t({})}_binaryDecode(e){const t=new DataView(e),s=t.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,n)}_decodeUserBroadcast(e,t,s){const n=t.getUint8(1),a=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4);let c=this.HEADER_LENGTH+4;const u=s.decode(e.slice(c,c+n));c=c+n;const d=s.decode(e.slice(c,c+a));c=c+a;const f=s.decode(e.slice(c,c+i));c=c+i;const m=e.slice(c,e.byteLength),p=o===this.JSON_ENCODING?JSON.parse(s.decode(m)):m,g={type:this.BROADCAST_EVENT,event:d,payload:p};return i>0&&(g.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e?.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>t.includes(s)))}}class ms{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var Z;(function(r){r.abstime="abstime",r.bool="bool",r.date="date",r.daterange="daterange",r.float4="float4",r.float8="float8",r.int2="int2",r.int4="int4",r.int4range="int4range",r.int8="int8",r.int8range="int8range",r.json="json",r.jsonb="jsonb",r.money="money",r.numeric="numeric",r.oid="oid",r.reltime="reltime",r.text="text",r.time="time",r.timestamp="timestamp",r.timestamptz="timestamptz",r.timetz="timetz",r.tsrange="tsrange",r.tstzrange="tstzrange"})(Z||(Z={}));const ps=(r,e,t={})=>{var s;const n=(s=t.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((a,i)=>(a[i]=la(i,r,e,n),a),{}):{}},la=(r,e,t,s)=>{const n=e.find(o=>o.name===r),a=n?.type,i=t[r];return a&&!s.includes(a)?gs(a,i):Nr(i)},gs=(r,e)=>{if(r.charAt(0)==="_"){const t=r.slice(1,r.length);return ha(e,t)}switch(r){case Z.bool:return ca(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return ua(e);case Z.json:case Z.jsonb:return da(e);case Z.timestamp:return fa(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return Nr(e);default:return Nr(e)}},Nr=r=>r,ca=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},ua=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},da=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},ha=(r,e)=>{if(typeof r!="string")return r;const t=r.length-1,s=r[t];if(r[0]==="{"&&s==="}"){let a;const i=r.slice(1,t);try{a=JSON.parse("["+i+"]")}catch{a=i?i.split(","):[]}return a.map(o=>gs(e,o))}return r},fa=r=>typeof r=="string"?r.replace(" ","T"):r,ys=r=>{const e=new URL(r);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Dr{constructor(e,t,s={},n=Cr){this.channel=e,this.event=t,this.payload=s,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t((s=this.receivedResp)===null||s===void 0?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(s=>s.status===e).forEach(s=>s.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var vs;(function(r){r.SYNC="sync",r.JOIN="join",r.LEAVE="leave"})(vs||(vs={}));class Mt{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=t?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{const{onJoin:a,onLeave:i,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Mt.syncState(this.state,n,a,i),this.pendingDiffs.forEach(c=>{this.state=Mt.syncDiff(this.state,c,a,i)}),this.pendingDiffs=[],o()}),this.channel._on(s.diff,{},n=>{const{onJoin:a,onLeave:i,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=Mt.syncDiff(this.state,n,a,i),o())}),this.onJoin((n,a,i)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:a,newPresences:i})}),this.onLeave((n,a,i)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:a,leftPresences:i})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,s,n){const a=this.cloneDeep(e),i=this.transformState(t),o={},c={};return this.map(a,(u,d)=>{i[u]||(c[u]=d)}),this.map(i,(u,d)=>{const f=a[u];if(f){const m=d.map(x=>x.presence_ref),p=f.map(x=>x.presence_ref),g=d.filter(x=>p.indexOf(x.presence_ref)<0),y=f.filter(x=>m.indexOf(x.presence_ref)<0);g.length>0&&(o[u]=g),y.length>0&&(c[u]=y)}else o[u]=d}),this.syncDiff(a,{joins:o,leaves:c},s,n)}static syncDiff(e,t,s,n){const{joins:a,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(a,(o,c)=>{var u;const d=(u=e[o])!==null&&u!==void 0?u:[];if(e[o]=this.cloneDeep(c),d.length>0){const f=e[o].map(p=>p.presence_ref),m=d.filter(p=>f.indexOf(p.presence_ref)<0);e[o].unshift(...m)}s(o,d,c)}),this.map(i,(o,c)=>{let u=e[o];if(!u)return;const d=c.map(f=>f.presence_ref);u=u.filter(f=>d.indexOf(f.presence_ref)<0),e[o]=u,n(o,u,c),u.length===0&&delete e[o]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(s=>t(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,s)=>{const n=e[s];return"metas"in n?t[s]=n.metas.map(a=>(a.presence_ref=a.phx_ref,delete a.phx_ref,delete a.phx_ref_prev,a)):t[s]=n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var bs;(function(r){r.ALL="*",r.INSERT="INSERT",r.UPDATE="UPDATE",r.DELETE="DELETE"})(bs||(bs={}));var Kt;(function(r){r.BROADCAST="broadcast",r.PRESENCE="presence",r.POSTGRES_CHANGES="postgres_changes",r.SYSTEM="system"})(Kt||(Kt={}));var Ye;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Ye||(Ye={}));class _t{constructor(e,t={config:{}},s){var n,a;if(this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=ge.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Dr(this,Ge.join,this.params,this.timeout),this.rejoinTimer=new ms(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=ge.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=ge.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=ge.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Ge.reply,{},(i,o)=>{this._trigger(this._replyEventName(o),i)}),this.presence=new Mt(this),this.broadcastEndpointURL=ys(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((a=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||a===void 0)&&a.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var s,n,a;if(this.socket.isConnected()||this.socket.connect(),this.state==ge.closed){const{config:{broadcast:i,presence:o,private:c}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(p=>p.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[Kt.PRESENCE]&&this.bindings[Kt.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,f={},m={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(p=>e?.(Ye.CHANNEL_ERROR,p)),this._onClose(()=>e?.(Ye.CLOSED)),this.updateJoinPayload(Object.assign({config:m},f)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:p})=>{var g;if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){e?.(Ye.SUBSCRIBED);return}else{const y=this.bindings.postgres_changes,x=(g=y?.length)!==null&&g!==void 0?g:0,b=[];for(let k=0;k<x;k++){const _=y[k],{filter:{event:O,schema:A,table:M,filter:E}}=_,N=p&&p[k];if(N&&N.event===O&&_t.isFilterValueEqual(N.schema,A)&&_t.isFilterValueEqual(N.table,M)&&_t.isFilterValueEqual(N.filter,E))b.push(Object.assign(Object.assign({},_),{id:N.id}));else{this.unsubscribe(),this.state=ge.errored,e?.(Ye.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e(Ye.SUBSCRIBED);return}}).receive("error",p=>{this.state=ge.errored,e?.(Ye.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(Ye.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this.state===ge.joined&&e===Kt.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,s)}async httpSend(e,t,s={}){var n;if(t==null)return Promise.reject("Payload is required for httpSend()");const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let c=o.statusText;try{const u=await o.json();c=u.error||u.message||c}catch{}return Promise.reject(new Error(c))}async send(e,t={}){var s,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:i,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(s=t.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var i,o,c;const u=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((c=(o=(i=this.params)===null||i===void 0?void 0:i.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&a("ok"),u.receive("ok",()=>a("ok")),u.receive("error",()=>a("error")),u.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=ge.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Ge.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new Dr(this,Ge.leave,{},e),s.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=ge.closed,this.bindings={}}async _fetchWithTimeout(e,t,s){const n=new AbortController,a=setTimeout(()=>n.abort(),s),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(a),i}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new Dr(this,e,t,s);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>ia){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var n,a;const i=e.toLocaleLowerCase(),{close:o,error:c,leave:u,join:d}=Ge;if(s&&[o,c,u,d].indexOf(i)>=0&&s!==this._joinRef())return;let m=this._onMessage(i,t,s);if(t&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(p=>{var g,y,x;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((x=(y=p.filter)===null||y===void 0?void 0:y.event)===null||x===void 0?void 0:x.toLocaleLowerCase())===i}).map(p=>p.callback(m,s)):(a=this.bindings[i])===null||a===void 0||a.filter(p=>{var g,y,x,b,k,_;if(["broadcast","presence","postgres_changes"].includes(i))if("id"in p){const O=p.id,A=(g=p.filter)===null||g===void 0?void 0:g.event;return O&&((y=t.ids)===null||y===void 0?void 0:y.includes(O))&&(A==="*"||A?.toLocaleLowerCase()===((x=t.data)===null||x===void 0?void 0:x.type.toLocaleLowerCase()))}else{const O=(k=(b=p?.filter)===null||b===void 0?void 0:b.event)===null||k===void 0?void 0:k.toLocaleLowerCase();return O==="*"||O===((_=t?.event)===null||_===void 0?void 0:_.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===i}).map(p=>{if(typeof m=="object"&&"ids"in m){const g=m.data,{schema:y,table:x,commit_timestamp:b,type:k,errors:_}=g;m=Object.assign(Object.assign({},{schema:y,table:x,commit_timestamp:b,eventType:k,new:{},old:{},errors:_}),this._getPayloadRecords(g))}p.callback(m,s)})}_isClosed(){return this.state===ge.closed}_isJoined(){return this.state===ge.joined}_isJoining(){return this.state===ge.joining}_isLeaving(){return this.state===ge.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const n=e.toLocaleLowerCase(),a={type:n,filter:t,callback:s};return this.bindings[n]?this.bindings[n].push(a):this.bindings[n]=[a],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(n=>{var a;return!(((a=n.type)===null||a===void 0?void 0:a.toLocaleLowerCase())===s&&_t.isEqual(n.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Ge.close,{},e)}_onError(e){this._on(Ge.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=ge.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=ps(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=ps(e.columns,e.old_record)),t}}const $r=()=>{},lr={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ma=[1e3,2e3,5e3,1e4],pa=1e4,ga=`
21
+ Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const ha="realtime-js/2.100.0",fa="1.0.0",vs="2.0.0",ma=vs,pa=1e4,ga=100,st={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ws={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Mr={connecting:"connecting",closing:"closing",closed:"closed"};class ya{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;const n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,s){var n,a;const i=e.topic,o=(n=e.ref)!==null&&n!==void 0?n:"",l=(a=e.join_ref)!==null&&a!==void 0?a:"",u=e.payload.event,d=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=Object.keys(d).length===0?"":JSON.stringify(d);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const m=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+i.length+u.length+f.length,p=new ArrayBuffer(this.HEADER_LENGTH+m);let g=new DataView(p),y=0;g.setUint8(y++,this.KINDS.userBroadcastPush),g.setUint8(y++,l.length),g.setUint8(y++,o.length),g.setUint8(y++,i.length),g.setUint8(y++,u.length),g.setUint8(y++,f.length),g.setUint8(y++,r),Array.from(l,_=>g.setUint8(y++,_.charCodeAt(0))),Array.from(o,_=>g.setUint8(y++,_.charCodeAt(0))),Array.from(i,_=>g.setUint8(y++,_.charCodeAt(0))),Array.from(u,_=>g.setUint8(y++,_.charCodeAt(0))),Array.from(f,_=>g.setUint8(y++,_.charCodeAt(0)));var x=new Uint8Array(p.byteLength+s.byteLength);return x.set(new Uint8Array(p),0),x.set(new Uint8Array(s),p.byteLength),x.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){const s=JSON.parse(e),[n,a,i,o,l]=s;return r({join_ref:n,ref:a,topic:i,event:o,payload:l})}return r({})}_binaryDecode(e){const r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;if(s===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,s){const n=r.getUint8(1),a=r.getUint8(2),i=r.getUint8(3),o=r.getUint8(4);let l=this.HEADER_LENGTH+4;const u=s.decode(e.slice(l,l+n));l=l+n;const d=s.decode(e.slice(l,l+a));l=l+a;const f=s.decode(e.slice(l,l+i));l=l+i;const m=e.slice(l,e.byteLength),p=o===this.JSON_ENCODING?JSON.parse(s.decode(m)):m,g={type:this.BROADCAST_EVENT,event:d,payload:p};return i>0&&(g.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([s])=>r.includes(s)))}}var Z;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(Z||(Z={}));const _s=(t,e,r={})=>{var s;const n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((a,i)=>(a[i]=ba(i,t,e,n),a),{}):{}},ba=(t,e,r,s)=>{const n=e.find(o=>o.name===t),a=n?.type,i=r[t];return a&&!s.includes(a)?ks(a,i):Br(i)},ks=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return ka(e,r)}switch(t){case Z.bool:return va(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return wa(e);case Z.json:case Z.jsonb:return _a(e);case Z.timestamp:return Sa(e);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:return Br(e);default:return Br(e)}},Br=t=>t,va=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},wa=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},_a=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},ka=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let a;const i=t.slice(1,r);try{a=JSON.parse("["+i+"]")}catch{a=i?i.split(","):[]}return a.map(o=>ks(e,o))}return t},Sa=t=>typeof t=="string"?t.replace(" ","T"):t,Ss=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Kt=t=>typeof t=="function"?t:function(){return t},xa=typeof self<"u"?self:null,kt=typeof window<"u"?window:null,Ve=xa||kt||globalThis,Ta="2.0.0",ja=1e4,Aa=1e3,Je={connecting:0,open:1,closing:2,closed:3},Pe={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Xe={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Kr={longpoll:"longpoll",websocket:"websocket"},Pa={complete:4},Fr="base64url.bearer.phx.",hr=class{constructor(t,e,r,s){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=s,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(s=>s.status===t).forEach(s=>s.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},xs=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Ea=class{constructor(t,e,r){this.state=Pe.closed,this.topic=t,this.params=Kt(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new hr(this,Xe.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new xs(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Pe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(s=>s.send()),this.pushBuffer=[]}),this.joinPush.receive("error",s=>{this.state=Pe.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Pe.closed,this.socket.remove(this)}),this.onError(s=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,s),this.isJoining()&&this.joinPush.reset(),this.state=Pe.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new hr(this,Xe.leave,Kt({}),this.timeout).send(),this.state=Pe.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Xe.reply,(s,n)=>{this.trigger(this.replyEventName(n),s)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Pe.closed,this.bindings=[]}onClose(t){this.on(Xe.close,t)}onError(t){return this.on(Xe.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let s=new hr(this,t,function(){return e},r);return this.canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Pe.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Xe.close,"leave")},r=new hr(this,Xe.leave,Kt({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,s){return this.topic!==t?!1:s&&s!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:s}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Pe.joining,this.joinPush.resend(t))}trigger(t,e,r,s){let n=this.onMessage(t,e,r,s);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let a=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<a.length;i++)a[i].callback(n,r,s||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Pe.closed}isErrored(){return this.state===Pe.errored}isJoined(){return this.state===Pe.joined}isJoining(){return this.state===Pe.joining}isLeaving(){return this.state===Pe.leaving}},fr=class{static request(t,e,r,s,n,a,i){if(Ve.XDomainRequest){let o=new Ve.XDomainRequest;return this.xdomainRequest(o,t,e,s,n,a,i)}else if(Ve.XMLHttpRequest){let o=new Ve.XMLHttpRequest;return this.xhrRequest(o,t,e,r,s,n,a,i)}else{if(Ve.fetch&&Ve.AbortController)return this.fetchRequest(t,e,r,s,n,a,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,s,n,a,i){let o={method:t,headers:r,body:s},l=null;return n&&(l=new AbortController,setTimeout(()=>l.abort(),n),o.signal=l.signal),Ve.fetch(e,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&a?a():i&&i(null)}),l}static xdomainRequest(t,e,r,s,n,a,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let o=this.parseJSON(t.responseText);i&&i(o)},a&&(t.ontimeout=a),t.onprogress=()=>{},t.send(s),t}static xhrRequest(t,e,r,s,n,a,i,o){t.open(e,r,!0),t.timeout=a;for(let[l,u]of Object.entries(s))t.setRequestHeader(l,u);return t.onerror=()=>o&&o(null),t.onreadystatechange=()=>{if(t.readyState===Pa.complete&&o){let l=this.parseJSON(t.responseText);o(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let n=e?`${e}[${s}]`:s,a=t[s];typeof a=="object"?r.push(this.serialize(a,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(a))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Oa=t=>{let e="",r=new Uint8Array(t),s=r.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(r[n]);return btoa(e)},St=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Fr)&&(this.authToken=atob(e[1].slice(Fr.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Je.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Kr.websocket),"$1/"+Kr.longpoll)}endpointURL(){return fr.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Je.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Je.open||this.readyState===Je.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:s,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=s}else r=0;switch(r){case 200:n.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Je.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Oa(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
22
+ `),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Je.closed;let s=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",s)):this.onclose(s)}ajax(t,e,r,s,n){let a,i=()=>{this.reqs.delete(a),s()};a=fr.request(t,this.endpointURL(),e,r,this.timeout,i,o=>{this.reqs.delete(a),this.isActive()&&n(o)}),this.reqs.add(a)}},Ca=class or{constructor(e,r={}){let s=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(s.state,n=>{let{onJoin:a,onLeave:i,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=or.syncState(this.state,n,a,i),this.pendingDiffs.forEach(l=>{this.state=or.syncDiff(this.state,l,a,i)}),this.pendingDiffs=[],o()}),this.channel.on(s.diff,n=>{let{onJoin:a,onLeave:i,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=or.syncDiff(this.state,n,a,i),o())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return or.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,s,n){let a=this.clone(e),i={},o={};return this.map(a,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let d=a[l];if(d){let f=u.metas.map(y=>y.phx_ref),m=d.metas.map(y=>y.phx_ref),p=u.metas.filter(y=>m.indexOf(y.phx_ref)<0),g=d.metas.filter(y=>f.indexOf(y.phx_ref)<0);p.length>0&&(i[l]=u,i[l].metas=p),g.length>0&&(o[l]=this.clone(d),o[l].metas=g)}else i[l]=u}),this.syncDiff(a,{joins:i,leaves:o},s,n)}static syncDiff(e,r,s,n){let{joins:a,leaves:i}=this.clone(r);return s||(s=function(){}),n||(n=function(){}),this.map(a,(o,l)=>{let u=e[o];if(e[o]=this.clone(l),u){let d=e[o].metas.map(m=>m.phx_ref),f=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);e[o].metas.unshift(...f)}s(o,u,l)}),this.map(i,(o,l)=>{let u=e[o];if(!u)return;let d=l.metas.map(f=>f.phx_ref);u.metas=u.metas.filter(f=>d.indexOf(f.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete e[o]}),e}static list(e,r){return r||(r=function(s,n){return n}),this.map(e,(s,n)=>r(s,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static clone(e){return JSON.parse(JSON.stringify(e))}},mr={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,s,n,a,i]=JSON.parse(t);return e({join_ref:r,ref:s,topic:n,event:a,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:s,topic:n,payload:a}=t,i=this.META_LENGTH+e.length+r.length+n.length+s.length,o=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(o),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,s.length),Array.from(e,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(r,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(n,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(s,f=>l.setUint8(u++,f.charCodeAt(0)));var d=new Uint8Array(o.byteLength+a.byteLength);return d.set(new Uint8Array(o),0),d.set(new Uint8Array(a),o.byteLength),d.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),s=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,s);case this.KINDS.reply:return this.decodeReply(t,e,s);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,s)}},decodePush(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(t.slice(i,i+s));i=i+s;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+a));i=i+a;let d=t.slice(i,t.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:d}},decodeReply(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=e.getUint8(3),i=e.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(o,o+s));o=o+s;let u=r.decode(t.slice(o,o+n));o=o+n;let d=r.decode(t.slice(o,o+a));o=o+a;let f=r.decode(t.slice(o,o+i));o=o+i;let m=t.slice(o,t.byteLength),p={status:f,response:m};return{join_ref:l,ref:u,topic:d,event:Xe.reply,payload:p}},decodeBroadcast(t,e,r){let s=e.getUint8(1),n=e.getUint8(2),a=this.HEADER_LENGTH+2,i=r.decode(t.slice(a,a+s));a=a+s;let o=r.decode(t.slice(a,a+n));a=a+n;let l=t.slice(a,t.byteLength);return{join_ref:null,ref:null,topic:i,event:o,payload:l}}},Ra=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||ja,this.transport=e.transport||Ve.WebSocket||St,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Ve&&Ve.sessionStorage,this.establishedConnections=0,this.defaultEncoder=mr.encode.bind(mr),this.defaultDecoder=mr.decode.bind(mr),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==St?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;kt&&kt.addEventListener&&(kt.addEventListener("pagehide",s=>{this.conn&&(this.disconnect(),r=this.connectClock)}),kt.addEventListener("pageshow",s=>{r===this.connectClock&&(r=null,this.connect())}),kt.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=s=>e.rejoinAfterMs?e.rejoinAfterMs(s):[1e3,2e3,5e3][s-1]||1e4,this.reconnectAfterMs=s=>e.reconnectAfterMs?e.reconnectAfterMs(s):[10,50,100,150,200,250,500,1e3,2e3][s-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(s,n,a)=>{console.log(`${s}: ${n}`,a)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Kt(e.params||{}),this.endPoint=`${t}/${Kr.websocket}`,this.vsn=e.vsn||Ta,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new xs(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return St}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=fr.appendParams(fr.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Kt(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==St?this.connectWithFallback(St,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let s=this.onMessage(n=>{n.ref===e&&(this.off([s]),t(Date.now()-r))});return!0}transportName(t){return t===St?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Fr}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,s=!0,n,a,i=this.transportName(t),o=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,a]),s=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return o("memorized");this.fallbackTimer=setTimeout(o,e),a=this.onError(l=>{this.log("transport","error",l),s&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!s){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Aa,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const s=this.conn;this.waitForBufferDone(s,()=>{e?s.close(e,r||""):s.close(),this.waitForSocketClosed(s,()=>{this.conn===s&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Je.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Xe.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Je.connecting:return"connecting";case Je.open:return"open";case Je.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new Ea(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:s,ref:n,join_ref:a}=t;this.log("push",`${e} ${r} (${a}, ${n})`,s)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:s,payload:n,ref:a,join_ref:i}=e;if(a&&a===this.pendingHeartbeatRef){const o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${s} ${a&&"("+a+")"||""}`.trim(),n);for(let o=0;o<this.channels.length;o++){const l=this.channels[o];l.isMember(r,s,n,i)&&l.trigger(s,n,a,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,s])=>{try{s(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Ft{constructor(e,r){const s=Ia(r);this.presence=new Ca(e.getChannel(),s),this.presence.onJoin((n,a,i)=>{const o=Ft.onJoinPayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onLeave((n,a,i)=>{const o=Ft.onLeavePayload(n,a,i);e.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Ft.transformState(this.presence.state)}static transformState(e){return e=Na(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{const n=e[s];return r[s]=pr(n),r},{})}static onJoinPayload(e,r,s){const n=Ts(r),a=pr(s);return{event:"join",key:e,currentPresences:n,newPresences:a}}static onLeavePayload(e,r,s){const n=Ts(r),a=pr(s);return{event:"leave",key:e,currentPresences:n,leftPresences:a}}}function pr(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Na(t){return JSON.parse(JSON.stringify(t))}function Ia(t){return t?.events&&{events:t.events}}function Ts(t){return t?.metas?pr(t):[]}var js;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(js||(js={}));class Da{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Ft(this.channel.channelAdapter,r)}}class $a{constructor(e,r,s){const n=La(s);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,s){let n;try{n=this.channel.push(e,r,s)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>ga){const a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return n}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===st.joined}isJoined(){return this.state===st.joined}isJoining(){return this.state===st.joining}isClosed(){return this.state===st.closed}isLeaving(){return this.state===st.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function La(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var As;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(As||(As={}));var qt;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(qt||(qt={}));var Ze;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ze||(Ze={}));class Wt{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},s){var n,a;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new $a(this.socket.socketAdapter,e,this.params),this.presence=new Da(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ss(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((a=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||a===void 0)&&a.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,n,a;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:i,presence:o,private:l}}=this.params,u=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(p=>p.filter))!==null&&n!==void 0?n:[],d=!!this.bindings[qt.PRESENCE]&&this.bindings[qt.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,f={},m={broadcast:i,presence:Object.assign(Object.assign({},o),{enabled:d}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(p=>{e?.(Ze.CHANNEL_ERROR,p)}),this._onClose(()=>e?.(Ze.CLOSED)),this.updateJoinPayload(Object.assign({config:m},f)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:p})=>{if(this.socket._isManualToken()||this.socket.setAuth(),p===void 0){e?.(Ze.SUBSCRIBED);return}this._updatePostgresBindings(p,e)}).receive("error",p=>{this.state=st.errored,e?.(Ze.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(Ze.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var s;const n=this.bindings.postgres_changes,a=(s=n?.length)!==null&&s!==void 0?s:0,i=[];for(let o=0;o<a;o++){const l=n[o],{filter:{event:u,schema:d,table:f,filter:m}}=l,p=e&&e[o];if(p&&p.event===u&&Wt.isFilterValueEqual(p.schema,d)&&Wt.isFilterValueEqual(p.table,f)&&Wt.isFilterValueEqual(p.filter,m))i.push(Object.assign(Object.assign({},l),{id:p.id}));else{this.unsubscribe(),this.state=st.errored,r?.(Ze.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=st.errored&&r&&r(Ze.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,s){if(this.channelAdapter.isJoined()&&e===qt.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,s)}async httpSend(e,r,s={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=s.timeout)!==null&&n!==void 0?n:this.timeout);if(o.status===202)return{success:!0};let l=o.statusText;try{const u=await o.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var s,n;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:i}=e,o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l={method:"POST",headers:o,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:i,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var i,o,l;const u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(o=(i=this.params)===null||i===void 0?void 0:i.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&a("ok"),u.receive("ok",()=>a("ok")),u.receive("error",()=>a("error")),u.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,s){const n=new AbortController,a=setTimeout(()=>n.abort(),s),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(a),i}_on(e,r,s){const n=e.toLocaleLowerCase(),a=this.channelAdapter.on(e,s),i={type:n,filter:r,callback:s,ref:a};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,s)=>{var n,a,i,o,l,u,d;const f=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(f,s))return!1;const m=(n=this.bindings[f])===null||n===void 0?void 0:n.find(p=>p.ref===e.ref);if(!m)return!0;if(["broadcast","presence","postgres_changes"].includes(f))if("id"in m){const p=m.id,g=(a=m.filter)===null||a===void 0?void 0:a.event;return p&&((i=r.ids)===null||i===void 0?void 0:i.includes(p))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{const p=(u=(l=m?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return p==="*"||p===((d=r?.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return m.type.toLocaleLowerCase()===f})}_notThisChannelEvent(e,r){const{close:s,error:n,leave:a,join:i}=ws;return r&&[s,n,a,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,s)=>{if(typeof r=="object"&&"ids"in r){const n=r.data,{schema:a,table:i,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:a,table:i,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=_s(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=_s(e.columns,e.old_record)),r}}class Ua{constructor(e,r){this.socket=new Ra(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,s,n=1e4){return new Promise(a=>{setTimeout(()=>a("timeout"),n),this.socket.disconnect(()=>{e(),a("ok")},r,s)})}push(e){this.socket.push(e)}log(e,r,s){this.socket.log(e,r,s)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Mr.connecting}isDisconnecting(){return this.socket.connectionState()==Mr.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const Ma={HEARTBEAT_INTERVAL:25e3},Ba=[1e3,2e3,5e3,1e4],Ka=1e4,Fa=`
22
23
  addEventListener("message", (e) => {
23
24
  if (e.data.event === "start") {
24
25
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
25
26
  }
26
- });`;class ya{constructor(e,t){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Cr,this.transport=null,this.heartbeatIntervalMs=lr.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=$r,this.ref=0,this.reconnectTimer=null,this.vsn=fs,this.logger=$r,this.conn=null,this.sendBuffer=[],this.serializer=new oa,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...a)=>n(...a):(...a)=>fetch(...a),!(!((s=t?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Ir.websocket}`,this.httpEndpoint=ys(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ra.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
27
+ });`;class qa{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var s;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new ya,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=a=>a?(...i)=>a(...i):(...i)=>fetch(...i),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const n=this._initializeOptions(r);this.socketAdapter=new Ua(e,n),this.httpEndpoint=Ss(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
27
28
 
28
29
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
29
30
 
@@ -36,26 +37,26 @@ Option 2: Install and provide the "ws" package:
36
37
  const client = new RealtimeClient(url, {
37
38
  ...options,
38
39
  transport: ws
39
- })`):new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case tt.connecting:return lt.Connecting;case tt.open:return lt.Open;case tt.closing:return lt.Closing;default:return lt.Closed}}isConnected(){return this.connectionState()===lt.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(a=>a.topic===s);if(n)return n;{const a=new _t(`realtime:${e}`,t,this);return this.channels.push(a),a}}push(e){const{topic:t,event:s,payload:n,ref:a}=e,i=()=>{this.encode(e,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${t} ${s} (${a})`,n),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(aa,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},lr.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(s=>s.topic===e&&(s._isJoined()||s._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply"&&t.ref&&t.ref===this.pendingHeartbeatRef){const u=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error",u)}catch(d){this.log("error","error in heartbeat callback",d)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:s,event:n,payload:a,ref:i}=t,o=i?`(${i})`:"",c=a.status||"";this.log("receive",`${c} ${s} ${n} ${o}`.trim(),a),this.channels.filter(u=>u._isMember(s)).forEach(u=>u._trigger(n,a,i)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===tt.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===tt.open||this.conn.readyState===tt.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(t=>{t.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(t=>{t._isJoining()&&(t.joinPush.sent=!1,t.joinPush.send())})),this.flushSendBuffer()}).catch(t=>{this.log("error","error waiting for auth on connect",t),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this._terminateWorker()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(t){this.log("error","error in heartbeat callback",t)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(Ge.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const s=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${s}${n}`}_workerObjectUrl(e){let t;if(e)t=e;else{const s=new Blob([ga],{type:"application/javascript"});t=URL.createObjectURL(s)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,s=!1;if(e)t=e,s=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),t=this.accessTokenValue}else t=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(n=>{const a={access_token:t,version:sa};t&&n.updateJoinPayload(a),n.joinedOnce&&n._isJoined()&&n._push(Ge.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(s=>{try{s(t)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new ms(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},lr.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,s,n,a,i,o,c,u,d,f,m,p;switch(this.transport=(t=e?.transport)!==null&&t!==void 0?t:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:Cr,this.heartbeatIntervalMs=(n=e?.heartbeatIntervalMs)!==null&&n!==void 0?n:lr.HEARTBEAT_INTERVAL,this.worker=(a=e?.worker)!==null&&a!==void 0?a:!1,this.accessToken=(i=e?.accessToken)!==null&&i!==void 0?i:null,this.heartbeatCallback=(o=e?.heartbeatCallback)!==null&&o!==void 0?o:$r,this.vsn=(c=e?.vsn)!==null&&c!==void 0?c:fs,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(u=e?.reconnectAfterMs)!==null&&u!==void 0?u:(g=>ma[g-1]||pa),this.vsn){case na:this.encode=(d=e?.encode)!==null&&d!==void 0?d:((g,y)=>y(JSON.stringify(g))),this.decode=(f=e?.decode)!==null&&f!==void 0?f:((g,y)=>y(JSON.parse(g)));break;case hs:this.encode=(m=e?.encode)!==null&&m!==void 0?m:this.serializer.encode.bind(this.serializer),this.decode=(p=e?.decode)!==null&&p!==void 0?p:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}}var Bt=class extends Error{constructor(r,e){super(r),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 va(r,e,t){const s=new URL(e,r);if(t)for(const[n,a]of Object.entries(t))a!==void 0&&s.searchParams.set(n,a);return s.toString()}async function ba(r){return!r||r.type==="none"?{}:r.type==="bearer"?{Authorization:`Bearer ${r.token}`}:r.type==="header"?{[r.name]:r.value}:r.type==="custom"?await r.getHeaders():{}}function wa(r){const e=r.fetchImpl??globalThis.fetch;return{async request({method:t,path:s,query:n,body:a,headers:i}){const o=va(r.baseUrl,s,n),c=await ba(r.auth),u=await e(o,{method:t,headers:{...a?{"Content-Type":"application/json"}:{},...c,...i},body:a?JSON.stringify(a):void 0}),d=await u.text(),f=(u.headers.get("content-type")||"").includes("application/json"),m=f&&d?JSON.parse(d):d;if(!u.ok){const p=f?m:void 0,g=p?.error;throw new Bt(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:p})}return{status:u.status,headers:u.headers,data:m}}}}function cr(r){return r.join("")}var _a=class{constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r){const e=r?{parent:cr(r.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}async createNamespace(r,e){const t={namespace:r.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(r){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${cr(r.namespace)}`})}async loadNamespaceMetadata(r){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cr(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${cr(r.namespace)}`}),!0}catch(e){if(e instanceof Bt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(r,e){try{return await this.createNamespace(r,e)}catch(t){if(t instanceof Bt&&t.status===409)return;throw t}}};function kt(r){return r.join("")}var ka=class{constructor(r,e="",t){this.client=r,this.prefix=e,this.accessDelegation=t}async listTables(r){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables`})).data.identifiers}async createTable(r,e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(r,e){const t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables/${r.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(r,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables/${r.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(r){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables/${r.name}`,headers:e})).data.metadata}async tableExists(r){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${kt(r.namespace)}/tables/${r.name}`,headers:e}),!0}catch(t){if(t instanceof Bt&&t.status===404)return!1;throw t}}async createTableIfNotExists(r,e){try{return await this.createTable(r,e)}catch(t){if(t instanceof Bt&&t.status===409)return await this.loadTable({namespace:r.namespace,name:e.name});throw t}}},Sa=class{constructor(r){let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);const t=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=wa({baseUrl:t,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=r.accessDelegation?.join(","),this.namespaceOps=new _a(this.client,e),this.tableOps=new ka(this.client,e,this.accessDelegation)}async listNamespaces(r){return this.namespaceOps.listNamespaces(r)}async createNamespace(r,e){return this.namespaceOps.createNamespace(r,e)}async dropNamespace(r){await this.namespaceOps.dropNamespace(r)}async loadNamespaceMetadata(r){return this.namespaceOps.loadNamespaceMetadata(r)}async listTables(r){return this.tableOps.listTables(r)}async createTable(r,e){return this.tableOps.createTable(r,e)}async updateTable(r,e){return this.tableOps.updateTable(r,e)}async dropTable(r,e){await this.tableOps.dropTable(r,e)}async loadTable(r){return this.tableOps.loadTable(r)}async namespaceExists(r){return this.namespaceOps.namespaceExists(r)}async tableExists(r){return this.tableOps.tableExists(r)}async createNamespaceIfNotExists(r,e){return this.namespaceOps.createNamespaceIfNotExists(r,e)}async createTableIfNotExists(r,e){return this.tableOps.createTableIfNotExists(r,e)}},ur=class extends Error{constructor(r,e="storage",t,s){super(r),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=t,this.statusCode=s}};function dr(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ft=class extends ur{constructor(r,e,t,s="storage"){super(r,s,e,t),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=t}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ws=class extends ur{constructor(r,e,t="storage"){super(r,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const xa=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),ja=r=>{if(typeof r!="object"||r===null)return!1;const e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)},Lr=r=>{if(Array.isArray(r))return r.map(t=>Lr(t));if(typeof r=="function"||r!==Object(r))return r;const e={};return Object.entries(r).forEach(([t,s])=>{const n=t.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[n]=Lr(s)}),e},Ta=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function qt(r){"@babel/helpers - typeof";return qt=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},qt(r)}function Pa(r,e){if(qt(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(qt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Ea(r){var e=Pa(r,"string");return qt(e)=="symbol"?e:e+""}function Aa(r,e,t){return(e=Ea(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function _s(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function I(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?_s(Object(t),!0).forEach(function(s){Aa(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):_s(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}const ks=r=>{var e;return r.msg||r.message||r.error_description||(typeof r.error=="string"?r.error:(e=r.error)===null||e===void 0?void 0:e.message)||JSON.stringify(r)},Oa=async(r,e,t,s)=>{if(r&&typeof r=="object"&&"status"in r&&"ok"in r&&typeof r.status=="number"){const n=r,a=n.status||500;if(typeof n.json=="function")n.json().then(i=>{const o=i?.statusCode||i?.code||a+"";e(new Ft(ks(i),a,o,s))}).catch(()=>{if(s==="vectors"){const i=a+"";e(new Ft(n.statusText||`HTTP ${a} error`,a,i,s))}else{const i=a+"";e(new Ft(n.statusText||`HTTP ${a} error`,a,i,s))}});else{const i=a+"";e(new Ft(n.statusText||`HTTP ${a} error`,a,i,s))}}else e(new ws(ks(r),r,s))},Ra=(r,e,t,s)=>{const n={method:r,headers:e?.headers||{}};return r==="GET"||r==="HEAD"||!s?I(I({},n),t):(ja(s)?(n.headers=I({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s)):n.body=s,e?.duplex&&(n.duplex=e.duplex),I(I({},n),t))};async function Wt(r,e,t,s,n,a,i){return new Promise((o,c)=>{r(t,Ra(e,s,n,a)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(i==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>Oa(u,c,s,i))})}function Ss(r="storage"){return{get:async(e,t,s,n)=>Wt(e,"GET",t,s,n,void 0,r),post:async(e,t,s,n,a)=>Wt(e,"POST",t,n,a,s,r),put:async(e,t,s,n,a)=>Wt(e,"PUT",t,n,a,s,r),head:async(e,t,s,n)=>Wt(e,"HEAD",t,I(I({},s),{},{noResolveJson:!0}),n,void 0,r),remove:async(e,t,s,n,a)=>Wt(e,"DELETE",t,n,a,s,r)}}const Ca=Ss("storage"),{get:Gt,post:He,put:Ur,head:Ia,remove:Mr}=Ca,Ie=Ss("vectors");var St=class{constructor(r,e={},t,s="storage"){this.shouldThrowOnError=!1,this.url=r,this.headers=e,this.fetch=xa(t),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(r,e){return this.headers=I(I({},this.headers),{},{[r]:e}),this}async handleOperation(r){var e=this;try{return{data:await r(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(dr(t))return{data:null,error:t};throw t}}},Na=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e}then(r,e){return this.execute().then(r,e)}async execute(){var r=this;try{return{data:(await r.downloadFn()).body,error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(dr(e))return{data:null,error:e};throw e}}};let xs;xs=Symbol.toStringTag;var Da=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[xs]="BlobDownloadBuilder",this.promise=null}asStream(){return new Na(this.downloadFn,this.shouldThrowOnError)}then(r,e){return this.getPromise().then(r,e)}catch(r){return this.getPromise().catch(r)}finally(r){return this.getPromise().finally(r)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var r=this;try{return{data:await(await r.downloadFn()).blob(),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(dr(e))return{data:null,error:e};throw e}}};const $a={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},js={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var La=class extends St{constructor(r,e={},t,s){super(r,e,s,"storage"),this.bucketId=t}async uploadOrUpdate(r,e,t,s){var n=this;return n.handleOperation(async()=>{let a;const i=I(I({},js),s);let o=I(I({},n.headers),r==="POST"&&{"x-upsert":String(i.upsert)});const c=i.metadata;typeof Blob<"u"&&t instanceof Blob?(a=new FormData,a.append("cacheControl",i.cacheControl),c&&a.append("metadata",n.encodeMetadata(c)),a.append("",t)):typeof FormData<"u"&&t instanceof FormData?(a=t,a.has("cacheControl")||a.append("cacheControl",i.cacheControl),c&&!a.has("metadata")&&a.append("metadata",n.encodeMetadata(c))):(a=t,o["cache-control"]=`max-age=${i.cacheControl}`,o["content-type"]=i.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!i.duplex&&(i.duplex="half")),s?.headers&&(o=I(I({},o),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),f=await(r=="PUT"?Ur:He)(n.fetch,`${n.url}/object/${d}`,a,I({headers:o},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:f.Id,fullPath:f.Key}})}async upload(r,e,t){return this.uploadOrUpdate("POST",r,e,t)}async uploadToSignedUrl(r,e,t,s){var n=this;const a=n._removeEmptyFolders(r),i=n._getFinalPath(a),o=new URL(n.url+`/object/upload/sign/${i}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let c;const u=I({upsert:js.upsert},s),d=I(I({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&t instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),c.append("",t)):typeof FormData<"u"&&t instanceof FormData?(c=t,c.append("cacheControl",u.cacheControl)):(c=t,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:a,fullPath:(await Ur(n.fetch,o.toString(),c,{headers:d})).Key}})}async createSignedUploadUrl(r,e){var t=this;return t.handleOperation(async()=>{let s=t._getFinalPath(r);const n=I({},t.headers);e?.upsert&&(n["x-upsert"]="true");const a=await He(t.fetch,`${t.url}/object/upload/sign/${s}`,{},{headers:n}),i=new URL(t.url+a.url),o=i.searchParams.get("token");if(!o)throw new ur("No token returned by API");return{signedUrl:i.toString(),path:r,token:o}})}async update(r,e,t){return this.uploadOrUpdate("PUT",r,e,t)}async move(r,e,t){var s=this;return s.handleOperation(async()=>await He(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:s.headers}))}async copy(r,e,t){var s=this;return s.handleOperation(async()=>({path:(await He(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:r,destinationKey:e,destinationBucket:t?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(r,e,t){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(r),a=await He(s.fetch,`${s.url}/object/sign/${n}`,I({expiresIn:e},t?.transform?{transform:t.transform}:{}),{headers:s.headers});const i=t?.download?`&download=${t.download===!0?"":t.download}`:"",o=t?.transform&&a.signedURL.includes("/object/sign/")?a.signedURL.replace("/object/sign/","/render/image/sign/"):a.signedURL;return{signedUrl:encodeURI(`${s.url}${o}${i}`)}})}async createSignedUrls(r,e,t){var s=this;return s.handleOperation(async()=>{const n=await He(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:r},{headers:s.headers}),a=t?.download?`&download=${t.download===!0?"":t.download}`:"";return n.map(i=>I(I({},i),{},{signedUrl:i.signedURL?encodeURI(`${s.url}${i.signedURL}${a}`):null}))})}download(r,e,t){const s=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),a=n?`?${n}`:"",i=this._getFinalPath(r),o=()=>Gt(this.fetch,`${this.url}/${s}/${i}${a}`,{headers:this.headers,noResolveJson:!0},t);return new Da(o,this.shouldThrowOnError)}async info(r){var e=this;const t=e._getFinalPath(r);return e.handleOperation(async()=>Lr(await Gt(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(r){var e=this;const t=e._getFinalPath(r);try{return await Ia(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(dr(n)){var s;const a=n instanceof Ft?n.status:n instanceof ws?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(a!==void 0&&[400,404].includes(a))return{data:!1,error:n}}throw n}}getPublicUrl(r,e){const t=this._getFinalPath(r),s=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const a=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&s.push(i);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${t}${o}`)}}}async remove(r){var e=this;return e.handleOperation(async()=>await Mr(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:r},{headers:e.headers}))}async list(r,e,t){var s=this;return s.handleOperation(async()=>{const n=I(I(I({},$a),e),{},{prefix:r||""});return await He(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},t)})}async listV2(r,e){var t=this;return t.handleOperation(async()=>{const s=I({},r);return await He(t.fetch,`${t.url}/object/list-v2/${t.bucketId}`,s,{headers:t.headers},e)})}encodeMetadata(r){return JSON.stringify(r)}toBase64(r){return typeof Buffer<"u"?Buffer.from(r).toString("base64"):btoa(r)}_getFinalPath(r){return`${this.bucketId}/${r.replace(/^\/+/,"")}`}_removeEmptyFolders(r){return r.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(r){const e=[];return r.width&&e.push(`width=${r.width}`),r.height&&e.push(`height=${r.height}`),r.resize&&e.push(`resize=${r.resize}`),r.format&&e.push(`format=${r.format}`),r.quality&&e.push(`quality=${r.quality}`),e.join("&")}};const Ht={"X-Client-Info":"storage-js/2.99.1"};var Ua=class extends St{constructor(r,e={},t,s){const n=new URL(r);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));const a=n.href.replace(/\/$/,""),i=I(I({},Ht),e);super(a,i,t,"storage")}async listBuckets(r){var e=this;return e.handleOperation(async()=>{const t=e.listBucketOptionsToQueryString(r);return await Gt(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Gt(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:!1}){var t=this;return t.handleOperation(async()=>await He(t.fetch,`${t.url}/bucket`,{id:r,name:r,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async updateBucket(r,e){var t=this;return t.handleOperation(async()=>await Ur(t.fetch,`${t.url}/bucket/${r}`,{id:r,name:r,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:t.headers}))}async emptyBucket(r){var e=this;return e.handleOperation(async()=>await He(e.fetch,`${e.url}/bucket/${r}/empty`,{},{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Mr(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(r){const e={};return r&&("limit"in r&&(e.limit=String(r.limit)),"offset"in r&&(e.offset=String(r.offset)),r.search&&(e.search=r.search),r.sortColumn&&(e.sortColumn=r.sortColumn),r.sortOrder&&(e.sortOrder=r.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Ma=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Ht),e);super(s,n,t,"storage")}async createBucket(r){var e=this;return e.handleOperation(async()=>await He(e.fetch,`${e.url}/bucket`,{name:r},{headers:e.headers}))}async listBuckets(r){var e=this;return e.handleOperation(async()=>{const t=new URLSearchParams;r?.limit!==void 0&&t.set("limit",r.limit.toString()),r?.offset!==void 0&&t.set("offset",r.offset.toString()),r?.sortColumn&&t.set("sortColumn",r.sortColumn),r?.sortOrder&&t.set("sortOrder",r.sortOrder),r?.search&&t.set("search",r.search);const s=t.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Gt(e.fetch,n,{headers:e.headers})})}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Mr(e.fetch,`${e.url}/bucket/${r}`,{},{headers:e.headers}))}from(r){var e=this;if(!Ta(r))throw new ur("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const t=new Sa({baseUrl:this.url,catalogName:r,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(t,{get(n,a){const i=n[a];return typeof i!="function"?i:async(...o)=>{try{return{data:await i.apply(n,o),error:null}}catch(c){if(s)throw c;return{data:null,error:c}}}}})}},Ka=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Ht),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors")}async createIndex(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/CreateIndex`,r,{headers:e.headers})||{})}async getIndex(r,e){var t=this;return t.handleOperation(async()=>await Ie.post(t.fetch,`${t.url}/GetIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers}))}async listIndexes(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListIndexes`,r,{headers:e.headers}))}async deleteIndex(r,e){var t=this;return t.handleOperation(async()=>await Ie.post(t.fetch,`${t.url}/DeleteIndex`,{vectorBucketName:r,indexName:e},{headers:t.headers})||{})}},Ba=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Ht),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors")}async putVectors(r){var e=this;if(r.vectors.length<1||r.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/PutVectors`,r,{headers:e.headers})||{})}async getVectors(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/GetVectors`,r,{headers:e.headers}))}async listVectors(r){var e=this;if(r.segmentCount!==void 0){if(r.segmentCount<1||r.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(r.segmentIndex!==void 0&&(r.segmentIndex<0||r.segmentIndex>=r.segmentCount))throw new Error(`segmentIndex must be between 0 and ${r.segmentCount-1}`)}return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListVectors`,r,{headers:e.headers}))}async queryVectors(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/QueryVectors`,r,{headers:e.headers}))}async deleteVectors(r){var e=this;if(r.keys.length<1||r.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/DeleteVectors`,r,{headers:e.headers})||{})}},Fa=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Ht),{},{"Content-Type":"application/json"},e);super(s,n,t,"vectors")}async createBucket(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:r},{headers:e.headers}))}async listBuckets(r={}){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/ListVectorBuckets`,r,{headers:e.headers}))}async deleteBucket(r){var e=this;return e.handleOperation(async()=>await Ie.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:r},{headers:e.headers})||{})}},qa=class extends Fa{constructor(r,e={}){super(r,e.headers||{},e.fetch)}from(r){return new Wa(this.url,this.headers,r,this.fetch)}async createBucket(r){var e=()=>super.createBucket,t=this;return e().call(t,r)}async getBucket(r){var e=()=>super.getBucket,t=this;return e().call(t,r)}async listBuckets(r={}){var e=()=>super.listBuckets,t=this;return e().call(t,r)}async deleteBucket(r){var e=()=>super.deleteBucket,t=this;return e().call(t,r)}},Wa=class extends Ka{constructor(r,e,t,s){super(r,e,s),this.vectorBucketName=t}async createIndex(r){var e=()=>super.createIndex,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName}))}async listIndexes(r={}){var e=()=>super.listIndexes,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName}))}async getIndex(r){var e=()=>super.getIndex,t=this;return e().call(t,t.vectorBucketName,r)}async deleteIndex(r){var e=()=>super.deleteIndex,t=this;return e().call(t,t.vectorBucketName,r)}index(r){return new Ga(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},Ga=class extends Ba{constructor(r,e,t,s,n){super(r,e,n),this.vectorBucketName=t,this.indexName=s}async putVectors(r){var e=()=>super.putVectors,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(r){var e=()=>super.getVectors,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(r={}){var e=()=>super.listVectors,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(r){var e=()=>super.queryVectors,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(r){var e=()=>super.deleteVectors,t=this;return e().call(t,I(I({},r),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},Ha=class extends Ua{constructor(r,e={},t,s){super(r,e,t,s)}from(r){return new La(this.url,this.headers,r,this.fetch)}get vectors(){return new qa(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ma(this.url+"/iceberg",this.headers,this.fetch)}};const Ts="2.99.1",xt=30*1e3,Kr=3,Br=Kr*xt,za="http://localhost:9999",Va="supabase.auth.token",Ja={"X-Client-Info":`gotrue-js/${Ts}`},Fr="X-Supabase-Api-Version",Ps={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Ya=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Qa=600*1e3;class zt extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function P(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}class Xa extends zt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function Za(r){return P(r)&&r.name==="AuthApiError"}class ct extends zt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Qe extends zt{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s}}class Ne extends Qe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function qr(r){return P(r)&&r.name==="AuthSessionMissingError"}class jt extends Qe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class hr extends Qe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class fr extends Qe{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ei(r){return P(r)&&r.name==="AuthImplicitGrantRedirectError"}class Es extends Qe{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class ti extends Qe{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Wr extends Qe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Gr(r){return P(r)&&r.name==="AuthRetryableFetchError"}class As extends Qe{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class Hr extends Qe{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const mr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Os=`
40
- \r=`.split(""),ri=(()=>{const r=new Array(128);for(let e=0;e<r.length;e+=1)r[e]=-1;for(let e=0;e<Os.length;e+=1)r[Os[e].charCodeAt(0)]=-2;for(let e=0;e<mr.length;e+=1)r[mr[e].charCodeAt(0)]=e;return r})();function Rs(r,e,t){if(r!==null)for(e.queue=e.queue<<8|r,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(mr[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;t(mr[s]),e.queuedBits-=6}}function Cs(r,e,t){const s=ri[r];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(r)}"`)}}function Is(r){const e=[],t=i=>{e.push(String.fromCodePoint(i))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},a=i=>{ai(i,s,t)};for(let i=0;i<r.length;i+=1)Cs(r.charCodeAt(i),n,a);return e.join("")}function si(r,e){if(r<=127){e(r);return}else if(r<=2047){e(192|r>>6),e(128|r&63);return}else if(r<=65535){e(224|r>>12),e(128|r>>6&63),e(128|r&63);return}else if(r<=1114111){e(240|r>>18),e(128|r>>12&63),e(128|r>>6&63),e(128|r&63);return}throw new Error(`Unrecognized Unicode codepoint: ${r.toString(16)}`)}function ni(r,e){for(let t=0;t<r.length;t+=1){let s=r.charCodeAt(t);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(r.charCodeAt(t+1)-56320&65535|n)+65536,t+=1}si(s,e)}}function ai(r,e,t){if(e.utf8seq===0){if(r<=127){t(r);return}for(let s=1;s<6;s+=1)if((r>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=r&31;else if(e.utf8seq===3)e.codepoint=r&15;else if(e.utf8seq===4)e.codepoint=r&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(r<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|r&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function Tt(r){const e=[],t={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<r.length;n+=1)Cs(r.charCodeAt(n),t,s);return new Uint8Array(e)}function ii(r){const e=[];return ni(r,t=>e.push(t)),new Uint8Array(e)}function ut(r){const e=[],t={queue:0,queuedBits:0},s=n=>{e.push(n)};return r.forEach(n=>Rs(n,t,s)),Rs(null,t,s),e.join("")}function oi(r){return Math.round(Date.now()/1e3)+r}function li(){return Symbol("auth-callback")}const we=()=>typeof window<"u"&&typeof document<"u",dt={tested:!1,writable:!1},Ns=()=>{if(!we())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(dt.tested)return dt.writable;const r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),dt.tested=!0,dt.writable=!0}catch{dt.tested=!0,dt.writable=!1}return dt.writable};function ci(r){const e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,a)=>{e[a]=n})}catch{}return t.searchParams.forEach((s,n)=>{e[n]=s}),e}const Ds=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),ui=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",Pt=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ht=async(r,e)=>{const t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},_e=async(r,e)=>{await r.removeItem(e)};class pr{constructor(){this.promise=new pr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}pr.promiseConstructor=Promise;function gr(r){const e=r.split(".");if(e.length!==3)throw new Hr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Ya.test(e[s]))throw new Hr("JWT not in base64url format");return{header:JSON.parse(Is(e[0])),payload:JSON.parse(Is(e[1])),signature:Tt(e[2]),raw:{header:e[0],payload:e[1]}}}async function di(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function hi(r,e){return new Promise((s,n)=>{(async()=>{for(let a=0;a<1/0;a++)try{const i=await r(a);if(!e(a,null,i)){s(i);return}}catch(i){if(!e(a,i)){n(i);return}}})()})}function fi(r){return("0"+r.toString(16)).substr(-2)}function mi(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=t.length;let n="";for(let a=0;a<56;a++)n+=t.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,fi).join("")}async function pi(r){const t=new TextEncoder().encode(r),s=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(s);return Array.from(n).map(a=>String.fromCharCode(a)).join("")}async function gi(r){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;const t=await pi(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Et(r,e,t=!1){const s=mi();let n=s;t&&(n+="/PASSWORD_RECOVERY"),await Pt(r,`${e}-code-verifier`,n);const a=await gi(s);return[a,s===a?"plain":"s256"]}const yi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function vi(r){const e=r.headers.get(Fr);if(!e||!e.match(yi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function bi(r){if(!r)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(r<=e)throw new Error("JWT has expired")}function wi(r){switch(r){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const _i=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function At(r){if(!_i.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function zr(){const r={};return new Proxy(r,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const s=t.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function ki(r,e){return new Proxy(r,{get:(t,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(t,s,n)}})}function $s(r){return JSON.parse(JSON.stringify(r))}const ft=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),Si=[502,503,504];async function Ls(r){var e;if(!ui(r))throw new Wr(ft(r),0);if(Si.includes(r.status))throw new Wr(ft(r),r.status);let t;try{t=await r.json()}catch(a){throw new ct(ft(a),a)}let s;const n=vi(r);if(n&&n.getTime()>=Ps["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?s=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(s=t.error_code),s){if(s==="weak_password")throw new As(ft(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new Ne}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((a,i)=>a&&typeof i=="string",!0))throw new As(ft(t),r.status,t.weak_password.reasons);throw new Xa(ft(t),r.status||500,s)}const xi=(r,e,t,s)=>{const n={method:r,headers:e?.headers||{}};return r==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),t))};async function R(r,e,t,s){var n;const a=Object.assign({},s?.headers);a[Fr]||(a[Fr]=Ps["2024-01-01"].name),s?.jwt&&(a.Authorization=`Bearer ${s.jwt}`);const i=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(i.redirect_to=s.redirectTo);const o=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",c=await ji(r,e,t+o,{headers:a,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(c):{data:Object.assign({},c),error:null}}async function ji(r,e,t,s,n,a){const i=xi(e,s,n,a);let o;try{o=await r(t,Object.assign({},i))}catch(c){throw console.error(c),new Wr(ft(c),0)}if(o.ok||await Ls(o),s?.noResolveJson)return o;try{return await o.json()}catch(c){await Ls(c)}}function ze(r){var e;let t=null;Ei(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=oi(r.expires_in)));const s=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:s},error:null}}function Us(r){const e=ze(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,s)=>t&&typeof s=="string",!0)&&(e.data.weak_password=r.weak_password),e}function rt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function Ti(r){return{data:r,error:null}}function Pi(r){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:a}=r,i=ir(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:a},c=Object.assign({},i);return{data:{properties:o,user:c},error:null}}function Ms(r){return r}function Ei(r){return r.access_token&&r.refresh_token&&r.expires_in}const Vr=["global","local","others"];class Ai{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=Ds(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=Vr[0]){if(Vr.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Vr.join(", ")}`);try{return await R(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(P(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,t={}){try{return await R(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:rt})}catch(s){if(P(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:t}=e,s=ir(e,["options"]),n=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await R(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Pi,redirectTo:t?.redirectTo})}catch(t){if(P(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await R(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:rt})}catch(t){if(P(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,s,n,a,i,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await R(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:Ms});if(d.error)throw d.error;const f=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(P(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){At(e);try{return await R(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:rt})}catch(t){if(P(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){At(e);try{return await R(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:rt})}catch(s){if(P(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,t=!1){At(e);try{return await R(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:rt})}catch(s){if(P(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){At(e.userId);try{const{data:t,error:s}=await R(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:s}}catch(t){if(P(t))return{data:null,error:t};throw t}}async _deleteFactor(e){At(e.userId),At(e.id);try{return{data:await R(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,s,n,a,i,o,c;try{const u={nextPage:null,lastPage:0,total:0},d=await R(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(t=e?.page)===null||t===void 0?void 0:t.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:Ms});if(d.error)throw d.error;const f=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(c=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&c!==void 0?c:[];return p.length>0&&(p.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(P(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await R(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(P(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await R(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(P(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await R(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(P(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await R(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await R(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(P(t))return{data:null,error:t};throw t}}async _listCustomProviders(e){try{const t={};return e?.type&&(t.type=e.type),await R(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(t){if(P(t))return{data:{providers:[]},error:t};throw t}}async _createCustomProvider(e){try{return await R(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(P(t))return{data:null,error:t};throw t}}async _getCustomProvider(e){try{return await R(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(P(t))return{data:null,error:t};throw t}}async _updateCustomProvider(e,t){try{return await R(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(P(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await R(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(P(t))return{data:null,error:t};throw t}}}function Ks(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}const Xe={debug:!!(globalThis&&Ns()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Bs extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Oi extends Bs{}async function Ri(r,e,t){Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const s=new globalThis.AbortController;e>0&&setTimeout(()=>{s.abort(),Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async n=>{if(n){Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,n.name);try{return await t()}finally{Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,n.name)}}else{if(e===0)throw Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Oi(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Xe.debug)try{const a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}})}catch(n){if(n?.name==="AbortError"&&e>0)return Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",r),console.warn(`@supabase/gotrue-js: Lock "${r}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,{mode:"exclusive",steal:!0},async a=>{if(a){Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",r,a.name);try{return await t()}finally{Xe.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",r,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await t()}));throw n}}function Ci(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Fs(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))throw new Error(`@supabase/auth-js: Address "${r}" is invalid.`);return r.toLowerCase()}function Ii(r){return parseInt(r,16)}function Ni(r){const e=new TextEncoder().encode(r);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function Di(r){var e;const{chainId:t,domain:s,expirationTime:n,issuedAt:a=new Date,nonce:i,notBefore:o,requestId:c,resources:u,scheme:d,uri:f,version:m}=r;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(m!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(!((e=r.statement)===null||e===void 0)&&e.includes(`
41
- `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${r.statement}`)}const p=Fs(r.address),g=d?`${d}://${s}`:s,y=r.statement?`${r.statement}
40
+ })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){const e=this.channels.map(async s=>{const n=await s.unsubscribe();return s.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,s){this.socketAdapter.log(e,r,s)}connectionState(){return this.socketAdapter.connectionState()||Mr.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const s=`realtime:${e}`,n=this.getChannels().find(a=>a.topic===s);if(n)return n;{const a=new Wt(`realtime:${e}`,r,this);return this.channels.push(a),a}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{const a={access_token:r,version:ha};r&&n.updateJoinPayload(a),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ws.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,s)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,s)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const s=new Blob([Fa],{type:"application/javascript"});r=URL.createObjectURL(s)}return r}_initializeOptions(e){var r,s,n,a,i,o,l,u,d;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(s=e?.accessToken)!==null&&s!==void 0?s:null;const f={};f.timeout=(n=e?.timeout)!==null&&n!==void 0?n:pa,f.heartbeatIntervalMs=(a=e?.heartbeatIntervalMs)!==null&&a!==void 0?a:Ma.HEARTBEAT_INTERVAL,f.transport=(i=e?.transport)!==null&&i!==void 0?i:da.getWebSocketConstructor(),f.params=e?.params,f.logger=e?.logger,f.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),f.reconnectAfterMs=(o=e?.reconnectAfterMs)!==null&&o!==void 0?o:(y=>Ba[y-1]||Ka);let m,p;const g=(l=e?.vsn)!==null&&l!==void 0?l:ma;switch(g){case fa:m=(y,x)=>x(JSON.stringify(y)),p=(y,x)=>x(JSON.parse(y));break;case vs:m=this.serializer.encode.bind(this.serializer),p=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${f.vsn}`)}if(f.vsn=g,f.encode=(u=e?.encode)!==null&&u!==void 0?u:m,f.decode=(d=e?.decode)!==null&&d!==void 0?d:p,f.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,f.params=Object.assign(Object.assign({},f.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,f.autoSendHeartbeat=!this.worker}return f}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Ht=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 Wa(t,e,r){const s=new URL(e,t);if(r)for(const[n,a]of Object.entries(r))a!==void 0&&s.searchParams.set(n,a);return s.toString()}async function Ha(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 Ga(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:a,headers:i}){const o=Wa(t.baseUrl,s,n),l=await Ha(t.auth),u=await e(o,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...l,...i},body:a?JSON.stringify(a):void 0}),d=await u.text(),f=(u.headers.get("content-type")||"").includes("application/json"),m=f&&d?JSON.parse(d):d;if(!u.ok){const p=f?m:void 0,g=p?.error;throw new Ht(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:p})}return{status:u.status,headers:u.headers,data:m}}}}function gr(t){return t.join("")}var za=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:gr(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){const 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/${gr(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${gr(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${gr(t.namespace)}`}),!0}catch(e){if(e instanceof Ht&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Ht&&r.status===409)return;throw r}}};function xt(t){return t.join("")}var Va=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/${xt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${xt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${xt(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/${xt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${xt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${xt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Ht&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Ht&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},Ja=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Ga({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new za(this.client,e),this.tableOps=new Va(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)}},yr=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 br(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var qr=class extends yr{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}}},Ps=class extends yr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const Ya=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Qa=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Wr=t=>{if(Array.isArray(t))return t.map(r=>Wr(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,s])=>{const n=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[n]=Wr(s)}),e},Xa=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Gt(t){"@babel/helpers - typeof";return Gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Gt(t)}function Za(t,e){if(Gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Gt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ei(t){var e=Za(t,"string");return Gt(e)=="symbol"?e:e+""}function ti(t,e,r){return(e=ei(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 R(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){ti(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}const Os=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!==null&&typeof t=="object"&&typeof t.json=="function"){const n=t;let a=parseInt(n.status,10);Number.isFinite(a)||(a=500),n.json().then(i=>{const o=i?.statusCode||i?.code||a+"";e(new qr(Os(i),a,o,s))}).catch(()=>{const i=a+"";e(new qr(n.statusText||`HTTP ${a} error`,a,i,s))})}else e(new Ps(Os(t),t,s))},si=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!s?R(R({},n),r):(Qa(s)?(n.headers=R({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s)):n.body=s,e?.duplex&&(n.duplex=e.duplex),R(R({},n),r))};async function zt(t,e,r,s,n,a,i){return new Promise((o,l)=>{t(r,si(e,s,n,a)).then(u=>{if(!u.ok)throw u;if(s?.noResolveJson)return u;if(i==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>o(u)).catch(u=>ri(u,l,s,i))})}function Cs(t="storage"){return{get:async(e,r,s,n)=>zt(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,a)=>zt(e,"POST",r,n,a,s,t),put:async(e,r,s,n,a)=>zt(e,"PUT",r,n,a,s,t),head:async(e,r,s,n)=>zt(e,"HEAD",r,R(R({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,a)=>zt(e,"DELETE",r,n,a,s,t)}}const ni=Cs("storage"),{get:Vt,post:He,put:Hr,head:ai,remove:Gr}=ni,Ne=Cs("vectors");var Tt=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Ya(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=R(R({},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(br(r))return{data:null,error:r};throw r}}},ii=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(br(e))return{data:null,error:e};throw e}}};let Rs;Rs=Symbol.toStringTag;var oi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Rs]="BlobDownloadBuilder",this.promise=null}asStream(){return new ii(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(br(e))return{data:null,error:e};throw e}}};const li={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ns={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var ci=class extends Tt{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 a;const i=R(R({},Ns),s);let o=R(R({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)});const l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",i.cacheControl),l&&a.append("metadata",n.encodeMetadata(l)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",i.cacheControl),l&&!a.has("metadata")&&a.append("metadata",n.encodeMetadata(l))):(a=r,o["cache-control"]=`max-age=${i.cacheControl}`,o["content-type"]=i.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!i.duplex&&(i.duplex="half")),s?.headers&&(o=R(R({},o),s.headers));const u=n._removeEmptyFolders(e),d=n._getFinalPath(u),f=await(t=="PUT"?Hr:He)(n.fetch,`${n.url}/object/${d}`,a,R({headers:o},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:f.Id,fullPath:f.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;const a=n._removeEmptyFolders(t),i=n._getFinalPath(a),o=new URL(n.url+`/object/upload/sign/${i}`);return o.searchParams.set("token",e),n.handleOperation(async()=>{let l;const u=R({upsert:Ns.upsert},s),d=R(R({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType),{path:a,fullPath:(await Hr(n.fetch,o.toString(),l,{headers:d})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t);const n=R({},r.headers);e?.upsert&&(n["x-upsert"]="true");const a=await He(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),i=new URL(r.url+a.url),o=i.searchParams.get("token");if(!o)throw new yr("No token returned by API");return{signedUrl:i.toString(),path:t,token:o}})}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 He(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 He(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);const a=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let i=await He(s.fetch,`${s.url}/object/sign/${n}`,R({expiresIn:e},a?{transform:r.transform}:{}),{headers:s.headers});const o=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=a&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${s.url}${l}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{const n=await He(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>R(R({},i),{},{signedUrl:i.signedURL?encodeURI(`${s.url}${i.signedURL}${a}`):null}))})}download(t,e,r){const s=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),a=n?`?${n}`:"",i=this._getFinalPath(t),o=()=>Vt(this.fetch,`${this.url}/${s}/${i}${a}`,{headers:this.headers,noResolveJson:!0},r);return new oi(o,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>Wr(await Vt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await ai(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(br(n)){var s;const a=n instanceof qr?n.status:n instanceof Ps?(s=n.originalError)===null||s===void 0?void 0:s.status:void 0;if(a!==void 0&&[400,404].includes(a))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){const r=this._getFinalPath(t),s=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);const a=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&s.push(i);let o=s.join("&");return o!==""&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${o}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Gr(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{const n=R(R(R({},li),e),{},{prefix:t||""});return await He(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const s=R({},t);return await He(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){const 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("&")}};const Jt={"X-Client-Info":"storage-js/2.100.0"};var ui=class extends Tt{constructor(t,e={},r,s){const 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."));const a=n.href.replace(/\/$/,""),i=R(R({},Jt),e);super(a,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Vt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Vt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await He(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 Hr(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 He(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Gr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const 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():""}},di=class extends Tt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=R(R({},Jt),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await He(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const 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);const s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Vt(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Gr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Xa(t))throw new yr("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Ja({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,a){const i=n[a];return typeof i!="function"?i:async(...o)=>{try{return{data:await i.apply(n,o),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},hi=class extends Tt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=R(R({},Jt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ne.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},fi=class extends Tt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=R(R({},Jt),{},{"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 Ne.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ne.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 Ne.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},mi=class extends Tt{constructor(t,e={},r){const s=t.replace(/\/$/,""),n=R(R({},Jt),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ne.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},pi=class extends mi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new gi(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)}},gi=class extends hi{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,R(R({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,R(R({},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 yi(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},yi=class extends fi{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,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,R(R({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},bi=class extends ui{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new ci(this.url,this.headers,t,this.fetch)}get vectors(){return new pi(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new di(this.url+"/iceberg",this.headers,this.fetch)}};const Is="2.100.0",jt=30*1e3,zr=3,Vr=zr*jt,vi="http://localhost:9999",wi="supabase.auth.token",_i={"X-Client-Info":`gotrue-js/${Is}`},Jr="X-Supabase-Api-Version",Ds={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ki=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Si=600*1e3;class Yt extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}}function A(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class xi extends Yt{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}}function Ti(t){return A(t)&&t.name==="AuthApiError"}class ut extends Yt{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class et extends Yt{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}}class Ie extends et{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Yr(t){return A(t)&&t.name==="AuthSessionMissingError"}class At extends et{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class vr extends et{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class wr extends et{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function ji(t){return A(t)&&t.name==="AuthImplicitGrantRedirectError"}class $s extends et{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Ai extends et{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Qr extends et{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Xr(t){return A(t)&&t.name==="AuthRetryableFetchError"}class Ls extends et{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}}class Zr extends et{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const _r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Us=`
41
+ \r=`.split(""),Pi=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Us.length;e+=1)t[Us[e].charCodeAt(0)]=-2;for(let e=0;e<_r.length;e+=1)t[_r[e].charCodeAt(0)]=e;return t})();function Ms(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(_r[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const s=e.queue>>e.queuedBits-6&63;r(_r[s]),e.queuedBits-=6}}function Bs(t,e,r){const s=Pi[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ks(t){const e=[],r=i=>{e.push(String.fromCodePoint(i))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},a=i=>{Ci(i,s,r)};for(let i=0;i<t.length;i+=1)Bs(t.charCodeAt(i),n,a);return e.join("")}function Ei(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Oi(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){const n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}Ei(s,e)}}function Ci(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Pt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)Bs(t.charCodeAt(n),r,s);return new Uint8Array(e)}function Ri(t){const e=[];return Oi(t,r=>e.push(r)),new Uint8Array(e)}function dt(t){const e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Ms(n,r,s)),Ms(null,r,s),e.join("")}function Ni(t){return Math.round(Date.now()/1e3)+t}function Ii(){return Symbol("auth-callback")}const ve=()=>typeof window<"u"&&typeof document<"u",ht={tested:!1,writable:!1},Fs=()=>{if(!ve())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ht.tested)return ht.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),ht.tested=!0,ht.writable=!0}catch{ht.tested=!0,ht.writable=!1}return ht.writable};function Di(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,a)=>{e[a]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}const qs=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),$i=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Et=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},ft=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},we=async(t,e)=>{await t.removeItem(e)};class kr{constructor(){this.promise=new kr.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}kr.promiseConstructor=Promise;function Sr(t){const e=t.split(".");if(e.length!==3)throw new Zr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!ki.test(e[s]))throw new Zr("JWT not in base64url format");return{header:JSON.parse(Ks(e[0])),payload:JSON.parse(Ks(e[1])),signature:Pt(e[2]),raw:{header:e[0],payload:e[1]}}}async function Li(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Ui(t,e){return new Promise((s,n)=>{(async()=>{for(let a=0;a<1/0;a++)try{const i=await t(a);if(!e(a,null,i)){s(i);return}}catch(i){if(!e(a,i)){n(i);return}}})()})}function Mi(t){return("0"+t.toString(16)).substr(-2)}function Bi(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length;let n="";for(let a=0;a<56;a++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,Mi).join("")}async function Ki(t){const r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(a=>String.fromCharCode(a)).join("")}async function Fi(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await Ki(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ot(t,e,r=!1){const s=Bi();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await Et(t,`${e}-code-verifier`,n);const a=await Fi(s);return[a,s===a?"plain":"s256"]}const qi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Wi(t){const e=t.headers.get(Jr);if(!e||!e.match(qi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Hi(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Gi(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const zi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Ct(t){if(!zi.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function es(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Vi(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){const a=s.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,s,n)}return!e.value&&typeof s=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,s,n)}})}function Ws(t){return JSON.parse(JSON.stringify(t))}const mt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Ji=[502,503,504];async function Hs(t){var e;if(!$i(t))throw new Qr(mt(t),0);if(Ji.includes(t.status))throw new Qr(mt(t),t.status);let r;try{r=await t.json()}catch(a){throw new ut(mt(a),a)}let s;const n=Wi(t);if(n&&n.getTime()>=Ds["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new Ls(mt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new Ie}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((a,i)=>a&&typeof i=="string",!0))throw new Ls(mt(r),t.status,r.weak_password.reasons);throw new xi(mt(r),t.status||500,s)}const Yi=(t,e,r,s)=>{const n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function E(t,e,r,s){var n;const a=Object.assign({},s?.headers);a[Jr]||(a[Jr]=Ds["2024-01-01"].name),s?.jwt&&(a.Authorization=`Bearer ${s.jwt}`);const i=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(i.redirect_to=s.redirectTo);const o=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await Qi(t,e,r+o,{headers:a,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function Qi(t,e,r,s,n,a){const i=Yi(e,s,n,a);let o;try{o=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Qr(mt(l),0)}if(o.ok||await Hs(o),s?.noResolveJson)return o;try{return await o.json()}catch(l){await Hs(l)}}function Ge(t){var e;let r=null;eo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Ni(t.expires_in)));const s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function Gs(t){const e=Ge(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function nt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Xi(t){return{data:t,error:null}}function Zi(t){const{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:a}=t,i=ur(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:a},l=Object.assign({},i);return{data:{properties:o,user:l},error:null}}function zs(t){return t}function eo(t){return t.access_token&&t.refresh_token&&t.expires_in}const ts=["global","local","others"];class to{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=qs(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,r=ts[0]){if(ts.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ts.join(", ")}`);try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if(A(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{const{options:r}=e,s=ur(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Zi,redirectTo:r?.redirectTo})}catch(r){if(A(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:nt})}catch(r){if(A(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,a,i,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:zs});if(d.error)throw d.error;const f=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(A(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Ct(e);try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:nt})}catch(r){if(A(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Ct(e);try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){Ct(e);try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:nt})}catch(s){if(A(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){Ct(e.userId);try{const{data:r,error:s}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Ct(e.userId),Ct(e.id);try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,a,i,o,l;try{const u={nextPage:null,lastPage:0,total:0},d=await E(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(a=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&a!==void 0?a:""},xform:zs});if(d.error)throw d.error;const f=await d.json(),m=(i=d.headers.get("x-total-count"))!==null&&i!==void 0?i:0,p=(l=(o=d.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(g=>{const y=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),x=JSON.parse(g.split(";")[1].split("=")[1]);u[`${x}Page`]=y}),u.total=parseInt(m)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(A(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await E(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await E(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(A(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e?.type&&(r.type=e.type),await E(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:s=>{var n;return{data:{providers:(n=s?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(A(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await E(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await E(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(A(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await E(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if(A(s))return{data:null,error:s};throw s}}async _deleteCustomProvider(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(A(r))return{data:null,error:r};throw r}}}function Vs(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const Ye={debug:!!(globalThis&&Fs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Js extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Ys extends Js{}async function ro(t,e,r){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async a=>{if(a){clearTimeout(n),Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,a.name);try{return await r()}finally{Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,a.name)}}else{if(e===0)throw Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Ys(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Ye.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(n),await r()}})}catch(a){if(e>0&&clearTimeout(n),a?.name==="AbortError"&&e>0){if(s.signal.aborted)return Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async i=>{if(i){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Ys(`Lock "${t}" was released because another request stole it`)}throw a}}function so(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function Qs(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function no(t){return parseInt(t,16)}function ao(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function io(t){var e;const{chainId:r,domain:s,expirationTime:n,issuedAt:a=new Date,nonce:i,notBefore:o,requestId:l,resources:u,scheme:d,uri:f,version:m}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(m!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${m}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
42
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const p=Qs(t.address),g=d?`${d}://${s}`:s,y=t.statement?`${t.statement}
42
43
  `:"",x=`${g} wants you to sign in with your Ethereum account:
43
44
  ${p}
44
45
 
45
- ${y}`;let b=`URI: ${f}
46
+ ${y}`;let _=`URI: ${f}
46
47
  Version: ${m}
47
- Chain ID: ${t}${i?`
48
+ Chain ID: ${r}${i?`
48
49
  Nonce: ${i}`:""}
49
- Issued At: ${a.toISOString()}`;if(n&&(b+=`
50
- Expiration Time: ${n.toISOString()}`),o&&(b+=`
51
- Not Before: ${o.toISOString()}`),c&&(b+=`
52
- Request ID: ${c}`),u){let k=`
53
- Resources:`;for(const _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);k+=`
54
- - ${_}`}b+=k}return`${x}
55
- ${b}`}class de extends Error{constructor({message:e,code:t,cause:s,name:n}){var a;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(a=n??(s instanceof Error?s.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=t}}class yr extends de{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function $i({error:r,options:e}){var t,s,n;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else if(r.name==="ConstraintError"){if(((t=a.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new de({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:r});if(e.mediation==="conditional"&&((s=a.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:r});if(((n=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:r})}else{if(r.name==="InvalidStateError")return new de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:r});if(r.name==="NotAllowedError")return new de({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="NotSupportedError")return a.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:r}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:r});if(r.name==="SecurityError"){const i=window.location.hostname;if(qs(i)){if(a.rp.id!==i)return new de({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new de({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:r})}else if(r.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}function Li({error:r,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(r.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:r})}else{if(r.name==="NotAllowedError")return new de({message:r.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r});if(r.name==="SecurityError"){const s=window.location.hostname;if(qs(s)){if(t.rpId!==s)return new de({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:r})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:r})}else if(r.name==="UnknownError")return new de({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:r})}return new de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r})}class Ui{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const Mi=new Ui;function Ki(r){if(!r)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(r);const{challenge:e,user:t,excludeCredentials:s}=r,n=ir(r,["challenge","user","excludeCredentials"]),a=Tt(e).buffer,i=Object.assign(Object.assign({},t),{id:Tt(t.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:a,user:i});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let c=0;c<s.length;c++){const u=s[c];o.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:Tt(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function Bi(r){if(!r)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(r);const{challenge:e,allowCredentials:t}=r,s=ir(r,["challenge","allowCredentials"]),n=Tt(e).buffer,a=Object.assign(Object.assign({},s),{challenge:n});if(t&&t.length>0){a.allowCredentials=new Array(t.length);for(let i=0;i<t.length;i++){const o=t[i];a.allowCredentials[i]=Object.assign(Object.assign({},o),{id:Tt(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return a}function Fi(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const t=r;return{id:r.id,rawId:r.id,response:{attestationObject:ut(new Uint8Array(r.response.attestationObject)),clientDataJSON:ut(new Uint8Array(r.response.clientDataJSON))},type:"public-key",clientExtensionResults:r.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function qi(r){var e;if("toJSON"in r&&typeof r.toJSON=="function")return r.toJSON();const t=r,s=r.getClientExtensionResults(),n=r.response;return{id:r.id,rawId:r.id,response:{authenticatorData:ut(new Uint8Array(n.authenticatorData)),clientDataJSON:ut(new Uint8Array(n.clientDataJSON)),signature:ut(new Uint8Array(n.signature)),userHandle:n.userHandle?ut(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function qs(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function Ws(){var r,e;return!!(we()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((r=navigator?.credentials)===null||r===void 0?void 0:r.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Wi(r){try{const e=await navigator.credentials.create(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yr("Browser returned unexpected credential type",e)}:{data:null,error:new yr("Empty credential response",e)}}catch(e){return{data:null,error:$i({error:e,options:r})}}}async function Gi(r){try{const e=await navigator.credentials.get(r);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new yr("Browser returned unexpected credential type",e)}:{data:null,error:new yr("Empty credential response",e)}}catch(e){return{data:null,error:Li({error:e,options:r})}}}const Hi={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},zi={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function vr(...r){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),t=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of r)if(n)for(const a in n){const i=n[a];if(i!==void 0)if(Array.isArray(i))s[a]=i;else if(t(i))s[a]=i;else if(e(i)){const o=s[a];e(o)?s[a]=vr(o,i):s[a]=vr(i)}else s[a]=i}return s}function Vi(r,e){return vr(Hi,r,e||{})}function Ji(r,e){return vr(zi,r,e||{})}class Yi{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:t,friendlyName:s,signal:n},a){var i;try{const{data:o,error:c}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:c};const u=n??Mi.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const f=s;if(f)d.name=`${d.id}:${f}`;else{const p=(await this.client.getUser()).data.user,g=((i=p?.user_metadata)===null||i===void 0?void 0:i.name)||p?.email||p?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=Vi(o.webauthn.credential_options.publicKey,a?.create),{data:f,error:m}=await Wi({publicKey:d,signal:u});return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:m}}case"request":{const d=Ji(o.webauthn.credential_options.publicKey,a?.request),{data:f,error:m}=await Gi(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:m}}}}catch(o){return P(o)?{data:null,error:o}:{data:null,error:new ct("Unexpected error in challenge",o)}}}async _verify({challengeId:e,factorId:t,webauthn:s}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},a){if(!t)return{data:null,error:new zt("rpId is required for WebAuthn authentication")};try{if(!Ws())return{data:null,error:new ct("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:s},signal:n},{request:a});if(!i)return{data:null,error:o};const{webauthn:c}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:s,credential_response:c.credential_response}})}catch(i){return P(i)?{data:null,error:i}:{data:null,error:new ct("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},a){if(!t)return{data:null,error:new zt("rpId is required for WebAuthn registration")};try{if(!Ws())return{data:null,error:new ct("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(d=>{var f;return(f=d.data)===null||f===void 0?void 0:f.all.find(m=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:c,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:s},signal:n},{create:a});return c?this._verify({factorId:i.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:s,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(i){return P(i)?{data:null,error:i}:{data:null,error:new ct("Unexpected error in register",i)}}}}Ci();const Qi={url:za,storageKey:Va,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ja,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Gs(r,e,t){return await t()}const Ot={};class Vt{get jwks(){var e,t;return(t=(e=Ot[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){Ot[this.storageKey]=Object.assign(Object.assign({},Ot[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=Ot[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ot[this.storageKey]=Object.assign(Object.assign({},Ot[this.storageKey]),{cachedAt:e})}constructor(e){var t,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;const a=Object.assign(Object.assign({},Qi),e);if(this.storageKey=a.storageKey,this.instanceID=(t=Vt.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,Vt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&we()){const i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new Ai({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Ds(a.fetch),this.lock=a.lock||Gs,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&we()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=Ri:this.lock=Gs,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 Yi(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?(a.storage?this.storage=a.storage:Ns()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ks(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=Ks(this.memoryStorage)),we()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}a.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ts}) ${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 t={},s="none";if(we()&&(t=ci(window.location.href),this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:a}=await this._getSessionFromURL(t,s);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),ei(a)){const c=(e=a.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return P(t)?this._returnResult({error:t}):this._returnResult({error:new ct("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,n;try{const a=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(t=e?.options)===null||t===void 0?void 0:t.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:ze}),{data:i,error:o}=a;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const c=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(a){if(P(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var t,s,n;try{let a;if("email"in e){const{email:d,password:f,options:m}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await Et(this.storage,this.storageKey)),a=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m?.emailRedirectTo,body:{email:d,password:f,data:(t=m?.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:p,code_challenge_method:g},xform:ze})}else if("phone"in e){const{phone:d,password:f,options:m}=e;a=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:f,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:ze})}else throw new hr("You must provide either an email or phone number and a password");const{data:i,error:o}=a;if(o||!i)return await _e(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const c=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let t;if("email"in e){const{email:a,password:i,options:o}=e;t=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Us})}else if("phone"in e){const{phone:a,password:i,options:o}=e;t=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Us})}else throw new hr("You must provide either an email or phone number and a password");const{data:s,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const a=new jt;return this._returnResult({data:{user:null,session:null},error:a})}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(t){if(P(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,s,n,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.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:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,s,n,a,i,o,c,u,d,f,m;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:y,wallet:x,statement:b,options:k}=e;let _;if(we())if(typeof x=="object")_=x;else{const L=window;if("ethereum"in L&&typeof L.ethereum=="object"&&"request"in L.ethereum&&typeof L.ethereum.request=="function")_=L.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 x!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=x}const O=new URL((t=k?.url)!==null&&t!==void 0?t:window.location.href),A=await _.request({method:"eth_requestAccounts"}).then(L=>L).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const M=Fs(A[0]);let E=(s=k?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!E){const L=await _.request({method:"eth_chainId"});E=Ii(L)}const N={domain:O.host,address:M,statement:b,uri:O.href,version:"1",chainId:E,nonce:(n=k?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(a=k?.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(o=k?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(c=k?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=k?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=k?.signInWithEthereum)===null||d===void 0?void 0:d.resources};p=Di(N),g=await _.request({method:"personal_sign",params:[Ni(p),M]})}try{const{data:y,error:x}=await R(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:g},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:ze});if(x)throw x;if(!y||!y.session||!y.user){const b=new jt;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:x})}catch(y){if(P(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(e){var t,s,n,a,i,o,c,u,d,f,m,p;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:x,wallet:b,statement:k,options:_}=e;let O;if(we())if(typeof b=="object")O=b;else{const M=window;if("solana"in M&&typeof M.solana=="object"&&("signIn"in M.solana&&typeof M.solana.signIn=="function"||"signMessage"in M.solana&&typeof M.solana.signMessage=="function"))O=M.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 b!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=b}const A=new URL((t=_?.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in O&&O.signIn){const M=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),k?{statement:k}:null));let E;if(Array.isArray(M)&&M[0]&&typeof M[0]=="object")E=M[0];else if(M&&typeof M=="object"&&"signedMessage"in M&&"signature"in M)E=M;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in E&&"signature"in E&&(typeof E.signedMessage=="string"||E.signedMessage instanceof Uint8Array)&&E.signature instanceof Uint8Array)g=typeof E.signedMessage=="string"?E.signedMessage:new TextDecoder().decode(E.signedMessage),y=E.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${A.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),...k?["",k,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(n=(s=_?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((a=_?.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((o=_?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((c=_?.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((f=(d=_?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||f===void 0)&&f.length?["Resources",..._.signInWithSolana.resources.map(E=>`- ${E}`)]:[]].join(`
56
- `);const M=await O.signMessage(new TextEncoder().encode(g),"utf8");if(!M||!(M instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=M}}try{const{data:x,error:b}=await R(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:ut(y)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:ze});if(b)throw b;if(!x||!x.session||!x.user){const k=new jt;return this._returnResult({data:{user:null,session:null},error:k})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:b})}catch(x){if(P(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async _exchangeCodeForSession(e){const t=await ht(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(t??"").split("/");try{if(!s&&this.flowType==="pkce")throw new ti;const{data:a,error:i}=await R(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:ze});if(await _e(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!a||!a.session||!a.user){const o=new jt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:n??null}),error:i})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:t,provider:s,token:n,access_token:a,nonce:i}=e,o=await R(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:a,nonce:i,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:ze}),{data:c,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new jt;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(t){if(P(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,s,n,a,i;try{if("email"in e){const{email:o,options:c}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Et(this.storage,this.storageKey));const{error:f}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(t=c?.data)!==null&&t!==void 0?t:{},create_user:(s=c?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:u,code_challenge_method:d},redirectTo:c?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:o,options:c}=e,{data:u,error:d}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(a=c?.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(i=c?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:d})}throw new hr("You must provide either an email or phone number.")}catch(o){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var t,s;try{let n,a;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,a=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:i,error:o}=await R(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:n,xform:ze});if(o)throw o;if(!i)throw new Error("An error occurred on token verification.");const c=i.session,u=i.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(n){if(P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,s,n,a,i;try{let o=null,c=null;this.flowType==="pkce"&&([o,c]=await Et(this.storage,this.storageKey));const u=await R(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=(t=e.options)===null||t===void 0?void 0:t.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:o,code_challenge_method:c}),headers:this.headers,xform:Ti});return!((a=u.data)===null||a===void 0)&&a.url&&we()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new Ne;const{error:n}=await R(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(P(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:a}=e,{error:i}=await R(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}},redirectTo:a?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){const{phone:s,type:n,options:a}=e,{data:i,error:o}=await R(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:o})}throw new hr("You must provide either an email or phone number and a type")}catch(t){if(P(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await t()))();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;const s=t();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const 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{const t=await this.__loadSession();return await e(t)}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;const t=await ht(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Br:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const i=await ht(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=zr()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const i={value:this.suppressGetSessionWarning};e.user=ki(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):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;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:rt}):await this._useSession(async t=>{var s,n,a;const{data:i,error:o}=t;if(o)throw o;return!(!((s=i.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ne}:await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0,xform:rt})})}catch(t){if(P(t))return qr(t)&&(await this._removeSession(),await _e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async s=>{const{data:n,error:a}=s;if(a)throw a;if(!n.session)throw new Ne;const i=n.session;let o=null,c=null;this.flowType==="pkce"&&e.email!=null&&([o,c]=await Et(this.storage,this.storageKey));const{data:u,error:d}=await R(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:c}),jwt:i.access_token,xform:rt});if(d)throw d;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(s){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(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 Ne;const t=Date.now()/1e3;let s=t,n=!0,a=null;const{payload:i}=gr(e.access_token);if(i.exp&&(s=i.exp,n=s<=t),n){const{data:o,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o)return{data:{user:null,session:null},error:null};a=o}else{const{data:o,error:c}=await this._getUser(e.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});a={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(t){if(P(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}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 t=>{var s;if(!e){const{data:i,error:o}=t;if(o)throw o;e=(s=i.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new Ne;const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(P(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!we())throw new fr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new fr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new Es("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new fr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Es("No code detected.");const{data:k,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;const O=new URL(window.location.href);return O.searchParams.delete("code"),window.history.replaceState(window.history.state,"",O.toString()),{data:{session:k.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:a,refresh_token:i,expires_in:o,expires_at:c,token_type:u}=e;if(!a||!o||!i||!u)throw new fr("No session defined in URL");const d=Math.round(Date.now()/1e3),f=parseInt(o);let m=d+f;c&&(m=parseInt(c));const p=m-d;p*1e3<=xt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);const g=m-f;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,d);const{data:y,error:x}=await this._getUser(a);if(x)throw x;const b={provider_token:s,provider_refresh_token:n,access_token:a,expires_in:f,expires_at:m,refresh_token:i,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(s){if(P(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){const t=await ht(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}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 t=>{var s;const{data:n,error:a}=t;if(a&&!qr(a))return this._returnResult({error:a});const i=(s=n.session)===null||s===void 0?void 0:s.access_token;if(i){const{error:o}=await this.admin.signOut(i,e);if(o&&!(Za(o)&&(o.status===404||o.status===401||o.status===403)||qr(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await _e(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=li(),s={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async t=>{var s,n;try{const{data:{session:a},error:i}=t;if(i)throw i;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){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",a),console.error(a)}})}async resetPasswordForEmail(e,t={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Et(this.storage,this.storageKey,!0));try{return await R(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(a){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:s,error:n}=await this._useSession(async a=>{var i,o,c,u,d;const{data:f,error:m}=a;if(m)throw m;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await R(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return we()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if(P(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var s;try{const{error:n,data:{session:a}}=t;if(n)throw n;const{options:i,provider:o,token:c,access_token:u,nonce:d}=e,f=await R(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=a?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:ze}),{data:m,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new jt}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:p}))}catch(n){if(await _e(this.storage,`${this.storageKey}-code-verifier`),P(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,n;const{data:a,error:i}=t;if(i)throw i;return await R(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const s=Date.now();return await hi(async n=>(n>0&&await di(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await R(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ze})),(n,a)=>{const i=200*Math.pow(2,n);return a&&Gr(a)&&Date.now()+i-s<xt})}catch(s){if(this._debug(t,"error",s),P(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),we()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,t;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ht(this.storage,this.storageKey);if(n&&this.userStorage){let i=await ht(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Pt(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:zr()}else if(n&&!n.user&&!n.user){const i=await ht(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await _e(this.storage,this.storageKey+"-user"),await Pt(this.storage,this.storageKey,n)):n.user=zr()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const a=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<Br;if(this._debug(s,`session has${a?"":" not"} expired with margin of ${Br}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Gr(i)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:i,error:o}=await this._getUser(n.access_token);!o&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(s,"error getting user data, skipping SIGNED_IN notification",i)}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 t,s;if(!e)throw new Ne;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new pr;const{data:a,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!a.session)throw new Ne;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const o={data:a.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(a){if(this._debug(n,"error",a),P(a)){const i={data:null,error:a};return Gr(a)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(i),i}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(a),a}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const a=[],i=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,t)}catch(c){a.push(c)}});if(await Promise.all(i),a.length>0){for(let o=0;o<a.length;o+=1)console.error(a[o]);throw a[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await _e(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),s=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&t.user&&await Pt(this.userStorage,this.storageKey+"-user",{user:t.user});const n=Object.assign({},t);delete n.user;const a=$s(n);await Pt(this.storage,this.storageKey,a)}else{const n=$s(t);await Pt(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await _e(this.storage,this.storageKey),await _e(this.storage,this.storageKey+"-code-verifier"),await _e(this.storage,this.storageKey+"-user"),this.userStorage&&await _e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),xt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/xt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${xt}ms, refresh threshold is ${Kr} ticks`),n<=Kr&&await this._callRefreshToken(s.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Bs)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!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){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"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(t,"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,t,s){const n=[`provider=${encodeURIComponent(t)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[a,i]=await Et(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(o.toString())}if(s?.queryParams){const a=new URLSearchParams(s.queryParams);n.push(a.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var s;const{data:n,error:a}=t;return a?this._returnResult({data:null,error:a}):await R(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(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var s,n;const{data:a,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:c,error:u}=await R(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=a?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&c.type==="totp"&&(!((n=c?.totp)===null||n===void 0)&&n.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;const{data:n,error:a}=t;if(a)return this._returnResult({data:null,error:a});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Fi(e.webauthn.credential_response):qi(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:c}=await R(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:c}))})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var s;const{data:n,error:a}=t;if(a)return this._returnResult({data:null,error:a});const i=await R(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(i.error)return i;const{data:o}=i;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Ki(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Bi(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}})}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=t?.factors)!==null&&e!==void 0?e:[])n.all.push(a),a.status==="verified"&&n[a.factor_type].push(a);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var t,s,n,a;if(e)try{const{payload:p}=gr(e);let g=null;p.aal&&(g=p.aal);let y=g;const{data:{user:x},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((s=(t=x?.factors)===null||t===void 0?void 0:t.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(y="aal2");const _=p.amr||[];return{data:{currentLevel:g,nextLevel:y,currentAuthenticationMethods:_},error:null}}catch(p){if(P(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:i},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=gr(i.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((a=(n=i.user.factors)===null||n===void 0?void 0:n.filter(p=>p.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(d="aal2");const m=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:s},error:n}=t;return n?this._returnResult({data:null,error:n}):s?await R(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new Ne});const i=await R(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&we()&&!t?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(P(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,t){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new Ne});const i=await R(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&we()&&!t?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(P(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:s}=e;return s?this._returnResult({data:null,error:s}):t?await R(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(e){if(P(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:s},error:n}=t;return n?this._returnResult({data:null,error:n}):s?(await R(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 Ne})})}catch(t){if(P(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Qa>n)return s;const{data:a,error:i}=await R(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=n,s=a.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,t={}){try{let s=e;if(!s){const{data:p,error:g}=await this.getSession();if(g||!p.session)return this._returnResult({data:null,error:g});s=p.session.access_token}const{header:n,payload:a,signature:i,raw:{header:o,payload:c}}=gr(s);t?.allowExpired||bi(a.exp);const u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!u){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:a,header:n,signature:i},error:null}}const d=wi(n.alg),f=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,f,i,ii(`${o}.${c}`)))throw new Hr("Invalid JWT signature");return{data:{claims:a,header:n,signature:i},error:null}}catch(s){if(P(s))return this._returnResult({data:null,error:s});throw s}}}Vt.nextInstanceID={};const Xi=Vt,Zi="2.99.1";let Jt="";typeof Deno<"u"?Jt="deno":typeof document<"u"?Jt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Jt="react-native":Jt="node";const eo={headers:{"X-Client-Info":`supabase-js-${Jt}/${Zi}`}},to={schema:"public"},ro={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},so={};function Yt(r){"@babel/helpers - typeof";return Yt=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},Yt(r)}function no(r,e){if(Yt(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Yt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function ao(r){var e=no(r,"string");return Yt(e)=="symbol"?e:e+""}function io(r,e,t){return(e=ao(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function Hs(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(r);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(r,n).enumerable})),t.push.apply(t,s)}return t}function ae(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Hs(Object(t),!0).forEach(function(s){io(r,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):Hs(Object(t)).forEach(function(s){Object.defineProperty(r,s,Object.getOwnPropertyDescriptor(t,s))})}return r}const oo=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),lo=()=>Headers,co=(r,e,t)=>{const s=oo(t),n=lo();return async(a,i)=>{var o;const c=(o=await e())!==null&&o!==void 0?o:r;let u=new n(i?.headers);return u.has("apikey")||u.set("apikey",r),u.has("Authorization")||u.set("Authorization",`Bearer ${c}`),s(a,ae(ae({},i),{},{headers:u}))}};function uo(r){return r.endsWith("/")?r:r+"/"}function ho(r,e){var t,s;const{db:n,auth:a,realtime:i,global:o}=r,{db:c,auth:u,realtime:d,global:f}=e,m={db:ae(ae({},c),n),auth:ae(ae({},u),a),realtime:ae(ae({},d),i),storage:{},global:ae(ae(ae({},f),o),{},{headers:ae(ae({},(t=f?.headers)!==null&&t!==void 0?t:{}),(s=o?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return r.accessToken?m.accessToken=r.accessToken:delete m.accessToken,m}function fo(r){const e=r?.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(uo(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var mo=class extends Xi{constructor(r){super(r)}},po=class{constructor(r,e,t){var s,n;this.supabaseUrl=r,this.supabaseKey=e;const a=fo(r);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const i=`sb-${a.hostname.split(".")[0]}-auth-token`,o={db:to,realtime:so,auth:ae(ae({},ro),{},{storageKey:i}),global:eo},c=ho(t??{},o);if(this.storageKey=(s=c.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=c.global.headers)!==null&&n!==void 0?n:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=co(e,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(ae({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new ta(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit}),this.storage=new Ha(this.storageUrl.href,this.headers,this.fetch,t?.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new zn(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(r){return this.rest.from(r)}schema(r){return this.rest.schema(r)}rpc(r,e={},t={head:!1,get:!1,count:void 0}){return this.rest.rpc(r,e,t)}channel(r,e={config:{}}){return this.realtime.channel(r,e)}getChannels(){return this.realtime.getChannels()}removeChannel(r){return this.realtime.removeChannel(r)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var r=this,e,t;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return(e=(t=s.session)===null||t===void 0?void 0:t.access_token)!==null&&e!==void 0?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:s,userStorage:n,storageKey:a,flowType:i,lock:o,debug:c,throwOnError:u},d,f){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new mo({url:this.authUrl.href,headers:ae(ae({},m),d),storageKey:a,autoRefreshToken:r,persistSession:e,detectSessionInUrl:t,storage:s,userStorage:n,flowType:i,lock:o,debug:c,throwOnError:u,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(r){return new ya(this.realtimeUrl.href,ae(ae({},r),{},{params:ae(ae({},{apikey:this.supabaseKey}),r?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((r,e)=>{this._handleTokenChanged(r,"CLIENT",e?.access_token)})}_handleTokenChanged(r,e,t){(r==="TOKEN_REFRESHED"||r==="SIGNED_IN")&&this.changedAccessToken!==t?(this.changedAccessToken=t,this.realtime.setAuth(t)):r==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const go=(r,e,t)=>new po(r,e,t);function yo(){if(typeof window<"u")return!1;const r=globalThis.process;if(!r)return!1;const e=r.version;if(e==null)return!1;const t=e.match(/^v(\d+)\./);return t?parseInt(t[1],10)<=18:!1}yo()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function zs(r,e){if(!r||!e)throw new Error("Supabase URL and anon key are required");return go(r,e)}function Vs(r){const e=[];let t="",s=!1;for(let n=0;n<r.length;n++){const a=r[n];a==='"'?s&&r[n+1]==='"'?(t+='"',n++):s=!s:a===","&&!s?(e.push(t),t=""):t+=a}return e.push(t),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Ue(r,...e){const t=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(r).forEach(([n,a])=>s.set(t(n),a));for(const n of e){const a=s.get(t(n));if(a!==void 0&&a.trim())return a.trim()}return""}function vo(r){const t=r.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
50
+ Issued At: ${a.toISOString()}`;if(n&&(_+=`
51
+ Expiration Time: ${n.toISOString()}`),o&&(_+=`
52
+ Not Before: ${o.toISOString()}`),l&&(_+=`
53
+ Request ID: ${l}`),u){let S=`
54
+ Resources:`;for(const k of u){if(!k||typeof k!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${k}`);S+=`
55
+ - ${k}`}_+=S}return`${x}
56
+ ${_}`}class de extends Error{constructor({message:e,code:r,cause:s,name:n}){var a;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(a=n??(s instanceof Error?s.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=r}}class xr extends de{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function oo({error:t,options:e}){var r,s,n;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=a.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new de({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=a.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new de({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=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new de({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 de({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new de({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new de({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const i=window.location.hostname;if(Xs(i)){if(a.rp.id!==i)return new de({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new de({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 de({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 de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function lo({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new de({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new de({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(Xs(s)){if(r.rpId!==s)return new de({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new de({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new de({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 de({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class co{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const uo=new co;function ho(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);const{challenge:e,user:r,excludeCredentials:s}=t,n=ur(t,["challenge","user","excludeCredentials"]),a=Pt(e).buffer,i=Object.assign(Object.assign({},r),{id:Pt(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:a,user:i});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const u=s[l];o.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:Pt(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return o}function fo(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);const{challenge:e,allowCredentials:r}=t,s=ur(t,["challenge","allowCredentials"]),n=Pt(e).buffer,a=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){const o=r[i];a.allowCredentials[i]=Object.assign(Object.assign({},o),{id:Pt(o.id).buffer,type:o.type||"public-key",transports:o.transports})}}return a}function mo(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:dt(new Uint8Array(t.response.attestationObject)),clientDataJSON:dt(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function po(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:dt(new Uint8Array(n.authenticatorData)),clientDataJSON:dt(new Uint8Array(n.clientDataJSON)),signature:dt(new Uint8Array(n.signature)),userHandle:n.userHandle?dt(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Xs(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Zs(){var t,e;return!!(ve()&&"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 go(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new xr("Browser returned unexpected credential type",e)}:{data:null,error:new xr("Empty credential response",e)}}catch(e){return{data:null,error:oo({error:e,options:t})}}}async function yo(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new xr("Browser returned unexpected credential type",e)}:{data:null,error:new xr("Empty credential response",e)}}catch(e){return{data:null,error:lo({error:e,options:t})}}}const bo={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},vo={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Tr(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const a in n){const i=n[a];if(i!==void 0)if(Array.isArray(i))s[a]=i;else if(r(i))s[a]=i;else if(e(i)){const o=s[a];e(o)?s[a]=Tr(o,i):s[a]=Tr(i)}else s[a]=i}return s}function wo(t,e){return Tr(bo,t,e||{})}function _o(t,e){return Tr(vo,t,e||{})}class ko{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},a){var i;try{const{data:o,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!o)return{data:null,error:l};const u=n??uo.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:d}=o.webauthn.credential_options.publicKey;if(!d.name){const f=s;if(f)d.name=`${d.id}:${f}`;else{const p=(await this.client.getUser()).data.user,g=((i=p?.user_metadata)===null||i===void 0?void 0:i.name)||p?.email||p?.id||"User";d.name=`${d.id}:${g}`}}d.displayName||(d.displayName=d.name)}switch(o.webauthn.type){case"create":{const d=wo(o.webauthn.credential_options.publicKey,a?.create),{data:f,error:m}=await go({publicKey:d,signal:u});return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:m}}case"request":{const d=_o(o.webauthn.credential_options.publicKey,a?.request),{data:f,error:m}=await yo(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:d,signal:u}));return f?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:m}}}}catch(o){return A(o)?{data:null,error:o}:{data:null,error:new ut("Unexpected error in challenge",o)}}}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}={}},a){if(!r)return{data:null,error:new Yt("rpId is required for WebAuthn authentication")};try{if(!Zs())return{data:null,error:new ut("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:a});if(!i)return{data:null,error:o};const{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(i){return A(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in authenticate",i)}}}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}={}},a){if(!r)return{data:null,error:new Yt("rpId is required for WebAuthn registration")};try{if(!Zs())return{data:null,error:new ut("Browser does not support WebAuthn",null)};const{data:i,error:o}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(d=>{var f;return(f=d.data)===null||f===void 0?void 0:f.all.find(m=>m.factor_type==="webauthn"&&m.friendly_name===e&&m.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d?.id}):void 0),{data:null,error:o};const{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:a});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return A(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in register",i)}}}}so();const So={url:vi,storageKey:wi,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:_i,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function en(t,e,r){return await r()}const Rt={};class Qt{get jwks(){var e,r;return(r=(e=Rt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Rt[this.storageKey]=Object.assign(Object.assign({},Rt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Rt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Rt[this.storageKey]=Object.assign(Object.assign({},Rt[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;const a=Object.assign(Object.assign({},So),e);if(this.storageKey=a.storageKey,this.instanceID=(r=Qt.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Qt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&ve()){const i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.admin=new to({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=qs(a.fetch),this.lock=a.lock||en,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&ve()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=ro:this.lock=en,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 ko(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?(a.storage?this.storage=a.storage:Fs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Vs(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=Vs(this.memoryStorage)),ve()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}a.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Is}) ${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(ve()&&(r=Di(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),ve()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:a}=await this._getSessionFromURL(r,s);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),ji(a)){const l=(e=a.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:a}}return{error:a}}const{session:i,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",i,"redirect type",o),await this._saveSession(i),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return A(r)?this._returnResult({error:r}):this._returnResult({error:new ut("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const a=await E(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:Ge}),{data:i,error:o}=a;if(o||!i)return this._returnResult({data:{user:null,session:null},error:o});const l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(A(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,s,n;try{let a;if("email"in e){const{email:d,password:f,options:m}=e;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await Ot(this.storage,this.storageKey)),a=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m?.emailRedirectTo,body:{email:d,password:f,data:(r=m?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:m?.captchaToken},code_challenge:p,code_challenge_method:g},xform:Ge})}else if("phone"in e){const{phone:d,password:f,options:m}=e;a=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:d,password:f,data:(s=m?.data)!==null&&s!==void 0?s:{},channel:(n=m?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:m?.captchaToken}},xform:Ge})}else throw new vr("You must provide either an email or phone number and a password");const{data:i,error:o}=a;if(o||!i)return await we(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});const l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(a){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:i,options:o}=e;r=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Gs})}else if("phone"in e){const{phone:a,password:i,options:o}=e;r=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:i,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:Gs})}else throw new vr("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const a=new At;return this._returnResult({data:{user:null,session:null},error:a})}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(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,a;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:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{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,a,i,o,l,u,d,f,m;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:y,wallet:x,statement:_,options:S}=e;let k;if(ve())if(typeof x=="object")k=x;else{const $=window;if("ethereum"in $&&typeof $.ethereum=="object"&&"request"in $.ethereum&&typeof $.ethereum.request=="function")k=$.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 x!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=x}const N=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href),O=await k.request({method:"eth_requestAccounts"}).then($=>$).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!O||O.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const B=Qs(O[0]);let P=(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!P){const $=await k.request({method:"eth_chainId"});P=no($)}const U={domain:N.host,address:B,statement:_,uri:N.href,version:"1",chainId:P,nonce:(n=S?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(a=S?.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(o=S?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=S?.signInWithEthereum)===null||d===void 0?void 0:d.resources};p=io(U),g=await k.request({method:"personal_sign",params:[ao(p),B]})}try{const{data:y,error:x}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:p,signature:g},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ge});if(x)throw x;if(!y||!y.session||!y.user){const _=new At;return this._returnResult({data:{user:null,session:null},error:_})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:x})}catch(y){if(A(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async signInWithSolana(e){var r,s,n,a,i,o,l,u,d,f,m,p;let g,y;if("message"in e)g=e.message,y=e.signature;else{const{chain:x,wallet:_,statement:S,options:k}=e;let N;if(ve())if(typeof _=="object")N=_;else{const B=window;if("solana"in B&&typeof B.solana=="object"&&("signIn"in B.solana&&typeof B.solana.signIn=="function"||"signMessage"in B.solana&&typeof B.solana.signMessage=="function"))N=B.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 _!="object"||!k?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");N=_}const O=new URL((r=k?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in N&&N.signIn){const B=await N.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},k?.signInWithSolana),{version:"1",domain:O.host,uri:O.href}),S?{statement:S}:null));let P;if(Array.isArray(B)&&B[0]&&typeof B[0]=="object")P=B[0];else if(B&&typeof B=="object"&&"signedMessage"in B&&"signature"in B)P=B;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)g=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),y=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in N)||typeof N.signMessage!="function"||!("publicKey"in N)||typeof N!="object"||!N.publicKey||!("toBase58"in N.publicKey)||typeof N.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${O.host} wants you to sign in with your Solana account:`,N.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${O.href}`,`Issued At: ${(n=(s=k?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((a=k?.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${k.signInWithSolana.notBefore}`]:[],...!((i=k?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${k.signInWithSolana.expirationTime}`]:[],...!((o=k?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${k.signInWithSolana.chainId}`]:[],...!((l=k?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${k.signInWithSolana.nonce}`]:[],...!((u=k?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${k.signInWithSolana.requestId}`]:[],...!((f=(d=k?.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||f===void 0)&&f.length?["Resources",...k.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
57
+ `);const B=await N.signMessage(new TextEncoder().encode(g),"utf8");if(!B||!(B instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");y=B}}try{const{data:x,error:_}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:dt(y)},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:Ge});if(_)throw _;if(!x||!x.session||!x.user){const S=new At;return this._returnResult({data:{user:null,session:null},error:S})}return x.session&&(await this._saveSession(x.session),await this._notifyAllSubscribers("SIGNED_IN",x.session)),this._returnResult({data:Object.assign({},x),error:_})}catch(x){if(A(x))return this._returnResult({data:{user:null,session:null},error:x});throw x}}async _exchangeCodeForSession(e){const r=await ft(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Ai;const{data:a,error:i}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Ge});if(await we(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!a||!a.session||!a.user){const o=new At;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:n??null}),error:i})}catch(a){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:a,nonce:i}=e,o=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:a,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Ge}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){const d=new At;return this._returnResult({data:{user:null,session:null},error:d})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,a,i;try{if("email"in e){const{email:o,options:l}=e;let u=null,d=null;this.flowType==="pkce"&&([u,d]=await Ot(this.storage,this.storageKey));const{error:f}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,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:u,code_challenge_method:d},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:o,options:l}=e,{data:u,error:d}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(a=l?.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:d})}throw new vr("You must provide either an email or phone number.")}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(e){var r,s;try{let n,a;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:i,error:o}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:n,xform:Ge});if(o)throw o;if(!i)throw new Error("An error occurred on token verification.");const l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(A(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,a,i;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await Ot(this.storage,this.storageKey));const u=await E(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:o,code_challenge_method:l}),headers:this.headers,xform:Xi});return!((a=u.data)===null||a===void 0)&&a.url&&ve()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new Ie;const{error:n}=await E(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(A(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:a}=e,{error:i}=await E(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}},redirectTo:a?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){const{phone:s,type:n,options:a}=e,{data:i,error:o}=await E(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:o})}throw new vr("You must provide either an email or phone number and a type")}catch(r){if(A(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){const 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;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const 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{const 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;const r=await ft(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};const s=e.expires_at?e.expires_at*1e3-Date.now()<Vr:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const i=await ft(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=es()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const i={value:this.suppressGetSessionWarning};e.user=Vi(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):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;const 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 E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:nt}):await this._useSession(async r=>{var s,n,a;const{data:i,error:o}=r;if(o)throw o;return!(!((s=i.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ie}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&a!==void 0?a:void 0,xform:nt})})}catch(r){if(A(r))return Yr(r)&&(await this._removeSession(),await we(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=>{const{data:n,error:a}=s;if(a)throw a;if(!n.session)throw new Ie;const i=n.session;let o=null,l=null;this.flowType==="pkce"&&e.email!=null&&([o,l]=await Ot(this.storage,this.storageKey));const{data:u,error:d}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:l}),jwt:i.access_token,xform:nt});if(d)throw d;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(s){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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 Ie;const r=Date.now()/1e3;let s=r,n=!0,a=null;const{payload:i}=Sr(e.access_token);if(i.exp&&(s=i.exp,n=s<=r),n){const{data:o,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};a=o}else{const{data:o,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});a={access_token:e.access_token,refresh_token:e.refresh_token,user:o.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(A(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){const{data:i,error:o}=r;if(o)throw o;e=(s=i.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new Ie;const{data:n,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(A(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!ve())throw new wr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new wr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new $s("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new wr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new $s("No code detected.");const{data:S,error:k}=await this._exchangeCodeForSession(e.code);if(k)throw k;const N=new URL(window.location.href);return N.searchParams.delete("code"),window.history.replaceState(window.history.state,"",N.toString()),{data:{session:S.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:n,access_token:a,refresh_token:i,expires_in:o,expires_at:l,token_type:u}=e;if(!a||!o||!i||!u)throw new wr("No session defined in URL");const d=Math.round(Date.now()/1e3),f=parseInt(o);let m=d+f;l&&(m=parseInt(l));const p=m-d;p*1e3<=jt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${f}s`);const g=m-f;d-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,d):d-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,d);const{data:y,error:x}=await this._getUser(a);if(x)throw x;const _={provider_token:s,provider_refresh_token:n,access_token:a,expires_in:f,expires_at:m,refresh_token:i,token_type:u,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(s){if(A(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){const r=await ft(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;const{data:n,error:a}=r;if(a&&!Yr(a))return this._returnResult({error:a});const i=(s=n.session)===null||s===void 0?void 0:s.access_token;if(i){const{error:o}=await this.admin.signOut(i,e);if(o&&!(Ti(o)&&(o.status===404||o.status===401||o.status===403)||Yr(o)))return this._returnResult({error:o})}return e!=="others"&&(await this._removeSession(),await we(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=Ii(),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{const{data:{session:a},error:i}=r;if(i)throw i;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){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",a),console.error(a)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await Ot(this.storage,this.storageKey,!0));try{return await E(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(a){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{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(A(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{const{data:s,error:n}=await this._useSession(async a=>{var i,o,l,u,d;const{data:f,error:m}=a;if(m)throw m;const p=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",p,{headers:this.headers,jwt:(d=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&d!==void 0?d:void 0})});if(n)throw n;return ve()&&!(!((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(A(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{const{error:n,data:{session:a}}=r;if(n)throw n;const{options:i,provider:o,token:l,access_token:u,nonce:d}=e,f=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=a?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:o,id_token:l,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Ge}),{data:m,error:p}=f;return p?this._returnResult({data:{user:null,session:null},error:p}):!m||!m.session||!m.user?this._returnResult({data:{user:null,session:null},error:new At}):(m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("USER_UPDATED",m.session)),this._returnResult({data:m,error:p}))}catch(n){if(await we(this.storage,`${this.storageKey}-code-verifier`),A(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;const{data:a,error:i}=r;if(i)throw i;return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await Ui(async n=>(n>0&&await Li(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ge})),(n,a)=>{const i=200*Math.pow(2,n);return a&&Xr(a)&&Date.now()+i-s<jt})}catch(s){if(this._debug(r,"error",s),A(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){const 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),ve()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await ft(this.storage,this.storageKey);if(n&&this.userStorage){let i=await ft(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Et(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:es()}else if(n&&!n.user&&!n.user){const i=await ft(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await we(this.storage,this.storageKey+"-user"),await Et(this.storage,this.storageKey,n)):n.user=es()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const a=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Vr;if(this._debug(s,`session has${a?"":" not"} expired with margin of ${Vr}s`),a){if(this.autoRefreshToken&&n.refresh_token){const{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Xr(i)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:i,error:o}=await this._getUser(n.access_token);!o&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(s,"error getting user data, skipping SIGNED_IN notification",i)}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 Ie;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new kr;const{data:a,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!a.session)throw new Ie;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const o={data:a.session,error:null};return this.refreshingDeferred.resolve(o),o}catch(a){if(this._debug(n,"error",a),A(a)){const i={data:null,error:a};return Xr(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(a),a}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],i=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(e,r)}catch(l){a.push(l)}});if(await Promise.all(i),a.length>0){for(let o=0;o<a.length;o+=1)console.error(a[o]);throw a[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await we(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await Et(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const a=Ws(n);await Et(this.storage,this.storageKey,a)}else{const n=Ws(r);await Et(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await we(this.storage,this.storageKey),await we(this.storage,this.storageKey+"-code-verifier"),await we(this.storage,this.storageKey+"-user"),this.userStorage&&await we(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ve()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),jt);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const 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()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const 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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/jt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${jt}ms, refresh threshold is ${zr} ticks`),n<=zr&&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 Js)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ve()||!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){const 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){const 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"){const[a,i]=await Ot(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(o.toString())}if(s?.queryParams){const a=new URLSearchParams(s.queryParams);n.push(a.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;const{data:n,error:a}=r;return a?this._returnResult({data:null,error:a}):await E(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(A(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:a,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=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:u}=await E(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(s=a?.session)===null||s===void 0?void 0:s.access_token});return u?this._returnResult({data:null,error:u}):(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(A(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;const{data:n,error:a}=r;if(a)return this._returnResult({data:null,error:a});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?mo(e.webauthn.credential_response):po(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:l}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,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)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:l}))})}catch(r){if(A(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;const{data:n,error:a}=r;if(a)return this._returnResult({data:null,error:a});const i=await E(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(i.error)return i;const{data:o}=i;if(o.type!=="webauthn")return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:ho(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:fo(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{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;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(a),a.status==="verified"&&n[a.factor_type].push(a);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,a;if(e)try{const{payload:p}=Sr(e);let g=null;p.aal&&(g=p.aal);let y=g;const{data:{user:x},error:_}=await this.getUser(e);if(_)return this._returnResult({data:null,error:_});((s=(r=x?.factors)===null||r===void 0?void 0:r.filter(N=>N.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(y="aal2");const k=p.amr||[];return{data:{currentLevel:g,nextLevel:y,currentAuthenticationMethods:k},error:null}}catch(p){if(A(p))return this._returnResult({data:null,error:p});throw p}const{data:{session:i},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Sr(i.access_token);let u=null;l.aal&&(u=l.aal);let d=u;((a=(n=i.user.factors)===null||n===void 0?void 0:n.filter(p=>p.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(d="aal2");const m=l.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:m},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await E(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new Ie})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new Ie});const i=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&ve()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(A(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:a}=s;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new Ie});const i=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return i.data&&i.data.redirect_url&&ve()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(s){if(A(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await E(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 Ie})})}catch(e){if(A(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await E(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 Ie})})}catch(r){if(A(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(o=>o.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(o=>o.kid===e),s&&this.jwks_cached_at+Si>n)return s;const{data:a,error:i}=await E(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=n,s=a.keys.find(o=>o.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:p,error:g}=await this.getSession();if(g||!p.session)return this._returnResult({data:null,error:g});s=p.session.access_token}const{header:n,payload:a,signature:i,raw:{header:o,payload:l}}=Sr(s);r?.allowExpired||Hi(a.exp);const u=!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(!u){const{error:p}=await this.getUser(s);if(p)throw p;return{data:{claims:a,header:n,signature:i},error:null}}const d=Gi(n.alg),f=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,f,i,Ri(`${o}.${l}`)))throw new Zr("Invalid JWT signature");return{data:{claims:a,header:n,signature:i},error:null}}catch(s){if(A(s))return this._returnResult({data:null,error:s});throw s}}}Qt.nextInstanceID={};const xo=Qt,To="2.100.0";let Xt="";typeof Deno<"u"?Xt="deno":typeof document<"u"?Xt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Xt="react-native":Xt="node";const jo={headers:{"X-Client-Info":`supabase-js-${Xt}/${To}`}},Ao={schema:"public"},Po={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Eo={};function Zt(t){"@babel/helpers - typeof";return Zt=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},Zt(t)}function Oo(t,e){if(Zt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(Zt(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Co(t){var e=Oo(t,"string");return Zt(e)=="symbol"?e:e+""}function Ro(t,e,r){return(e=Co(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function tn(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 ae(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?tn(Object(r),!0).forEach(function(s){Ro(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):tn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const No=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Io=()=>Headers,Do=(t,e,r)=>{const s=No(r),n=Io();return async(a,i)=>{var o;const l=(o=await e())!==null&&o!==void 0?o:t;let u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),s(a,ae(ae({},i),{},{headers:u}))}};function $o(t){return t.endsWith("/")?t:t+"/"}function Lo(t,e){var r,s;const{db:n,auth:a,realtime:i,global:o}=t,{db:l,auth:u,realtime:d,global:f}=e,m={db:ae(ae({},l),n),auth:ae(ae({},u),a),realtime:ae(ae({},d),i),storage:{},global:ae(ae(ae({},f),o),{},{headers:ae(ae({},(r=f?.headers)!==null&&r!==void 0?r:{}),(s=o?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?m.accessToken=t.accessToken:delete m.accessToken,m}function Uo(t){const 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($o(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Mo=class extends xo{constructor(t){super(t)}},Bo=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const a=Uo(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const i=`sb-${a.hostname.split(".")[0]}-auth-token`,o={db:Ao,realtime:Eo,auth:ae(ae({},Po),{},{storageKey:i}),global:jo},l=Lo(r??{},o);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:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Do(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(ae({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new ua(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new bi(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new ra(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();const{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:a,flowType:i,lock:o,debug:l,throwOnError:u},d,f){const m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Mo({url:this.authUrl.href,headers:ae(ae({},m),d),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:i,lock:o,debug:l,throwOnError:u,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(p=>p.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new qa(this.realtimeUrl.href,ae(ae({},t),{},{params:ae(ae({},{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)}};const Ko=(t,e,r)=>new Bo(t,e,r);function Fo(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Fo()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");function rn(t,e){if(!t||!e)throw new Error("Supabase URL and anon key are required");return Ko(t,e)}function sn(t){const e=[];let r="",s=!1;for(let n=0;n<t.length;n++){const a=t[n];a==='"'?s&&t[n+1]==='"'?(r+='"',n++):s=!s:a===","&&!s?(e.push(r),r=""):r+=a}return e.push(r),e.map(n=>n.trim().replace(/^"|"$/g,""))}function Ue(t,...e){const r=n=>n.trim().toLowerCase().replace(/[_\s]+/g," ").trim(),s=new Map;Object.entries(t).forEach(([n,a])=>s.set(r(n),a));for(const n of e){const a=s.get(r(n));if(a!==void 0&&a.trim())return a.trim()}return""}function qo(t){const r=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
57
58
  `).trim().split(`
58
- `);if(t.length<2)return[];const s=Vs(t[0]),n=[];for(let a=1;a<t.length;a++){const i=Vs(t[a]);if(i.length<s.length)continue;const o={};s.forEach((m,p)=>{o[m]=i[p]??""});const c=Ue(o,"store_id","store id"),u=Ue(o,"pooja_title","pooja title","puja title");if(!c||!u)continue;const d=Ue(o,"cover_media_url","cover media url","cover image"),f=Ue(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:c,pooja_title:u,temple_name:Ue(o,"temple_name","temple name")||"",pooja_title_english:Ue(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Ue(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:f||void 0,puja_link:Ue(o,"puja_link","puja link","pooja link")||Ue(o,"puja link","pooja link")||"",puja_link_hindi:Ue(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Ue(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Ue(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const Js={mangal:["mangal","manglik","kuja","मंगल","मांगलिक","30 day","30-day","30 din"],"kaal-sarp":["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],kaalSarp:["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],pitra:["pitru","pitra","पितृ","पितर","pitra dosha","pitru dosha"],shani:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"],sadeSati:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"]};function bo(r){const e=r.split("/");if(e.length!==3)return null;const t=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,t)}function Ys(r,e){const t=Js[e]||Js[e.toLowerCase()];if(!t||t.length===0)return null;const s=r.filter(i=>{const o=(i.pooja_title||"").toLowerCase(),c=(i.pooja_title_english||"").toLowerCase();return o.includes("rashi")||c.includes("rashi")?!1:t.some(u=>o.includes(u.toLowerCase())||c.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(i=>{const o=bo(i.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Rt=[],Qs=0;const wo=3600*1e3;async function _o(r){const e=Date.now();if(Rt.length>0&&e-Qs<wo)return Rt;try{const{data:t,error:s}=await r.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Rt;const n=typeof t=="string"?t:"";if(!n)return Rt;const a=vo(n);return Rt=a,Qs=e,a}catch(t){return console.warn("[DoshaCalculator] fetchPujas error:",t),Rt}}const Xs={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti","पितृ दोष शांति महापूजा एवं काशी गंगा आरती":"Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti","पितृ दोष निवारण पूजा एवं काशी गंगा आरती":"Pitra Dosha Nivaran Puja & Kashi Ganga Aarti","त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा":"Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja","काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक":"Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek","राहु-सूर्य दोष निवारण पूजा":"Rahu-Surya Dosha Nivaran Puja","मंगल दोष निवारण पूजा":"Mangal Dosha Nivaran Puja","शनि शांति पूजा":"Shani Shanti Puja","शनि साढ़े साती शांति पूजा":"Shani Sade Sati Shanti Puja","नवग्रह शांति पूजा":"Navagraha Shanti Puja","गुरु चांडाल दोष निवारण पूजा":"Guru Chandal Dosha Nivaran Puja","श्रापित दोष निवारण पूजा":"Shrapit Dosha Nivaran Puja","काल सर्प दोष पूजा":"Kaal Sarp Dosha Puja","मंगल पूजा":"Mangal Puja","शनि पूजा":"Shani Puja","राहु पूजा":"Rahu Puja","केतु पूजा":"Ketu Puja","नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ":"Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya","30 दिन मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिनों में मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिन मंगल पूजा":"30-Day Mangal Puja","30 लाख मंगल जाप":"30 Lakh Mangal Jaap","शनि साढ़ेसाती शांति पूजा":"Shani Sade Sati Shanti Puja","शनि महादशा शांति पूजा":"Shani Mahadasha Shanti Puja","शनि दोष निवारण पूजा":"Shani Dosha Nivaran Puja","काल सर्प दोष निवारण महापूजा":"Kaal Sarp Dosha Nivaran Mahapuja","पिशाच मोचन कुंड पूजा":"Pishach Mochan Kund Puja","पितृ तर्पण पूजा":"Pitru Tarpan Puja"},ko={पूजा:"Puja",महापूजा:"Mahapuja",दोष:"Dosha",निवारण:"Nivaran",शांति:"Shanti",महायज्ञ:"Mahayagya",यज्ञ:"Yagya",अभिषेक:"Abhishek",रुद्राभिषेक:"Rudrabhishek",आरती:"Aarti",महाआरती:"Maha Aarti",महादशा:"Mahadasha",मंदिर:"Temple",ज्योतिर्लिंग:"Jyotirlinga",देव:"Dev",एवं:"&",और:"and",तिल:"Til",तेल:"Tel",गंगा:"Ganga",पाप:"Paap",ग्रह:"Graha",नवग्रह:"Navagraha",मंगल:"Mangal",शनि:"Shani","साढ़े साती":"Sade Sati",साढ़ेसाती:"Sade Sati",राहु:"Rahu",केतु:"Ketu",गुरु:"Guru",सूर्य:"Surya",चंद्र:"Chandra",चन्द्र:"Chandra",बुध:"Budh",शुक्र:"Shukra","काल सर्प":"Kaal Sarp",कालसर्प:"Kaal Sarp",पितृ:"Pitru",पितर:"Pitra",श्रापित:"Shrapit",चांडाल:"Chandal",काशी:"Kashi",त्र्यंबकेश्वर:"Trimbakeshwar",हथला:"Hathla"},Zs={"काशी विश्वनाथ मंदिर":"Kashi Vishwanath Temple","त्र्यंबकेश्वर मंदिर":"Trimbakeshwar Temple","त्र्यंबकेश्वर ज्योतिर्लिंग":"Trimbakeshwar Jyotirlinga","महाकालेश्वर मंदिर":"Mahakaleshwar Temple","सोमनाथ मंदिर":"Somnath Temple","केदारनाथ मंदिर":"Kedarnath Temple","बद्रीनाथ मंदिर":"Badrinath Temple","रामेश्वरम मंदिर":"Rameshwaram Temple","द्वारकाधीश मंदिर":"Dwarkadhish Temple","जगन्नाथ पुरी मंदिर":"Jagannath Puri Temple","हथला शनि देव मंदिर":"Hathla Shani Dev Temple"};function So(r){const e=r.split("/");if(e.length!==3)return null;const t=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,t)}function en(r){let e=r;return Object.entries(ko).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(a,n)}),e.replace(/\s+/g," ").trim()}function Jr(r,e){const t=e?.toLowerCase().startsWith("hi"),s=typeof r=="string"?r:r.pooja_title,n=typeof r=="string"?void 0:r.pooja_title_english;if(t)return s;if(n?.trim())return n;if(Xs[s])return Xs[s];const a=en(s);return a!==s?a:s}function tn(r,e){const t=e?.toLowerCase().startsWith("hi"),s=typeof r=="string"?r:r.temple_name,n=typeof r=="string"?void 0:r.temple_name_english;if(t)return s;if(n?.trim())return n;if(Zs[s])return Zs[s];const a=en(s);return a!==s?a:s}function rn(r,e="en"){const t=So(r);if(!t)return r;const n=e?.toLowerCase().startsWith("hi")?"hi-IN":"en-GB";return new Intl.DateTimeFormat(n,{day:"numeric",month:"short",year:"numeric"}).format(t)}function xo(r){if(!r||typeof window>"u")return r;try{const e=new URLSearchParams(window.location.search),t=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!t&&!s&&!n)return r;const a=new URL(r);return t&&a.searchParams.set("utm_source",t),s&&a.searchParams.set("utm_medium",s),n&&a.searchParams.set("utm_content",n),a.toString()}catch{return r}}function Yr(r,e){const s=e?.toLowerCase().startsWith("hi")?r.puja_link_hindi||r.puja_link:r.puja_link||r.puja_link_hindi;return xo(s||"")}function sn(r,e){return e?.toLowerCase().startsWith("hi")?r.cover_media_url||r.cover_media_url_english||"":r.cover_media_url_english||r.cover_media_url||""}const jo={container:"_container_m8vst_1"},To=["en","hi"],Po={en:"English",hi:"हिन्दी"},nn={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"I was facing delay in marriage and also tension in career. After checking my kundli I understood the problems clearly. I followed the remedies with faith and slowly things started improving. Now my marriage is fixed and job situation is also better. Feeling very thankful.",feedbackTestimonial2:"My health was not good from long time and money problems also coming again and again. The report explained everything in simple way. After doing small remedies I feel more positive and health is improving. Very good experience.",feedbackTestimonial3:"Career was fully stuck and no promotion from 3 years. I created my kundli here and got to know about some dosha affecting work life. After remedies within few months I changed job with better salary. Really happy.",feedbackTestimonial4:"I checked kundli for marriage but it also told about finance issues. Remedies were easy to follow. Slowly money stability came and good rishta also came in family. Feeling peaceful now.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"Too much stress in life related to marriage and future. Kundli reading was very detailed but easy to understand. After doing puja and mantra I feel calm and recently got good marriage proposal. Thank you so much.",feedbackTestimonial7:"Finance loss was happening again and again in business. They told reason from kundli and suggested remedy. I followed for few weeks and situation slowly became stable. Good support.",feedbackTestimonial8:"I almost lost hope for marriage and career both. But this kundli analysis gave me new confidence. Within 2 months I got interview call and also one good match from relatives. Things are moving finally.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"Marriage delay, money tension, family stress everything was going wrong. Remedies were small but powerful. Now engagement done and finance also improving slowly. Feeling blessed.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"Kundli reading helped me understand many hidden issues in life like marriage delay and job confusion. Remedies were simple daily things. Slowly life becoming stable. Nice experience overall.",feedbackTestimonial15:"Good for anyone facing problems in marriage career or finance. Simple language and true guidance. I saw positive change in few months only. Highly recommended.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"My marriage was getting delayed again and again and we were very worried. After creating my kundli here I came to know about Mangal dosh and some other issues. The remedies suggested were simple and within few months things started moving. Now my engagement is fixed. Feeling very thankful.",feedbackTestimonialMarriage2:"I was honestly not believing in kundli much but my parents forced me to try. They found a marriage dosha in my chart and gave puja guidance. After doing it I met a very good person through relatives. Sometimes these things really work.",feedbackTestimonialMarriage3:"Got my kundli checked because nothing was working for my wedding. Every match was breaking. The report clearly explained the doshas and what to do. Followed the remedy for 40 days and suddenly one perfect match came. Married now and happy.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"I was 32 and tension in home was too much. Kundli showed Shani related problem affecting marriage. Did the suggested donation and mantra. Within 3 months alliance got finalised. Still feels like miracle honestly.",feedbackTestimonialMarriage6:"The explanation was simple and easy to understand. I liked that they did not scare me but gave practical remedies. After doing them my long pending relationship got approval from both families and we are getting married soon.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"Many astrologers told different things and I was confused. Here the kundli analysis felt genuine and detailed. They pointed out exact dosha causing breakups. After remedies my partner came back and families agreed. Feeling peaceful now.",feedbackTestimonialMarriage9:"I created my kundli just casually but result shocked me. There was strong manglik issue. Followed puja on Tuesday as told. Within few months I got good proposal from same city. Everything went smooth after that.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"For 5 years nothing was happening in my life regarding marriage. After kundli matching they told to wait few months and do certain prayers. Exactly in that time I met my husband through office. Now happily married for 1 year.",feedbackTestimonialMarriage12:"Very emotional moment for me writing this. I had almost lost hope. The dosha remedies gave me confidence and positivity also. Slowly situations changed and today my roka ceremony is done. Truly grateful.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"My daughter kundli was checked here. They found dosha and suggested simple temple visit and fasting. We followed sincerely. Within short time good proposal came from nice family. As parents we are very relieved.",feedbackTestimonialMarriage15:"I recommend this to anyone facing marriage delay. Kundli analysis felt real not copy paste. Small small remedies but big change in life. Thank you from heart.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3:"Is this a generic report?",faqA3:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"The calculator identifies doshas that may be causing marriage delay. Once detected, we recommend specific pujas and remedies that have helped thousands of users overcome marriage obstacles.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"While we follow established astrological rules, dosha interpretation can vary among astrologers. We recommend consulting an astrologer you trust if you wish to explore additional viewpoints.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
59
+ `);if(r.length<2)return[];const s=sn(r[0]),n=[];for(let a=1;a<r.length;a++){const i=sn(r[a]);if(i.length<s.length)continue;const o={};s.forEach((m,p)=>{o[m]=i[p]??""});const l=Ue(o,"store_id","store id"),u=Ue(o,"pooja_title","pooja title","puja title");if(!l||!u)continue;const d=Ue(o,"cover_media_url","cover media url","cover image"),f=Ue(o,"cover_media_url_english","cover media url english","cover image english");n.push({store_id:l,pooja_title:u,temple_name:Ue(o,"temple_name","temple name")||"",pooja_title_english:Ue(o,"pooja_title_english","pooja title english","puja title english")||void 0,temple_name_english:Ue(o,"temple_name_english","temple name english")||void 0,cover_media_url:d||void 0,cover_media_url_english:f||void 0,puja_link:Ue(o,"puja_link","puja link","pooja link")||Ue(o,"puja link","pooja link")||"",puja_link_hindi:Ue(o,"puja_link_hindi","puja link hindi","pooja link hindi")||void 0,individual_pack_price_inr:parseFloat(Ue(o,"individual_pack_price_inr","individual pack price inr","price"))||0,schedule_date_ist:Ue(o,"schedule_date_ist","schedule date ist","schedule date")||""})}return n}const nn={mangal:["mangal","manglik","kuja","मंगल","मांगलिक","30 day","30-day","30 din"],"kaal-sarp":["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],kaalSarp:["kaal sarp","kaal-sarp","kaalsarp","काल सर्प","कालसर्प","sarp"],pitra:["pitru","pitra","पितृ","पितर","pitra dosha","pitru dosha"],shani:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"],sadeSati:["shani","saturn","शनि","sade sati","साढ़े साती","साढ़ेसाती","sade saati"]};function Wo(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function an(t,e){const r=nn[e]||nn[e.toLowerCase()];if(!r||r.length===0)return null;const s=t.filter(i=>{const o=(i.pooja_title||"").toLowerCase(),l=(i.pooja_title_english||"").toLowerCase();return o.includes("rashi")||l.includes("rashi")?!1:r.some(u=>o.includes(u.toLowerCase())||l.includes(u.toLowerCase()))});if(s.length===0)return null;const n=new Date;return n.setHours(0,0,0,0),(s.filter(i=>{const o=Wo(i.schedule_date_ist);return o?o.getTime()>=n.getTime():!0})[0]??s[0])||null}let Nt=[],on=0;const Ho=3600*1e3;async function Go(t){const e=Date.now();if(Nt.length>0&&e-on<Ho)return Nt;try{const{data:r,error:s}=await t.functions.invoke("fetch-pujas");if(s)return console.warn("[DoshaCalculator] fetch-pujas error:",s),Nt;const n=typeof r=="string"?r:"";if(!n)return Nt;const a=qo(n);return Nt=a,on=e,a}catch(r){return console.warn("[DoshaCalculator] fetchPujas error:",r),Nt}}const ln={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"Pitru Dosha Nivaran Mahayagya & Kashi Ganga Maha Aarti","पितृ दोष शांति महापूजा एवं काशी गंगा आरती":"Pitra Dosha Shanti Mahapuja & Kashi Ganga Aarti","पितृ दोष निवारण पूजा एवं काशी गंगा आरती":"Pitra Dosha Nivaran Puja & Kashi Ganga Aarti","त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक और काल सर्प दोष निवारण पूजा":"Trimbakeshwar Jyotirlinga Rudrabhishek & Kaal Sarp Dosha Nivaran Puja","काल सर्प दोष निवारण पूजा एवं त्र्यंबकेश्वर ज्योतिर्लिंग रुद्राभिषेक":"Kaal Sarp Dosha Nivaran Puja & Trimbakeshwar Jyotirlinga Rudrabhishek","राहु-सूर्य दोष निवारण पूजा":"Rahu-Surya Dosha Nivaran Puja","मंगल दोष निवारण पूजा":"Mangal Dosha Nivaran Puja","शनि शांति पूजा":"Shani Shanti Puja","शनि साढ़े साती शांति पूजा":"Shani Sade Sati Shanti Puja","नवग्रह शांति पूजा":"Navagraha Shanti Puja","गुरु चांडाल दोष निवारण पूजा":"Guru Chandal Dosha Nivaran Puja","श्रापित दोष निवारण पूजा":"Shrapit Dosha Nivaran Puja","काल सर्प दोष पूजा":"Kaal Sarp Dosha Puja","मंगल पूजा":"Mangal Puja","शनि पूजा":"Shani Puja","राहु पूजा":"Rahu Puja","केतु पूजा":"Ketu Puja","नवग्रह शांति पूजा, शनि तिल तेल अभिषेक और पाप ग्रह शांति यज्ञ":"Navagraha Shanti Puja, Shani Til Tel Abhishek and Paap Graha Shanti Yagya","30 दिन मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिनों में मंगल दोष निवारण पूजा":"30-Day Mangal Dosha Nivaran Puja","30 दिन मंगल पूजा":"30-Day Mangal Puja","30 लाख मंगल जाप":"30 Lakh Mangal Jaap","शनि साढ़ेसाती शांति पूजा":"Shani Sade Sati Shanti Puja","शनि महादशा शांति पूजा":"Shani Mahadasha Shanti Puja","शनि दोष निवारण पूजा":"Shani Dosha Nivaran Puja","काल सर्प दोष निवारण महापूजा":"Kaal Sarp Dosha Nivaran Mahapuja","पिशाच मोचन कुंड पूजा":"Pishach Mochan Kund Puja","पितृ तर्पण पूजा":"Pitru Tarpan Puja"},zo={पूजा:"Puja",महापूजा:"Mahapuja",दोष:"Dosha",निवारण:"Nivaran",शांति:"Shanti",महायज्ञ:"Mahayagya",यज्ञ:"Yagya",अभिषेक:"Abhishek",रुद्राभिषेक:"Rudrabhishek",आरती:"Aarti",महाआरती:"Maha Aarti",महादशा:"Mahadasha",मंदिर:"Temple",ज्योतिर्लिंग:"Jyotirlinga",देव:"Dev",एवं:"&",और:"and",तिल:"Til",तेल:"Tel",गंगा:"Ganga",पाप:"Paap",ग्रह:"Graha",नवग्रह:"Navagraha",मंगल:"Mangal",शनि:"Shani","साढ़े साती":"Sade Sati",साढ़ेसाती:"Sade Sati",राहु:"Rahu",केतु:"Ketu",गुरु:"Guru",सूर्य:"Surya",चंद्र:"Chandra",चन्द्र:"Chandra",बुध:"Budh",शुक्र:"Shukra","काल सर्प":"Kaal Sarp",कालसर्प:"Kaal Sarp",पितृ:"Pitru",पितर:"Pitra",श्रापित:"Shrapit",चांडाल:"Chandal",काशी:"Kashi",त्र्यंबकेश्वर:"Trimbakeshwar",हथला:"Hathla"},cn={"काशी विश्वनाथ मंदिर":"Kashi Vishwanath Temple","त्र्यंबकेश्वर मंदिर":"Trimbakeshwar Temple","त्र्यंबकेश्वर ज्योतिर्लिंग":"Trimbakeshwar Jyotirlinga","महाकालेश्वर मंदिर":"Mahakaleshwar Temple","सोमनाथ मंदिर":"Somnath Temple","केदारनाथ मंदिर":"Kedarnath Temple","बद्रीनाथ मंदिर":"Badrinath Temple","रामेश्वरम मंदिर":"Rameshwaram Temple","द्वारकाधीश मंदिर":"Dwarkadhish Temple","जगन्नाथ पुरी मंदिर":"Jagannath Puri Temple","हथला शनि देव मंदिर":"Hathla Shani Dev Temple"};function Vo(t){const e=t.split("/");if(e.length!==3)return null;const r=parseInt(e[0],10),s=parseInt(e[1],10)-1,n=parseInt(e[2],10);return new Date(n,s,r)}function un(t){let e=t;return Object.entries(zo).sort((s,n)=>n[0].length-s[0].length).forEach(([s,n])=>{const a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi");e=e.replace(a,n)}),e.replace(/\s+/g," ").trim()}function rs(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.pooja_title,n=typeof t=="string"?void 0:t.pooja_title_english;if(r)return s;if(n?.trim())return n;if(ln[s])return ln[s];const a=un(s);return a!==s?a:s}function dn(t,e){const r=e?.toLowerCase().startsWith("hi"),s=typeof t=="string"?t:t.temple_name,n=typeof t=="string"?void 0:t.temple_name_english;if(r)return s;if(n?.trim())return n;if(cn[s])return cn[s];const a=un(s);return a!==s?a:s}function hn(t,e="en"){const r=Vo(t);if(!r)return t;const n=e?.toLowerCase().startsWith("hi")?"hi-IN":"en-GB";return new Intl.DateTimeFormat(n,{day:"numeric",month:"short",year:"numeric"}).format(r)}function Jo(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search),r=e.get("utm_source"),s=e.get("utm_medium"),n=e.get("utm_content");if(!r&&!s&&!n)return t;const a=new URL(t);return r&&a.searchParams.set("utm_source",r),s&&a.searchParams.set("utm_medium",s),n&&a.searchParams.set("utm_content",n),a.toString()}catch{return t}}function ss(t,e){const s=e?.toLowerCase().startsWith("hi")?t.puja_link_hindi||t.puja_link:t.puja_link||t.puja_link_hindi;return Jo(s||"")}function fn(t,e){return e?.toLowerCase().startsWith("hi")?t.cover_media_url||t.cover_media_url_english||"":t.cover_media_url_english||t.cover_media_url||""}const Yo={container:"_container_m8vst_1"},Qo=["en","hi"],Xo={en:"English",hi:"हिन्दी"},mn={en:{language:"Language",guest:"Guest",sriMandir:"Sri Mandir",ratingText:"3 Crore+ app downloads",feedbackTitle:"What Others Discovered Through Their Dosha Analysis",feedbackTrust:"Trusted by over 5 crore users worldwide",feedbackRating:"4.9",feedbackTestimonial1:"I was facing delay in marriage and also tension in career. After checking my kundli I understood the problems clearly. I followed the remedies with faith and slowly things started improving. Now my marriage is fixed and job situation is also better. Feeling very thankful.",feedbackTestimonial2:"My health was not good from long time and money problems also coming again and again. The report explained everything in simple way. After doing small remedies I feel more positive and health is improving. Very good experience.",feedbackTestimonial3:"Career was fully stuck and no promotion from 3 years. I created my kundli here and got to know about some dosha affecting work life. After remedies within few months I changed job with better salary. Really happy.",feedbackTestimonial4:"I checked kundli for marriage but it also told about finance issues. Remedies were easy to follow. Slowly money stability came and good rishta also came in family. Feeling peaceful now.",feedbackTestimonial5:"Simple and clear guidance. Problems in job and health both reduced after remedies. Good service.",feedbackTestimonial6:"Too much stress in life related to marriage and future. Kundli reading was very detailed but easy to understand. After doing puja and mantra I feel calm and recently got good marriage proposal. Thank you so much.",feedbackTestimonial7:"Finance loss was happening again and again in business. They told reason from kundli and suggested remedy. I followed for few weeks and situation slowly became stable. Good support.",feedbackTestimonial8:"I almost lost hope for marriage and career both. But this kundli analysis gave me new confidence. Within 2 months I got interview call and also one good match from relatives. Things are moving finally.",feedbackTestimonial9:"Very genuine report not copy paste. Health issue reason also explained. After remedies I feel more energy and mind peace. Satisfied.",feedbackTestimonial10:"Marriage delay, money tension, family stress everything was going wrong. Remedies were small but powerful. Now engagement done and finance also improving slowly. Feeling blessed.",feedbackTestimonial11:"I was not believing before but result surprised me. Career growth started after long time and new opportunities coming. Good guidance and honest prediction.",feedbackTestimonial12:"Health problems and negative thoughts were too much. After following remedies I feel mentally strong and peaceful. Family also noticing the change. Very grateful.",feedbackTestimonial13:"Short review. Career better now and money flow also improved after remedy. Thank you.",feedbackTestimonial14:"Kundli reading helped me understand many hidden issues in life like marriage delay and job confusion. Remedies were simple daily things. Slowly life becoming stable. Nice experience overall.",feedbackTestimonial15:"Good for anyone facing problems in marriage career or finance. Simple language and true guidance. I saw positive change in few months only. Highly recommended.",feedbackAuthor1:"Abhishek Mishra",feedbackAuthor2:"Pooja Verma",feedbackAuthor3:"Amit Patel",feedbackAuthor4:"Sneha Gupta",feedbackAuthor5:"Vikas Yadav",feedbackAuthor6:"Neha Singh",feedbackAuthor7:"Rahul Jain",feedbackAuthor8:"Kavita Mishra",feedbackAuthor9:"Sandeep Kumar",feedbackAuthor10:"Anjali Mehta",feedbackAuthor11:"Deepak Arora",feedbackAuthor12:"Ritu Saxena",feedbackAuthor13:"Manoj Tiwari",feedbackAuthor14:"Priya Nair",feedbackAuthor15:"Karan Malhotra",feedbackAuthor1AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor2AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639293055.png",feedbackAuthor3AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",feedbackAuthor4AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639427379.png",feedbackAuthor5AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639381899.png",feedbackAuthor6AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639416587.png",feedbackAuthor7AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639454626.png",feedbackAuthor8AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639319028.png",feedbackAuthor9AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639271096.png",feedbackAuthor10AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639254172.png",feedbackAuthor11AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639345411.png",feedbackAuthor12AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639306698.png",feedbackAuthor13AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639330970.png",feedbackAuthor14AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639402894.png",feedbackAuthor15AvatarUrl:"https://srm-cdn.a4b.io/yoda/1770639358174.png",readMoreReviews:"Read More Reviews",readLess:"Read Less",feedbackTitleMarriage:"What others facing marriage delay discovered",feedbackTestimonialMarriage1:"My marriage was getting delayed again and again and we were very worried. After creating my kundli here I came to know about Mangal dosh and some other issues. The remedies suggested were simple and within few months things started moving. Now my engagement is fixed. Feeling very thankful.",feedbackTestimonialMarriage2:"I was honestly not believing in kundli much but my parents forced me to try. They found a marriage dosha in my chart and gave puja guidance. After doing it I met a very good person through relatives. Sometimes these things really work.",feedbackTestimonialMarriage3:"Got my kundli checked because nothing was working for my wedding. Every match was breaking. The report clearly explained the doshas and what to do. Followed the remedy for 40 days and suddenly one perfect match came. Married now and happy.",feedbackTestimonialMarriage4:"Very helpful service. Found reason for delay in marriage and solution also given. Things improved slowly.",feedbackTestimonialMarriage5:"I was 32 and tension in home was too much. Kundli showed Shani related problem affecting marriage. Did the suggested donation and mantra. Within 3 months alliance got finalised. Still feels like miracle honestly.",feedbackTestimonialMarriage6:"The explanation was simple and easy to understand. I liked that they did not scare me but gave practical remedies. After doing them my long pending relationship got approval from both families and we are getting married soon.",feedbackTestimonialMarriage7:"Short review but true. Marriage dosh removed after remedies and now wedding date fixed. Thank you so much.",feedbackTestimonialMarriage8:"Many astrologers told different things and I was confused. Here the kundli analysis felt genuine and detailed. They pointed out exact dosha causing breakups. After remedies my partner came back and families agreed. Feeling peaceful now.",feedbackTestimonialMarriage9:"I created my kundli just casually but result shocked me. There was strong manglik issue. Followed puja on Tuesday as told. Within few months I got good proposal from same city. Everything went smooth after that.",feedbackTestimonialMarriage10:"Service is good and fast. Report is clear. My marriage problem solved after remedy. Satisfied.",feedbackTestimonialMarriage11:"For 5 years nothing was happening in my life regarding marriage. After kundli matching they told to wait few months and do certain prayers. Exactly in that time I met my husband through office. Now happily married for 1 year.",feedbackTestimonialMarriage12:"Very emotional moment for me writing this. I had almost lost hope. The dosha remedies gave me confidence and positivity also. Slowly situations changed and today my roka ceremony is done. Truly grateful.",feedbackTestimonialMarriage13:"Nice guidance and honest prediction. No false promises. Remedies worked for my delayed marriage issue.",feedbackTestimonialMarriage14:"My daughter kundli was checked here. They found dosha and suggested simple temple visit and fasting. We followed sincerely. Within short time good proposal came from nice family. As parents we are very relieved.",feedbackTestimonialMarriage15:"I recommend this to anyone facing marriage delay. Kundli analysis felt real not copy paste. Small small remedies but big change in life. Thank you from heart.",faqTitle:"Frequently Asked Questions",faqQ1:"Is this really free?",faqA1:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2:"What if I don't know birth time?",faqA2:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3:"Is this a generic report?",faqA3:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ1Marriage:"Is this really free?",faqA1Marriage:"Yes, the Dosha Calculator is completely free to use. You can check your kundli for doshas and get detailed analysis at no cost.",faqQ2Marriage:"What if I don't know birth time?",faqA2Marriage:"You can enter an approximate birth time or use 12:00 PM as default. Some doshas like Mangal Dosha and Kaal Sarp Dosha can still be detected with approximate time.",faqQ3Marriage:"Is this a generic report?",faqA3Marriage:"No, your report is personalized based on your exact date, time, and place of birth. Each kundli analysis is unique and the dosha detection is specific to your birth chart.",faqQ4Marriage:"Will this fix my marriage delay?",faqA4Marriage:"The calculator identifies doshas that may be causing marriage delay. Once detected, we recommend specific pujas and remedies that have helped thousands of users overcome marriage obstacles.",formPrivacyBanner:"100% Private & Secure",formTitle:"Enter your details",formSubtitle:"We'll generate your kundli to know your doshas",formNameLabel:"Enter Your Name",formNamePlaceholder:"Your Name",formGenderLabel:"Your Gender",formGenderMale:"Male",formGenderFemale:"Female",formProblemLabel:"What problem is bothering you?",formProblemMarriage:"Marriage",formProblemMoney:"Money",formProblemOther:"Others",formProblemHealth:"Health",formProblemEducation:"Education",formProblemCareer:"Career",formProblemOtherPlaceholder:"Please describe your problem",formProblemOtherHint:"Max 100 characters",formDobLabel:"Select Date of Birth",formDobInfo:"Your date of birth is used to calculate your dosha balance.",formTimeLabel:"Exact Time of Birth",formTimeInfo:"Birth time helps improve accuracy of the analysis.",formTimeUnknown:"I don't know my birth time",formTimeUnknownHelp:"Note - Without exact birth time, accuracy will be reduced. We'll run Moon-based checks only.",formPlaceLabel:"Enter your birth place",formPlaceInfo:"City and state/country help us refine your result.",formPlacePlaceholder:"City, State",formFooterNote:"Analysis Takes Only 60 seconds",formFooterNoteBefore:"Analysis Takes Only ",formFooterNoteBold:"60 seconds",formFooterNoteAfter:"",formCta:"Check My Dosha for FREE",formCtaCalculate:"Calculate my Dosha",calculating:"Calculating...",bookPuja:"Book Puja",resultPageTitle:"Find Puja Remedy for Free",resultPageSubtitle:"Analyse your kundli to find out which doshas (if any) appear in your Vedic chart—and see devotional remedies.",calculationSuccess:"Your dosha analysis is ready.",calculationError:"Something went wrong. Please try again.",formError:"Please correct the highlighted fields.",formNameRequired:"Name is required.",formGenderRequired:"Gender is required.",formDobRequired:"Date of birth is required.",formTimeRequired:"Time is required when birth time is known.",formPlaceRequired:"Birth place is required.",formPlaceSelectFromDropdown:"Please select a place from the dropdown list.",formAgeMarriageRestriction:"Please select appropriate problem areas. Marriage, financial, career, and business-related issues are applicable for users above 18 years.",locationError:"Could not get location coordinates. Please try again.",calculationResolvingPlace:"Resolving place…",info:"Info",resultTitle:"Your Dosha Analysis",resultSomeDoshas:"Some Doshas Have Been Detected",resultNoDoshas:"No Major Doshas Found",resultNoDoshasDesc:"Your birth chart shows no major doshas.",resultMangal:"Mangal Dosha",resultKaalSarp:"Kaal Sarp Dosha",resultPitra:"Pitra Dosha",resultSadeSati:"Shani Sade Sati",resultStatusPresent:"Present",resultStatusAbsent:"Absent",resultStatusInactive:"Inactive",resultExplanation:"Explanation",resultRemedies:"Remedies",resultEditForm:"Edit details",drStatus:"Status",drSeverity:"Severity",drType:"Type",drPhase:"Phase",drExplanation:"Explanation",drWhyPresent:"Why Present",drWhyAbsent:"Why Absent",drImpact:"Impact",drPlanetaryPositions:"Planetary Positions",drTraditionalRemedies:"Traditional Remedies",drDetailedAnalysis:"Detailed Analysis & Remedies",drBasedOnChart:"Based on your birth chart calculations",drDisclaimer:"While we follow established astrological rules, dosha interpretation can vary among astrologers. We recommend consulting an astrologer you trust if you wish to explore additional viewpoints.",drStatusPresent:"Present",drStatusAbsent:"Absent",drStatusInactive:"Inactive",drStatusActive:"Active",drStatusSuggested:"Suggested",drStatusNullified:"Present (Nullified)",drMangalName:"Mangal Dosha (Manglik)",drMangalDesc:"Mangal (Manglik/Kuja) Dosha — Linked with Mars in certain houses; traditionally associated with friction in relationships and decisiveness.",drMangalImpact:"Greater likelihood of friction in close relationships, impatience/anger spikes, or delays and stops/starts in marriage or partnerships.",drMangalRemedies:`Recite Hanuman Chalisa daily
59
60
  Fast on Tuesdays
60
61
  Donate red items like lentils or cloth
61
62
  Wear a coral gemstone after consultation`,drKaalSarpName:"Kaal Sarp Dosha",drKaalSarpDesc:"Kaal Sarp Dosha — All planets hemmed between Rahu and Ketu; often framed as a pattern indicating inner tension and transformation.",drKaalSarpImpact:"A pattern of inner restlessness and periodic setbacks; plans may feel blocked or get delayed despite effort, requiring extra persistence.",drKaalSarpRemedies:`Recite Maha Mrityunjaya Mantra 108 times daily
@@ -163,12 +164,12 @@ Visit Navagraha temples`,ctaKundliCreated:"3L+ Kundli Reports Created.",ctaCerti
163
164
  परामर्श के बाद लहसुनिया पहनें`,drOtherNavagrahaRemedies:`व्यापक नवग्रह शांति पूजा करें
164
165
  नवग्रह मंत्र का पाठ करें
165
166
  सभी नौ ग्रहों के लिए वस्तुओं का दान करें
166
- नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},an=w.createContext(null);function on(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function Eo(r){const{pathname:e,search:t,hash:s}=window.location,n=e.split("/").filter(Boolean);n[0]==="en"||n[0]==="hi"?n[0]=r:n.unshift(r),window.location.href="/"+n.join("/")+t+s}function Ao({locale:r,onLocaleChange:e,children:t}){const[s,n]=w.useState(()=>r||on());w.useEffect(()=>{if(r)n(r);else{const o=()=>n(on());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[r]);const a=o=>{e?e(o):Eo(o)},i=w.useMemo(()=>o=>nn[s]?.[o]??o,[s]);return l.jsx(an.Provider,{value:{locale:s,setLocale:a,t:i},children:t})}function Qr(){return w.useContext(an)}function Oo(){const e=Qr()?.locale==="hi";return l.jsx("div",{className:jo.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Me=r=>({width:r,height:r});function Xr(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"}),l.jsx("path",{d:"M12 9v4"}),l.jsx("path",{d:"M12 17h.01"})]})}function ln(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),l.jsx("path",{d:"m9 11 3 3L22 4"})]})}function br(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("path",{d:"M12 16v-4"}),l.jsx("path",{d:"M12 8h.01"})]})}function Ro(r){const{size:e=24,...t}=r;return l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:l.jsx("path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"})})}function Co(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),l.jsx("path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),l.jsx("path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"})]})}function Io(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),l.jsx("circle",{cx:"9",cy:"7",r:"4"}),l.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),l.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function No(r){const{size:e=24,...t}=r;return l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:l.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function Do(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"m5 12 7-7 7 7"}),l.jsx("path",{d:"M12 19V5"})]})}function cn(r){const{size:e=24,...t}=r;return l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:l.jsx("path",{d:"m6 9 6 6 6-6"})})}function Zr(r){const{size:e=24,className:t="",...s}=r;return l.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${t}`,style:{animation:"spin 1s linear infinite"},...Me(e),...s,children:l.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function $o(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),l.jsx("polyline",{points:"15 3 21 3 21 9"}),l.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function Lo(r){const{size:e=24,...t}=r;return l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...t,children:[l.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),l.jsx("path",{d:"M3 3v5h5"})]})}const Ke={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},Ze=r=>{const{priority:e,fetchPriority:t,width:s,height:n,...a}=r;return w.createElement("img",{...a,width:s??1,height:n??1,decoding:"async",loading:a.loading??(e?"eager":"lazy"),...t&&{fetchPriority:t}})},Uo="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function Mo({isFormComplete:r,onPress:e,labelDefault:t,labelFilled:s,isLoading:n=!1,mode:a="form",firstPuja:i,showingResults:o=!1,bookPujaLabel:c="Book Puja",loadingLabel:u="Calculating..."}){return a==="book-puja"&&i&&o?l.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Ke.bookPujaButton,children:l.jsxs("div",{className:Ke.bookPujaContent,children:[l.jsxs("div",{className:Ke.pujaInfo,children:[l.jsx("span",{className:Ke.pujaName,children:i.name}),i.price>0&&l.jsxs("div",{className:Ke.pujaPrice,children:[l.jsx("span",{className:Ke.priceLabel,children:"Starting from "}),l.jsxs("span",{className:Ke.priceAmount,children:["₹",i.price]})]})]}),l.jsxs("span",{className:Ke.bookButton,children:[c," →"]})]})}):l.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:r?Ke.ctaFilled:void 0,children:n?l.jsxs("span",{className:Ke.ctaFilledContent,children:[l.jsx(Zr,{className:"w-5 h-5 animate-spin"}),u]}):r?l.jsxs("span",{className:Ke.ctaFilledContent,children:[s,l.jsx(Ze,{src:Uo,alt:"",className:Ke.chevronRight,width:20,height:20,loading:"lazy"})]}):t})}const wr={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function Ko({bannerConfig:r,className:e="",imageComponent:t=Ze}){const s=t;return l.jsxs("section",{className:`${wr.bannerContainer} ${e}`,children:[l.jsx(s,{src:r.imageUrl,alt:r.alt,className:wr.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),l.jsx("div",{className:wr.ticker,children:l.jsx("div",{className:wr.tickerContent,children:r.tickerText})})]})}const Bo=112;function st({section:r,children:e,onImpression:t}){const s=w.useRef(null),n=w.useRef(!1);return w.useEffect(()=>{const a=s.current;if(!a)return;const i=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,t(r))},{threshold:.1,rootMargin:`0px 0px -${Bo}px 0px`});return i.observe(a),()=>i.disconnect()},[r,t]),l.jsx("div",{ref:s,children:e})}const Ct={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},Fo="https://srm-cdn.a4b.io/yoda/1770372045894.svg",qo=r=>{if(!r)return"";const[e,t,s]=r.split("-");return`${s}/${t}/${e}`};function Wo({id:r,value:e,onChange:t,onOpen:s,className:n=""}){const a=w.useRef(null),i=w.useMemo(()=>{const c=new Date,u=d=>String(d).padStart(2,"0");return`${c.getFullYear()}-${u(c.getMonth()+1)}-${u(c.getDate())}`},[]),o=()=>{s?.();const c=a.current;if(c&&typeof c.showPicker=="function")try{c.showPicker()}catch{c?.focus()}else c?.focus()};return l.jsxs("div",{className:`${Ct.wrap} ${n}`,children:[!e&&l.jsx("span",{className:Ct.placeholder,children:"Select Date of Birth"}),e&&l.jsx("div",{className:Ct.dateDisplay,children:qo(e)}),l.jsx("input",{ref:a,id:r,type:"date",className:Ct.input,value:e,max:i,onChange:c=>{const u=c.target.value,d=new Date,f=p=>String(p).padStart(2,"0"),m=`${d.getFullYear()}-${f(d.getMonth()+1)}-${f(d.getDate())}`;u&&u>m||t(u)},onClick:o,onFocus:o}),l.jsx("button",{type:"button",className:Ct.iconBtn,"aria-label":"Open date picker",onMouseDown:c=>c.preventDefault(),onClick:c=>{c.preventDefault(),c.stopPropagation(),o()},children:l.jsx(Ze,{className:Ct.iconImg,src:Fo,alt:"",width:22,height:22,loading:"lazy"})})]})}const be={wrap:"_wrap_spo2g_1",input:"_input_spo2g_6",iconBtn:"_iconBtn_spo2g_24",iconImg:"_iconImg_spo2g_38",timePopover:"_timePopover_spo2g_42",timePickerRow:"_timePickerRow_spo2g_58",timePickerSelect:"_timePickerSelect_spo2g_64",timePickerColon:"_timePickerColon_spo2g_80",meridiemToggle:"_meridiemToggle_spo2g_88",meridiemBtn:"_meridiemBtn_spo2g_97",meridiemActive:"_meridiemActive_spo2g_112",timePopoverActions:"_timePopoverActions_spo2g_117",timePopoverBtn:"_timePopoverBtn_spo2g_123",timePopoverOk:"_timePopoverOk_spo2g_142"},Go="https://srm-cdn.a4b.io/yoda/1770372014782.svg",un=r=>String(r).padStart(2,"0");function Ho(r){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(r);if(!e)return r;const t=Number(e[1]),s=e[2],n=t>=12?"PM":"AM";return`${t%12===0?12:t%12}:${s} ${n}`}function zo(r){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(r);if(!e)return{hour12:12,minute:"00",meridiem:"AM"};const t=Number(e[1]),s=e[2],n=t>=12?"PM":"AM";return{hour12:t%12===0?12:t%12,minute:s,meridiem:n}}function Vo(r){const e=Math.min(12,Math.max(1,r.hour12)),t=/^([0-5]\d)$/.test(r.minute)?r.minute:"00";let s=e%12;return r.meridiem==="PM"&&(s+=12),`${un(s)}:${t}`}function Jo({id:r,value:e,onChange:t,onOpen:s,placeholder:n="Exact Time of Birth",disabled:a=!1,className:i=""}){const o=w.useRef(null),[c,u]=w.useState(!1),[d,f]=w.useState({hour12:12,minute:"00",meridiem:"AM"});w.useEffect(()=>{const g=y=>{o.current&&(o.current.contains(y.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const m=()=>{a||(s?.(),f(zo(e||"12:00")),u(g=>!g))},p=()=>{const g=Vo(d);t(g),u(!1)};return l.jsxs("div",{className:`${be.wrap} ${i}`,ref:o,children:[l.jsx("input",{id:r,className:be.input,type:"text",value:e?Ho(e):"",readOnly:!0,disabled:a,placeholder:n,onClick:m}),l.jsx("button",{type:"button",className:be.iconBtn,"aria-label":"Open time picker",disabled:a,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),m()},children:l.jsx(Ze,{className:be.iconImg,src:Go,alt:"",width:22,height:22,loading:"lazy"})}),c&&!a&&l.jsxs("div",{className:be.timePopover,role:"dialog","aria-label":"Select time",children:[l.jsxs("div",{className:be.timePickerRow,children:[l.jsx("select",{className:be.timePickerSelect,value:d.hour12,onChange:g=>f(y=>({...y,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,y)=>y+1).map(g=>l.jsx("option",{value:g,children:g},g))}),l.jsx("span",{className:be.timePickerColon,children:":"}),l.jsx("select",{className:be.timePickerSelect,value:d.minute,onChange:g=>f(y=>({...y,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,y)=>un(y)).map(g=>l.jsx("option",{value:g,children:g},g))}),l.jsxs("div",{className:be.meridiemToggle,"aria-label":"AM/PM",children:[l.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="AM"?be.meridiemActive:""}`,onClick:()=>f(g=>({...g,meridiem:"AM"})),children:"AM"}),l.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="PM"?be.meridiemActive:""}`,onClick:()=>f(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),l.jsxs("div",{className:be.timePopoverActions,children:[l.jsx("button",{type:"button",className:be.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),l.jsx("button",{type:"button",className:`${be.timePopoverBtn} ${be.timePopoverOk}`,onClick:p,"aria-label":"OK",children:l.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:l.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function dn(r,e){const{visitorId:t,sessionId:s,problemStatements:n,language:a}=e;if(n.length!==0)try{await r.from("session_problem_statements").insert({visitor_id:t,session_id:s,problem_statements:n,language:a??"en"})}catch{}}async function hn(r,e,t){const{data:s,error:n}=await r.functions.invoke("calculate-dosha",{body:e,headers:t??{}});return n?{success:!1,error:n.message||"Calculation failed"}:s&&typeof s=="object"&&"success"in s?s.success===!0?s:{success:!1,error:s.error??"Unknown error",details:s.details}:{success:!1,error:"Invalid response from server"}}async function fn(r,e,t={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:a=!0,problemStatements:i=[],language:o="en"}=t;return a&&i.length>0&&await dn(r,{visitorId:s,sessionId:n,problemStatements:i,language:o}),hn(r,e,{"x-visitor-id":s,"x-session-id":n})}let _r=null;const Yo=(r,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():_r||(_r=new Promise((t,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),c=()=>{if(window.google?.maps?.places){t();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(c,50)};n.getAttribute("src")?c():(n.addEventListener("load",()=>c()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const a=document.createElement("script"),i=new URL("https://maps.googleapis.com/maps/api/js");i.searchParams.set("key",r),i.searchParams.set("libraries","places"),i.searchParams.set("loading","async"),e&&i.searchParams.set("language",e),a.src=i.toString(),a.async=!0,a.defer=!0,a.setAttribute("data-google-maps-places","true"),a.onload=()=>{const o=Date.now(),c=()=>{if(window.google?.maps?.places){t();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(c,50)};c()},a.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(a)}),_r),mn=(r={})=>{const{apiKey:e,language:t="en",restrictCountry:s}=r,[n,a]=w.useState(!1),[i,o]=w.useState([]),[c,u]=w.useState(!1),[d,f]=w.useState(null),m=w.useRef(null),p=w.useRef(null),g=w.useRef(null);w.useEffect(()=>{if(!e){a(!1),f(null);return}Yo(e,t).then(()=>{try{m.current=new google.maps.places.AutocompleteService;const k=document.createElement("div");p.current=new google.maps.places.PlacesService(k),g.current=new google.maps.places.AutocompleteSessionToken,a(!0),f(null)}catch(k){a(!1),f(k instanceof Error?k.message:"Failed to create Places services")}}).catch(k=>{a(!1),f(k instanceof Error?k.message:"Failed to load location service")})},[e,t]);const y=w.useCallback(async k=>{if(!k||k.length<2||!m.current){o([]);return}u(!0);try{const _={input:k,types:["(cities)"],sessionToken:g.current??void 0};s&&(_.componentRestrictions={country:s});const O=await new Promise((A,M)=>{m.current.getPlacePredictions(_,(E,N)=>{N===google.maps.places.PlacesServiceStatus.OK&&E?A(E):N===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?A([]):M(new Error(`Places API error: ${N}`))})});o(O.map(A=>({place_id:A.place_id,description:A.description,structured_formatting:{main_text:A.structured_formatting?.main_text||A.description,secondary_text:A.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),x=w.useCallback(async k=>{if(!p.current)return null;try{const _=await new Promise((L,De)=>{p.current.getDetails({placeId:k,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ye,Ae)=>{Ae===google.maps.places.PlacesServiceStatus.OK&&ye?L(ye):De(new Error(`Place details error: ${Ae}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const O=_.geometry?.location?.lat()||0,A=_.geometry?.location?.lng()||0;let M="",E="",N="";return _.address_components?.forEach(L=>{L.types.includes("locality")&&(M=L.long_name),L.types.includes("administrative_area_level_1")&&(E=L.long_name),L.types.includes("country")&&(N=L.long_name)}),{display_name:_.formatted_address||"",lat:O,lng:A,city:M,state:E,country:N}}catch{return null}},[]),b=w.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:i,isSearching:c,loadError:d,searchPlaces:y,getPlaceDetails:x,clearPredictions:b}},Qo=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Xo(){try{const r="analytics_visitor_id";let e=typeof localStorage<"u"?localStorage.getItem(r):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(r,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Zo(){try{const r="analytics_session_id";let e=typeof localStorage<"u"?localStorage.getItem(r):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(r,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function el(r){if(!r)return 0;const e=new Date(r);if(Number.isNaN(e.getTime()))return 0;const t=new Date;let s=t.getFullYear()-e.getFullYear();const n=t.getMonth()-e.getMonth();return(n<0||n===0&&t.getDate()<e.getDate())&&s--,s}const es=w.forwardRef(function({t:e,className:t="",initialValues:s,onValuesChange:n,onFormValidityChange:a,supabase:i,resolvePlace:o,onResult:c,onError:u,onLoadingChange:d,analytics:f,googleMapsApiKey:m},p){const g=T=>T.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[y,x]=w.useState(s?.name??""),[b,k]=w.useState(s?.gender??""),[_,O]=w.useState(s?.problems??[]),[A,M]=w.useState(s?.dateOfBirth??""),[E,N]=w.useState(s?.birthTime??""),[L,De]=w.useState(s?.birthTimeUnknown??!1),[ye,Ae]=w.useState(s?.birthPlace??""),[ee,te]=w.useState(s?.otherProblemText??""),[he,Je]=w.useState(null),[Oe,re]=w.useState(!1),[fe,Se]=w.useState(null),[Q,v]=w.useState({}),B=w.useCallback(T=>{const D=ie=>{const Ve=document.getElementById(ie);return Ve?(Ve.focus(),Ve.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(T==="name"){D("dosha-name");return}if(T==="gender"){const ie=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ie&&(ie.focus(),ie.scrollIntoView({behavior:"smooth",block:"center"}));return}if(T==="dateOfBirth"){D("dosha-dob");return}if(T==="birthTime"){D("dosha-time");return}T==="birthPlace"&&D("dosha-place")},[]),z=w.useRef(!1),G=w.useRef(!1),V=w.useRef(!1),K=w.useRef(!1),U=w.useRef(!1),J=w.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:Te,getPlaceDetails:Nt,clearPredictions:Fe}=mn({apiKey:m,language:"en"}),$e=w.useCallback(()=>{z.current||(z.current=!0,f?.trackFormFillInitiated?.())},[f]);w.useEffect(()=>{const T=D=>{J.current&&(J.current.contains(D.target)||re(!1))};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[]),w.useEffect(()=>{if(!Oe)return;if(ye.length<2){Fe();return}const T=window.setTimeout(async()=>{await Te(ye)},300);return()=>window.clearTimeout(T)},[ye,Fe,Oe,Te]);const yt=y.trim()!==""&&(b==="male"||b==="female")&&A!==""&&(E!==""||L)&&ye.trim()!=="";w.useEffect(()=>{a?.(yt)},[yt,a]),w.useEffect(()=>{n?.({name:y,gender:b,problems:_,otherProblemText:ee,dateOfBirth:A,birthTime:E,birthTimeUnknown:L,birthPlace:ye})},[y,b,_,ee,A,E,L,ye,n]),w.useEffect(()=>{!_.includes("formProblemOther")&&ee&&te("")},[_,ee]);const vt=w.useCallback(async(T,D)=>{if(!m)return"UTC";try{const ie=Math.floor(Date.now()/1e3),Ve=`https://maps.googleapis.com/maps/api/timezone/json?location=${T},${D}&timestamp=${ie}&key=${m}`,ke=await(await fetch(Ve)).json();return ke.status==="OK"&&ke.timeZoneId?ke.timeZoneId:"UTC"}catch{return"UTC"}},[m]),et=w.useCallback(async()=>{const T=(ce,Pe,qe=!1)=>{Pe&&(v(Le=>({...Le,[Pe]:ce})),B(Pe)),Se(qe?ce:null),u?.(ce)};if(v({}),Se(null),!i){T(e("calculationError"));return}if(!y.trim()){T(e("formNameRequired"),"name");return}if(b!=="male"&&b!=="female"){T(e("formGenderRequired"),"gender");return}if(!A){T(e("formDobRequired"),"dateOfBirth");return}if(!L&&!E){T(e("formTimeRequired"),"birthTime");return}const D=ye.trim();if(!D){T(e("formPlaceRequired"),"birthPlace");return}const ie=g(D).trim();if(!ie){T(e("formPlaceRequired"),"birthPlace");return}const Ve=el(A),it=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),ke=_.some(ce=>it.has(ce));if(Ve<18&&ke){T(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){T(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,Pe,qe;if(he)ce=he.lat,Pe=he.lon,he.tz?qe=he.tz:(qe=await vt(ce,Pe),Je({...he,tz:qe}));else if(o){const ve=await o(D);if(!ve){T(e("locationError")),d?.(!1);return}ce=ve.lat,Pe=ve.lon,qe=ve.tz}else{T(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Le={problemAreaValues:[..._.filter(ve=>ve!=="formProblemOther").map(ve=>e(ve)).filter(Boolean),..._.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:y.trim(),gender:b==="male"?"M":"F",date:A,time:L?"":E||"12:00",unknownTime:L,tz:qe||"UTC",lat:ce,lon:Pe,place:ie,problemArea:void 0};Le.problemArea=Le.problemAreaValues.length>0?Le.problemAreaValues.join(", "):void 0;const er=Xo(),C=Zo(),ne=Le.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",je=await fn(i,Le,{visitorId:er,sessionId:C,trackProblemStatements:!0,problemStatements:ne,language:xe});if(je.success){Se(null);const[ve,tr,rr]=(Le.date||"").split("-").map(Number),Pr=Le.time||"12:00",[ot,sr]=Pr.split(":").map(Ar=>parseInt(Ar,10)||0);c?.(je,{day:rr||1,month:tr||1,year:ve||2e3,hour:ot,minute:sr,lat:ce,lon:Pe,tzone:5.5})}else{let ve=je.error??e("calculationError");(ve.includes("Expected 'M' | 'F'")||ve.includes("gender"))&&(ve=e("formGenderRequired")),T(ve)}}catch(ce){const Pe=ce instanceof Error?ce.message:String(ce);T(Pe)}finally{d?.(!1)}},[i,o,he,ye,y,b,A,E,L,_,e,u,d,f,c,vt,B]);w.useImperativeHandle(p,()=>({submit:et}),[et]);const Zt=Qo.map(T=>({key:T,label:e(T)}));return l.jsxs(q.FormContainer,{className:t,"aria-label":e("formTitle"),children:[l.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),l.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),l.jsx("div",{onFocusCapture:()=>{$e(),f?.trackNameSectionClicked?.()},children:l.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[l.jsx(q.FormTextInput,{id:"dosha-name",value:y,onChange:T=>{const D=T.target.value;D&&!G.current&&(G.current=!0,f?.trackNameSectionFilled?.()),x(D),Q.name&&v(ie=>({...ie,name:void 0})),fe&&Se(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),l.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[l.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:b,onChange:T=>{k(T),Q.gender&&v(D=>({...D,gender:void 0})),fe&&Se(null)}}),Q.gender&&l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.gender})]}),l.jsxs(q.FormField,{id:"dosha-problems",label:e("formProblemLabel"),children:[l.jsx(q.FormTagPills,{id:"dosha-problems",options:Zt,selected:_,onChange:T=>{O(T),T.includes("formProblemOther")||te("")}}),_.includes("formProblemOther")&&l.jsxs("div",{style:{marginTop:"8px"},children:[l.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:T=>{const D=T.target.value.slice(0,100);te(D)},placeholder:e("formProblemOtherPlaceholder")}),l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),l.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:l.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[l.jsx(Wo,{id:"dosha-dob",value:A,onOpen:()=>{$e(),f?.trackDobClicked?.()},onChange:T=>{T&&!V.current&&(V.current=!0,f?.trackDobFilled?.()),M(T),Q.dateOfBirth&&v(D=>({...D,dateOfBirth:void 0})),fe&&Se(null)}}),Q.dateOfBirth&&l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.dateOfBirth})]})}),l.jsx(q.FormField,{id:"dosha-time",label:e("formTimeLabel"),required:!0,children:l.jsxs("div",{style:{minHeight:Q.birthTime?"72px":"48px",transition:"min-height 0.2s"},children:[l.jsx(Jo,{id:"dosha-time",value:E,onOpen:()=>{$e(),f?.trackTimeClicked?.()},onChange:T=>{T&&!K.current&&(K.current=!0,f?.trackTimeFilled?.()),N(T),Q.birthTime&&v(D=>({...D,birthTime:void 0})),fe&&Se(null)},disabled:L}),Q.birthTime&&l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),l.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:L,onChange:T=>{$e(),f?.trackTimeCheckboxClicked?.(),De(T),T&&Q.birthTime&&v(D=>({...D,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),l.jsx("div",{onFocusCapture:()=>{$e(),f?.trackPlaceOfBirthClicked?.()},children:l.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:l.jsxs("div",{ref:J,style:{position:"relative"},children:[l.jsx(q.FormLocationInput,{id:"dosha-place",value:ye,onChange:T=>{const D=g(T.target.value);Ae(D),Je(null),re(!0),D&&!U.current&&(U.current=!0,f?.trackPlaceOfBirthChosen?.(D)),Q.birthPlace&&v(ie=>({...ie,birthPlace:void 0})),fe&&Se(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&l.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Oe&&se.length>0&&l.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(T=>l.jsxs("button",{type:"button",onClick:async()=>{if(Ae(g(T.description)),Nt){const D=await Nt(T.place_id);D&&(Je({lat:D.lat,lon:D.lng}),Q.birthPlace&&v(ie=>({...ie,birthPlace:void 0})),fe&&Se(null))}Fe(),re(!1),U.current||(U.current=!0,f?.trackPlaceOfBirthChosen?.(T.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:D=>{D.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:D=>{D.currentTarget.style.backgroundColor="transparent"},onFocus:D=>{D.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:D=>{D.currentTarget.style.backgroundColor="transparent"},children:[l.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:T.structured_formatting?.main_text??T.description}),T.structured_formatting?.secondary_text&&l.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:T.structured_formatting.secondary_text})]},T.place_id))}),Oe&&m&&me&&l.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Oe&&m&&!me&&le&&l.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),l.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),l.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&l.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[l.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[l.jsx("circle",{cx:"12",cy:"12",r:"10"}),l.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),l.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),l.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),It=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("div",{ref:t,className:`animate-pulse rounded-md bg-muted ${r}`,...e}));It.displayName="Skeleton";const nt=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("div",{ref:t,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${r}`,...e}));nt.displayName="Card";const mt=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("div",{ref:t,className:`flex flex-col space-y-1.5 p-6 ${r}`,...e}));mt.displayName="CardHeader";const pt=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("h3",{ref:t,className:`text-2xl font-semibold leading-none tracking-tight ${r}`,...e}));pt.displayName="CardTitle";const kr=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("p",{ref:t,className:`text-sm text-muted-foreground ${r}`,...e}));kr.displayName="CardDescription";const gt=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("div",{ref:t,className:`p-6 pt-0 ${r}`,...e}));gt.displayName="CardContent";const Qt=Ce.forwardRef(({className:r="",size:e="default",variant:t="default",...s},n)=>{const a={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},i={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return l.jsx("button",{ref:n,type:"button",className:`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${a[e]} ${i[t]} ${r}`,...s})});Qt.displayName="Button";function pn({puja:r,doshaType:e,language:t,onBookClick:s,imageComponent:n=Ze,analytics:a}){const i=n,o=t?.toLowerCase().startsWith("hi"),c=Jr(r,t),u=tn(r,t),d=rn(r.schedule_date_ist,t),f=Yr(r,t),m=sn(r,t),p=async()=>{if(a?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:f,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(f,"_blank","noopener,noreferrer")};return l.jsx(nt,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:l.jsxs("div",{className:"relative",children:[l.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:l.jsx("span",{className:"inline-flex items-center px-2 py-1 text-[10px] font-medium bg-destructive/90 text-destructive-foreground rounded-br-md shadow-sm",children:o?"सीमित सीटें":"Limited Seats"})}),m&&l.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:l.jsx(i,{src:m,alt:c,className:"w-full h-full object-contain",loading:"lazy"})}),l.jsxs("div",{className:"p-3 space-y-2",children:[l.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:c}),r.temple_name&&l.jsx("p",{className:"text-sm text-muted-foreground",children:u}),r.schedule_date_ist&&l.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),r.individual_pack_price_inr>0&&l.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${r.individual_pack_price_inr} से शुरू`:`Starting from ₹${r.individual_pack_price_inr}`}),l.jsxs(Qt,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await p()},children:[o?"पूजा बुक करें":"Book Puja",l.jsx($o,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),l.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const at={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function gn({t:r,className:e="",bannerType:t="generic"}){const s=r("whatFromAnalysisTitle"),n=t==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",a=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return l.jsxs("section",{className:`${at.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[l.jsx("h2",{id:"what-from-analysis-heading",className:at.heading,children:s}),l.jsx("ol",{className:at.list,children:a.map(({titleKey:i,descKey:o},c)=>l.jsxs("li",{className:at.item,children:[l.jsx("span",{className:at.stepNumber,"aria-hidden":"true",children:c+1}),l.jsxs("div",{className:at.itemContent,children:[l.jsx("span",{className:at.itemTitle,children:r(i)}),l.jsx("span",{className:at.itemDesc,children:r(o)})]})]},i))})]})}const tl={marriage:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137437775.webp",alt:"Marriage dosha analysis banner",tickerText:"★ 4.9 Rated By Users Facing Marriage Delay"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137493287.webp",alt:"विवाह दोष विश्लेषण बैनर",tickerText:"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड"}},generic:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137415503.webp",alt:"Dosha analysis banner",tickerText:"★ 4.9 Rated By Users Seeking Clarity"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137476046.webp",alt:"दोष विश्लेषण बैनर",tickerText:"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},rl={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function yn(r,e){let t="generic";if(r){for(const[s,n]of Object.entries(rl))if(r.includes(s)){t=n;break}}return tl[t][e]}function sl(r){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(r)}function Sr(){return sl("utm_term")}const nl=w.lazy(()=>Promise.resolve().then(()=>jl).then(r=>({default:r.DoshaResultsFull}))),al="https://srm-cdn.a4b.io/yoda/1770362904947.svg",il="https://srm-cdn.a4b.io/yoda/1770375694934.svg",ol="https://srm-cdn.a4b.io/yoda/1770375720933.svg",ll="https://srm-cdn.a4b.io/yoda/1770707793537.svg",cl="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function vn(r){const e=new Set([r]);switch(r){case"kaal-sarp":e.add("kaalSarp"),e.add("kaalsarp"),e.add("kaal_sarp");break;case"shani":e.add("sadeSati"),e.add("shaniSadeSati"),e.add("sade-sati");break;case"mangal":e.add("mangalDosha"),e.add("manglik");break;case"pitra":e.add("pitru"),e.add("pitraDosha");break}return Array.from(e)}function xr(r){if(!r)return!1;const e=r.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function bn(r){if(!r)return 2;const e=r.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function wn(r){if(!r||typeof window>"u")return r;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return r;const t=new URL(r,window.location.href);return e.forEach((s,n)=>{t.searchParams.set(n,s)}),t.toString()}catch{return r}}function ts(r){const e=[];return xr(r.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof r.kaalSarpSeverity=="string"?r.kaalSarpSeverity:void 0}),xr(r.pitra)&&e.push({type:"pitra",severity:typeof r.pitraSeverity=="string"?r.pitraSeverity:void 0}),xr(r.shaniSadeSati||r.sadeSati)&&e.push({type:"shani",severity:typeof r.sadeSatiSeverity=="string"?r.sadeSatiSeverity:void 0}),xr(r.mangal)&&!r.mangal?.toLowerCase().includes("nullified")&&e.push({type:"mangal",severity:typeof r.mangalSeverity=="string"?r.mangalSeverity:void 0}),e.length===0?null:(e.sort((t,s)=>bn(s.severity)-bn(t.severity)),e[0]?.type??null)}function ul({t:r}){return l.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[l.jsxs("span",{className:q.footerShellStyles.badge,children:[l.jsx(Ze,{src:il,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),r("ctaKundliCreated")]}),l.jsxs("span",{className:q.footerShellStyles.badge,children:[l.jsx(Ze,{src:ol,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),r("ctaCertified")]}),l.jsxs("span",{className:q.footerShellStyles.badge,children:[l.jsx(Ze,{src:ll,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),r("ctaSecurePayment")]})]})}const dl=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],hl=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function fl({className:r="",logoUrl:e=al,languageSelector:t,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:a,supabaseUrl:i,supabaseAnonKey:o,googleMapsApiKey:c,supabase:u,resolvePlace:d,onResult:f,onError:m,renderPujaCard:p,isLoadingPujas:g=!1,renderKundali:y,kundaliSectionId:x="kundali-chart-section",analytics:b,getFirstPujaInfo:k,onBookPujaClick:_,imageComponent:O=Ze}){const A=w.useMemo(()=>{if(u)return u;if(i&&o)try{return zs(i,o)}catch{return null}return null},[u,i,o]),M=O,E=Qr(),N=E?.t??(C=>C),L=E?.locale??"en",De=E?.setLocale,ye=L.toLowerCase().startsWith("hi"),Ae=w.useRef(null),ee=w.useRef(null),[te,he]=w.useState(!1),[Je,Oe]=w.useState(!1),[re,fe]=w.useState(null),[Se,Q]=w.useState(null),[v,B]=w.useState(void 0),[z,G]=w.useState(!1),[V,K]=w.useState([]),[U,J]=w.useState(!1),[se,me]=w.useState(null),le=w.useRef(!1);w.useEffect(()=>{le.current||(le.current=!0,b?.trackDoshaCalculatorWebView?.())},[]);const Te=!p||!k;w.useEffect(()=>{if(!Te||!A)return;let C=!0;return J(!0),_o(A).then(ne=>{C&&K(ne)}).finally(()=>{C&&J(!1)}),()=>{C=!1}},[Te,A]);const Nt=w.useCallback(C=>{const ne=Ys(V,C);return ne?l.jsx(pn,{puja:ne,doshaType:C,language:L,imageComponent:O,analytics:b}):null},[V,L,O,b]),Fe=w.useCallback(C=>{const ne=Ys(V,C);return ne?{name:Jr(ne,L),price:ne.individual_pack_price_inr,link:Yr(ne,L)}:null},[V,L]),$e=p??Nt,yt=k??Fe,vt=g||!p&&U,[et,Zt]=w.useState(()=>{const C=typeof window<"u"?Sr():null;return yn(C,L)}),[T,D]=w.useState(()=>{if(typeof window>"u")return"generic";const C=Sr();return C&&C.toLowerCase().includes("marriage")?"marriage":"generic"});w.useEffect(()=>{const C=Sr(),ne=yn(C,L);Zt(ne);let xe="generic";C&&C.toLowerCase().includes("marriage")&&(xe="marriage"),D(xe)},[L]);const[ie,Ve]=w.useState(!1);w.useEffect(()=>{const C=Sr();C&&C.toLowerCase().includes("what-you")&&Ve(!0)},[]);const it=()=>{Ae.current?.scrollIntoView({behavior:"smooth"})},ke=w.useCallback(C=>{b?.trackDoshaSectionImpression?.({section:C,timestamp:new Date().toISOString()})},[b]),ce=(C,ne)=>{if(fe(C),Q(ne??null),G(!1),C.summary){const xe=C.summary,je=ts(xe);if(je){const ve=vn(je).map(tr=>yt(tr)).find(Boolean)??null;me(ve)}else me(null)}else me(null);f?.(C,ne)};w.useEffect(()=>{if(k||!re?.summary)return;const C=ts(re.summary);if(!C){me(null);return}const ne=vn(C).map(xe=>Fe(xe)).find(Boolean)??null;me(ne)},[Fe,k,re]);const Pe=()=>{G(!0),window.scrollTo({top:0,behavior:"smooth"})},qe=()=>{if(re&&!z&&se){if(se.link){const C=wn(se.link);b?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:C,isOldDosha:!1})}if(_)_();else if(se.link){const C=wn(se.link);window.open(C,"_blank","noopener,noreferrer")}return}console.log("supabase",A),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),A&&ee.current?(b?.trackFloatingCtaClicked?.(te?ar.all_fields_filled:ar.fields_not_filled),te||it(),ee.current.submit()):(b?.trackFloatingCtaClicked?.(ar.fields_not_filled),it())},er=s&&!n?l.jsxs("button",{type:"button",onClick:()=>{De&&De(ye?"en":"hi")},"aria-label":ye?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!De,children:[l.jsx(M,{src:cl,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),l.jsx("span",{children:ye?"English":"हिंदी"})]}):null;return l.jsxs("div",{className:r,children:[l.jsx(q.PageHeader,{t:N,logoUrl:e,languageSelector:er,showLanguageSelector:s}),l.jsx(q.MarqueeStrip,{children:l.jsx(ul,{t:N})}),!re&&l.jsx(st,{section:"banner",onImpression:ke,children:l.jsx(Ko,{bannerConfig:et,imageComponent:O})}),l.jsx("main",{className:"pb-28",children:re?l.jsx(st,{section:"result",onImpression:ke,children:l.jsx(w.Suspense,{fallback:l.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[l.jsx(It,{className:"h-12 w-3/4 mx-auto"}),l.jsx(It,{className:"h-32 w-full"}),l.jsx(It,{className:"h-48 w-full"}),l.jsx(It,{className:"h-48 w-full"})]}),children:l.jsx(nl,{result:re,t:N,onEdit:z?void 0:Pe,inlineEditForm:z?l.jsx(es,{ref:ee,t:N,initialValues:v,onValuesChange:B,onFormValidityChange:he,supabase:A??void 0,resolvePlace:d,googleMapsApiKey:c,onResult:ce,onError:m,onLoadingChange:Oe,analytics:b}):void 0,renderPujaCard:$e,isLoadingPujas:vt,renderKundali:y,kundaliSectionId:x,birthDetails:Se,supabase:A,language:E?.locale??"en",readMoreReviewsHref:a,analytics:b,problemArea:(()=>{const C=v?.problems||[],ne=C.filter(je=>je!=="formProblemOther").map(je=>N(je)).filter(Boolean),xe=v?.otherProblemText?.trim();return C.includes("formProblemOther")&&xe&&ne.push(xe),ne.join(", ")})(),problemAreaIds:v?.problems||[],customProblemText:v?.otherProblemText||""})})}):l.jsxs(l.Fragment,{children:[ie&&l.jsx(st,{section:"what_from_analysis",onImpression:ke,children:l.jsx(gn,{t:N,bannerType:T})}),l.jsx(st,{section:"form",onImpression:ke,children:l.jsx("div",{ref:Ae,children:l.jsx(es,{ref:ee,t:N,initialValues:v,onValuesChange:B,onFormValidityChange:he,supabase:A??void 0,resolvePlace:d,googleMapsApiKey:c,onResult:ce,onError:m,onLoadingChange:Oe,analytics:b})})}),!ie&&l.jsx(st,{section:"what_from_analysis",onImpression:ke,children:l.jsx(gn,{t:N,bannerType:T})}),l.jsx(st,{section:"user_reviews",onImpression:ke,children:l.jsx(q.UserReviewsSection,{t:C=>{if(T==="marriage"){if(C==="feedbackTitle")return N("feedbackTitleMarriage");if(C.startsWith("feedbackTestimonial")){const xe=`feedbackTestimonialMarriage${C.replace("feedbackTestimonial","")}`,je=N(xe);return je===xe?N(C):je}}return N(C)},readMoreHref:a,onReadMore:b?.trackReadMoreReviewsClicked?()=>b.trackReadMoreReviewsClicked():void 0})}),l.jsx(st,{section:"faq",onImpression:ke,children:l.jsx(q.FAQAccordion,{t:N,items:T==="marriage"?hl:dl,defaultOpenIndex:0,onItemOpen:C=>b?.trackFaqQuestionClicked?.(C)})}),l.jsx(st,{section:"contact",onImpression:ke,children:l.jsx(q.ContactUsSection,{title:N("contactTitle"),brandName:N("contactBrandName"),whatsAppLine:N("contactWhatsAppDomestic"),emailLine:N("contactEmail")})})]})}),!(re&&!z&&ts(re.summary)===null)&&l.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&l.jsx(Oo,{}),l.jsx(Mo,{isFormComplete:te,onPress:qe,labelDefault:N("formCta"),labelFilled:N("formCtaCalculate"),loadingLabel:N("calculating"),isLoading:Je,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:N("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},ml=[{key:"mangal",labelKey:"resultMangal",summaryKey:"mangal"},{key:"kaalSarp",labelKey:"resultKaalSarp",summaryKey:"kaalSarp"},{key:"pitra",labelKey:"resultPitra",summaryKey:"pitra"},{key:"sadeSati",labelKey:"resultSadeSati",summaryKey:"shaniSadeSati"}];function Xt(r){if(!r)return!1;const e=r.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function pl(r,e){if(Array.isArray(r))return r.find(s=>(s.name??s.type)===e);if(r&&typeof r=="object"&&e in r){const t=r[e];if(!t)return;const s=typeof t.remedies=="string"?t.remedies:Array.isArray(t.remedies)?t.remedies.join(`
167
- `):void 0;return{explanation:t.explanation,remedies:s}}}function gl(r,e){if(!r)return"";const t=r.toLowerCase();return t.includes("nullified")||t==="present"||t==="active"||t==="partial"||t==="suggested"?e("resultStatusPresent"):t==="absent"?e("resultStatusAbsent"):t==="inactive"?e("resultStatusInactive"):r}function yl({result:r,t:e,onEdit:t,className:s=""}){const n=r.summary??{},a=r.details??{},i=n.shaniSadeSati??n.sadeSati,o=Xt(n.mangal)||Xt(n.kaalSarp)||Xt(n.pitra)||Xt(i);return l.jsxs("section",{className:`${oe.section} ${s}`,"aria-labelledby":"dosha-results-heading",children:[l.jsx("h2",{id:"dosha-results-heading",className:o?`${oe.heading} ${oe.headingSuccess}`:oe.heading,children:e(o?"resultSomeDoshas":"resultNoDoshas")}),o?l.jsx("div",{children:ml.map(({key:c,labelKey:u,summaryKey:d})=>{const f=d==="shaniSadeSati"?i:n[d],m=Xt(f),p=pl(a,c==="sadeSati"?"sadeSati":c),g=p?.explanation,y=typeof p?.remedies=="string"?p.remedies:void 0;return l.jsxs("div",{className:`${oe.card} ${m?oe.cardPresent:oe.cardAbsent}`,children:[l.jsxs("div",{className:oe.cardHeader,children:[l.jsx("span",{className:oe.doshaName,children:e(u)}),l.jsx("span",{className:`${oe.badge} ${m?oe.badgePresent:f==="inactive"?oe.badgeInactive:oe.badgeAbsent}`,children:gl(f,e)})]}),(g||y)&&l.jsxs("div",{className:oe.body,children:[g&&l.jsxs("div",{children:[l.jsx("div",{className:oe.bodyLabel,children:e("resultExplanation")}),l.jsx("p",{className:oe.accordionContent,children:g})]}),y&&l.jsxs("div",{style:{marginTop:g?"0.75rem":0},children:[l.jsx("div",{className:oe.bodyLabel,children:e("resultRemedies")}),l.jsx("p",{className:oe.accordionContent,children:y})]})]})]},c)})}):l.jsxs("div",{className:oe.noDoshas,children:[l.jsx("p",{children:e("resultNoDoshas")}),l.jsx("p",{className:oe.noDoshasDesc,children:e("resultNoDoshasDesc")})]}),t&&l.jsx("button",{type:"button",className:oe.editBtn,onClick:t,"aria-label":e("resultEditForm"),children:e("resultEditForm")})]})}const jr=Ce.forwardRef(({className:r="",variant:e="default",...t},s)=>{const n={default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive/10 text-destructive",outline:"border-border text-muted-foreground bg-transparent"};return l.jsx("div",{ref:s,className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${n[e]} ${r}`,...t})});jr.displayName="Badge";const rs=Ce.createContext(null);function _n({type:r="single",collapsible:e=!0,className:t="",children:s,onValueChange:n}){const[a,i]=Ce.useState(null),o=Ce.useCallback(c=>{i(u=>{const d=u===c?e?null:u:c;return n?.(d),d})},[e,n]);return l.jsx(rs.Provider,{value:{value:a,onToggle:o},children:l.jsx("div",{className:t,children:s})})}function kn({value:r,className:e="",children:t}){return l.jsx("div",{"data-state":r,className:`border-b border-border ${e}`,children:t})}function Sn({className:r="",children:e,value:t}){const s=Ce.useContext(rs),n=s?.value===t;return l.jsxs("button",{type:"button",onClick:()=>s?.onToggle(t),className:`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${r}`,"aria-expanded":n,children:[e,l.jsx(cn,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function xn({className:r="",children:e,value:t}){return Ce.useContext(rs)?.value===t?l.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${r}`,children:e}):null}const ss=new Map,jn=1800*1e3;function vl(r,e,t){return`D1|${e}|svg|${r.day}-${r.month}-${r.year}-${r.hour}-${r.minute}-${r.lat}-${r.lon}-${r.tzone}|${t}`}function bl(r){const e=ss.get(r);if(e&&Date.now()-e.timestamp<jn)return e.svg;try{const t=sessionStorage.getItem(`kundali_${r}`);if(t){const s=JSON.parse(t);if(Date.now()-s.timestamp<jn)return ss.set(r,s),s.svg;sessionStorage.removeItem(`kundali_${r}`)}}catch{}return null}function wl(r,e){const t={svg:e,timestamp:Date.now()};ss.set(r,t);try{sessionStorage.setItem(`kundali_${r}`,JSON.stringify(t))}catch{}}function _l(r){try{const t=new DOMParser().parseFromString(r,"image/svg+xml"),s=t.querySelector("svg");return s?(s.removeAttribute("width"),s.removeAttribute("height"),s.getAttribute("viewBox")||s.setAttribute("viewBox","0 0 350 350"),s.setAttribute("preserveAspectRatio","xMidYMid meet"),s.setAttribute("style","width:100%;height:auto;display:block;"),new XMLSerializer().serializeToString(t)):r}catch(e){return console.error("[kundaliChart] SVG transform error:",e),r}}async function Tn(r,e){const{birthDetails:t,chartType:s,language:n,signal:a}=e,i=vl(t,s,n),o=bl(i);if(o)return o;const c=await r.functions.invoke("get-kundali-chart",{body:{...t,chartType:s,language:n}});if(a?.aborted)throw new DOMException("Aborted","AbortError");if(c.error)throw new Error(c.error.message||"Failed to fetch kundali chart");const u=c.data?.data?.svg;if(!u)throw new Error("No SVG data in response");const d=_l(u);return wl(i,d),d}function Pn({birthDetails:r,supabase:e,language:t,t:s}){const[n,a]=w.useState("North"),[i,o]=w.useState("idle"),[c,u]=w.useState(""),[d,f]=w.useState(""),m=w.useRef(null),p=w.useRef(null),y=(t||"").toLowerCase().startsWith("hi")?"hi":"en",x=w.useCallback(async _=>{m.current&&m.current.abort();const O=new AbortController;m.current=O,o("loading"),f("");try{const A=await Tn(e,{birthDetails:r,chartType:_,language:y,signal:O.signal});O.signal.aborted||(u(A),o("success"))}catch(A){if(A instanceof Error&&A.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",A),O.signal.aborted||(f(A instanceof Error?A.message:"Failed to load chart"),o("error"))}},[r,e,y]);w.useEffect(()=>(x(n),()=>{m.current&&m.current.abort()}),[n,x]);const b=_=>{_!==n&&a(_)},k=()=>{x(n)};return l.jsxs(nt,{ref:p,className:"spiritual-glow border border-primary/10",children:[l.jsxs(mt,{className:"pb-3",children:[l.jsx(pt,{className:"text-xl font-bold",children:s("drYourKundali")}),l.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[l.jsx(Qt,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>b("North"),children:s("kundaliChartNorth")}),l.jsx(Qt,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>b("South"),children:s("kundaliChartSouth")})]})]}),l.jsx(gt,{children:l.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[i==="loading"&&l.jsx(It,{className:"w-full aspect-square rounded-lg"}),i==="success"&&c&&l.jsx("div",{className:"w-full aspect-square",dangerouslySetInnerHTML:{__html:c}}),i==="error"&&l.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border",children:[l.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s("kundaliChartLoadError")}),l.jsxs(Qt,{type:"button",variant:"outline",size:"sm",onClick:k,className:"gap-2",children:[l.jsx(Lo,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const kl=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],En=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:Co,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:Io,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:No,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:Ro,summaryKey:"mangal",severityKey:"mangalSeverity"}];function Sl(r,e){const t=new Set([r]);switch(e&&t.add(e),r){case"kaal-sarp":t.add("kaalSarp"),t.add("kaalsarp"),t.add("kaal_sarp");break;case"shani":t.add("sadeSati"),t.add("shaniSadeSati"),t.add("sade-sati");break;case"mangal":t.add("mangalDosha"),t.add("manglik");break;case"pitra":t.add("pitru"),t.add("pitraDosha");break}return Array.from(t)}function Be(r){if(!r)return!1;const e=r.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Tr(r){return r?r.toLowerCase().includes("nullified"):!1}function An(r,e){if(Array.isArray(r)){const t=r.find(a=>(a.name??a.type)===e);if(!t)return;const s=typeof t.remedies=="string"?t.remedies:Array.isArray(t.remedies)?t.remedies.join(`
168
- `):void 0,n=Array.isArray(t.placements)?t.placements:void 0;return{explanation:t.explanation,remedies:s,placements:n}}if(r&&typeof r=="object"&&e in r){const t=r[e];if(!t)return;const s=typeof t.remedies=="string"?t.remedies:Array.isArray(t.remedies)?t.remedies.join(`
169
- `):void 0;return{explanation:t.explanation,remedies:s,placements:t.placements}}}function On(r,e){if(!r)return"";const t=r.toLowerCase();return t.includes("nullified")?e("drStatusNullified"):t==="present"||t==="active"||t==="partial"||t==="suggested"?e("drStatusPresent"):t==="absent"?e("drStatusAbsent"):t==="inactive"?e("drStatusInactive"):r}function Rn(r){if(!r)return 2;const e=r.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function Cn(r,e){if(!r)return e("drSeverityMedium");const t=r.toLowerCase();return e(t==="severe"||t==="high"?"drSeverityHigh":t==="moderate"||t==="medium"?"drSeverityMedium":t==="mild"||t==="low"?"drSeverityLow":"drSeverityMedium")}function xl(r){return!r||/[\u0900-\u097F]/.test(r)?!1:/[A-Za-z]/.test(r)}function In({result:r,t:e,onEdit:t,className:s="",kundaliSectionId:n,feedbackEmail:a="pujaseva@appsforbharat.com",renderPujaCard:i,isLoadingPujas:o=!1,renderKundali:c,birthDetails:u,supabase:d,language:f="en",readMoreReviewsHref:m,inlineEditForm:p,analytics:g,problemArea:y,problemAreaIds:x,customProblemText:b}){const[k,_]=w.useState({}),[O,A]=w.useState(!1),M=!c&&u&&d,E=r.summary??{},N=r.details??{};w.useEffect(()=>{if(!y||!y.trim()||!d){A(!1);return}A(!0),_({}),(async()=>{const B={},G=["mangal","kaal-sarp","pitra","shani"].filter(K=>K==="mangal"?Be(E.mangal)&&!Tr(E.mangal):K==="kaal-sarp"?Be(E.kaalSarp):K==="pitra"?Be(E.pitra):K==="shani"?Be(E.shaniSadeSati??E.sadeSati):!1);console.log("[DoshaResultsFull] Generating impacts for:",G,"problemArea:",y);const V=G.map(async K=>{try{const U={formProblemMarriage:"marriage",formProblemMoney:"financial",formProblemHealth:"health",formProblemEducation:"education",formProblemCareer:"career",formProblemBusiness:"business",formProblemFamily:"family",formProblemFinancial:"financial",formProblemOther:"other"},J=x?.filter(le=>le!=="formProblemOther").map(le=>U[le]||le.toLowerCase()).filter(Boolean)||[];x?.includes("formProblemOther")&&b?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${K}`,{originalProblemAreaIds:x,mappedProblemAreaIds:J,problemArea:y,problemAreaId:se,customProblemText:b,language:f?.toLowerCase().startsWith("hi")?"hi":"en"});const me=await d.functions.invoke("generate-impact",{body:{doshaType:K,problemArea:y,problemAreaId:se,problemAreaIds:J,customProblemText:b,language:f?.toLowerCase().startsWith("hi")?"hi":"en"}});if(console.log(`[DoshaResultsFull] Impact response for ${K}:`,me.data),me.error){console.error(`[DoshaResultsFull] Error generating impact for ${K}:`,me.error);return}me.data?.impactText&&(B[K]={title:me.data.impactTitle||e("drImpactIfPresent"),text:me.data.impactText})}catch(U){console.error(`[DoshaResultsFull] Failed to generate impact for ${K}:`,U)}});await Promise.all(V),console.log("[DoshaResultsFull] Final personalized impacts:",B),_(B),A(!1)})()},[y,x,b,f,d,E]),w.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const L=E.shaniSadeSati??E.sadeSati,De=[{summaryKey:"grahan",detailKey:"grahan",labelKey:"drOtherGrahan",descKey:"drOtherGrahanDesc",impactKey:"drOtherGrahanImpact",remediesKey:"drOtherGrahanRemedies"},{summaryKey:"shrapit",detailKey:"shrapit",labelKey:"drOtherShrapit",descKey:"drOtherShrapitDesc",impactKey:"drOtherShrapitImpact",remediesKey:"drOtherShrapitRemedies"},{summaryKey:"guruChandal",detailKey:"guruChandal",labelKey:"drOtherGuruChandal",descKey:"drOtherGuruChandalDesc",impactKey:"drOtherGuruChandalImpact",remediesKey:"drOtherGuruChandalRemedies"},{summaryKey:"punarphoo",detailKey:"punarphoo",labelKey:"drOtherPunarphoo",descKey:"drOtherPunarphooDesc",impactKey:"drOtherPunarphooImpact",remediesKey:"drOtherPunarphooRemedies"},{summaryKey:"kemadruma",detailKey:"kemadruma",labelKey:"drOtherKemadruma",descKey:"drOtherKemadrumaDesc",impactKey:"drOtherKemadrumaImpact",remediesKey:"drOtherKemadrumaRemedies"},{summaryKey:"gandmool",detailKey:"gandmool",labelKey:"drOtherGandmool",descKey:"drOtherGandmoolDesc",impactKey:"drOtherGandmoolImpact",remediesKey:"drOtherGandmoolRemedies"},{summaryKey:"kalathra",detailKey:"kalathra",labelKey:"drOtherKalathra",descKey:"drOtherKalathraDec",impactKey:"drOtherKalathraImpact",remediesKey:"drOtherKalathraRemedies"},{summaryKey:"vishDaridra",detailKey:"vishDaridra",labelKey:"drOtherVishDaridra",descKey:"drOtherVishDaridraDesc",impactKey:"drOtherVishDaridraImpact",remediesKey:"drOtherVishDaridraRemedies"},{summaryKey:"ketuNaga",detailKey:"ketuNaga",labelKey:"drOtherKetuNaga",descKey:"drOtherKetuNagaDesc",impactKey:"drOtherKetuNagaImpact",remediesKey:"drOtherKetuNagaRemedies"},{summaryKey:"navagrahaUmbrella",detailKey:"navagraha",labelKey:"drOtherNavagraha",descKey:"drOtherNavagrahaDesc",impactKey:"drOtherNavagrahaImpact",remediesKey:"drOtherNavagrahaRemedies"}],Ae=De.filter(v=>Be(E[v.summaryKey])).length>0,ee=Be(E.mangal)&&!Tr(E.mangal)||Be(E.kaalSarp)||Be(E.pitra)||Be(L)||Ae,te=[];for(const v of En){const B=v.summaryKey==="shaniSadeSati"?L:E[v.summaryKey];if(!Be(B)||v.type==="mangal"&&Tr(B))continue;const z=E[v.severityKey],G=v.type==="shani"?E.shaniPhase??E.shaniPhase:void 0,V=An(N,v.detailKey==="sadeSati"?"sadeSati":v.detailKey),K=V?.explanation,U=K&&!(f.toLowerCase().startsWith("hi")&&xl(K))?K:e(v.descKey),se=(V?.remedies??e(v.remediesKey)).split(`
170
- `).map(Te=>Te.trim()).filter(Boolean),le=e(v.benefitsKey).split(`
171
- `).map(Te=>Te.trim()).filter(Boolean);te.push({type:v.type,detailKey:v.detailKey,label:e(v.nameKey),icon:v.icon,status:B??"",severity:z||"moderate",phase:G??void 0,explanation:U,placements:V?.placements,impact:e(v.impactKey),remedies:se,benefits:le})}te.sort((v,B)=>Rn(B.severity)-Rn(v.severity));const[he,Je]=w.useState(!1),Oe=/\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\d+|conjunction|aspect)\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i,re=N&&typeof N=="object"&&!Array.isArray(N)?N:{},fe=[];te.forEach(v=>{const B=re[v.detailKey==="sadeSati"?"sadeSati":v.detailKey]||{},z=[...B.placements||[],...B.triggeredBy||[],...B.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),G=Array.from(new Set(z)),V=G.filter(U=>Oe.test(U)),K=V.length>0?V:G;K.length>0&&fe.push({label:v.label,evidence:K})}),De.forEach(v=>{if(!Be(E[v.summaryKey]))return;const B=re[v.detailKey]||{},z=[...B.placements||[],...B.triggeredBy||[],...B.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),G=Array.from(new Set(z)),V=G.filter(U=>Oe.test(U)),K=V.length>0?V:G;if(K.length>0){const U=e(v.labelKey);fe.some(J=>J.label===U)||fe.push({label:U,evidence:K})}});const Se=v=>v===1?e("drPhaseRising"):v===2?e("drPhasePeak"):v===3?e("drPhaseSetting"):"",Q=["bg-orange-50/50 border-l-4 border-l-orange-400","bg-blue-50/50 border-l-4 border-l-blue-400","bg-purple-50/50 border-l-4 border-l-purple-400","bg-amber-50/50 border-l-4 border-l-amber-400"];return l.jsxs("div",{className:`w-full max-w-2xl mx-auto space-y-6 ${s}`,children:[l.jsxs("div",{className:"px-4 pt-4 pb-2 mb-6",children:[l.jsxs("div",{className:"text-center",children:[l.jsx("h1",{className:"text-2xl font-bold mb-2",style:{color:"#1F2937",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageTitle")}),l.jsx("p",{className:"text-sm leading-relaxed",style:{color:"#6B7280",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageSubtitle")})]}),p?l.jsx("div",{className:"mt-4",children:p}):t?l.jsxs("button",{type:"button",onClick:t,className:"mt-4 inline-flex items-center gap-2 min-h-[44px] px-4 text-sm font-medium border border-gray-300 bg-white rounded-md hover:bg-gray-50 transition-colors text-gray-700",style:{fontFamily:'"Plus Jakarta Sans", sans-serif'},children:[l.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[l.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),l.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),e("resultEditForm")]}):null]}),l.jsxs(nt,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[l.jsx(mt,{children:l.jsx(pt,{id:"dosha-results-heading",className:`text-2xl sm:text-3xl font-bold break-words ${ee?"text-primary":"text-success"}`,children:ee?e("resultSomeDoshas"):`✓ ${e("resultNoDoshas")}`})}),l.jsx(gt,{children:ee?l.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(v=>l.jsxs("div",{className:"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full",children:[l.jsx(Xr,{className:"w-4 h-4 text-primary"}),l.jsxs("span",{className:"font-medium text-sm text-foreground",children:[v.label,": ",On(v.status,e)]})]},v.type))}):l.jsxs("div",{className:"text-center py-8",children:[l.jsx(ln,{className:"w-12 h-12 mx-auto mb-4 text-success"}),l.jsx("p",{className:"text-lg font-medium text-foreground",children:e("resultNoDoshas")}),l.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:e("resultNoDoshasDesc")})]})})]}),te.map((v,B)=>{const z=v.icon,G=v.type==="shani"&&v.phase?Se(v.phase):"",V=Q[B%Q.length],K=e("drDoshaOf").replace("{{index}}",String(B+1)).replace("{{total}}",String(te.length));return l.jsxs(nt,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[l.jsx("div",{className:"px-4 pt-3",children:l.jsx(jr,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:K})}),l.jsxs(mt,{className:"pb-3 pt-2",children:[l.jsxs(pt,{className:"flex items-center gap-3 text-xl",children:[l.jsx(z,{className:"w-6 h-6 text-primary"}),v.label]}),l.jsxs(kr,{children:[e("drSeverity"),": ",Cn(v.severity,e),v.phase!=null&&` • ${e("drPhase")}: ${v.phase}`]})]}),l.jsxs(gt,{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs("h4",{className:"font-semibold text-base flex items-center gap-2",children:[l.jsx(br,{className:"w-4 h-4 text-primary"}),e("drWhyMarked"),n&&l.jsxs("button",{type:"button",onClick:()=>{g?.trackDoshaCalculatorResultViewKundliClick?.();const U=document.getElementById(n);U&&U.scrollIntoView({behavior:"smooth",block:"center"})},className:"text-xs text-primary hover:underline ml-auto whitespace-nowrap",children:[e("drViewKundli")," ↓"]})]}),l.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:v.explanation}),G&&l.jsxs("div",{className:"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20",children:[l.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPhaseMeaning")}),l.jsx("p",{className:"text-sm text-muted-foreground",children:G})]}),v.type!=="pitra"&&v.placements&&v.placements.length>0&&l.jsxs("div",{className:"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20",children:[l.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPlanetaryPositions")}),l.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:v.placements.map((U,J)=>l.jsx("li",{children:U},J))})]})]}),l.jsxs("div",{className:"p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:[l.jsx("h4",{className:"font-semibold text-sm mb-2 text-destructive",children:k[v.type]?.title||e("drImpactIfPresent")}),O?l.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[l.jsx(Zr,{className:"w-4 h-4 animate-spin"}),l.jsx("span",{children:f==="hi"?"प्रभाव विश्लेषण हो रहा है...":"Analyzing impact..."})]}):l.jsx("p",{className:"text-sm text-muted-foreground",children:k[v.type]?.text||v.impact})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h4",{className:"font-semibold text-base",children:e("drPujaRecommendation")}),i?o?l.jsx("div",{className:"flex items-center justify-center py-6",children:l.jsx(Zr,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const U=Sl(v.type,v.detailKey),J=U.map(se=>i(se)).find(Boolean);return!J&&typeof window<"u"&&console.warn(`[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${v.type} (tried: ${U.join(", ")})`),J||l.jsx("p",{className:"text-sm text-muted-foreground italic",children:e("drNoPujaAvailable")})})():l.jsxs("p",{className:"text-sm text-muted-foreground italic",children:[e("drNoPujaAvailable"),typeof window<"u"&&(console.warn("[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations."),null)]})]}),v.benefits.length>0&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("h4",{className:"font-semibold text-base flex items-center gap-2",children:e("drHowPujaHelps")}),l.jsx("ul",{className:"text-sm text-muted-foreground space-y-3 ml-1",children:v.benefits.map((U,J)=>l.jsxs("li",{className:"flex items-start gap-3",children:[l.jsx("span",{className:"text-primary mt-1.5 flex-shrink-0",children:"•"}),l.jsx("span",{children:U})]},J))})]})]})]},v.type)}),te.length>0&&l.jsx("p",{className:"text-xs text-muted-foreground text-center italic px-4",children:e("drFomoLine")}),l.jsxs("div",{className:"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center",children:[l.jsx("p",{className:"text-sm text-foreground/80 font-medium",children:e("drFeedbackContact")}),l.jsx("a",{href:`mailto:${a}`,className:"text-primary hover:underline font-semibold text-base mt-1 inline-block",children:a})]}),l.jsxs(nt,{className:"spiritual-glow mx-4",children:[l.jsxs(mt,{children:[l.jsx(pt,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),l.jsx(kr,{className:"text-center",children:e("drBasedOnChart")})]}),l.jsx(gt,{className:"space-y-4",children:l.jsx(_n,{type:"single",collapsible:!0,className:"w-full space-y-4",children:En.map(v=>{const B=v.detailKey==="sadeSati"?"sadeSati":v.detailKey,z=v.summaryKey==="shaniSadeSati"?L:E[v.summaryKey],G=An(N,v.detailKey==="sadeSati"?"sadeSati":v.detailKey),V=E[v.severityKey],K=v.type==="shani"?E.shaniPhase:void 0,U=v.icon,me=(G?.remedies?.trim()||e(v.remediesKey)).split(`
172
- `).map(le=>le.trim()).filter(Boolean);return l.jsxs(kn,{value:B,className:"border border-border rounded-lg px-4",children:[l.jsx(Sn,{value:B,className:"hover:no-underline",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(U,{className:"w-5 h-5 text-destructive"}),l.jsxs("div",{className:"text-left",children:[l.jsx("h3",{className:"font-semibold text-lg",children:e(v.nameKey)}),l.jsxs("p",{className:"text-sm text-muted-foreground",children:[e("drStatus"),": ",On(z,e),V&&!Tr(z)&&` • ${e("drSeverity")}: ${Cn(V,e)}`,v.type==="shani"&&K!=null&&` • ${e("drPhase")}: ${K}`]})]})]})}),l.jsxs(xn,{value:B,className:"pt-4 space-y-4",children:[l.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(v.descKey)}),G?.explanation&&l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium mb-2",children:e("drExplanation")}),l.jsx("p",{className:"text-sm text-muted-foreground",children:G.explanation})]}),G?.placements&&G.placements.length>0&&l.jsxs("div",{className:"p-3 bg-accent/10 rounded-md",children:[l.jsx("h4",{className:"font-medium mb-2",children:e("drPlanetaryPositions")}),l.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:G.placements.map((le,Te)=>l.jsx("li",{children:le},Te))})]}),l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium mb-2",children:e("drTraditionalRemedies")}),l.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:me.map((le,Te)=>l.jsx("li",{children:le},Te))})]})]})]},B)})})})]}),l.jsxs(nt,{className:"mx-4",children:[l.jsx(mt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>Je(v=>!v),children:l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsxs("div",{className:"text-left flex-1 min-w-0",children:[l.jsx(pt,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),l.jsx(kr,{children:e(Ae?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),l.jsx(cn,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&l.jsx(gt,{children:l.jsx(_n,{type:"single",collapsible:!0,className:"w-full space-y-2",children:De.map(v=>{const B=E[v.summaryKey],z=Be(B),G=re[v.detailKey]??{},V=G.explanation,K=G.placements;return l.jsxs(kn,{value:v.summaryKey,className:"border border-border rounded-lg px-3",children:[l.jsx(Sn,{value:v.summaryKey,className:"hover:no-underline py-3",children:l.jsxs("div",{className:"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"font-semibold text-sm text-left leading-tight",children:e(v.labelKey)}),l.jsx(br,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?l.jsxs(jr,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[l.jsx(Xr,{size:10}),e("drStatusPresent")]}):l.jsxs(jr,{variant:"secondary",className:"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none",style:{borderColor:"#e4decd",color:"#000000"},children:[l.jsx(ln,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),l.jsxs(xn,{value:v.summaryKey,className:"space-y-3 pt-0 pb-3",children:[l.jsx("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:l.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(v.descKey)})}),K&&K.length>0&&l.jsxs("div",{className:"p-3 bg-accent/10 rounded-md border border-accent/20",children:[l.jsxs("h5",{className:"font-medium mb-2 flex items-center gap-2 text-sm",children:[l.jsx(br,{size:14}),e("drPlanetaryPositions")]}),l.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed",children:K.map((U,J)=>l.jsx("li",{children:U},J))})]}),V&&l.jsxs("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:[l.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2",children:[l.jsx(br,{size:14}),e(z?"drWhyPresent":"drWhyAbsent")]}),l.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),z&&l.jsxs("div",{className:"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2",children:[l.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2 text-red-600",children:[l.jsx(Xr,{size:14}),e("drImpact")]}),l.jsx("p",{className:"text-sm text-muted-foreground",children:e(v.impactKey)})]}),z&&l.jsxs("div",{children:[l.jsx("h5",{className:"font-medium mb-2 text-sm",children:e("drTraditionalRemedies")}),l.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:e(v.remediesKey).split(`
173
- `).map((U,J)=>l.jsx("li",{children:U},J))})]})]})]},v.summaryKey)})})})]}),l.jsx("div",{id:n||"kundali-chart-section",className:"px-4",children:(c||M||fe.length>0)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"flex justify-end mb-2",children:l.jsxs("button",{type:"button",onClick:()=>document.getElementById("dosha-results-heading")?.scrollIntoView({behavior:"smooth",block:"start"}),className:"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium",children:[l.jsx(Do,{className:"w-4 h-4"}),e("drGoBack")]})}),c?l.jsxs("div",{className:"mt-2",children:[l.jsx("h2",{className:"text-xl font-semibold text-foreground mb-3",children:e("drYourKundali")}),c()]}):M&&u&&d?l.jsx("div",{className:"mt-2",children:l.jsx(Pn,{birthDetails:u,supabase:d,language:f,t:e})}):null,fe.length>0&&l.jsxs(nt,{className:"mt-4 bg-accent/10 border border-accent/30",children:[l.jsx(mt,{className:"pb-2",children:l.jsx(pt,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),l.jsx(gt,{className:"pt-0",children:l.jsx("ul",{className:"space-y-3 text-sm text-muted-foreground",children:fe.map((v,B)=>l.jsxs("li",{children:[l.jsxs("div",{className:"font-semibold text-foreground mb-1",children:[v.label,":"]}),l.jsx("ul",{className:"ml-4 space-y-1",children:v.evidence.map((z,G)=>l.jsxs("li",{className:"flex items-start gap-2",children:[l.jsx("span",{className:"text-primary flex-shrink-0",children:"→"}),l.jsx("span",{children:z})]},G))})]},B))})})]})]})}),l.jsx("p",{className:"text-xs text-muted-foreground/70 text-center px-4",children:e("drDisclaimer")}),l.jsx(q.UserReviewsSection,{t:e,readMoreHref:m,onReadMore:g?.trackReadMoreReviewsClicked?()=>g.trackReadMoreReviewsClicked():void 0}),l.jsx(q.FAQAccordion,{t:e,items:kl,defaultOpenIndex:0}),l.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const jl=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:In},Symbol.toStringTag,{value:"Module"}));function Tl(r){return!r||r.trim()===""?async()=>null:async e=>{try{if(!e?.trim())return null;const t=`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${r}`,n=await(await fetch(t)).json();if(n.status!=="OK"||!n.results?.[0])return null;const{lat:a,lng:i}=n.results[0].geometry.location,o=Math.floor(Date.now()/1e3),c=`https://maps.googleapis.com/maps/api/timezone/json?location=${a},${i}&timestamp=${o}&key=${r}`,d=await(await fetch(c)).json();if(d.status!=="OK")return null;const f=d.timeZoneId,m=(d.rawOffset+d.dstOffset)/3600;return{lat:a,lon:i,tz:f,tzoneOffset:m}}catch{return null}}}H.DoshaCalculator=fl,H.DoshaFormSection=es,H.DoshaResultsFull=In,H.DoshaResultsView=yl,H.FLOATING_CTA_STATUS=ar,H.I18nProvider=Ao,H.KundaliCard=Pn,H.LOCALE_LABELS=Po,H.SUPPORTED_LOCALES=To,H.SriMandirPujaVerticalCard=pn,H.createGoogleMapsResolver=Tl,H.createSupabaseClient=zs,H.fetchKundaliSvg=Tn,H.formatScheduleDate=rn,H.getCoverImageUrl=sn,H.getPujaLink=Yr,H.getPujaTitle=Jr,H.getTempleName=tn,H.insertSessionProblemStatements=dn,H.invokeCalculateDosha=hn,H.submitDoshaCalculation=fn,H.translations=nn,H.useGooglePlacesAutocomplete=mn,H.useI18n=Qr,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})}));
167
+ नवग्रह मंदिरों में जाएं`,ctaKundliCreated:"3L+ कुंडली रिपोर्ट बनाई।",ctaCertified:"BHU प्रमाणित ज्योतिषी।",ctaSecurePayment:"सुरक्षित भुगतान।",contactTitle:"संपर्क करें",contactBrandName:"श्री मंदिर",contactWhatsAppGlobal:"व्हाट्सएप: 8296947757",contactWhatsAppDomestic:"व्हाट्सएप: 08071174417",contactEmail:"ईमेल: pujaseva@appsforbharat.com",whatFromAnalysisTitle:"इस विश्लेषण से आपको क्या मिलेगा",whatFromAnalysisMarriage1Title:"शादी पर प्रभाव जानें",whatFromAnalysisMarriage1Desc:"क्या शादी में देरी होगी, कोई समस्या आएगी या मैच सही रहेगा।",whatFromAnalysisMarriage2Title:"मंगल दोष की पुष्टि",whatFromAnalysisMarriage2Desc:"जानें कि मंगल दोष है या नहीं और वह कितना मजबूत है।",whatFromAnalysisMarriage3Title:"उपाय और पूजा की जानकारी",whatFromAnalysisMarriage3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।",whatFromAnalysisGeneric1Title:"जीवन पर प्रभाव का संक्षेप",whatFromAnalysisGeneric1Desc:"शादी, करियर, पैसे, सेहत और पढ़ाई में होने वाली देरी, परेशानी या अवसरों को समझें",whatFromAnalysisGeneric2Title:"दोष की पुष्टि",whatFromAnalysisGeneric2Desc:"जानें कि कोई दोष या ग्रहों का असंतुलन आपकी प्रगति को प्रभावित कर रहा है या नहीं",whatFromAnalysisGeneric3Title:"उपाय की दिशा",whatFromAnalysisGeneric3Desc:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},pn=v.createContext(null);function gn(){return typeof window>"u"?"en":window.location.pathname.split("/").filter(Boolean)[0]==="hi"?"hi":"en"}function Zo(t){const{pathname:e,search:r,hash:s}=window.location,n=e.split("/").filter(Boolean);n[0]==="en"||n[0]==="hi"?n[0]=t:n.unshift(t),window.location.href="/"+n.join("/")+r+s}function el({locale:t,onLocaleChange:e,children:r}){const[s,n]=v.useState(()=>t||gn());v.useEffect(()=>{if(t)n(t);else{const o=()=>n(gn());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[t]);const a=o=>{e?e(o):Zo(o)},i=v.useMemo(()=>o=>mn[s]?.[o]??o,[s]);return c.jsx(pn.Provider,{value:{locale:s,setLocale:a,t:i},children:r})}function ns(){return v.useContext(pn)}function tl(){const e=ns()?.locale==="hi";return c.jsx("div",{className:Yo.container,children:e?"100% सटीक • सुरक्षित • 30 लाख+ परिवारों द्वारा विश्वसनीय":"100% Accurate • Secure • Trusted by 30L+ families"})}const Me=t=>({width:t,height:t});function as(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}function yn(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),c.jsx("path",{d:"m9 11 3 3L22 4"})]})}function jr(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("path",{d:"M12 16v-4"}),c.jsx("path",{d:"M12 8h.01"})]})}function rl(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:c.jsx("path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"})})}function sl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),c.jsx("path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"}),c.jsx("path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1"})]})}function nl(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function al(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:c.jsx("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function il(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"m5 12 7-7 7 7"}),c.jsx("path",{d:"M12 19V5"})]})}function bn(t){const{size:e=24,...r}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:c.jsx("path",{d:"m6 9 6 6 6-6"})})}function is(t){const{size:e=24,className:r="",...s}=t;return c.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`animate-spin ${r}`,style:{animation:"spin 1s linear infinite"},...Me(e),...s,children:c.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function ol(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",x2:"21",y1:"14",y2:"3"})]})}function ll(t){const{size:e=24,...r}=t;return c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...Me(e),...r,children:[c.jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),c.jsx("path",{d:"M3 3v5h5"})]})}const Be={ctaFilled:"_ctaFilled_8nukz_2",ctaFilledContent:"_ctaFilledContent_8nukz_7",chevronRight:"_chevronRight_8nukz_14",bookPujaButton:"_bookPujaButton_8nukz_21",bookPujaContent:"_bookPujaContent_8nukz_27",pujaInfo:"_pujaInfo_8nukz_36",pujaName:"_pujaName_8nukz_44",pujaPrice:"_pujaPrice_8nukz_57",priceLabel:"_priceLabel_8nukz_64",priceAmount:"_priceAmount_8nukz_68",bookButton:"_bookButton_8nukz_74"},tt=t=>{const{priority:e,fetchPriority:r,width:s,height:n,...a}=t;return v.createElement("img",{...a,width:s??1,height:n??1,decoding:"async",loading:a.loading??(e?"eager":"lazy"),...r&&{fetchPriority:r}})},cl="https://srm-cdn.a4b.io/yoda/1771588545907.svg";function ul({isFormComplete:t,onPress:e,labelDefault:r,labelFilled:s,isLoading:n=!1,mode:a="form",firstPuja:i,showingResults:o=!1,bookPujaLabel:l="Book Puja",loadingLabel:u="Calculating..."}){return a==="book-puja"&&i&&o?c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:Be.bookPujaButton,children:c.jsxs("div",{className:Be.bookPujaContent,children:[c.jsxs("div",{className:Be.pujaInfo,children:[c.jsx("span",{className:Be.pujaName,children:i.name}),i.price>0&&c.jsxs("div",{className:Be.pujaPrice,children:[c.jsx("span",{className:Be.priceLabel,children:"Starting from "}),c.jsxs("span",{className:Be.priceAmount,children:["₹",i.price]})]})]}),c.jsxs("span",{className:Be.bookButton,children:[l," →"]})]})}):c.jsx(q.FooterCTAButton,{onClick:e,disabled:n,className:t?Be.ctaFilled:void 0,children:n?c.jsxs("span",{className:Be.ctaFilledContent,children:[c.jsx(is,{className:"w-5 h-5 animate-spin"}),u]}):t?c.jsxs("span",{className:Be.ctaFilledContent,children:[s,c.jsx(tt,{src:cl,alt:"",className:Be.chevronRight,width:20,height:20,loading:"lazy"})]}):r})}const Ar={bannerContainer:"_bannerContainer_1s29r_1",bannerImage:"_bannerImage_1s29r_13",ticker:"_ticker_1s29r_20",tickerContent:"_tickerContent_1s29r_30"};function dl({bannerConfig:t,className:e="",imageComponent:r=tt}){const s=r;return c.jsxs("section",{className:`${Ar.bannerContainer} ${e}`,children:[c.jsx(s,{src:t.imageUrl,alt:t.alt,className:Ar.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),c.jsx("div",{className:Ar.ticker,children:c.jsx("div",{className:Ar.tickerContent,children:t.tickerText})})]})}const hl=112;function at({section:t,children:e,onImpression:r}){const s=v.useRef(null),n=v.useRef(!1);return v.useEffect(()=>{const a=s.current;if(!a)return;const i=new IntersectionObserver(([o])=>{!o?.isIntersecting||n.current||(n.current=!0,r(t))},{threshold:.1,rootMargin:`0px 0px -${hl}px 0px`});return i.observe(a),()=>i.disconnect()},[t,r]),c.jsx("div",{ref:s,children:e})}const It={wrap:"_wrap_1mrzx_1",input:"_input_1mrzx_6",iconBtn:"_iconBtn_1mrzx_35",iconImg:"_iconImg_1mrzx_49",placeholder:"_placeholder_1mrzx_53",dateDisplay:"_dateDisplay_1mrzx_65"},fl="https://srm-cdn.a4b.io/yoda/1770372045894.svg",ml=t=>{if(!t)return"";const[e,r,s]=t.split("-");return`${s}/${r}/${e}`};function pl({id:t,value:e,onChange:r,onOpen:s,className:n=""}){const a=v.useRef(null),i=v.useMemo(()=>{const l=new Date,u=d=>String(d).padStart(2,"0");return`${l.getFullYear()}-${u(l.getMonth()+1)}-${u(l.getDate())}`},[]),o=()=>{s?.();const l=a.current;if(l&&typeof l.showPicker=="function")try{l.showPicker()}catch{l?.focus()}else l?.focus()};return c.jsxs("div",{className:`${It.wrap} ${n}`,children:[!e&&c.jsx("span",{className:It.placeholder,children:"Select Date of Birth"}),e&&c.jsx("div",{className:It.dateDisplay,children:ml(e)}),c.jsx("input",{ref:a,id:t,type:"date",className:It.input,value:e,max:i,onChange:l=>{const u=l.target.value,d=new Date,f=p=>String(p).padStart(2,"0"),m=`${d.getFullYear()}-${f(d.getMonth()+1)}-${f(d.getDate())}`;u&&u>m||r(u)},onClick:o,onFocus:o}),c.jsx("button",{type:"button",className:It.iconBtn,"aria-label":"Open date picker",onMouseDown:l=>l.preventDefault(),onClick:l=>{l.preventDefault(),l.stopPropagation(),o()},children:c.jsx(tt,{className:It.iconImg,src:fl,alt:"",width:22,height:22,loading:"lazy"})})]})}const be={wrap:"_wrap_spo2g_1",input:"_input_spo2g_6",iconBtn:"_iconBtn_spo2g_24",iconImg:"_iconImg_spo2g_38",timePopover:"_timePopover_spo2g_42",timePickerRow:"_timePickerRow_spo2g_58",timePickerSelect:"_timePickerSelect_spo2g_64",timePickerColon:"_timePickerColon_spo2g_80",meridiemToggle:"_meridiemToggle_spo2g_88",meridiemBtn:"_meridiemBtn_spo2g_97",meridiemActive:"_meridiemActive_spo2g_112",timePopoverActions:"_timePopoverActions_spo2g_117",timePopoverBtn:"_timePopoverBtn_spo2g_123",timePopoverOk:"_timePopoverOk_spo2g_142"},gl="https://srm-cdn.a4b.io/yoda/1770372014782.svg",vn=t=>String(t).padStart(2,"0");function yl(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return t;const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return`${r%12===0?12:r%12}:${s} ${n}`}function bl(t){const e=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(t);if(!e)return{hour12:12,minute:"00",meridiem:"AM"};const r=Number(e[1]),s=e[2],n=r>=12?"PM":"AM";return{hour12:r%12===0?12:r%12,minute:s,meridiem:n}}function vl(t){const e=Math.min(12,Math.max(1,t.hour12)),r=/^([0-5]\d)$/.test(t.minute)?t.minute:"00";let s=e%12;return t.meridiem==="PM"&&(s+=12),`${vn(s)}:${r}`}function wl({id:t,value:e,onChange:r,onOpen:s,placeholder:n="Exact Time of Birth",disabled:a=!1,className:i=""}){const o=v.useRef(null),[l,u]=v.useState(!1),[d,f]=v.useState({hour12:12,minute:"00",meridiem:"AM"});v.useEffect(()=>{const g=y=>{o.current&&(o.current.contains(y.target)||u(!1))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[]);const m=()=>{a||(s?.(),f(bl(e||"12:00")),u(g=>!g))},p=()=>{const g=vl(d);r(g),u(!1)};return c.jsxs("div",{className:`${be.wrap} ${i}`,ref:o,children:[c.jsx("input",{id:t,className:be.input,type:"text",value:e?yl(e):"",readOnly:!0,disabled:a,placeholder:n,onClick:m}),c.jsx("button",{type:"button",className:be.iconBtn,"aria-label":"Open time picker",disabled:a,onMouseDown:g=>g.preventDefault(),onClick:g=>{g.preventDefault(),g.stopPropagation(),m()},children:c.jsx(tt,{className:be.iconImg,src:gl,alt:"",width:22,height:22,loading:"lazy"})}),l&&!a&&c.jsxs("div",{className:be.timePopover,role:"dialog","aria-label":"Select time",children:[c.jsxs("div",{className:be.timePickerRow,children:[c.jsx("select",{className:be.timePickerSelect,value:d.hour12,onChange:g=>f(y=>({...y,hour12:Number(g.target.value)})),"aria-label":"Hour",children:Array.from({length:12},(g,y)=>y+1).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsx("span",{className:be.timePickerColon,children:":"}),c.jsx("select",{className:be.timePickerSelect,value:d.minute,onChange:g=>f(y=>({...y,minute:g.target.value})),"aria-label":"Minute",children:Array.from({length:60},(g,y)=>vn(y)).map(g=>c.jsx("option",{value:g,children:g},g))}),c.jsxs("div",{className:be.meridiemToggle,"aria-label":"AM/PM",children:[c.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="AM"?be.meridiemActive:""}`,onClick:()=>f(g=>({...g,meridiem:"AM"})),children:"AM"}),c.jsx("button",{type:"button",className:`${be.meridiemBtn} ${d.meridiem==="PM"?be.meridiemActive:""}`,onClick:()=>f(g=>({...g,meridiem:"PM"})),children:"PM"})]})]}),c.jsxs("div",{className:be.timePopoverActions,children:[c.jsx("button",{type:"button",className:be.timePopoverBtn,onClick:()=>u(!1),children:"Cancel"}),c.jsx("button",{type:"button",className:`${be.timePopoverBtn} ${be.timePopoverOk}`,onClick:p,"aria-label":"OK",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M20 6L9 17l-5-5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})}async function wn(t,e){const{visitorId:r,sessionId:s,problemStatements:n,language:a}=e;if(n.length!==0)try{await t.from("session_problem_statements").insert({visitor_id:r,session_id:s,problem_statements:n,language:a??"en"})}catch{}}async function _n(t,e,r){const{data:s,error:n}=await t.functions.invoke("calculate-dosha",{body:e,headers:r??{}});return n?{success:!1,error:n.message||"Calculation failed"}:s&&typeof s=="object"&&"success"in s?s.success===!0?s:{success:!1,error:s.error??"Unknown error",details:s.details}:{success:!1,error:"Invalid response from server"}}async function kn(t,e,r={}){const{visitorId:s="unknown",sessionId:n="unknown",trackProblemStatements:a=!0,problemStatements:i=[],language:o="en"}=r;return a&&i.length>0&&await wn(t,{visitorId:s,sessionId:n,problemStatements:i,language:o}),_n(t,e,{"x-visitor-id":s,"x-session-id":n})}let Pr=null;const _l=(t,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():Pr||(Pr=new Promise((r,s)=>{const n=document.querySelector('script[data-google-maps-places="true"]');if(n){const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>5e3){s(new Error("Google Maps script present but Places library did not become available."));return}window.setTimeout(l,50)};n.getAttribute("src")?l():(n.addEventListener("load",()=>l()),n.addEventListener("error",()=>s(new Error("Failed to load Google Maps API"))));return}const a=document.createElement("script"),i=new URL("https://maps.googleapis.com/maps/api/js");i.searchParams.set("key",t),i.searchParams.set("libraries","places"),i.searchParams.set("loading","async"),e&&i.searchParams.set("language",e),a.src=i.toString(),a.async=!0,a.defer=!0,a.setAttribute("data-google-maps-places","true"),a.onload=()=>{const o=Date.now(),l=()=>{if(window.google?.maps?.places){r();return}if(Date.now()-o>2e3){s(new Error("Google Maps loaded but Places library is unavailable. Check API key restrictions / enabled APIs."));return}window.setTimeout(l,50)};l()},a.onerror=()=>s(new Error("Failed to load Google Maps API")),document.head.appendChild(a)}),Pr),Sn=(t={})=>{const{apiKey:e,language:r="en",restrictCountry:s}=t,[n,a]=v.useState(!1),[i,o]=v.useState([]),[l,u]=v.useState(!1),[d,f]=v.useState(null),m=v.useRef(null),p=v.useRef(null),g=v.useRef(null);v.useEffect(()=>{if(!e){a(!1),f(null);return}_l(e,r).then(()=>{try{m.current=new google.maps.places.AutocompleteService;const S=document.createElement("div");p.current=new google.maps.places.PlacesService(S),g.current=new google.maps.places.AutocompleteSessionToken,a(!0),f(null)}catch(S){a(!1),f(S instanceof Error?S.message:"Failed to create Places services")}}).catch(S=>{a(!1),f(S instanceof Error?S.message:"Failed to load location service")})},[e,r]);const y=v.useCallback(async S=>{if(!S||S.length<2||!m.current){o([]);return}u(!0);try{const k={input:S,types:["(cities)"],sessionToken:g.current??void 0};s&&(k.componentRestrictions={country:s});const N=await new Promise((O,B)=>{m.current.getPlacePredictions(k,(P,U)=>{U===google.maps.places.PlacesServiceStatus.OK&&P?O(P):U===google.maps.places.PlacesServiceStatus.ZERO_RESULTS?O([]):B(new Error(`Places API error: ${U}`))})});o(N.map(O=>({place_id:O.place_id,description:O.description,structured_formatting:{main_text:O.structured_formatting?.main_text||O.description,secondary_text:O.structured_formatting?.secondary_text||""}})))}catch{o([])}finally{u(!1)}},[s]),x=v.useCallback(async S=>{if(!p.current)return null;try{const k=await new Promise(($,De)=>{p.current.getDetails({placeId:S,fields:["geometry","address_components","formatted_address"],sessionToken:g.current??void 0},(ge,Ee)=>{Ee===google.maps.places.PlacesServiceStatus.OK&&ge?$(ge):De(new Error(`Place details error: ${Ee}`))})});g.current=new google.maps.places.AutocompleteSessionToken;const N=k.geometry?.location?.lat()||0,O=k.geometry?.location?.lng()||0;let B="",P="",U="";return k.address_components?.forEach($=>{$.types.includes("locality")&&(B=$.long_name),$.types.includes("administrative_area_level_1")&&(P=$.long_name),$.types.includes("country")&&(U=$.long_name)}),{display_name:k.formatted_address||"",lat:N,lng:O,city:B,state:P,country:U}}catch{return null}},[]),_=v.useCallback(()=>o([]),[]);return{isLoaded:n,predictions:i,isSearching:l,loadError:d,searchPlaces:y,getPlaceDetails:x,clearPredictions:_}},kl=["formProblemMarriage","formProblemMoney","formProblemHealth","formProblemEducation","formProblemCareer","formProblemOther"];function Sl(){try{const t="analytics_visitor_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function xl(){try{const t="analytics_session_id";let e=typeof localStorage<"u"?localStorage.getItem(t):null;if(!e){e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,10)}`;try{localStorage.setItem(t,e)}catch{}}return e??"unknown"}catch{return"unknown"}}function Tl(t){if(!t)return 0;const e=new Date(t);if(Number.isNaN(e.getTime()))return 0;const r=new Date;let s=r.getFullYear()-e.getFullYear();const n=r.getMonth()-e.getMonth();return(n<0||n===0&&r.getDate()<e.getDate())&&s--,s}const os=v.forwardRef(function({t:e,className:r="",initialValues:s,onValuesChange:n,onFormValidityChange:a,supabase:i,resolvePlace:o,onResult:l,onError:u,onLoadingChange:d,analytics:f,googleMapsApiKey:m},p){const g=j=>j.replace(/[^a-zA-Z\u0900-\u097F\s]/g,"").replace(/\s{2,}/g," "),[y,x]=v.useState(s?.name??""),[_,S]=v.useState(s?.gender??""),[k,N]=v.useState(s?.problems??[]),[O,B]=v.useState(s?.dateOfBirth??""),[P,U]=v.useState(s?.birthTime??""),[$,De]=v.useState(s?.birthTimeUnknown??!1),[ge,Ee]=v.useState(s?.birthPlace??""),[ee,te]=v.useState(s?.otherProblemText??""),[he,Qe]=v.useState(null),[Oe,re]=v.useState(!1),[fe,ke]=v.useState(null),[Q,b]=v.useState({}),K=v.useCallback(j=>{const I=ie=>{const ze=document.getElementById(ie);return ze?(ze.focus(),ze.scrollIntoView({behavior:"smooth",block:"center"}),!0):!1};if(j==="name"){I("dosha-name");return}if(j==="gender"){const ie=document.querySelector('[role="group"][aria-labelledby="dosha-gender-label"] button');ie&&(ie.focus(),ie.scrollIntoView({behavior:"smooth",block:"center"}));return}if(j==="dateOfBirth"){I("dosha-dob");return}if(j==="birthTime"){I("dosha-time");return}j==="birthPlace"&&I("dosha-place")},[]),z=v.useRef(!1),H=v.useRef(!1),V=v.useRef(!1),M=v.useRef(!1),L=v.useRef(!1),J=v.useRef(null),{predictions:se,isSearching:me,loadError:le,searchPlaces:Te,getPlaceDetails:$t,clearPredictions:Fe}=Sn({apiKey:m,language:"en"}),$e=v.useCallback(()=>{z.current||(z.current=!0,f?.trackFormFillInitiated?.())},[f]);v.useEffect(()=>{const j=I=>{J.current&&(J.current.contains(I.target)||re(!1))};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]),v.useEffect(()=>{if(!Oe)return;if(ge.length<2){Fe();return}const j=window.setTimeout(async()=>{await Te(ge)},300);return()=>window.clearTimeout(j)},[ge,Fe,Oe,Te]);const bt=y.trim()!==""&&(_==="male"||_==="female")&&O!==""&&(P!==""||$)&&ge.trim()!=="";v.useEffect(()=>{a?.(bt)},[bt,a]),v.useEffect(()=>{n?.({name:y,gender:_,problems:k,otherProblemText:ee,dateOfBirth:O,birthTime:P,birthTimeUnknown:$,birthPlace:ge})},[y,_,k,ee,O,P,$,ge,n]),v.useEffect(()=>{!k.includes("formProblemOther")&&ee&&te("")},[k,ee]);const vt=v.useCallback(async(j,I)=>{if(!m)return"UTC";try{const ie=Math.floor(Date.now()/1e3),ze=`https://maps.googleapis.com/maps/api/timezone/json?location=${j},${I}&timestamp=${ie}&key=${m}`,_e=await(await fetch(ze)).json();return _e.status==="OK"&&_e.timeZoneId?_e.timeZoneId:"UTC"}catch{return"UTC"}},[m]),rt=v.useCallback(async()=>{const j=(ce,je,qe=!1)=>{je&&(b(Le=>({...Le,[je]:ce})),K(je)),ke(qe?ce:null),u?.(ce)};if(b({}),ke(null),!i){j(e("calculationError"));return}if(!y.trim()){j(e("formNameRequired"),"name");return}if(_!=="male"&&_!=="female"){j(e("formGenderRequired"),"gender");return}if(!O){j(e("formDobRequired"),"dateOfBirth");return}if(!$&&!P){j(e("formTimeRequired"),"birthTime");return}const I=ge.trim();if(!I){j(e("formPlaceRequired"),"birthPlace");return}const ie=g(I).trim();if(!ie){j(e("formPlaceRequired"),"birthPlace");return}const ze=Tl(O),lt=new Set(["formProblemMarriage","formProblemMoney","formProblemCareer","formProblemBusiness","marriage","financial","career","business"]),_e=k.some(ce=>lt.has(ce));if(ze<18&&_e){j(e("formAgeMarriageRestriction"),void 0,!0);return}if(!he&&!o){j(e("formPlaceSelectFromDropdown"),"birthPlace");return}d?.(!0);try{let ce,je,qe;if(he)ce=he.lat,je=he.lon,he.tz?qe=he.tz:(qe=await vt(ce,je),Qe({...he,tz:qe}));else if(o){const ye=await o(I);if(!ye){j(e("locationError")),d?.(!1);return}ce=ye.lat,je=ye.lon,qe=ye.tz}else{j(e("formPlaceSelectFromDropdown"),"birthPlace"),d?.(!1);return}const Le={problemAreaValues:[...k.filter(ye=>ye!=="formProblemOther").map(ye=>e(ye)).filter(Boolean),...k.includes("formProblemOther")&&ee.trim()?[ee.trim()]:[]],name:y.trim(),gender:_==="male"?"M":"F",date:O,time:$?"":P||"12:00",unknownTime:$,tz:qe||"UTC",lat:ce,lon:je,place:ie,problemArea:void 0};Le.problemArea=Le.problemAreaValues.length>0?Le.problemAreaValues.join(", "):void 0;const sr=Sl(),C=xl(),ne=Le.problemAreaValues,Se=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",xe=await kn(i,Le,{visitorId:sr,sessionId:C,trackProblemStatements:!0,problemStatements:ne,language:Se});if(xe.success){ke(null);const[ye,nr,ar]=(Le.date||"").split("-").map(Number),Ir=Le.time||"12:00",[ct,ir]=Ir.split(":").map($r=>parseInt($r,10)||0);l?.(xe,{day:ar||1,month:nr||1,year:ye||2e3,hour:ct,minute:ir,lat:ce,lon:je,tzone:5.5})}else{let ye=xe.error??e("calculationError");(ye.includes("Expected 'M' | 'F'")||ye.includes("gender"))&&(ye=e("formGenderRequired")),j(ye)}}catch(ce){const je=ce instanceof Error?ce.message:String(ce);j(je)}finally{d?.(!1)}},[i,o,he,ge,y,_,O,P,$,k,e,u,d,f,l,vt,K]);v.useImperativeHandle(p,()=>({submit:rt}),[rt]);const rr=kl.map(j=>({key:j,label:e(j)}));return c.jsxs(q.FormContainer,{className:r,"aria-label":e("formTitle"),children:[c.jsx(q.PrivacyBanner,{text:e("formPrivacyBanner")}),c.jsx(q.FormSectionHeader,{title:e("formTitle"),subtitle:e("formSubtitle")}),c.jsx("div",{onFocusCapture:()=>{$e(),f?.trackNameSectionClicked?.()},children:c.jsxs(q.FormField,{id:"dosha-name",label:e("formNameLabel"),required:!0,children:[c.jsx(q.FormTextInput,{id:"dosha-name",value:y,onChange:j=>{const I=j.target.value;I&&!H.current&&(H.current=!0,f?.trackNameSectionFilled?.()),x(I),Q.name&&b(ie=>({...ie,name:void 0})),fe&&ke(null)},placeholder:e("formNamePlaceholder"),autoComplete:"name"}),Q.name&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.name})]})}),c.jsxs(q.FormField,{id:"dosha-gender",label:e("formGenderLabel"),required:!0,children:[c.jsx(q.FormSegmentedControl,{id:"dosha-gender",options:[{value:"male",label:e("formGenderMale")},{value:"female",label:e("formGenderFemale")}],value:_,onChange:j=>{S(j),Q.gender&&b(I=>({...I,gender:void 0})),fe&&ke(null)}}),Q.gender&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.gender})]}),c.jsxs(q.FormField,{id:"dosha-problems",label:e("formProblemLabel"),children:[c.jsx(q.FormTagPills,{id:"dosha-problems",options:rr,selected:k,onChange:j=>{N(j),j.includes("formProblemOther")||te("")}}),k.includes("formProblemOther")&&c.jsxs("div",{style:{marginTop:"8px"},children:[c.jsx(q.FormTextInput,{id:"dosha-problem-other",value:ee,onChange:j=>{const I=j.target.value.slice(0,100);te(I)},placeholder:e("formProblemOtherPlaceholder")}),c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#8f6e56"},children:e("formProblemOtherHint")})]})]}),c.jsx(q.FormField,{id:"dosha-dob",label:e("formDobLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.dateOfBirth?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(pl,{id:"dosha-dob",value:O,onOpen:()=>{$e(),f?.trackDobClicked?.()},onChange:j=>{j&&!V.current&&(V.current=!0,f?.trackDobFilled?.()),B(j),Q.dateOfBirth&&b(I=>({...I,dateOfBirth:void 0})),fe&&ke(null)}}),Q.dateOfBirth&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.dateOfBirth})]})}),c.jsx(q.FormField,{id:"dosha-time",label:e("formTimeLabel"),required:!0,children:c.jsxs("div",{style:{minHeight:Q.birthTime?"72px":"48px",transition:"min-height 0.2s"},children:[c.jsx(wl,{id:"dosha-time",value:P,onOpen:()=>{$e(),f?.trackTimeClicked?.()},onChange:j=>{j&&!M.current&&(M.current=!0,f?.trackTimeFilled?.()),U(j),Q.birthTime&&b(I=>({...I,birthTime:void 0})),fe&&ke(null)},disabled:$}),Q.birthTime&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthTime})]})}),c.jsx(q.FormCheckboxWithHelp,{id:"dosha-time-unknown",checked:$,onChange:j=>{$e(),f?.trackTimeCheckboxClicked?.(),De(j),j&&Q.birthTime&&b(I=>({...I,birthTime:void 0}))},primaryText:e("formTimeUnknown"),helpText:e("formTimeUnknownHelp")}),c.jsx("div",{onFocusCapture:()=>{$e(),f?.trackPlaceOfBirthClicked?.()},children:c.jsx(q.FormField,{id:"dosha-place",label:e("formPlaceLabel"),required:!0,children:c.jsxs("div",{ref:J,style:{position:"relative"},children:[c.jsx(q.FormLocationInput,{id:"dosha-place",value:ge,onChange:j=>{const I=g(j.target.value);Ee(I),Qe(null),re(!0),I&&!L.current&&(L.current=!0,f?.trackPlaceOfBirthChosen?.(I)),Q.birthPlace&&b(ie=>({...ie,birthPlace:void 0})),fe&&ke(null)},onFocus:()=>re(!0),placeholder:e("formPlacePlaceholder")}),Q.birthPlace&&c.jsx("p",{style:{marginTop:"6px",fontSize:"12px",color:"#dc2626"},children:Q.birthPlace}),Oe&&se.length>0&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",maxHeight:"240px",overflowY:"auto",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},role:"listbox",children:se.slice(0,8).map(j=>c.jsxs("button",{type:"button",onClick:async()=>{if(Ee(g(j.description)),$t){const I=await $t(j.place_id);I&&(Qe({lat:I.lat,lon:I.lng}),Q.birthPlace&&b(ie=>({...ie,birthPlace:void 0})),fe&&ke(null))}Fe(),re(!1),L.current||(L.current=!0,f?.trackPlaceOfBirthChosen?.(j.description))},style:{width:"100%",padding:"10px 12px",textAlign:"left",border:"none",backgroundColor:"transparent",cursor:"pointer",display:"flex",flexDirection:"column",gap:"2px",outline:"none"},onMouseEnter:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onMouseLeave:I=>{I.currentTarget.style.backgroundColor="transparent"},onFocus:I=>{I.currentTarget.style.backgroundColor="rgba(247, 94, 34, 0.06)"},onBlur:I=>{I.currentTarget.style.backgroundColor="transparent"},children:[c.jsx("span",{style:{fontSize:"14px",fontWeight:600,color:"#111827"},children:j.structured_formatting?.main_text??j.description}),j.structured_formatting?.secondary_text&&c.jsx("span",{style:{fontSize:"12px",color:"#6b7280"},children:j.structured_formatting.secondary_text})]},j.place_id))}),Oe&&m&&me&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#6b7280",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:"Loading…"}),Oe&&m&&!me&&le&&c.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,right:0,padding:"10px 12px",backgroundColor:"#fff",border:"1px solid rgba(229, 231, 235, 0.95)",borderRadius:"12px",fontSize:"12px",color:"#dc2626",boxShadow:"0 10px 24px rgba(17, 24, 39, 0.12)",zIndex:9999},children:le})]})})}),c.jsxs(q.FormFooterNote,{children:["⚡ ",e("formFooterNoteBefore"),c.jsx("strong",{children:e("formFooterNoteBold")}),e("formFooterNoteAfter")]}),fe&&c.jsxs("div",{style:{marginTop:"4px",width:"100%",borderRadius:"14px",border:"1px solid #FCA5A5",background:"#FEF2F2",padding:"16px",display:"flex",alignItems:"flex-start",gap:"10px"},role:"alert","aria-live":"assertive",children:[c.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:"16px",height:"16px",marginTop:"2px",flexShrink:0},"aria-hidden":"true",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),c.jsx("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),c.jsx("p",{style:{margin:0,fontSize:"14px",lineHeight:"1.5",color:"#EF4444"},children:fe})]})]})}),Dt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`animate-pulse rounded-md bg-muted ${t}`,...e}));Dt.displayName="Skeleton";const it=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`rounded-lg border border-border bg-card text-card-foreground shadow-sm ${t}`,...e}));it.displayName="Card";const pt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`flex flex-col space-y-1.5 p-6 ${t}`,...e}));pt.displayName="CardHeader";const gt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("h3",{ref:r,className:`text-2xl font-semibold leading-none tracking-tight ${t}`,...e}));gt.displayName="CardTitle";const Er=Re.forwardRef(({className:t="",...e},r)=>c.jsx("p",{ref:r,className:`text-sm text-muted-foreground ${t}`,...e}));Er.displayName="CardDescription";const yt=Re.forwardRef(({className:t="",...e},r)=>c.jsx("div",{ref:r,className:`p-6 pt-0 ${t}`,...e}));yt.displayName="CardContent";const er=Re.forwardRef(({className:t="",size:e="default",variant:r="default",...s},n)=>{const a={default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8"},i={default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"};return c.jsx("button",{ref:n,type:"button",className:`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 ${a[e]} ${i[r]} ${t}`,...s})});er.displayName="Button";function xn({puja:t,doshaType:e,language:r,onBookClick:s,imageComponent:n=tt,analytics:a}){const i=n,o=r?.toLowerCase().startsWith("hi"),l=rs(t,r),u=dn(t,r),d=hn(t.schedule_date_ist,r),f=ss(t,r),m=fn(t,r),p=async()=>{if(a?.trackDoshaCalculatorResultBookCtaClicked?.({position:"puja_card",url:f,isOldDosha:!1}),s)try{await s()}catch(g){console.error("Error in onBookClick:",g)}window.open(f,"_blank","noopener,noreferrer")};return c.jsx(it,{className:"overflow-hidden hover:shadow-lg transition-shadow relative",children:c.jsxs("div",{className:"relative",children:[c.jsx("div",{className:"absolute -top-1 -left-1 z-10",children:c.jsx("span",{className:"inline-flex items-center px-2 py-1 text-[10px] font-medium bg-destructive/90 text-destructive-foreground rounded-br-md shadow-sm",children:o?"सीमित सीटें":"Limited Seats"})}),m&&c.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden bg-muted",children:c.jsx(i,{src:m,alt:l,className:"w-full h-full object-contain",loading:"lazy"})}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsx("h4",{className:"font-semibold text-sm line-clamp-2 text-card-foreground",children:l}),t.temple_name&&c.jsx("p",{className:"text-sm text-muted-foreground",children:u}),t.schedule_date_ist&&c.jsx("p",{className:"text-sm font-medium text-card-foreground",children:d}),t.individual_pack_price_inr>0&&c.jsx("p",{className:"text-base font-bold text-primary",children:o?`₹${t.individual_pack_price_inr} से शुरू`:`Starting from ₹${t.individual_pack_price_inr}`}),c.jsxs(er,{size:"lg",className:"book-puja-cta w-full h-14 text-lg font-bold",onClick:async g=>{g.preventDefault(),await p()},children:[o?"पूजा बुक करें":"Book Puja",c.jsx(ol,{className:"ml-1.5 h-3.5 w-3.5",size:14})]}),c.jsx("p",{className:"text-[10px] text-center text-muted-foreground",children:o?"श्री मंदिर द्वारा संचालित":"Powered by Sri Mandir"})]})]})})}const ot={section:"_section_15ygl_1",heading:"_heading_15ygl_5",list:"_list_15ygl_16",item:"_item_15ygl_20",stepNumber:"_stepNumber_15ygl_24",itemContent:"_itemContent_15ygl_30",itemTitle:"_itemTitle_15ygl_34",itemDesc:"_itemDesc_15ygl_39"};function Tn({t,className:e="",bannerType:r="generic"}){const s=t("whatFromAnalysisTitle"),n=r==="marriage"?"whatFromAnalysisMarriage":"whatFromAnalysisGeneric",a=[{titleKey:`${n}1Title`,descKey:`${n}1Desc`},{titleKey:`${n}2Title`,descKey:`${n}2Desc`},{titleKey:`${n}3Title`,descKey:`${n}3Desc`}];return c.jsxs("section",{className:`${ot.section} ${e}`,"aria-labelledby":"what-from-analysis-heading",children:[c.jsx("h2",{id:"what-from-analysis-heading",className:ot.heading,children:s}),c.jsx("ol",{className:ot.list,children:a.map(({titleKey:i,descKey:o},l)=>c.jsxs("li",{className:ot.item,children:[c.jsx("span",{className:ot.stepNumber,"aria-hidden":"true",children:l+1}),c.jsxs("div",{className:ot.itemContent,children:[c.jsx("span",{className:ot.itemTitle,children:t(i)}),c.jsx("span",{className:ot.itemDesc,children:t(o)})]})]},i))})]})}const jl={marriage:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137437775.webp",alt:"Marriage dosha analysis banner",tickerText:"★ 4.9 Rated By Users Facing Marriage Delay"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137493287.webp",alt:"विवाह दोष विश्लेषण बैनर",tickerText:"★ 4.9 शादी में देरी का सामना कर रहे उपयोगकर्ताओं द्वारा रेटेड"}},generic:{en:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137415503.webp",alt:"Dosha analysis banner",tickerText:"★ 4.9 Rated By Users Seeking Clarity"},hi:{imageUrl:"https://srm-cdn.a4b.io/yoda/1773137476046.webp",alt:"दोष विश्लेषण बैनर",tickerText:"★ 4.9 रेटिंग अपने दोषा को जानने वाले यूज़र्स ने दी"}}},Al={"marriage-what-you'll-get-first":"marriage","marriage-form-first":"marriage","generic-what-you'll-get-first":"generic","generic-form-first":"generic"};function jn(t,e){let r="generic";if(t){for(const[s,n]of Object.entries(Al))if(t.includes(s)){r=n;break}}return jl[r][e]}function Pl(t){return typeof window>"u"?null:new URLSearchParams(window.location.search).get(t)}function Or(){return Pl("utm_term")}const El=v.lazy(()=>Promise.resolve().then(()=>Yl).then(t=>({default:t.DoshaResultsFull}))),Ol="https://srm-cdn.a4b.io/yoda/1770362904947.svg",Cl="https://srm-cdn.a4b.io/yoda/1770375694934.svg",Rl="https://srm-cdn.a4b.io/yoda/1770375720933.svg",Nl="https://srm-cdn.a4b.io/yoda/1770707793537.svg",Il="https://srm-cdn.a4b.io/yoda/1770362713543.svg";function An(t){const e=new Set([t]);switch(t){case"kaal-sarp":e.add("kaalSarp"),e.add("kaalsarp"),e.add("kaal_sarp");break;case"shani":e.add("sadeSati"),e.add("shaniSadeSati"),e.add("sade-sati");break;case"mangal":e.add("mangalDosha"),e.add("manglik");break;case"pitra":e.add("pitru"),e.add("pitraDosha");break}return Array.from(e)}function Cr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Pn(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function En(t){if(!t||typeof window>"u")return t;try{const e=new URLSearchParams(window.location.search);if(Array.from(e.keys()).length===0)return t;const r=new URL(t,window.location.href);return e.forEach((s,n)=>{r.searchParams.set(n,s)}),r.toString()}catch{return t}}function ls(t){const e=[];return Cr(t.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof t.kaalSarpSeverity=="string"?t.kaalSarpSeverity:void 0}),Cr(t.pitra)&&e.push({type:"pitra",severity:typeof t.pitraSeverity=="string"?t.pitraSeverity:void 0}),Cr(t.shaniSadeSati||t.sadeSati)&&e.push({type:"shani",severity:typeof t.sadeSatiSeverity=="string"?t.sadeSatiSeverity:void 0}),Cr(t.mangal)&&!t.mangal?.toLowerCase().includes("nullified")&&e.push({type:"mangal",severity:typeof t.mangalSeverity=="string"?t.mangalSeverity:void 0}),e.length===0?null:(e.sort((r,s)=>Pn(s.severity)-Pn(r.severity)),e[0]?.type??null)}function Dl({t}){return c.jsxs("div",{className:q.footerShellStyles.marqueeContent,children:[c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Cl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaKundliCreated")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Rl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaCertified")]}),c.jsxs("span",{className:q.footerShellStyles.badge,children:[c.jsx(tt,{src:Nl,alt:"",className:q.footerShellStyles.badgeIcon,width:16,height:16,loading:"lazy"}),t("ctaSecurePayment")]})]})}const $l=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Ll=[{qKey:"faqQ1Marriage",aKey:"faqA1Marriage"},{qKey:"faqQ2Marriage",aKey:"faqA2Marriage"},{qKey:"faqQ3Marriage",aKey:"faqA3Marriage"},{qKey:"faqQ4Marriage",aKey:"faqA4Marriage"}];function Ul({className:t="",logoUrl:e=Ol,languageSelector:r,showLanguageSelector:s=!0,isGlobal:n=!1,readMoreReviewsHref:a,supabaseUrl:i,supabaseAnonKey:o,googleMapsApiKey:l,supabase:u,resolvePlace:d,onResult:f,onError:m,renderPujaCard:p,isLoadingPujas:g=!1,renderKundali:y,kundaliSectionId:x="kundali-chart-section",analytics:_,getFirstPujaInfo:S,onBookPujaClick:k,imageComponent:N=tt}){const O=v.useMemo(()=>{if(u)return u;if(i&&o)try{return rn(i,o)}catch{return null}return null},[u,i,o]),B=N,P=ns(),U=P?.t??(C=>C),$=P?.locale??"en",De=P?.setLocale,ge=$.toLowerCase().startsWith("hi"),Ee=v.useRef(null),ee=v.useRef(null),[te,he]=v.useState(!1),[Qe,Oe]=v.useState(!1),[re,fe]=v.useState(null),[ke,Q]=v.useState(null),[b,K]=v.useState(void 0),[z,H]=v.useState(!1),[V,M]=v.useState([]),[L,J]=v.useState(!1),[se,me]=v.useState(null),le=v.useRef(!1);v.useEffect(()=>{le.current||(le.current=!0,_?.trackDoshaCalculatorWebView?.())},[]);const Te=!p||!S;v.useEffect(()=>{if(!Te||!O)return;let C=!0;return J(!0),Go(O).then(ne=>{C&&M(ne)}).finally(()=>{C&&J(!1)}),()=>{C=!1}},[Te,O]);const $t=v.useCallback(C=>{const ne=an(V,C);return ne?c.jsx(xn,{puja:ne,doshaType:C,language:$,imageComponent:N,analytics:_}):null},[V,$,N,_]),Fe=v.useCallback(C=>{const ne=an(V,C);return ne?{name:rs(ne,$),price:ne.individual_pack_price_inr,link:ss(ne,$)}:null},[V,$]),$e=p??$t,bt=S??Fe,vt=g||!p&&L,[rt,rr]=v.useState(()=>{const C=typeof window<"u"?Or():null;return jn(C,$)}),[j,I]=v.useState(()=>{if(typeof window>"u")return"generic";const C=Or();return C&&C.toLowerCase().includes("marriage")?"marriage":"generic"});v.useEffect(()=>{const C=Or(),ne=jn(C,$);rr(ne);let Se="generic";C&&C.toLowerCase().includes("marriage")&&(Se="marriage"),I(Se)},[$]);const[ie,ze]=v.useState(!1);v.useEffect(()=>{const C=Or();C&&C.toLowerCase().includes("what-you")&&ze(!0)},[]);const lt=()=>{Ee.current?.scrollIntoView({behavior:"smooth"})},_e=v.useCallback(C=>{_?.trackDoshaSectionImpression?.({section:C,timestamp:new Date().toISOString()})},[_]),ce=(C,ne)=>{if(fe(C),Q(ne??null),H(!1),C.summary){const Se=C.summary,xe=ls(Se);if(xe){const ye=An(xe).map(nr=>bt(nr)).find(Boolean)??null;me(ye)}else me(null)}else me(null);f?.(C,ne)};v.useEffect(()=>{if(S||!re?.summary)return;const C=ls(re.summary);if(!C){me(null);return}const ne=An(C).map(Se=>Fe(Se)).find(Boolean)??null;me(ne)},[Fe,S,re]);const je=()=>{H(!0),window.scrollTo({top:0,behavior:"smooth"})},qe=()=>{if(re&&!z&&se){if(se.link){const C=En(se.link);_?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:C,isOldDosha:!1})}if(k)k();else if(se.link){const C=En(se.link);window.open(C,"_blank","noopener,noreferrer")}return}console.log("supabase",O),console.log("resolvePlaceProp",d),console.log("isFormComplete",te),console.log("formSubmitRef.current",ee.current),O&&ee.current?(_?.trackFloatingCtaClicked?.(te?cr.all_fields_filled:cr.fields_not_filled),te||lt(),ee.current.submit()):(_?.trackFloatingCtaClicked?.(cr.fields_not_filled),lt())},sr=s&&!n?c.jsxs("button",{type:"button",onClick:()=>{De&&De(ge?"en":"hi")},"aria-label":ge?"Switch to English":"हिंदी में बदलें",className:"flex items-center justify-center gap-1.5 py-2 rounded-lg text-white text-sm font-medium hover:opacity-90 transition-colors",style:{backgroundColor:"#E13A44",borderRadius:"8px",width:"100px"},disabled:!De,children:[c.jsx(B,{src:Il,alt:"",className:"w-5 h-5 brightness-0 invert",width:20,height:20,loading:"lazy"}),c.jsx("span",{children:ge?"English":"हिंदी"})]}):null;return c.jsxs("div",{className:t,children:[c.jsx(q.PageHeader,{t:U,logoUrl:e,languageSelector:sr,showLanguageSelector:s}),c.jsx(q.MarqueeStrip,{children:c.jsx(Dl,{t:U})}),!re&&c.jsx(at,{section:"banner",onImpression:_e,children:c.jsx(dl,{bannerConfig:rt,imageComponent:N})}),c.jsx("main",{className:"pb-28",children:re?c.jsx(at,{section:"result",onImpression:_e,children:c.jsx(v.Suspense,{fallback:c.jsxs("div",{className:"container mx-auto px-4 py-8 space-y-4",children:[c.jsx(Dt,{className:"h-12 w-3/4 mx-auto"}),c.jsx(Dt,{className:"h-32 w-full"}),c.jsx(Dt,{className:"h-48 w-full"}),c.jsx(Dt,{className:"h-48 w-full"})]}),children:c.jsx(El,{result:re,t:U,onEdit:z?void 0:je,inlineEditForm:z?c.jsx(os,{ref:ee,t:U,initialValues:b,onValuesChange:K,onFormValidityChange:he,supabase:O??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:_}):void 0,renderPujaCard:$e,isLoadingPujas:vt,renderKundali:y,kundaliSectionId:x,birthDetails:ke,supabase:O,language:P?.locale??"en",readMoreReviewsHref:a,analytics:_,problemArea:(()=>{const C=b?.problems||[],ne=C.filter(xe=>xe!=="formProblemOther").map(xe=>U(xe)).filter(Boolean),Se=b?.otherProblemText?.trim();return C.includes("formProblemOther")&&Se&&ne.push(Se),ne.join(", ")})(),problemAreaIds:b?.problems||[],customProblemText:b?.otherProblemText||""})})}):c.jsxs(c.Fragment,{children:[ie&&c.jsx(at,{section:"what_from_analysis",onImpression:_e,children:c.jsx(Tn,{t:U,bannerType:j})}),c.jsx(at,{section:"form",onImpression:_e,children:c.jsx("div",{ref:Ee,children:c.jsx(os,{ref:ee,t:U,initialValues:b,onValuesChange:K,onFormValidityChange:he,supabase:O??void 0,resolvePlace:d,googleMapsApiKey:l,onResult:ce,onError:m,onLoadingChange:Oe,analytics:_})})}),!ie&&c.jsx(at,{section:"what_from_analysis",onImpression:_e,children:c.jsx(Tn,{t:U,bannerType:j})}),c.jsx(at,{section:"user_reviews",onImpression:_e,children:c.jsx(q.UserReviewsSection,{t:C=>{if(j==="marriage"){if(C==="feedbackTitle")return U("feedbackTitleMarriage");if(C.startsWith("feedbackTestimonial")){const Se=`feedbackTestimonialMarriage${C.replace("feedbackTestimonial","")}`,xe=U(Se);return xe===Se?U(C):xe}}return U(C)},readMoreHref:a,onReadMore:_?.trackReadMoreReviewsClicked?()=>_.trackReadMoreReviewsClicked():void 0})}),c.jsx(at,{section:"faq",onImpression:_e,children:c.jsx(q.FAQAccordion,{t:U,items:j==="marriage"?Ll:$l,defaultOpenIndex:0,onItemOpen:C=>_?.trackFaqQuestionClicked?.(C)})}),c.jsx(at,{section:"contact",onImpression:_e,children:c.jsx(q.ContactUsSection,{title:U("contactTitle"),brandName:U("contactBrandName"),whatsAppLine:U("contactWhatsAppDomestic"),emailLine:U("contactEmail")})})]})}),!(re&&!z&&ls(re.summary)===null)&&c.jsxs(q.FooterShell,{children:[!(re&&!z&&se)&&c.jsx(tl,{}),c.jsx(ul,{isFormComplete:te,onPress:qe,labelDefault:U("formCta"),labelFilled:U("formCtaCalculate"),loadingLabel:U("calculating"),isLoading:Qe,mode:re&&!z&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!z,bookPujaLabel:U("bookPuja")})]})]})}const oe={section:"_section_ji9so_1",heading:"_heading_ji9so_6",headingSuccess:"_headingSuccess_ji9so_13",card:"_card_ji9so_17",cardPresent:"_cardPresent_ji9so_25",cardAbsent:"_cardAbsent_ji9so_29",cardHeader:"_cardHeader_ji9so_33",doshaName:"_doshaName_ji9so_41",badge:"_badge_ji9so_46",badgePresent:"_badgePresent_ji9so_53",badgeAbsent:"_badgeAbsent_ji9so_58",badgeInactive:"_badgeInactive_ji9so_63",body:"_body_ji9so_68",bodyLabel:"_bodyLabel_ji9so_75",noDoshas:"_noDoshas_ji9so_81",noDoshasDesc:"_noDoshasDesc_ji9so_88",editBtn:"_editBtn_ji9so_94",accordionContent:"_accordionContent_ji9so_128"},Ml=[{key:"mangal",labelKey:"resultMangal",summaryKey:"mangal"},{key:"kaalSarp",labelKey:"resultKaalSarp",summaryKey:"kaalSarp"},{key:"pitra",labelKey:"resultPitra",summaryKey:"pitra"},{key:"sadeSati",labelKey:"resultSadeSati",summaryKey:"shaniSadeSati"}];function tr(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Bl(t,e){if(Array.isArray(t))return t.find(s=>(s.name??s.type)===e);if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
168
+ `):void 0;return{explanation:r.explanation,remedies:s}}}function Kl(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")||r==="present"||r==="active"||r==="partial"||r==="suggested"?e("resultStatusPresent"):r==="absent"?e("resultStatusAbsent"):r==="inactive"?e("resultStatusInactive"):t}function Fl({result:t,t:e,onEdit:r,className:s=""}){const n=t.summary??{},a=t.details??{},i=n.shaniSadeSati??n.sadeSati,o=tr(n.mangal)||tr(n.kaalSarp)||tr(n.pitra)||tr(i);return c.jsxs("section",{className:`${oe.section} ${s}`,"aria-labelledby":"dosha-results-heading",children:[c.jsx("h2",{id:"dosha-results-heading",className:o?`${oe.heading} ${oe.headingSuccess}`:oe.heading,children:e(o?"resultSomeDoshas":"resultNoDoshas")}),o?c.jsx("div",{children:Ml.map(({key:l,labelKey:u,summaryKey:d})=>{const f=d==="shaniSadeSati"?i:n[d],m=tr(f),p=Bl(a,l==="sadeSati"?"sadeSati":l),g=p?.explanation,y=typeof p?.remedies=="string"?p.remedies:void 0;return c.jsxs("div",{className:`${oe.card} ${m?oe.cardPresent:oe.cardAbsent}`,children:[c.jsxs("div",{className:oe.cardHeader,children:[c.jsx("span",{className:oe.doshaName,children:e(u)}),c.jsx("span",{className:`${oe.badge} ${m?oe.badgePresent:f==="inactive"?oe.badgeInactive:oe.badgeAbsent}`,children:Kl(f,e)})]}),(g||y)&&c.jsxs("div",{className:oe.body,children:[g&&c.jsxs("div",{children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultExplanation")}),c.jsx("p",{className:oe.accordionContent,children:g})]}),y&&c.jsxs("div",{style:{marginTop:g?"0.75rem":0},children:[c.jsx("div",{className:oe.bodyLabel,children:e("resultRemedies")}),c.jsx("p",{className:oe.accordionContent,children:y})]})]})]},l)})}):c.jsxs("div",{className:oe.noDoshas,children:[c.jsx("p",{children:e("resultNoDoshas")}),c.jsx("p",{className:oe.noDoshasDesc,children:e("resultNoDoshasDesc")})]}),r&&c.jsx("button",{type:"button",className:oe.editBtn,onClick:r,"aria-label":e("resultEditForm"),children:e("resultEditForm")})]})}const Rr=Re.forwardRef(({className:t="",variant:e="default",...r},s)=>{const n={default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-transparent bg-destructive/10 text-destructive",outline:"border-border text-muted-foreground bg-transparent"};return c.jsx("div",{ref:s,className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors ${n[e]} ${t}`,...r})});Rr.displayName="Badge";const cs=Re.createContext(null);function On({type:t="single",collapsible:e=!0,className:r="",children:s,onValueChange:n}){const[a,i]=Re.useState(null),o=Re.useCallback(l=>{i(u=>{const d=u===l?e?null:u:l;return n?.(d),d})},[e,n]);return c.jsx(cs.Provider,{value:{value:a,onToggle:o},children:c.jsx("div",{className:r,children:s})})}function Cn({value:t,className:e="",children:r}){return c.jsx("div",{"data-state":t,className:`border-b border-border ${e}`,children:r})}function Rn({className:t="",children:e,value:r}){const s=Re.useContext(cs),n=s?.value===r;return c.jsxs("button",{type:"button",onClick:()=>s?.onToggle(r),className:`flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline w-full text-left ${t}`,"aria-expanded":n,children:[e,c.jsx(bn,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function Nn({className:t="",children:e,value:r}){return Re.useContext(cs)?.value===r?c.jsx("div",{className:`overflow-hidden text-sm pb-4 pt-0 ${t}`,children:e}):null}const us=new Map,In=1800*1e3;function ql(t,e,r){return`D1|${e}|svg|${t.day}-${t.month}-${t.year}-${t.hour}-${t.minute}-${t.lat}-${t.lon}-${t.tzone}|${r}`}function Wl(t){const e=us.get(t);if(e&&Date.now()-e.timestamp<In)return e.svg;try{const r=sessionStorage.getItem(`kundali_${t}`);if(r){const s=JSON.parse(r);if(Date.now()-s.timestamp<In)return us.set(t,s),s.svg;sessionStorage.removeItem(`kundali_${t}`)}}catch{}return null}function Hl(t,e){const r={svg:e,timestamp:Date.now()};us.set(t,r);try{sessionStorage.setItem(`kundali_${t}`,JSON.stringify(r))}catch{}}function Gl(t){try{const r=new DOMParser().parseFromString(t,"image/svg+xml"),s=r.querySelector("svg");return s?(s.removeAttribute("width"),s.removeAttribute("height"),s.getAttribute("viewBox")||s.setAttribute("viewBox","0 0 350 350"),s.setAttribute("preserveAspectRatio","xMidYMid meet"),s.setAttribute("style","width:100%;height:auto;display:block;"),new XMLSerializer().serializeToString(r)):t}catch(e){return console.error("[kundaliChart] SVG transform error:",e),t}}async function Dn(t,e){const{birthDetails:r,chartType:s,language:n,signal:a}=e,i=ql(r,s,n),o=Wl(i);if(o)return o;const l=await t.functions.invoke("get-kundali-chart",{body:{...r,chartType:s,language:n}});if(a?.aborted)throw new DOMException("Aborted","AbortError");if(l.error)throw new Error(l.error.message||"Failed to fetch kundali chart");const u=l.data?.data?.svg;if(!u)throw new Error("No SVG data in response");const d=Gl(u);return Hl(i,d),d}function $n({birthDetails:t,supabase:e,language:r,t:s}){const[n,a]=v.useState("North"),[i,o]=v.useState("idle"),[l,u]=v.useState(""),[d,f]=v.useState(""),m=v.useRef(null),p=v.useRef(null),y=(r||"").toLowerCase().startsWith("hi")?"hi":"en",x=v.useCallback(async k=>{m.current&&m.current.abort();const N=new AbortController;m.current=N,o("loading"),f("");try{const O=await Dn(e,{birthDetails:t,chartType:k,language:y,signal:N.signal});N.signal.aborted||(u(O),o("success"))}catch(O){if(O instanceof Error&&O.name==="AbortError")return;console.error("[KundaliCard] Fetch error:",O),N.signal.aborted||(f(O instanceof Error?O.message:"Failed to load chart"),o("error"))}},[t,e,y]);v.useEffect(()=>(x(n),()=>{m.current&&m.current.abort()}),[n,x]);const _=k=>{k!==n&&a(k)},S=()=>{x(n)};return c.jsxs(it,{ref:p,className:"spiritual-glow border border-primary/10",children:[c.jsxs(pt,{className:"pb-3",children:[c.jsx(gt,{className:"text-xl font-bold",children:s("drYourKundali")}),c.jsxs("div",{className:"flex gap-2 mt-3 pt-2",children:[c.jsx(er,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>_("North"),children:s("kundaliChartNorth")}),c.jsx(er,{type:"button",size:"sm",variant:n==="South"?"default":"outline",className:"rounded-full px-4",onClick:()=>_("South"),children:s("kundaliChartSouth")})]})]}),c.jsx(yt,{children:c.jsxs("div",{className:"w-full max-w-[360px] mx-auto",children:[i==="loading"&&c.jsx(Dt,{className:"w-full aspect-square rounded-lg"}),i==="success"&&l&&c.jsx("div",{className:"w-full aspect-square",dangerouslySetInnerHTML:{__html:l}}),i==="error"&&c.jsxs("div",{className:"w-full aspect-square flex flex-col items-center justify-center bg-muted/30 rounded-lg border border-border",children:[c.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:s("kundaliChartLoadError")}),c.jsxs(er,{type:"button",variant:"outline",size:"sm",onClick:S,className:"gap-2",children:[c.jsx(ll,{className:"w-4 h-4"}),s("kundaliChartRetry")]})]})]})})]})}const zl=[{qKey:"faqQ1",aKey:"faqA1"},{qKey:"faqQ2",aKey:"faqA2"},{qKey:"faqQ3",aKey:"faqA3"}],Ln=[{type:"kaal-sarp",detailKey:"kaalSarp",nameKey:"drKaalSarpName",descKey:"drKaalSarpDesc",impactKey:"drKaalSarpImpact",remediesKey:"drKaalSarpRemedies",benefitsKey:"drPujaBenefitsKaalSarp",icon:sl,summaryKey:"kaalSarp",severityKey:"kaalSarpSeverity"},{type:"pitra",detailKey:"pitra",nameKey:"drPitraName",descKey:"drPitraDesc",impactKey:"drPitraImpact",remediesKey:"drPitraRemedies",benefitsKey:"drPujaBenefitsPitra",icon:nl,summaryKey:"pitra",severityKey:"pitraSeverity"},{type:"shani",detailKey:"sadeSati",nameKey:"drSadeSatiName",descKey:"drSadeSatiDesc",impactKey:"drSadeSatiImpact",remediesKey:"drSadeSatiRemedies",benefitsKey:"drPujaBenefitsShani",icon:al,summaryKey:"shaniSadeSati",severityKey:"sadeSatiSeverity"},{type:"mangal",detailKey:"mangal",nameKey:"drMangalName",descKey:"drMangalDesc",impactKey:"drMangalImpact",remediesKey:"drMangalRemedies",benefitsKey:"drPujaBenefitsMangal",icon:rl,summaryKey:"mangal",severityKey:"mangalSeverity"}];function Vl(t,e){const r=new Set([t]);switch(e&&r.add(e),t){case"kaal-sarp":r.add("kaalSarp"),r.add("kaalsarp"),r.add("kaal_sarp");break;case"shani":r.add("sadeSati"),r.add("shaniSadeSati"),r.add("sade-sati");break;case"mangal":r.add("mangalDosha"),r.add("manglik");break;case"pitra":r.add("pitru"),r.add("pitraDosha");break}return Array.from(r)}function Ke(t){if(!t)return!1;const e=t.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function Nr(t){return t?t.toLowerCase().includes("nullified"):!1}function Un(t,e){if(Array.isArray(t)){const r=t.find(a=>(a.name??a.type)===e);if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
169
+ `):void 0,n=Array.isArray(r.placements)?r.placements:void 0;return{explanation:r.explanation,remedies:s,placements:n}}if(t&&typeof t=="object"&&e in t){const r=t[e];if(!r)return;const s=typeof r.remedies=="string"?r.remedies:Array.isArray(r.remedies)?r.remedies.join(`
170
+ `):void 0;return{explanation:r.explanation,remedies:s,placements:r.placements}}}function Mn(t,e){if(!t)return"";const r=t.toLowerCase();return r.includes("nullified")?e("drStatusNullified"):r==="present"||r==="active"||r==="partial"||r==="suggested"?e("drStatusPresent"):r==="absent"?e("drStatusAbsent"):r==="inactive"?e("drStatusInactive"):t}function Bn(t){if(!t)return 2;const e=t.toLowerCase();return e==="severe"||e==="high"?3:e==="moderate"||e==="medium"?2:e==="mild"||e==="low"?1:2}function Kn(t,e){if(!t)return e("drSeverityMedium");const r=t.toLowerCase();return e(r==="severe"||r==="high"?"drSeverityHigh":r==="moderate"||r==="medium"?"drSeverityMedium":r==="mild"||r==="low"?"drSeverityLow":"drSeverityMedium")}function Jl(t){return!t||/[\u0900-\u097F]/.test(t)?!1:/[A-Za-z]/.test(t)}function Fn({result:t,t:e,onEdit:r,className:s="",kundaliSectionId:n,feedbackEmail:a="pujaseva@appsforbharat.com",renderPujaCard:i,isLoadingPujas:o=!1,renderKundali:l,birthDetails:u,supabase:d,language:f="en",readMoreReviewsHref:m,inlineEditForm:p,analytics:g,problemArea:y,problemAreaIds:x,customProblemText:_}){const[S,k]=v.useState({}),[N,O]=v.useState(!1),B=!l&&u&&d,P=t.summary??{},U=t.details??{};v.useEffect(()=>{if(!y||!y.trim()||!d){O(!1);return}O(!0),k({}),(async()=>{const K={},H=["mangal","kaal-sarp","pitra","shani"].filter(M=>M==="mangal"?Ke(P.mangal)&&!Nr(P.mangal):M==="kaal-sarp"?Ke(P.kaalSarp):M==="pitra"?Ke(P.pitra):M==="shani"?Ke(P.shaniSadeSati??P.sadeSati):!1);console.log("[DoshaResultsFull] Generating impacts for:",H,"problemArea:",y);const V=H.map(async M=>{try{const L={formProblemMarriage:"marriage",formProblemMoney:"financial",formProblemHealth:"health",formProblemEducation:"education",formProblemCareer:"career",formProblemBusiness:"business",formProblemFamily:"family",formProblemFinancial:"financial",formProblemOther:"other"},J=x?.filter(le=>le!=="formProblemOther").map(le=>L[le]||le.toLowerCase()).filter(Boolean)||[];x?.includes("formProblemOther")&&_?.trim()&&J.push("other");const se=J[0]||void 0;console.log(`[DoshaResultsFull] Calling generate-impact for ${M}`,{originalProblemAreaIds:x,mappedProblemAreaIds:J,problemArea:y,problemAreaId:se,customProblemText:_,language:f?.toLowerCase().startsWith("hi")?"hi":"en"});const me=await d.functions.invoke("generate-impact",{body:{doshaType:M,problemArea:y,problemAreaId:se,problemAreaIds:J,customProblemText:_,language:f?.toLowerCase().startsWith("hi")?"hi":"en"}});if(console.log(`[DoshaResultsFull] Impact response for ${M}:`,me.data),me.error){console.error(`[DoshaResultsFull] Error generating impact for ${M}:`,me.error);return}me.data?.impactText&&(K[M]={title:me.data.impactTitle||e("drImpactIfPresent"),text:me.data.impactText})}catch(L){console.error(`[DoshaResultsFull] Failed to generate impact for ${M}:`,L)}});await Promise.all(V),console.log("[DoshaResultsFull] Final personalized impacts:",K),k(K),O(!1)})()},[y,x,_,f,d,P]),v.useEffect(()=>{g?.trackDoshaCalculatorResultPageView?.()},[g]);const $=P.shaniSadeSati??P.sadeSati,De=[{summaryKey:"grahan",detailKey:"grahan",labelKey:"drOtherGrahan",descKey:"drOtherGrahanDesc",impactKey:"drOtherGrahanImpact",remediesKey:"drOtherGrahanRemedies"},{summaryKey:"shrapit",detailKey:"shrapit",labelKey:"drOtherShrapit",descKey:"drOtherShrapitDesc",impactKey:"drOtherShrapitImpact",remediesKey:"drOtherShrapitRemedies"},{summaryKey:"guruChandal",detailKey:"guruChandal",labelKey:"drOtherGuruChandal",descKey:"drOtherGuruChandalDesc",impactKey:"drOtherGuruChandalImpact",remediesKey:"drOtherGuruChandalRemedies"},{summaryKey:"punarphoo",detailKey:"punarphoo",labelKey:"drOtherPunarphoo",descKey:"drOtherPunarphooDesc",impactKey:"drOtherPunarphooImpact",remediesKey:"drOtherPunarphooRemedies"},{summaryKey:"kemadruma",detailKey:"kemadruma",labelKey:"drOtherKemadruma",descKey:"drOtherKemadrumaDesc",impactKey:"drOtherKemadrumaImpact",remediesKey:"drOtherKemadrumaRemedies"},{summaryKey:"gandmool",detailKey:"gandmool",labelKey:"drOtherGandmool",descKey:"drOtherGandmoolDesc",impactKey:"drOtherGandmoolImpact",remediesKey:"drOtherGandmoolRemedies"},{summaryKey:"kalathra",detailKey:"kalathra",labelKey:"drOtherKalathra",descKey:"drOtherKalathraDec",impactKey:"drOtherKalathraImpact",remediesKey:"drOtherKalathraRemedies"},{summaryKey:"vishDaridra",detailKey:"vishDaridra",labelKey:"drOtherVishDaridra",descKey:"drOtherVishDaridraDesc",impactKey:"drOtherVishDaridraImpact",remediesKey:"drOtherVishDaridraRemedies"},{summaryKey:"ketuNaga",detailKey:"ketuNaga",labelKey:"drOtherKetuNaga",descKey:"drOtherKetuNagaDesc",impactKey:"drOtherKetuNagaImpact",remediesKey:"drOtherKetuNagaRemedies"},{summaryKey:"navagrahaUmbrella",detailKey:"navagraha",labelKey:"drOtherNavagraha",descKey:"drOtherNavagrahaDesc",impactKey:"drOtherNavagrahaImpact",remediesKey:"drOtherNavagrahaRemedies"}],Ee=De.filter(b=>Ke(P[b.summaryKey])).length>0,ee=Ke(P.mangal)&&!Nr(P.mangal)||Ke(P.kaalSarp)||Ke(P.pitra)||Ke($)||Ee,te=[];for(const b of Ln){const K=b.summaryKey==="shaniSadeSati"?$:P[b.summaryKey];if(!Ke(K)||b.type==="mangal"&&Nr(K))continue;const z=P[b.severityKey],H=b.type==="shani"?P.shaniPhase??P.shaniPhase:void 0,V=Un(U,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),M=V?.explanation,L=M&&!(f.toLowerCase().startsWith("hi")&&Jl(M))?M:e(b.descKey),se=(V?.remedies??e(b.remediesKey)).split(`
171
+ `).map(Te=>Te.trim()).filter(Boolean),le=e(b.benefitsKey).split(`
172
+ `).map(Te=>Te.trim()).filter(Boolean);te.push({type:b.type,detailKey:b.detailKey,label:e(b.nameKey),icon:b.icon,status:K??"",severity:z||"moderate",phase:H??void 0,explanation:L,placements:V?.placements,impact:e(b.impactKey),remedies:se,benefits:le})}te.sort((b,K)=>Bn(K.severity)-Bn(b.severity));const[he,Qe]=v.useState(!1),Oe=/\b(house|lagna|ascendant|moon|mars|saturn|rahu|ketu|sun|jupiter|venus|mercury|sign|degree|H\d+|conjunction|aspect)\b|भाव|लग्न|चंद्र|मंगल|शनि|राहु|केतु|सूर्य|बृहस्पति|शुक्र|बुध/i,re=U&&typeof U=="object"&&!Array.isArray(U)?U:{},fe=[];te.forEach(b=>{const K=re[b.detailKey==="sadeSati"?"sadeSati":b.detailKey]||{},z=[...K.placements||[],...K.triggeredBy||[],...K.notes||[]].map(L=>String(L||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(L=>Oe.test(L)),M=V.length>0?V:H;M.length>0&&fe.push({label:b.label,evidence:M})}),De.forEach(b=>{if(!Ke(P[b.summaryKey]))return;const K=re[b.detailKey]||{},z=[...K.placements||[],...K.triggeredBy||[],...K.notes||[]].map(L=>String(L||"").trim()).filter(Boolean),H=Array.from(new Set(z)),V=H.filter(L=>Oe.test(L)),M=V.length>0?V:H;if(M.length>0){const L=e(b.labelKey);fe.some(J=>J.label===L)||fe.push({label:L,evidence:M})}});const ke=b=>b===1?e("drPhaseRising"):b===2?e("drPhasePeak"):b===3?e("drPhaseSetting"):"",Q=["bg-orange-50/50 border-l-4 border-l-orange-400","bg-blue-50/50 border-l-4 border-l-blue-400","bg-purple-50/50 border-l-4 border-l-purple-400","bg-amber-50/50 border-l-4 border-l-amber-400"];return c.jsxs("div",{className:`w-full max-w-2xl mx-auto space-y-6 ${s}`,children:[c.jsxs("div",{className:"px-4 pt-4 pb-2 mb-6",children:[c.jsxs("div",{className:"text-center",children:[c.jsx("h1",{className:"text-2xl font-bold mb-2",style:{color:"#1F2937",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageTitle")}),c.jsx("p",{className:"text-sm leading-relaxed",style:{color:"#6B7280",fontFamily:'"Plus Jakarta Sans", sans-serif'},children:e("resultPageSubtitle")})]}),p?c.jsx("div",{className:"mt-4",children:p}):r?c.jsxs("button",{type:"button",onClick:r,className:"mt-4 inline-flex items-center gap-2 min-h-[44px] px-4 text-sm font-medium border border-gray-300 bg-white rounded-md hover:bg-gray-50 transition-colors text-gray-700",style:{fontFamily:'"Plus Jakarta Sans", sans-serif'},children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),e("resultEditForm")]}):null]}),c.jsxs(it,{className:"spiritual-glow border-2 border-primary/20 mx-4",children:[c.jsx(pt,{children:c.jsx(gt,{id:"dosha-results-heading",className:`text-2xl sm:text-3xl font-bold break-words ${ee?"text-primary":"text-success"}`,children:ee?e("resultSomeDoshas"):`✓ ${e("resultNoDoshas")}`})}),c.jsx(yt,{children:ee?c.jsx("div",{className:"flex flex-wrap gap-2",children:te.map(b=>c.jsxs("div",{className:"inline-flex items-center gap-2 bg-accent/20 border border-accent/30 px-4 py-2 rounded-full",children:[c.jsx(as,{className:"w-4 h-4 text-primary"}),c.jsxs("span",{className:"font-medium text-sm text-foreground",children:[b.label,": ",Mn(b.status,e)]})]},b.type))}):c.jsxs("div",{className:"text-center py-8",children:[c.jsx(yn,{className:"w-12 h-12 mx-auto mb-4 text-success"}),c.jsx("p",{className:"text-lg font-medium text-foreground",children:e("resultNoDoshas")}),c.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:e("resultNoDoshasDesc")})]})})]}),te.map((b,K)=>{const z=b.icon,H=b.type==="shani"&&b.phase?ke(b.phase):"",V=Q[K%Q.length],M=e("drDoshaOf").replace("{{index}}",String(K+1)).replace("{{total}}",String(te.length));return c.jsxs(it,{className:`spiritual-glow border border-primary/10 mx-4 ${V}`,children:[c.jsx("div",{className:"px-4 pt-3",children:c.jsx(Rr,{variant:"outline",className:"text-xs font-normal text-muted-foreground",children:M})}),c.jsxs(pt,{className:"pb-3 pt-2",children:[c.jsxs(gt,{className:"flex items-center gap-3 text-xl",children:[c.jsx(z,{className:"w-6 h-6 text-primary"}),b.label]}),c.jsxs(Er,{children:[e("drSeverity"),": ",Kn(b.severity,e),b.phase!=null&&` • ${e("drPhase")}: ${b.phase}`]})]}),c.jsxs(yt,{className:"space-y-4",children:[c.jsxs("div",{className:"space-y-2",children:[c.jsxs("h4",{className:"font-semibold text-base flex items-center gap-2",children:[c.jsx(jr,{className:"w-4 h-4 text-primary"}),e("drWhyMarked"),n&&c.jsxs("button",{type:"button",onClick:()=>{g?.trackDoshaCalculatorResultViewKundliClick?.();const L=document.getElementById(n);L&&L.scrollIntoView({behavior:"smooth",block:"center"})},className:"text-xs text-primary hover:underline ml-auto whitespace-nowrap",children:[e("drViewKundli")," ↓"]})]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:b.explanation}),H&&c.jsxs("div",{className:"mt-3 p-3 bg-warning/10 rounded-md border border-warning/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPhaseMeaning")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H})]}),b.type!=="pitra"&&b.placements&&b.placements.length>0&&c.jsxs("div",{className:"mt-3 p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsx("h5",{className:"font-medium text-sm mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:b.placements.map((L,J)=>c.jsx("li",{children:L},J))})]})]}),c.jsxs("div",{className:"p-4 bg-destructive/10 border border-destructive/20 rounded-lg",children:[c.jsx("h4",{className:"font-semibold text-sm mb-2 text-destructive",children:S[b.type]?.title||e("drImpactIfPresent")}),N?c.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[c.jsx(is,{className:"w-4 h-4 animate-spin"}),c.jsx("span",{children:f==="hi"?"प्रभाव विश्लेषण हो रहा है...":"Analyzing impact..."})]}):c.jsx("p",{className:"text-sm text-muted-foreground",children:S[b.type]?.text||b.impact})]}),c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base",children:e("drPujaRecommendation")}),i?o?c.jsx("div",{className:"flex items-center justify-center py-6",children:c.jsx(is,{className:"w-6 h-6 text-primary animate-spin",size:24})}):(()=>{const L=Vl(b.type,b.detailKey),J=L.map(se=>i(se)).find(Boolean);return!J&&typeof window<"u"&&console.warn(`[DoshaCalculator] renderPujaCard returned null/undefined for dosha type: ${b.type} (tried: ${L.join(", ")})`),J||c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e("drNoPujaAvailable")})})():c.jsxs("p",{className:"text-sm text-muted-foreground italic",children:[e("drNoPujaAvailable"),typeof window<"u"&&(console.warn("[DoshaCalculator] renderPujaCard prop not provided. Pass renderPujaCard to show puja recommendations."),null)]})]}),b.benefits.length>0&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h4",{className:"font-semibold text-base flex items-center gap-2",children:e("drHowPujaHelps")}),c.jsx("ul",{className:"text-sm text-muted-foreground space-y-3 ml-1",children:b.benefits.map((L,J)=>c.jsxs("li",{className:"flex items-start gap-3",children:[c.jsx("span",{className:"text-primary mt-1.5 flex-shrink-0",children:"•"}),c.jsx("span",{children:L})]},J))})]})]})]},b.type)}),te.length>0&&c.jsx("p",{className:"text-xs text-muted-foreground text-center italic px-4",children:e("drFomoLine")}),c.jsxs("div",{className:"mx-4 p-4 bg-muted/30 rounded-lg border border-border/50 text-center",children:[c.jsx("p",{className:"text-sm text-foreground/80 font-medium",children:e("drFeedbackContact")}),c.jsx("a",{href:`mailto:${a}`,className:"text-primary hover:underline font-semibold text-base mt-1 inline-block",children:a})]}),c.jsxs(it,{className:"spiritual-glow mx-4",children:[c.jsxs(pt,{children:[c.jsx(gt,{className:"text-2xl font-bold text-center gradient-spiritual bg-clip-text text-transparent",children:e("drDetailedAnalysis")}),c.jsx(Er,{className:"text-center",children:e("drBasedOnChart")})]}),c.jsx(yt,{className:"space-y-4",children:c.jsx(On,{type:"single",collapsible:!0,className:"w-full space-y-4",children:Ln.map(b=>{const K=b.detailKey==="sadeSati"?"sadeSati":b.detailKey,z=b.summaryKey==="shaniSadeSati"?$:P[b.summaryKey],H=Un(U,b.detailKey==="sadeSati"?"sadeSati":b.detailKey),V=P[b.severityKey],M=b.type==="shani"?P.shaniPhase:void 0,L=b.icon,me=(H?.remedies?.trim()||e(b.remediesKey)).split(`
173
+ `).map(le=>le.trim()).filter(Boolean);return c.jsxs(Cn,{value:K,className:"border border-border rounded-lg px-4",children:[c.jsx(Rn,{value:K,className:"hover:no-underline",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(L,{className:"w-5 h-5 text-destructive"}),c.jsxs("div",{className:"text-left",children:[c.jsx("h3",{className:"font-semibold text-lg",children:e(b.nameKey)}),c.jsxs("p",{className:"text-sm text-muted-foreground",children:[e("drStatus"),": ",Mn(z,e),V&&!Nr(z)&&` • ${e("drSeverity")}: ${Kn(V,e)}`,b.type==="shani"&&M!=null&&` • ${e("drPhase")}: ${M}`]})]})]})}),c.jsxs(Nn,{value:K,className:"pt-4 space-y-4",children:[c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)}),H?.explanation&&c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drExplanation")}),c.jsx("p",{className:"text-sm text-muted-foreground",children:H.explanation})]}),H?.placements&&H.placements.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md",children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drPlanetaryPositions")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:H.placements.map((le,Te)=>c.jsx("li",{children:le},Te))})]}),c.jsxs("div",{children:[c.jsx("h4",{className:"font-medium mb-2",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:me.map((le,Te)=>c.jsx("li",{children:le},Te))})]})]})]},K)})})})]}),c.jsxs(it,{className:"mx-4",children:[c.jsx(pt,{className:"cursor-pointer hover:bg-accent/5 transition-colors",onClick:()=>Qe(b=>!b),children:c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsxs("div",{className:"text-left flex-1 min-w-0",children:[c.jsx(gt,{className:"text-xl font-semibold",children:e("drOtherDoshas")}),c.jsx(Er,{children:e(Ee?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),c.jsx(bn,{className:`h-5 w-5 flex-shrink-0 text-muted-foreground transition-transform duration-200 ${he?"rotate-180":""}`})]})}),he&&c.jsx(yt,{children:c.jsx(On,{type:"single",collapsible:!0,className:"w-full space-y-2",children:De.map(b=>{const K=P[b.summaryKey],z=Ke(K),H=re[b.detailKey]??{},V=H.explanation,M=H.placements;return c.jsxs(Cn,{value:b.summaryKey,className:"border border-border rounded-lg px-3",children:[c.jsx(Rn,{value:b.summaryKey,className:"hover:no-underline py-3",children:c.jsxs("div",{className:"flex items-center justify-between gap-2 flex-1 min-w-0 mr-2",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm text-left leading-tight",children:e(b.labelKey)}),c.jsx(jr,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),z?c.jsxs(Rr,{variant:"destructive",className:"flex-shrink-0 text-xs flex items-center gap-1 pointer-events-none",children:[c.jsx(as,{size:10}),e("drStatusPresent")]}):c.jsxs(Rr,{variant:"secondary",className:"flex-shrink-0 text-xs flex items-center gap-1 bg-white border pointer-events-none",style:{borderColor:"#e4decd",color:"#000000"},children:[c.jsx(yn,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),c.jsxs(Nn,{value:b.summaryKey,className:"space-y-3 pt-0 pb-3",children:[c.jsx("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:c.jsx("p",{className:"text-sm text-muted-foreground italic",children:e(b.descKey)})}),M&&M.length>0&&c.jsxs("div",{className:"p-3 bg-accent/10 rounded-md border border-accent/20",children:[c.jsxs("h5",{className:"font-medium mb-2 flex items-center gap-2 text-sm",children:[c.jsx(jr,{size:14}),e("drPlanetaryPositions")]}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1 leading-relaxed",children:M.map((L,J)=>c.jsx("li",{children:L},J))})]}),V&&c.jsxs("div",{className:"border-l-4 border-orange-500 bg-orange-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2",children:[c.jsx(jr,{size:14}),e(z?"drWhyPresent":"drWhyAbsent")]}),c.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),z&&c.jsxs("div",{className:"border-l-4 border-red-500 bg-red-50 rounded-lg pl-3 py-2",children:[c.jsxs("h5",{className:"font-medium mb-2 text-sm flex items-center gap-2 text-red-600",children:[c.jsx(as,{size:14}),e("drImpact")]}),c.jsx("p",{className:"text-sm text-muted-foreground",children:e(b.impactKey)})]}),z&&c.jsxs("div",{children:[c.jsx("h5",{className:"font-medium mb-2 text-sm",children:e("drTraditionalRemedies")}),c.jsx("ul",{className:"list-disc list-inside text-sm text-muted-foreground space-y-1",children:e(b.remediesKey).split(`
174
+ `).map((L,J)=>c.jsx("li",{children:L},J))})]})]})]},b.summaryKey)})})})]}),c.jsx("div",{id:n||"kundali-chart-section",className:"px-4",children:(l||B||fe.length>0)&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"flex justify-end mb-2",children:c.jsxs("button",{type:"button",onClick:()=>document.getElementById("dosha-results-heading")?.scrollIntoView({behavior:"smooth",block:"start"}),className:"inline-flex items-center gap-1.5 text-sm text-primary hover:text-primary/80 transition-colors font-medium",children:[c.jsx(il,{className:"w-4 h-4"}),e("drGoBack")]})}),l?c.jsxs("div",{className:"mt-2",children:[c.jsx("h2",{className:"text-xl font-semibold text-foreground mb-3",children:e("drYourKundali")}),l()]}):B&&u&&d?c.jsx("div",{className:"mt-2",children:c.jsx($n,{birthDetails:u,supabase:d,language:f,t:e})}):null,fe.length>0&&c.jsxs(it,{className:"mt-4 bg-accent/10 border border-accent/30",children:[c.jsx(pt,{className:"pb-2",children:c.jsx(gt,{className:"text-base font-semibold",children:e("drPlanetaryPositionsCausing")})}),c.jsx(yt,{className:"pt-0",children:c.jsx("ul",{className:"space-y-3 text-sm text-muted-foreground",children:fe.map((b,K)=>c.jsxs("li",{children:[c.jsxs("div",{className:"font-semibold text-foreground mb-1",children:[b.label,":"]}),c.jsx("ul",{className:"ml-4 space-y-1",children:b.evidence.map((z,H)=>c.jsxs("li",{className:"flex items-start gap-2",children:[c.jsx("span",{className:"text-primary flex-shrink-0",children:"→"}),c.jsx("span",{children:z})]},H))})]},K))})})]})]})}),c.jsx("p",{className:"text-xs text-muted-foreground/70 text-center px-4",children:e("drDisclaimer")}),c.jsx(q.UserReviewsSection,{t:e,readMoreHref:m,onReadMore:g?.trackReadMoreReviewsClicked?()=>g.trackReadMoreReviewsClicked():void 0}),c.jsx(q.FAQAccordion,{t:e,items:zl,defaultOpenIndex:0}),c.jsx(q.ContactUsSection,{title:e("contactTitle"),brandName:e("contactBrandName"),whatsAppLine:e("contactWhatsAppDomestic"),emailLine:e("contactEmail")})]})}const Yl=Object.freeze(Object.defineProperty({__proto__:null,DoshaResultsFull:Fn},Symbol.toStringTag,{value:"Module"}));function Ql(t){return!t||t.trim()===""?async()=>null:async e=>{try{if(!e?.trim())return null;const r=`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(e)}&key=${t}`,n=await(await fetch(r)).json();if(n.status!=="OK"||!n.results?.[0])return null;const{lat:a,lng:i}=n.results[0].geometry.location,o=Math.floor(Date.now()/1e3),l=`https://maps.googleapis.com/maps/api/timezone/json?location=${a},${i}&timestamp=${o}&key=${t}`,d=await(await fetch(l)).json();if(d.status!=="OK")return null;const f=d.timeZoneId,m=(d.rawOffset+d.dstOffset)/3600;return{lat:a,lon:i,tz:f,tzoneOffset:m}}catch{return null}}}G.DoshaCalculator=Ul,G.DoshaFormSection=os,G.DoshaResultsFull=Fn,G.DoshaResultsView=Fl,G.FLOATING_CTA_STATUS=cr,G.I18nProvider=el,G.KundaliCard=$n,G.LOCALE_LABELS=Xo,G.SUPPORTED_LOCALES=Qo,G.SriMandirPujaVerticalCard=xn,G.createGoogleMapsResolver=Ql,G.createSupabaseClient=rn,G.fetchKundaliSvg=Dn,G.formatScheduleDate=hn,G.getCoverImageUrl=fn,G.getPujaLink=ss,G.getPujaTitle=rs,G.getTempleName=dn,G.insertSessionProblemStatements=wn,G.invokeCalculateDosha=_n,G.submitDoshaCalculation=kn,G.translations=mn,G.useGooglePlacesAutocomplete=Sn,G.useI18n=ns,Object.defineProperty(G,Symbol.toStringTag,{value:"Module"})}));
174
175
  //# sourceMappingURL=dosha-calculator.umd.cjs.map