@srimandir/dosha-calculator 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- (function(z,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):(z=typeof globalThis<"u"?globalThis:z||self,w(z.DoshaCalculator={},z.React,z.AstrologyCommon))})(this,(function(z,w,q){"use strict";function Bn(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=Bn(w);var sr={exports:{}},$t={};var as;function Fn(){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 qn(){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,Ye,Oe,re,fe,Se,Q,v;function B(){}B.__reactDisabledLog=!0;function H(){{if(he===0){Ye=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:Ye}),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,H();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(`
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
3
  `),Ee=$.stack.split(`
4
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 Xt(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 Zt(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 er(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),Zt(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 tr=b.ReactCurrentOwner,Tr=b.ReactDebugCurrentFrame;function ot(h){if(h){var S=h._owner,j=Fe(h.type,h._source,S?S.type:null);Tr.setExtraStackFrame(j)}else Tr.setExtraStackFrame(null)}var rr;rr=!1;function Pr(h){return typeof h=="object"&&h!==null&&h.$$typeof===e}function Er(){{if(tr.current){var h=ee(tr.current.type);if(h)return`
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`
6
6
 
7
- Check the render method of \``+h+"`."}return""}}function Pl(h){return""}var Dn={};function El(h){{var S=Er();if(!S){var j=typeof h=="string"?h:h.displayName||h.name;j&&(S=`
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=`
8
8
 
9
- Check the top-level render call using <`+j+">.")}return S}}function $n(h,S){{if(!h._store||h._store.validated||h.key!=null)return;h._store.validated=!0;var j=El(S);if(Dn[j])return;Dn[j]=!0;var $="";h&&h._owner&&h._owner!==tr.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 Ln(h,S){{if(typeof h!="object")return;if(D(h))for(var j=0;j<h.length;j++){var $=h[j];Pr($)&&$n($,S)}else if(Pr(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;)Pr(W.value)&&$n(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);Xt(j,h.props,"prop",$,h)}else if(S.PropTypes!==void 0&&!rr){rr=!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 Un={};function Mn(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+=Er();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=er(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++)Ln(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 Ln(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(!Un[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 <`+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:
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),Un[bt+ns]=!0}}return h===s?Ol(pe):Al(pe),pe}}function Rl(h,S,j){return Mn(h,S,j,!0)}function Cl(h,S,j){return Mn(h,S,j,!1)}var Il=Cl,Nl=Rl;Lt.Fragment=s,Lt.jsx=Il,Lt.jsxs=Nl})()),Lt}var os;function Wn(){return os||(os=1,process.env.NODE_ENV==="production"?sr.exports=Fn():sr.exports=qn()),sr.exports}var l=Wn();const nr={all_fields_filled:"all_fields_filled",fields_not_filled:"fields_not_filled",puja_clicked:"puja_clicked"};function ar(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 Gn(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 zn=r=>r?(...e)=>r(...e):(...e)=>fetch(...e);class Ar extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class Hn extends Ar{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class ls extends Ar{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class cs extends Ar{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Or;(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"})(Or||(Or={}));class Vn{constructor(e,{headers:t={},customFetch:s,region:n=Or.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=zn(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Gn(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 Jn=class extends Error{constructor(r){super(r.message),this.name="PostgrestError",this.details=r.details,this.hint=r.hint,this.code=r.code}},Yn=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 Jn(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} />`,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+=`
15
15
 
16
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}},Qn=class extends Yn{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 Qn{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).filter(([e,t])=>t!==void 0).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}},Xn=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 Zn(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 ea(r){var e=Zn(r,"string");return Ut(e)=="symbol"?e:e+""}function ta(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 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 ir(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){ta(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 ra=class Kn{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,ir(ir({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(f),m.removeEventListener("abort",p)})}return o(c,ir(ir({},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 Xn(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Kn(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 sa{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:
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:
18
18
  import ws from "ws"
19
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+=`
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 na="realtime-js/2.99.3",aa="1.0.0",hs="2.0.0",fs=hs,Rr=1e4,ia=1e3,oa=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 Cr;(function(r){r.websocket="websocket"})(Cr||(Cr={}));var lt;(function(r){r.Connecting="connecting",r.Open="open",r.Closing="closing",r.Closed="closed"})(lt||(lt={}));class la{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]=ca(i,r,e,n),a),{}):{}},ca=(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):Ir(i)},gs=(r,e)=>{if(r.charAt(0)==="_"){const t=r.slice(1,r.length);return fa(e,t)}switch(r){case Z.bool:return ua(e);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return da(e);case Z.json:case Z.jsonb:return ha(e);case Z.timestamp:return ma(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 Ir(e);default:return Ir(e)}},Ir=r=>r,ua=r=>{switch(r){case"t":return!0;case"f":return!1;default:return r}},da=r=>{if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return e}return r},ha=r=>{if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r},fa=(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},ma=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 Nr{constructor(e,t,s={},n=Rr){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 Qe;(function(r){r.SUBSCRIBED="SUBSCRIBED",r.TIMED_OUT="TIMED_OUT",r.CLOSED="CLOSED",r.CHANNEL_ERROR="CHANNEL_ERROR"})(Qe||(Qe={}));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 Nr(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?.(Qe.CHANNEL_ERROR,p)),this._onClose(()=>e?.(Qe.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?.(Qe.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?.(Qe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=b,e&&e(Qe.SUBSCRIBED);return}}).receive("error",p=>{this.state=ge.errored,e?.(Qe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(p).join(", ")||"error")))}).receive("timeout",()=>{e?.(Qe.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 Nr(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 Nr(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>oa){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 Dr=()=>{},or={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},pa=[1e3,2e3,5e3,1e4],ga=1e4,ya=`
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=`
22
22
  addEventListener("message", (e) => {
23
23
  if (e.data.event === "start") {
24
24
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
25
25
  }
26
- });`;class va{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=Rr,this.transport=null,this.heartbeatIntervalMs=or.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Dr,this.ref=0,this.reconnectTimer=null,this.vsn=fs,this.logger=Dr,this.conn=null,this.sendBuffer=[],this.serializer=new la,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}/${Cr.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=sa.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t}
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
27
 
28
28
  To use Realtime in Node.js, you need to provide a WebSocket implementation:
29
29
 
@@ -36,9 +36,9 @@ Option 2: Install and provide the "ws" package:
36
36
  const client = new RealtimeClient(url, {
37
37
  ...options,
38
38
  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(ia,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},or.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([ya],{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:na};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()},or.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:Rr,this.heartbeatIntervalMs=(n=e?.heartbeatIntervalMs)!==null&&n!==void 0?n:or.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:Dr,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=>pa[g-1]||ga),this.vsn){case aa: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 ba(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 wa(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 _a(r){const e=r.fetchImpl??globalThis.fetch;return{async request({method:t,path:s,query:n,body:a,headers:i}){const o=ba(r.baseUrl,s,n),c=await wa(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 lr(r){return r.join("")}var ka=class{constructor(r,e=""){this.client=r,this.prefix=e}async listNamespaces(r){const e=r?{parent:lr(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/${lr(r.namespace)}`})}async loadNamespaceMetadata(r){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${lr(r.namespace)}`})).data.properties}}async namespaceExists(r){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${lr(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 Sa=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}}},xa=class{constructor(r){let e="v1";r.catalogName&&(e+=`/${r.catalogName}`);const t=r.baseUrl.endsWith("/")?r.baseUrl:`${r.baseUrl}/`;this.client=_a({baseUrl:t,auth:r.auth,fetchImpl:r.fetch}),this.accessDelegation=r.accessDelegation?.join(","),this.namespaceOps=new ka(this.client,e),this.tableOps=new Sa(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)}},cr=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 ur(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var $r=class extends cr{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 cr{constructor(r,e,t="storage"){super(r,t),this.name=t==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};const ja=r=>r?(...e)=>r(...e):(...e)=>fetch(...e),Ta=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},Pa=r=>!r||typeof r!="string"||r.length===0||r.length>100||r.trim()!==r||r.includes("/")||r.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(r);function Ft(r){"@babel/helpers - typeof";return Ft=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},Ft(r)}function Ea(r,e){if(Ft(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Ft(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function Aa(r){var e=Ea(r,"string");return Ft(e)=="symbol"?e:e+""}function Oa(r,e,t){return(e=Aa(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){Oa(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)},Ra=async(r,e,t,s)=>{if(r!==null&&typeof r=="object"&&typeof r.json=="function"){const n=r;let a=parseInt(n.status,10);Number.isFinite(a)||(a=500),n.json().then(i=>{const o=i?.statusCode||i?.code||a+"";e(new $r(ks(i),a,o,s))}).catch(()=>{const i=a+"";e(new $r(n.statusText||`HTTP ${a} error`,a,i,s))})}else e(new ws(ks(r),r,s))},Ca=(r,e,t,s)=>{const n={method:r,headers:e?.headers||{}};return r==="GET"||r==="HEAD"||!s?I(I({},n),t):(Ta(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 qt(r,e,t,s,n,a,i){return new Promise((o,c)=>{r(t,Ca(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=>Ra(u,c,s,i))})}function Ss(r="storage"){return{get:async(e,t,s,n)=>qt(e,"GET",t,s,n,void 0,r),post:async(e,t,s,n,a)=>qt(e,"POST",t,n,a,s,r),put:async(e,t,s,n,a)=>qt(e,"PUT",t,n,a,s,r),head:async(e,t,s,n)=>qt(e,"HEAD",t,I(I({},s),{},{noResolveJson:!0}),n,void 0,r),remove:async(e,t,s,n,a)=>qt(e,"DELETE",t,n,a,s,r)}}const Ia=Ss("storage"),{get:Wt,post:ze,put:Ur,head:Na,remove:Mr}=Ia,Ie=Ss("vectors");var St=class{constructor(r,e={},t,s="storage"){this.shouldThrowOnError=!1,this.url=r,this.headers=e,this.fetch=ja(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(ur(t))return{data:null,error:t};throw t}}},Da=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(ur(e))return{data:null,error:e};throw e}}};let xs;xs=Symbol.toStringTag;var $a=class{constructor(r,e){this.downloadFn=r,this.shouldThrowOnError=e,this[xs]="BlobDownloadBuilder",this.promise=null}asStream(){return new Da(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(ur(e))return{data:null,error:e};throw e}}};const La={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},js={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Ua=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:ze)(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 ze(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 cr("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 ze(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 ze(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);const a=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0;let i=await ze(s.fetch,`${s.url}/object/sign/${n}`,I({expiresIn:e},a?{transform:t.transform}:{}),{headers:s.headers});const o=t?.download?`&download=${t.download===!0?"":t.download}`:"",c=a&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${s.url}${c}${o}`)}})}async createSignedUrls(r,e,t){var s=this;return s.handleOperation(async()=>{const n=await ze(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=()=>Wt(this.fetch,`${this.url}/${s}/${i}${a}`,{headers:this.headers,noResolveJson:!0},t);return new $a(o,this.shouldThrowOnError)}async info(r){var e=this;const t=e._getFinalPath(r);return e.handleOperation(async()=>Lr(await Wt(e.fetch,`${e.url}/object/info/${t}`,{headers:e.headers})))}async exists(r){var e=this;const t=e._getFinalPath(r);try{return await Na(e.fetch,`${e.url}/object/${t}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(ur(n)){var s;const a=n instanceof $r?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({},La),e),{},{prefix:r||""});return await ze(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 ze(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 Gt={"X-Client-Info":"storage-js/2.99.3"};var Ma=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({},Gt),e);super(a,i,t,"storage")}async listBuckets(r){var e=this;return e.handleOperation(async()=>{const t=e.listBucketOptionsToQueryString(r);return await Wt(e.fetch,`${e.url}/bucket${t}`,{headers:e.headers})})}async getBucket(r){var e=this;return e.handleOperation(async()=>await Wt(e.fetch,`${e.url}/bucket/${r}`,{headers:e.headers}))}async createBucket(r,e={public:!1}){var t=this;return t.handleOperation(async()=>await ze(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 ze(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():""}},Ka=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Gt),e);super(s,n,t,"storage")}async createBucket(r){var e=this;return e.handleOperation(async()=>await ze(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 Wt(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(!Pa(r))throw new cr("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 xa({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}}}}})}},Ba=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Gt),{},{"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})||{})}},Fa=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Gt),{},{"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})||{})}},qa=class extends St{constructor(r,e={},t){const s=r.replace(/\/$/,""),n=I(I({},Gt),{},{"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})||{})}},Wa=class extends qa{constructor(r,e={}){super(r,e.headers||{},e.fetch)}from(r){return new Ga(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)}},Ga=class extends Ba{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 za(this.url,this.headers,this.vectorBucketName,r,this.fetch)}},za=class extends Fa{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 Ma{constructor(r,e={},t,s){super(r,e,t,s)}from(r){return new Ua(this.url,this.headers,r,this.fetch)}get vectors(){return new Wa(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Ka(this.url+"/iceberg",this.headers,this.fetch)}};const Ts="2.99.3",xt=30*1e3,Kr=3,Br=Kr*xt,Va="http://localhost:9999",Ja="supabase.auth.token",Ya={"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"}},Qa=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Xa=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 Za extends zt{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function ei(r){return P(r)&&r.name==="AuthApiError"}class ct extends zt{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Xe extends zt{constructor(e,t,s,n){super(e,s,n),this.name=t,this.status=s}}class Ne extends Xe{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function qr(r){return P(r)&&r.name==="AuthSessionMissingError"}class jt extends Xe{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class dr extends Xe{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class hr extends Xe{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 ti(r){return P(r)&&r.name==="AuthImplicitGrantRedirectError"}class Es extends Xe{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 ri extends Xe{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 Xe{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Gr(r){return P(r)&&r.name==="AuthRetryableFetchError"}class As extends Xe{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}class zr extends Xe{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const fr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Os=`
40
- \r=`.split(""),si=(()=>{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<fr.length;e+=1)r[fr[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(fr[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(fr[s]),e.queuedBits-=6}}function Cs(r,e,t){const s=si[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=>{ii(i,s,t)};for(let i=0;i<r.length;i+=1)Cs(r.charCodeAt(i),n,a);return e.join("")}function ni(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 ai(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}ni(s,e)}}function ii(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 oi(r){const e=[];return ai(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 li(r){return Math.round(Date.now()/1e3)+r}function ci(){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 ui(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),di=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 mr{constructor(){this.promise=new mr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}mr.promiseConstructor=Promise;function pr(r){const e=r.split(".");if(e.length!==3)throw new zr("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Qa.test(e[s]))throw new zr("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 hi(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function fi(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 mi(r){return("0"+r.toString(16)).substr(-2)}function pi(){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,mi).join("")}async function gi(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 yi(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 gi(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Et(r,e,t=!1){const s=pi();let n=s;t&&(n+="/PASSWORD_RECOVERY"),await Pt(r,`${e}-code-verifier`,n);const a=await yi(s);return[a,s===a?"plain":"s256"]}const vi=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function bi(r){const e=r.headers.get(Fr);if(!e||!e.match(vi))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function wi(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 _i(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 ki=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function At(r){if(!ki.test(r))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Hr(){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 Si(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),xi=[502,503,504];async function Ls(r){var e;if(!di(r))throw new Wr(ft(r),0);if(xi.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=bi(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 Za(ft(t),r.status||500,s)}const ji=(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 Ti(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 Ti(r,e,t,s,n,a){const i=ji(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 He(r){var e;let t=null;Ai(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=li(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=He(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 Pi(r){return{data:r,error:null}}function Ei(r){const{action_link:e,email_otp:t,hashed_token:s,redirect_to:n,verification_type:a}=r,i=ar(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 Ai(r){return r.access_token&&r.refresh_token&&r.expires_in}const Vr=["global","local","others"];class Oi{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=ar(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:Ei,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 Je={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 Fs extends Bs{}async function Ri(r,e,t){Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);const s=new globalThis.AbortController;let n;e>0&&(n=setTimeout(()=>{s.abort(),Je.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 a=>{if(a){clearTimeout(n),Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,a.name);try{return await t()}finally{Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,a.name)}}else{if(e===0)throw Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Fs(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Je.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 t()}})}catch(a){if(e>0&&clearTimeout(n),a?.name==="AbortError"&&e>0){if(s.signal.aborted)return Je.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 i=>{if(i){Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",r,i.name);try{return await t()}finally{Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",r,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await t()}));throw Je.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",r),new Fs(`Lock "${r}" was released because another request stole it`)}throw a}}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 qs(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=qs(r.address),g=d?`${d}://${s}`:s,y=r.statement?`${r.statement}
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}
42
42
  `:"",x=`${g} wants you to sign in with your Ethereum account:
43
43
  ${p}
44
44
 
@@ -52,10 +52,10 @@ Not Before: ${o.toISOString()}`),c&&(b+=`
52
52
  Request ID: ${c}`),u){let k=`
53
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
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 gr 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(Ws(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(Ws(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=ar(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=ar(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 Ws(r){return r==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(r)}function Gs(){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 gr("Browser returned unexpected credential type",e)}:{data:null,error:new gr("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 gr("Browser returned unexpected credential type",e)}:{data:null,error:new gr("Empty credential response",e)}}catch(e){return{data:null,error:Li({error:e,options:r})}}}const zi={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Hi={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function yr(...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]=yr(o,i):s[a]=yr(i)}else s[a]=i}return s}function Vi(r,e){return yr(zi,r,e||{})}function Ji(r,e){return yr(Hi,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(!Gs())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(!Gs())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:Va,storageKey:Ja,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ya,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function zs(r,e,t){return await t()}const Ot={};class Ht{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=Ht.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,Ht.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 Oi({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||zs,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=zs,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=ui(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),ti(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:He}),{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:He})}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:He})}else throw new dr("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 dr("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=qs(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:He});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:He});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 ri;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:He});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:He}),{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 dr("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:He});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:Pi});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 dr("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=Hr()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const i={value:this.suppressGetSessionWarning};e.user=Si(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}=pr(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 hr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new hr(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 hr("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 hr("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&&!(ei(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=ci(),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:He}),{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 fi(async n=>(n>0&&await hi(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:He})),(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:Hr()}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=Hr()}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 mr;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}=pr(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}=pr(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+Xa>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}}=pr(s);t?.allowExpired||wi(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=_i(n.alg),f=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,f,i,oi(`${o}.${c}`)))throw new zr("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}}}Ht.nextInstanceID={};const Xi=Ht,Zi="2.99.3";let Vt="";typeof Deno<"u"?Vt="deno":typeof document<"u"?Vt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Vt="react-native":Vt="node";const eo={headers:{"X-Client-Info":`supabase-js-${Vt}/${Zi}`}},to={schema:"public"},ro={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},so={};function Jt(r){"@babel/helpers - typeof";return Jt=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},Jt(r)}function no(r,e){if(Jt(r)!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var s=t.call(r,e);if(Jt(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 Jt(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 ra(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 Vn(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 va(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 Vs(r,e){if(!r||!e)throw new Error("Supabase URL and anon key are required");return go(r,e)}function Js(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,`
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,`
57
57
  `).trim().split(`
58
- `);if(t.length<2)return[];const s=Js(t[0]),n=[];for(let a=1;a<t.length;a++){const i=Js(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 Ys={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 Qs(r,e){const t=Ys[e]||Ys[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=[],Xs=0;const wo=3600*1e3;async function _o(r){const e=Date.now();if(Rt.length>0&&e-Xs<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,Xs=e,a}catch(t){return console.warn("[DoshaCalculator] fetchPujas error:",t),Rt}}const Zs={"पितृ दोष निवारण महायज्ञ एवं काशी गंगा महाआरती":"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"},en={"काशी विश्वनाथ मंदिर":"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 tn(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(Zs[s])return Zs[s];const a=tn(s);return a!==s?a:s}function rn(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(en[s])return en[s];const a=tn(s);return a!==s?a:s}function sn(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 nn(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:"हिन्दी"},an={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
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
59
  Fast on Tuesdays
60
60
  Donate red items like lentils or cloth
61
61
  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 +163,12 @@ Visit Navagraha temples`,ctaKundliCreated:"3L+ Kundli Reports Created.",ctaCerti
163
163
  परामर्श के बाद लहसुनिया पहनें`,drOtherNavagrahaRemedies:`व्यापक नवग्रह शांति पूजा करें
164
164
  नवग्रह मंत्र का पाठ करें
165
165
  सभी नौ ग्रहों के लिए वस्तुओं का दान करें
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:"कौन सा उपाय या पूजा आपके लिए सही रहेगा।"}},on=w.createContext(null);function ln(){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||ln());w.useEffect(()=>{if(r)n(r);else{const o=()=>n(ln());return window.addEventListener("popstate",o),()=>window.removeEventListener("popstate",o)}},[r]);const a=o=>{e?e(o):Eo(o)},i=w.useMemo(()=>o=>an[s]?.[o]??o,[s]);return l.jsx(on.Provider,{value:{locale:s,setLocale:a,t:i},children:t})}function Qr(){return w.useContext(on)}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 cn(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 vr(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 un(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 br={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:`${br.bannerContainer} ${e}`,children:[l.jsx(s,{src:r.imageUrl,alt:r.alt,className:br.bannerImage,loading:"eager",priority:!0,fetchPriority:"high"}),l.jsx("div",{className:br.ticker,children:l.jsx("div",{className:br.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",dn=r=>String(r).padStart(2,"0");function zo(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 Ho(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),`${dn(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(Ho(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?zo(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)=>dn(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 hn(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 fn(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 mn(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 hn(r,{visitorId:s,sessionId:n,problemStatements:i,language:o}),fn(r,e,{"x-visitor-id":s,"x-session-id":n})}let wr=null;const Yo=(r,e)=>typeof window>"u"||window.google?.maps?.places?Promise.resolve():wr||(wr=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)}),wr),pn=(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,Ye]=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")},[]),H=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}=pn({apiKey:m,language:"en"}),$e=w.useCallback(()=>{H.current||(H.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),Ye({...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 Zt=Xo(),C=Zo(),ne=Le.problemAreaValues,xe=typeof navigator<"u"&&navigator.language?.toLowerCase().startsWith("hi")?"hi":"en",je=await mn(i,Le,{visitorId:Zt,sessionId:C,trackProblemStatements:!0,problemStatements:ne,language:xe});if(je.success){Se(null);const[ve,er,tr]=(Le.date||"").split("-").map(Number),Tr=Le.time||"12:00",[ot,rr]=Tr.split(":").map(Er=>parseInt(Er,10)||0);c?.(je,{day:tr||1,month:er||1,year:ve||2e3,hour:ot,minute:rr,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 Xt=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:Xt,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),Ye(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&&(Ye({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 _r=Ce.forwardRef(({className:r="",...e},t)=>l.jsx("p",{ref:t,className:`text-sm text-muted-foreground ${r}`,...e}));_r.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 Yt=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})});Yt.displayName="Button";function gn({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=rn(r,t),d=sn(r.schedule_date_ist,t),f=Yr(r,t),m=nn(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(Yt,{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 yn({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 vn(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 kr(){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 bn(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 Sr(r){if(!r)return!1;const e=r.toLowerCase();return e==="present"||e==="active"||e==="partial"||e==="suggested"}function wn(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 _n(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 Sr(r.kaalSarp)&&e.push({type:"kaal-sarp",severity:typeof r.kaalSarpSeverity=="string"?r.kaalSarpSeverity:void 0}),Sr(r.pitra)&&e.push({type:"pitra",severity:typeof r.pitraSeverity=="string"?r.pitraSeverity:void 0}),Sr(r.shaniSadeSati||r.sadeSati)&&e.push({type:"shani",severity:typeof r.sadeSatiSeverity=="string"?r.sadeSatiSeverity:void 0}),Sr(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)=>wn(s.severity)-wn(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 Vs(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),[Ye,Oe]=w.useState(!1),[re,fe]=w.useState(null),[Se,Q]=w.useState(null),[v,B]=w.useState(void 0),[H,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=Qs(V,C);return ne?l.jsx(gn,{puja:ne,doshaType:C,language:L,imageComponent:O,analytics:b}):null},[V,L,O,b]),Fe=w.useCallback(C=>{const ne=Qs(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,Xt]=w.useState(()=>{const C=typeof window<"u"?kr():null;return vn(C,L)}),[T,D]=w.useState(()=>{if(typeof window>"u")return"generic";const C=kr();return C&&C.toLowerCase().includes("marriage")?"marriage":"generic"});w.useEffect(()=>{const C=kr(),ne=vn(C,L);Xt(ne);let xe="generic";C&&C.toLowerCase().includes("marriage")&&(xe="marriage"),D(xe)},[L]);const[ie,Ve]=w.useState(!1);w.useEffect(()=>{const C=kr();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=bn(je).map(er=>yt(er)).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=bn(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&&!H&&se){if(se.link){const C=_n(se.link);b?.trackDoshaCalculatorResultBookCtaClicked?.({position:"floating_cta",url:C,isOldDosha:!1})}if(_)_();else if(se.link){const C=_n(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?nr.all_fields_filled:nr.fields_not_filled),te||it(),ee.current.submit()):(b?.trackFloatingCtaClicked?.(nr.fields_not_filled),it())},Zt=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:Zt,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:H?void 0:Pe,inlineEditForm:H?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(yn,{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(yn,{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&&!H&&ts(re.summary)===null)&&l.jsxs(q.FooterShell,{children:[!(re&&!H&&se)&&l.jsx(Oo,{}),l.jsx(Mo,{isFormComplete:te,onPress:qe,labelDefault:N("formCta"),labelFilled:N("formCtaCalculate"),loadingLabel:N("calculating"),isLoading:Ye,mode:re&&!H&&se?"book-puja":"form",firstPuja:se||void 0,showingResults:!!re&&!H,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 Qt(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=Qt(n.mangal)||Qt(n.kaalSarp)||Qt(n.pitra)||Qt(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=Qt(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 xr=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})});xr.displayName="Badge";const rs=Ce.createContext(null);function kn({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 Sn({value:r,className:e="",children:t}){return l.jsx("div",{"data-state":r,className:`border-b border-border ${e}`,children:t})}function xn({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(un,{className:`h-4 w-4 shrink-0 transition-transform duration-200 ${n?"rotate-180":""}`})]})}function jn({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,Tn=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<Tn)return e.svg;try{const t=sessionStorage.getItem(`kundali_${r}`);if(t){const s=JSON.parse(t);if(Date.now()-s.timestamp<Tn)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 Pn(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 En({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 Pn(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(Yt,{type:"button",size:"sm",variant:n==="North"?"default":"outline",className:"rounded-full px-4",onClick:()=>b("North"),children:s("kundaliChartNorth")}),l.jsx(Yt,{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(Yt,{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"}],An=[{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 jr(r){return r?r.toLowerCase().includes("nullified"):!1}function On(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(`
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
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 Rn(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 Cn(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 In(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 Nn({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)&&!jr(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)&&!jr(E.mangal)||Be(E.kaalSarp)||Be(E.pitra)||Be(L)||Ae,te=[];for(const v of An){const B=v.summaryKey==="shaniSadeSati"?L:E[v.summaryKey];if(!Be(B)||v.type==="mangal"&&jr(B))continue;const H=E[v.severityKey],G=v.type==="shani"?E.shaniPhase??E.shaniPhase:void 0,V=On(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(`
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
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:H||"moderate",phase:G??void 0,explanation:U,placements:V?.placements,impact:e(v.impactKey),remedies:se,benefits:le})}te.sort((v,B)=>Cn(B.severity)-Cn(v.severity));const[he,Ye]=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]||{},H=[...B.placements||[],...B.triggeredBy||[],...B.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),G=Array.from(new Set(H)),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]||{},H=[...B.placements||[],...B.triggeredBy||[],...B.notes||[]].map(U=>String(U||"").trim()).filter(Boolean),G=Array.from(new Set(H)),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,": ",Rn(v.status,e)]})]},v.type))}):l.jsxs("div",{className:"text-center py-8",children:[l.jsx(cn,{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 H=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(xr,{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(H,{className:"w-6 h-6 text-primary"}),v.label]}),l.jsxs(_r,{children:[e("drSeverity"),": ",In(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(vr,{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(_r,{className:"text-center",children:e("drBasedOnChart")})]}),l.jsx(gt,{className:"space-y-4",children:l.jsx(kn,{type:"single",collapsible:!0,className:"w-full space-y-4",children:An.map(v=>{const B=v.detailKey==="sadeSati"?"sadeSati":v.detailKey,H=v.summaryKey==="shaniSadeSati"?L:E[v.summaryKey],G=On(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(Sn,{value:B,className:"border border-border rounded-lg px-4",children:[l.jsx(xn,{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"),": ",Rn(H,e),V&&!jr(H)&&` • ${e("drSeverity")}: ${In(V,e)}`,v.type==="shani"&&K!=null&&` • ${e("drPhase")}: ${K}`]})]})]})}),l.jsxs(jn,{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:()=>Ye(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(_r,{children:e(Ae?"drOtherDoshasStatusActive":"drOtherDoshasStatusNone")})]}),l.jsx(un,{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(kn,{type:"single",collapsible:!0,className:"w-full space-y-2",children:De.map(v=>{const B=E[v.summaryKey],H=Be(B),G=re[v.detailKey]??{},V=G.explanation,K=G.placements;return l.jsxs(Sn,{value:v.summaryKey,className:"border border-border rounded-lg px-3",children:[l.jsx(xn,{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(vr,{size:14,className:"text-muted-foreground flex-shrink-0"})]}),H?l.jsxs(xr,{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(xr,{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(cn,{size:10,color:"#000000"}),e("drStatusAbsent")]})]})}),l.jsxs(jn,{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(vr,{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(vr,{size:14}),e(H?"drWhyPresent":"drWhyAbsent")]}),l.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:V})]}),H&&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)})]}),H&&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(En,{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((H,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:H})]},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:Nn},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}}}z.DoshaCalculator=fl,z.DoshaFormSection=es,z.DoshaResultsFull=Nn,z.DoshaResultsView=yl,z.FLOATING_CTA_STATUS=nr,z.I18nProvider=Ao,z.KundaliCard=En,z.LOCALE_LABELS=Po,z.SUPPORTED_LOCALES=To,z.SriMandirPujaVerticalCard=gn,z.createGoogleMapsResolver=Tl,z.createSupabaseClient=Vs,z.fetchKundaliSvg=Pn,z.formatScheduleDate=sn,z.getCoverImageUrl=nn,z.getPujaLink=Yr,z.getPujaTitle=Jr,z.getTempleName=rn,z.insertSessionProblemStatements=hn,z.invokeCalculateDosha=fn,z.submitDoshaCalculation=mn,z.translations=an,z.useGooglePlacesAutocomplete=pn,z.useI18n=Qr,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"})}));
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"})}));
174
174
  //# sourceMappingURL=dosha-calculator.umd.cjs.map