1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,75254,e=>{"use strict";var t=e.i(71645);let s=e=>{let t=e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,s)=>s?s.toUpperCase():t.toLowerCase());return t.charAt(0).toUpperCase()+t.slice(1)},i=(...e)=>e.filter((e,t,s)=>!!e&&""!==e.trim()&&s.indexOf(e)===t).join(" ").trim();var n={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let r=(0,t.forwardRef)(({color:e="currentColor",size:s=24,strokeWidth:r=2,absoluteStrokeWidth:o,className:a="",children:u,iconNode:h,...l},c)=>(0,t.createElement)("svg",{ref:c,...n,width:s,height:s,stroke:e,strokeWidth:o?24*Number(r)/Number(s):r,className:i("lucide",a),...!u&&!(e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0})(l)&&{"aria-hidden":"true"},...l},[...h.map(([e,s])=>(0,t.createElement)(e,s)),...Array.isArray(u)?u:[u]]));e.s(["default",0,(e,n)=>{let o=(0,t.forwardRef)(({className:o,...a},u)=>(0,t.createElement)(r,{ref:u,iconNode:n,className:i(`lucide-${s(e).replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,`lucide-${e}`,o),...a}));return o.displayName=s(e),o}],75254)},14001,e=>{"use strict";e.s(["version",0,"1.31.7"])},90798,95543,2082,88218,1737,3697,6689,e=>{"use strict";for(var t,s,i=[],n=[],r=Uint8Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,u=o.length;a<u;++a)i[a]=o[a],n[o.charCodeAt(a)]=a;function h(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=t);var i=s===t?0:4-s%4;return[s,i]}function l(e){var t,s,i=h(e),o=i[0],a=i[1],u=new r((o+a)*3/4-a),l=0,c=a>0?o-4:o;for(s=0;s<c;s+=4)t=n[e.charCodeAt(s)]<<18|n[e.charCodeAt(s+1)]<<12|n[e.charCodeAt(s+2)]<<6|n[e.charCodeAt(s+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===a&&(t=n[e.charCodeAt(s)]<<2|n[e.charCodeAt(s+1)]>>4,u[l++]=255&t),1===a&&(t=n[e.charCodeAt(s)]<<10|n[e.charCodeAt(s+1)]<<4|n[e.charCodeAt(s+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u}function c(e){for(var t,s=e.length,n=s%3,r=[],o=0,a=s-n;o<a;o+=16383)r.push(function(e,t,s){for(var n,r=[],o=t;o<s;o+=3)n=(e[o]<<16&0xff0000)+(e[o+1]<<8&65280)+(255&e[o+2]),r.push(i[n>>18&63]+i[n>>12&63]+i[n>>6&63]+i[63&n]);return r.join("")}(e,o,o+16383>a?a:o+16383));return 1===n?r.push(i[(t=e[s-1])>>2]+i[t<<4&63]+"=="):2===n&&r.push(i[(t=(e[s-2]<<8)+e[s-1])>>10]+i[t>>4&63]+i[t<<2&63]+"="),r.join("")}function d(e){let t="object"==typeof e,s=Object.getPrototypeOf(e),i=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&i}n[45]=62,n[95]=63,e.s(["byteLength",0,function(e){var t=h(e),s=t[0],i=t[1];return(s+i)*3/4-i},"fromByteArray",0,c,"fromByteArrayUrlSafeNoPadding",0,function(e){return c(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"toByteArray",0,l],95543),e.s(["isSimpleObject",0,d,"parseArgs",0,function(e){if(void 0===e)return{};if(!d(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e},"validateDeploymentUrl",0,function(e){if(void 0===e)throw Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof e)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}],2082);let f=BigInt("-9223372036854775808"),g=BigInt("9223372036854775807"),p=BigInt("0"),y=BigInt("8"),m=BigInt("256");function v(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}let b=DataView.prototype.setBigInt64?function(e){if(e<f||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),c(new Uint8Array(t))}:function(e){e<p&&(e-=f+f);let t=e.toString(16);t.length%2==1&&(t="0"+t);let s=new Uint8Array(new ArrayBuffer(8)),i=0;for(let n of t.match(/.{2}/g).reverse())s.set([parseInt(n,16)],i++),e>>=y;return c(s)},w=DataView.prototype.getBigInt64?function(e){let t=l(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){let t=l(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=p,i=p;for(let e of t)s+=BigInt(e)*m**i,i++;return s>g&&(s+=f+f),s};function k(e){if(e.length>1024)throw Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let s=e.charCodeAt(t);if(s<32||s>=127)throw Error(`Field name ${e}
1 has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function S(e){let t=JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t);if(t.length>16384){let e="[...truncated]",s=16384-e.length,i=t.codePointAt(s-1);return void 0!==i&&i>65535&&(s-=1),t.substring(0,s)+e}return t}function C(e,t,s,i){if(void 0===e){let e=s&&` (present at path ${s} in original object ${S(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===e)return e;if("bigint"==typeof e){if(e<f||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:b(e)}}if("number"==typeof e)if(!v(e))return e;else{let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:c(new Uint8Array(t))}}if("boolean"==typeof e||"string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:c(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,i)=>C(e,t,s+`[${i}]`,!1));if(e instanceof Set)throw Error(T(s,"Set",[...e],t));if(e instanceof Map)throw Error(T(s,"Map",[...e],t));if(!d(e)){let i=e?.constructor?.name;throw Error(T(s,i?`${i} `:"",e,t))}let n={},r=Object.entries(e);for(let[e,o]of(r.sort(([e,t],[s,i])=>e===s?0:e<s?-1:1),r))void 0!==o?(k(e),n[e]=C(o,t,s+`.${e}`,!1)):i&&(k(e),n[e]=R(o,t,s+`.${e}`));return n}function T(e,t,s,i){return e?`${t}${S(s)} is not a supported Convex type (present at path ${e} in original object ${S(i)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${S(s)} is not a supported Convex type.`}function R(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw Error(`Programming error. Current value is ${S(e)} but original value is undefined`);return C(e,t,s,!1)}function A(e){return C(e,e,"",!1)}e.s(["convexOrUndefinedToJson",0,function(e){return R(e,e,"")},"convexToJson",0,A,"jsonToConvex",0,function e(t){if(null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t)return t;if(Array.isArray(t))return t.map(t=>e(t));if("object"!=typeof t)throw Error(`Unexpected type of ${t}`);let s=Object.entries(t);if(1===s.length){let e=s[0][0];if("$bytes"===e){if("string"!=typeof t.$bytes)throw Error(`Malformed $bytes field on ${t}`);return l(t.$bytes).buffer}if("$integer"===e){if("string"!=typeof t.$integer)throw Error(`Malformed $integer field on ${t}`);return w(t.$integer)}if("$float"===e){if("string"!=typeof t.$float)throw Error(`Malformed $float field on ${t}`);let e=l(t.$float);if(8!==e.byteLength)throw Error(`Received ${e.byteLength} bytes, expected 8 for $float`);let s=new DataView(e.buffer).getFloat64(0,!0);if(!v(s))throw Error(`Float ${s} should be encoded as a number`);return s}if("$set"===e)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===e)throw Error("Received a Map which is no longer supported as a Convex type.")}let i={};for(let[s,n]of Object.entries(t))k(s),i[s]=e(n);return i},"patchValueToJson",0,function(e){return C(e,e,"",!0)},"stringifyValueForError",0,S],88218);var x=Object.defineProperty,q=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?x(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function O(e,t){let s=void 0!==t?` for field "${t}"`:"";throw Error(`A validator is undefined${s} in ${e}. This is often caused by circular imports. See https://docs.convex.dev/error#undefined-validator for details.`)}class M{constructor({isOptional:e}){q(this,"type"),q(this,"fieldPaths"),q(this,"isOptional"),q(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}}class E extends M{constructor({isOptional:e,tableName:t}){if(super({isOptional:e}),q(this,"tableName"),q(this,"kind","id"),"string"!=typeof t)throw Error("v.id(tableName) requires a string");this.tableName=t}get json(){return{type:"id",tableName:this.tableName}}asOptional(){return new E({isOptional:"optional",tableName:this.tableName})}}class $ extends M{constructor(){super(...arguments),q(this,"kind","float64")}get json(){return{type:"number"}}asOptional(){return new $({isOptional:"optional"})}}class Q extends M{constructor(){super(...arguments),q(this,"kind","int64")}get json(){return{type:"bigint"}}asOptional(){return new Q({isOptional:"optional"})}}class I extends M{constructor(){super(...arguments),q(this,"kind","boolean")}get json(){return{type:this.kind}}asOptional(){return new I({isOptional:"optional"})}}class P extends M{constructor(){super(...arguments),q(this,"kind","bytes")}get json(){return{type:this.kind}}asOptional(){return new P({isOptional:"optional"})}}class V extends M{constructor(){super(...arguments),q(this,"kind","string")}get json(){return{type:this.kind}}asOptional(){return new V({isOptional:"optional"})}}class L extends M{constructor(){super(...arguments),q(this,"kind","null")}get json(){return{type:this.kind}}asOptional(){return new L({isOptional:"optional"})}}class j extends M{constructor(){super(...arguments),q(this,"kind","any")}get json(){return{type:this.kind}}asOptional(){return new j({isOptional:"optional"})}}class _ extends M{constructor({isOptional:e,fields:t}){super({isOptional:e}),q(this,"fields"),q(this,"kind","object"),globalThis.Object.entries(t).forEach(([e,t])=>
1{if(void 0===t&&O("v.object()",e),!t.isConvexValidator)throw Error("v.object() entries must be validators")}),this.fields=t}get json(){return{type:this.kind,value:globalThis.Object.fromEntries(globalThis.Object.entries(this.fields).map(([e,t])=>[e,{fieldType:t.json,optional:"optional"===t.isOptional}]))}}asOptional(){return new _({isOptional:"optional",fields:this.fields})}omit(...e){let t={...this.fields};for(let s of e)delete t[s];return new _({isOptional:this.isOptional,fields:t})}pick(...e){let t={};for(let s of e)t[s]=this.fields[s];return new _({isOptional:this.isOptional,fields:t})}partial(){let e={};for(let[t,s]of globalThis.Object.entries(this.fields))e[t]=s.asOptional();return new _({isOptional:this.isOptional,fields:e})}extend(e){return new _({isOptional:this.isOptional,fields:{...this.fields,...e}})}}class N extends M{constructor({isOptional:e,value:t}){if(super({isOptional:e}),q(this,"value"),q(this,"kind","literal"),"string"!=typeof t&&"boolean"!=typeof t&&"number"!=typeof t&&"bigint"!=typeof t)throw Error("v.literal(value) must be a string, number, or boolean");this.value=t}get json(){return{type:this.kind,value:A(this.value)}}asOptional(){return new N({isOptional:"optional",value:this.value})}}class F extends M{constructor({isOptional:e,element:t}){super({isOptional:e}),q(this,"element"),q(this,"kind","array"),void 0===t&&O("v.array()"),this.element=t}get json(){return{type:this.kind,value:this.element.json}}asOptional(){return new F({isOptional:"optional",element:this.element})}}class D extends M{constructor({isOptional:e,key:t,value:s}){if(super({isOptional:e}),q(this,"key"),q(this,"value"),q(this,"kind","record"),void 0===t&&O("v.record()","key"),void 0===s&&O("v.record()","value"),"optional"===t.isOptional)throw Error("Record validator cannot have optional keys");if("optional"===s.isOptional)throw Error("Record validator cannot have optional values");if(!t.isConvexValidator||!s.isConvexValidator)throw Error("Key and value of v.record() but be validators");this.key=t,this.value=s}get json(){return{type:this.kind,keys:this.key.json,values:{fieldType:this.value.json,optional:!1}}}asOptional(){return new D({isOptional:"optional",key:this.key,value:this.value})}}class U extends M{constructor({isOptional:e,members:t}){super({isOptional:e}),q(this,"members"),q(this,"kind","union"),t.forEach((e,t)=>{if(void 0===e&&O("v.union()",`member at index ${t}`),!e.isConvexValidator)throw Error("All members of v.union() must be validators")}),this.members=t}get json(){return{type:this.kind,value:this.members.map(e=>e.json)}}asOptional(){return new U({isOptional:"optional",members:this.members})}}function B(e){return!!e.isConvexValidator}let J={id:e=>new E({isOptional:"required",tableName:e}),null:()=>new L({isOptional:"required"}),number:()=>new $({isOptional:"required"}),float64:()=>new $({isOptional:"required"}),bigint:()=>new Q({isOptional:"required"}),int64:()=>new Q({isOptional:"required"}),boolean:()=>new I({isOptional:"required"}),string:()=>new V({isOptional:"required"}),bytes:()=>new P({isOptional:"required"}),literal:e=>new N({isOptional:"required",value:e}),array:e=>new F({isOptional:"required",element:e}),object:e=>new _({isOptional:"required",fields:e}),record:(e,t)=>new D({isOptional:"required",key:e,value:t}),union:(...e)=>new U({isOptional:"required",members:e}),any:()=>new j({isOptional:"required"}),optional:e=>e.asOptional(),nullable:e=>J.union(e,J.null())};e.s(["asObjectValidator",0,function(e){return B(e)?e:J.object(e)},"isValidator",0,B,"v",0,J],1737),e.i(95543);var W=Object.defineProperty,K=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?W(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};let z=Symbol.for("ConvexError");class H extends(s=Error,t=z,s){constructor(e){super("string"==typeof e?e:S(e)),K(this,"name","ConvexError"),K(this,"data"),K(this,t,!0),this.data=e}}e.s(["ConvexError",0,H],3697);let G=()=>Array.from({length:4},()=>0);G(),G(),e.s([],6689),e.s([],90798)},50711,39197,62849,71482,20344,82045,81958,82295,e=>{"use strict";let t,s;var i=e.i(71645);e.i(90798),e.s(["ConvexProvider",()=>eS,"ConvexReactClient",()=>eb,"useAction",()=>eR,"useConvex",()=>ek,"useMutation",()=>eT,"useQuery",()=>eC],82045),e.s([],20344);var n=e.i(14001),r=e.i(88218),o=Object.defineProperty,a=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?o(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function u(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class h{constructor(e){a(this,"_onLogLineFuncs"),a(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&void 0!==this._onLogLineFuncs[t];e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t("error",...e)}}function l(e){let t=new h(e);return t.addLogLineListener((e,...t)=>{switch(e){case"debug":console.debug(...t);break;case"info":default:console.log(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}),t}function c(e,t,s,i,n){let r=u(s);if("object"==typeof n&&(n=`ConvexError ${JSON.stringify(n.errorData,null,2)}`),"info"===t){let t=n.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${i})] Could not parse console.log`);let s=n.slice(1,t[0].length-2),o=n.slice(t[0].length);e.log(`%c[CONVEX ${r}(${i})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${r}(${i})] ${n}`)}function d(e,t,s){let i=u(e);return`[CONVEX ${i}(${t})] ${s.errorMessage} 2 Called by client`}function f(e,t){return t.data=e.errorData,t}function g(e){let t,s,i=e.split(":");return 1===i.length?(t=i[0],s="default"):(t=i.slice(0,i.length-1).join(":"),s=i[i.length-1]),t.endsWith(".js")&&(t=t.
2slice(0,-3)),`${t}:${s}`}function p(e,t){return JSON.stringify({udfPath:g(e),args:(0,r.convexToJson)(t)})}function y(e,t,s){let{initialNumItems:i,id:n}=s;return JSON.stringify({type:"paginated",udfPath:g(e),args:(0,r.convexToJson)(t),options:(0,r.convexToJson)({initialNumItems:i,id:n})})}var m=Object.defineProperty,v=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?m(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class b{constructor(){v(this,"nextQueryId"),v(this,"querySetVersion"),v(this,"querySet"),v(this,"queryIdToToken"),v(this,"identityVersion"),v(this,"auth"),v(this,"outstandingQueriesOlderThanRestart"),v(this,"outstandingAuthOlderThanRestart"),v(this,"paused"),v(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return 0===this.outstandingQueriesOlderThanRestart.size&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,s,i){let n=g(e),o=p(n,t),a=this.querySet.get(o);if(void 0!==a)return a.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{let e=this.nextQueryId++;this.querySet.set(o,{id:e,canonicalizedUdfPath:n,args:t,numSubscribers:1,journal:s,componentPath:i}),this.queryIdToToken.set(e,o);let a=this.querySetVersion,u=this.querySetVersion+1,h={type:"Add",queryId:e,udfPath:n,args:[(0,r.convexToJson)(t)],journal:s,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(e,h):this.querySetVersion=u,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:a,newVersion:u,modifications:[h]},unsubscribe:()=>this.removeSubscriber(o)}}}transition(e){for(let t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(void 0!==e){let s=this.queryIdToToken.get(t.queryId);void 0!==s&&(this.querySet.get(s).journal=e)}break}case"QueryRemoved":this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let s=p(g(e),t),i=this.querySet.get(s);return void 0!==i?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){let s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;let i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let t=[];for(let s of this.querySet.values()){let i={type:"Add",queryId:s.id,udfPath:s.canonicalizedUdfPath,args:[(0,r.convexToJson)(s.args)],journal:s.journal,componentPath:s.componentPath};t.push(i),e.has(s.id)||this.outstandingQueriesOlderThanRestart.add(s.id)}this.querySetVersion=1;let s={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:t};if(!this.auth)return this.identityVersion=0,[s,void 0];this.outstandingAuthOlderThanRestart=!0;let i={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[s,i]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=void 0!==this.auth?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return t.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let s=this.querySetVersion,i=this.querySetVersion+1,n={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,n):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:s,newVersion:i,modifications:[n]}}}}var w=Object.defineProperty,k=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?w(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class S{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,k(this,"inflightRequests"),k(this,"requestsOlderThanRestart"),k(this,"inflightMutationsCount",0),k(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let s=new Promise(s=>{this.inflightRequests.set(e.requestId,{message:e,status:{status:t?"Requested":"NotSent",requestedAt:new Date,onResult:s}}),"Mutation"===e.type?this.inflightMutationsCount++:"Action"===e.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),s}onResponse(e){let t,s,i=this.inflightRequests.get(e.requestId);if(void 0===i||"Completed"===i.status.status)return null;let n="Mutation"===i.message.type?"mutation":"action",o=i.message.udfPath;
2for(let t of e.logLines)c(this.logger,"info",n,o,t);let a=i.status;if(e.success)t={success:!0,logLines:e.logLines,value:(0,r.jsonToConvex)(e.result)},s=()=>a.onResult(t);else{let i=e.result,{errorData:u}=e;c(this.logger,"error",n,o,i),t={success:!1,errorMessage:i,errorData:void 0!==u?(0,r.jsonToConvex)(u):void 0,logLines:e.logLines},s=()=>a.onResult(t)}return"ActionResponse"!==e.type&&e.success?(i.status={status:"Completed",result:t,ts:e.ts,onResolve:s},null):(s(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===i.message.type?this.inflightActionsCount--:"Mutation"===i.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:t})}removeCompleted(e){let t=new Map;for(let[s,i]of this.inflightRequests.entries()){let n=i.status;"Completed"===n.status&&n.ts.lessThanOrEqual(e)&&(n.onResolve(),t.set(s,n.result),"Mutation"===i.message.type?this.inflightMutationsCount--:"Action"===i.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(s),this.requestsOlderThanRestart.delete(s))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,s]of this.inflightRequests){if("NotSent"===s.status.status){s.status.status="Requested",e.push(s.message);continue}if("Mutation"===s.message.type)e.push(s.message);else if("Action"===s.message.type){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,"Completed"===s.status.status)throw Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if("NotSent"===t.status.status){t.status.status="Requested",e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if("Requested"===e.status.status)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return 0===this.requestsOlderThanRestart.size}timeOfOldestInflightRequest(){if(0===this.inflightRequests.size)return null;let e=Date.now();for(let t of this.inflightRequests.values())"Completed"!==t.status.status&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}let C=Symbol.for("functionName"),T=Symbol.for("toReferencePath");function R(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[C])t={name:e[C]};else{let s=e[T]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}function A(e){let t=R(e);if(void 0===t.name){if(void 0!==t.functionHandle)throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(void 0!==t.reference)throw Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`);throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`)}if("string"==typeof e)return e;let s=e[C];if(!s)throw Error(`${e} is not a functionReference`);return s}function x(e){return{[C]:e}}e.s(["getFunctionAddress",0,R,"setReferencePath",0,function(e,t){e[T]=t},"toReferencePath",0,T],39197);let q=function e(t=[]){return new Proxy({},{get(s,i){if("string"==typeof i)return e([...t,i]);if(i===C){if(t.length<2){let e=["api",...t].join(".");throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${e}\``)}let e=t.slice(0,-1).join("/"),s=t[t.length-1];return"default"===s?e:e+":"+s}return i===Symbol.toStringTag?"FunctionReference":void 0}})}();e.s(["anyApi",0,q,"getFunctionName",0,A,"makeFunctionReference",0,x],62849);var O=e.i(2082),M=e.i(3697),E=Object.defineProperty,$=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?E(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class Q{constructor(e){$(this,"queryResults"),$(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=(0,O.parseArgs)(t[0]),i=A(e),n=this.queryResults.get(p(i,s));if(void 0!==n)return Q.queryValue(n.result)}getAllQueries(e){let t=[],s=A(e);for(let e of this.queryResults.values())e.udfPath===g(s)&&t.push({args:e.args,value:Q.queryValue(e.result)});return t}setQuery(e,t,s){let i=(0,O.parseArgs)(t),n=A(e),r=p(n,i);this.queryResults.set(r,{udfPath:n,args:i,result:void 0===s?void 0:{success:!0,value:s,logLines:[]}}),this.modifiedQueries.push(r)}static queryValue(e){return void 0===e?void 0:e.success?e.value:void 0}}class I{constructor(){$(this,"queryResults"),$(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let s=this.queryResults;this.queryResults=new Map(e);let i=new Q(this.queryResults);for(let e of this.optimisticUpdates)e.update(i);let n=[];for(let[e,t]of this.queryResults){let i=s.get(e);(void 0===i||i.result!==t.result)&&n.push(e)}return n}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new Q(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(void 0!==t)return t.result}queryResult(e){let t=this.queryResults.get(e);if(void 0===t)return;let s=t.result;if(void 0!==s){if(s.success)return s.value;if(void 0!==s.errorData)throw f(s,new M.ConvexError(d("query",t.udfPath,s)));throw Error(d("query",t.udfPath,s))}}hasQueryResult(e){return void 0!==this.queryResults.get(e)}queryLogs(e){let t=this.queryResults.get(e);return t?.result?.logLines}}var P=Object.defineProperty,V=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?P(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class L{constructor(e,t){V(this,"low"),V(this,"high"),V(this,"__isUnsignedLong__"),this.low=0|e,this.high=0|t,this.__isUnsignedLong__=!0}static isLong(e){return!0===(e&&e.__isUnsignedLong__)}static fromBytesLE(e){return new L(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?j:e>=N?F:new L(e%_|0,e/_|0)}toString(){return(BigInt(this.high)*BigInt(_)+BigInt(this.low)).toString()}equals(e){return L.isLong(e)||(e=L.fromValue(e)),(this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return(L.isLong(e)||(e=L.fromValue(e)),this.equals(e))?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return 0>=this.comp(e)}static fromValue(e){return"number"==typeof e?L.fromNumber(e):new L(e.low,e.high)}}let j=new L(0,0),_=0x100000000,N=0xffffffffffffffff,F=new L(-1,-1);var D=Object.defineProperty,U=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?D(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class B{constructor(e,t){U(this,"version"),U(this,"remoteQuerySet"),U(this,"queryPath"),U(this,"logger"),this.version={querySet:0,ts:L.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case"QueryUpdated":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)c(this.logger,"info","query",e,s);let s=(0,r.jsonToConvex)(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:s,logLines:t.logLines});break}case"QueryFailed":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)c(this.logger,"info","query",e,s);let{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?(0,r.jsonToConvex)(s):void 0,logLines:t.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}var J=e.i(95543),J=J;function W(e){let t=J.toByteArray(e);return L.fromBytesLE(Array.from(t))}function K(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:W(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:W(e.startVersion.ts)},endVersion:{...e.endVersion,ts:W(e.endVersion.ts)}}}}var z=Object.defineProperty,H=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?z(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function G(){return(void 0===t&&(t=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(t+performance.now())}function X(){return`t=${Math.round((G()-t)/100)/10}s`}let Z={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};class Y{constructor(e,t,s,i,n,r){this.markConnectionStateDirty=n,this.debug=r,H(this,"socket"),H(this,"connectionCount"),H(this,"_hasEverConnected",!1),H(this,"lastCloseReason"),H(this,"transitionChunkBuffer",null),H(this,"defaultInitialBackoff"),H(this,"maxBackoff"),H(this,"retries"),H(this,"serverInactivityThreshold"),H(this,"reconnectDueToServerInactivityTimeout"),H(this,"scheduledReconnect",null),H(this,"networkOnlineHandler",null),H(this,"pendingNetworkRecoveryInfo",null),H(this,"uri"),H(this,"onOpen"),H(this,"onResume"),H(this,"onMessage"),H(this,"webSocketConstructor"),H(this,"logger"),H(this,"onServerDisconnectError"),this.webSocketConstructor=s,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){"u"<typeof window||"function"!=typeof window.addEventListener||null===this.networkOnlineHandler&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&"u">typeof window&&"function"==typeof window.removeEventListener&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||0===e.totalParts||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;
2throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let t=K(JSON.parse(e));if("Transition"!==t.type)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if("terminated"===this.socket.state)return;if("disconnected"!==this.socket.state&&"stopped"!==this.socket.state)throw Error("Didn't start connection from disconnected state: "+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:"yes"===this.socket.paused?"uninitialized":"no"}),this.resetServerInactivityTimeout(),"no"===this.socket.paused&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:G()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",X(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",X())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,s=K(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${s.type}`),"Ping"!==s.type){if("TransitionChunk"===s.type){let e=this.assembleTransition(s);if(!e)return;s=e,this._logVerbose(`assembled full ws message of type ${s.type}`)}null!==this.transitionChunkBuffer&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${s.type} while buffering TransitionChunks`)),"Transition"===s.type&&this.reportLargeTransition({messageLength:t,transition:s}),this.onMessage(s).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,null===this.lastCloseReason&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),1e3!==e.code&&1001!==e.code&&1005!==e.code&&4040!==e.code){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=function(e){if(void 0===e)return"Unknown";for(let t of Object.keys(Z))if(e.startsWith(t))return t;return"Unknown"}(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,..."Authenticate"===e.type&&"User"===e.tokenType?{value:`...${e.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){let s=JSON.stringify(function(e){switch(e.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...e};case"Connect":let t;if(void 0===e.maxObservedTimestamp)return{...e,maxObservedTimestamp:void 0};return{...e,maxObservedTimestamp:(t=new Uint8Array(e.maxObservedTimestamp.toBytesLE()),J.fromByteArray(t))}}}(e)),i=!1;try{this.socket.ws.send(s),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let s=G(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:i,scheduledAt:s,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose("Ignoring message received after close")},new Promise(t=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),t()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");let e=this.socket.ws;e.onmessage=e=>{this._logVerbose("Ignoring message received after close")};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":this.socket={...this.socket,paused:"yes"};return;default:return void this.socket}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),"disconnected"!==this.socket.state)return void this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);let e=null;if(this.scheduledReconnect){let t=G()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=null!==e?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":"uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:G()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:"ready"===this.socket.state,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=("client"===e?100:"Unknown"===e?this.defaultInitialBackoff:Z[e].timeout)*Math.pow(2,this.retries);this.retries+=1;let s=Math.min(t,this.maxBackoff),i=s*(Math.random()-.5);return s+i}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;let s=G()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(s)}ms`,n=`${Math.round(t/1e4)/100}MB`,r=t/(s/1e3),o=`${Math.round(r/1e4)/100}MB per second`;this._logVerbose(`received ${n} transition in ${i} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${n}
2) which will take a long time to download on slower connections`):s>2e4&&this.logger.log(`received query results totaling ${n} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:s,messageLength:t}})}}class ee extends Error{}function et(e,t){let s;if("string"!=typeof e)throw new ee("Invalid token specified: must be a string");t||(t={});let i=+(!0!==t.header),n=e.split(".")[i];if("string"!=typeof n)throw new ee(`Invalid token specified: missing part #${i+1}`);try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw Error("base64 string is not of the correct length")}try{var s;return s=t,decodeURIComponent(atob(s).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}catch{return atob(t)}}(n)}catch(e){throw new ee(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new ee(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}ee.prototype.name="InvalidTokenError";var es=Object.defineProperty,ei=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?es(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class en{constructor(e,t,s){ei(this,"authState",{state:"noAuth"}),ei(this,"configVersion",0),ei(this,"syncState"),ei(this,"authenticate"),ei(this,"stopSocket"),ei(this,"tryRestartSocket"),ei(this,"pauseSocket"),ei(this,"resumeSocket"),ei(this,"clearAuth"),ei(this,"logger"),ei(this,"refreshTokenLeewaySeconds"),ei(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=s.logger,this.refreshTokenLeewaySeconds=s.refreshTokenLeewaySeconds}async setConfig(e,t){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let s=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});s.isFromOutdatedConfig||(s.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:t},hasRetried:!1}),this.authenticate(s.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:t}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if("waitingForServerConfirmationOfCachedToken"===this.authState.state){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(!1===e.authUpdateAttempted&&("waitingForServerConfirmationOfFreshToken"===this.authState.state||"waitingForServerConfirmationOfCachedToken"===this.authState.state))return void this._logVerbose("ignoring non-auth token expired error");let{baseVersion:t}=e;this.syncState.isCurrentOrNewerAuthVersion(t+1)?this.tryToReauthenticate(e):this._logVerbose("ignoring auth error for previous auth attempt")}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),"noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),"noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:t.value,hadAuth:"notRefetching"===this.authState.state||"waitingForScheduledRefetch"===this.authState.state})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if("noAuth"===this.authState.state)return;this._logVerbose("refetching auth token");let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if("noAuth"===this.authState.state)return;let t=this.decodeToken(e);if(!t)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");let{iat:s,exp:i}=t;if(!s||!i)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let n=i-s;if(n<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");let r=Math.min(1728e6,(n-this.refreshTokenLeewaySeconds)*1e3);r<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${n}s`),r=0);let o=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},r);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:o,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${r}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);let i=await e(t);
2return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){let t="waitingForServerConfirmationOfFreshToken"===e.state?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return et(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}let er=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function eo(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var ea=Object.defineProperty,eu=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ea(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eh{constructor(e,t,s){let i;if(eu(this,"address"),eu(this,"state"),eu(this,"requestManager"),eu(this,"webSocketManager"),eu(this,"authenticationManager"),eu(this,"remoteQuerySet"),eu(this,"optimisticQueryResults"),eu(this,"_transitionHandlerCounter",0),eu(this,"_nextRequestId"),eu(this,"_onTransitionFns",new Map),eu(this,"_sessionId"),eu(this,"firstMessageReceived",!1),eu(this,"debug"),eu(this,"logger"),eu(this,"maxObservedTimestamp"),eu(this,"connectionStateSubscribers",new Map),eu(this,"nextConnectionStateSubscriberId",0),eu(this,"_lastPublishedConnectionState"),eu(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState))for(let t of(this._lastPublishedConnectionState=e,this.connectionStateSubscribers.values()))t(e)})}),eu(this,"mark",e=>{var t;this.debug&&(t=this.sessionId,"u">typeof performance&&performance.mark&&performance.mark(e,{detail:{sessionId:t}}))}),"object"==typeof e)throw Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");s?.skipConvexDeploymentUrlCheck!==!0&&(0,O.validateDeploymentUrl)(e);const r=(s={...s}).authRefreshTokenLeewaySeconds??2;let o=s.webSocketConstructor;if(!o&&"u"<typeof WebSocket)throw Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");o=o||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=!1===s.logger?function(e){return new h(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:l({verbose:s.verbose??!1});const a=e.search("://");if(-1===a)throw Error("Provided address was not an absolute URL.");const u=e.substring(a+3),c=e.substring(0,a);if("http"===c)i="ws";else if("https"===c)i="wss";else throw Error(`Unknown parent protocol ${c}`);const d=`${i}://${u}/api/${n.version}/sync`;this.state=new b,this.remoteQuerySet=new B(e=>this.state.queryPath(e),this.logger),this.requestManager=new S(this.logger,this.markConnectionStateDirty);const f=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new en(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:f,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r}),this.optimisticQueryResults=new I,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});const{unsavedChangesWarning:g}=s;if("u"<typeof window||void 0===window.addEventListener){if(!0===g)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==g&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=t,t}});this.webSocketManager=new Y(d,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});let t=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new B(e=>this.state.queryPath(e),this.logger);let[s,i]=this.state.restart(t);for(let e of(i&&this.webSocketManager.sendMessage(i),this.webSocketManager.sendMessage(s),this.requestManager.restart()))this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();for(let s of(t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e),this.requestManager.resume()))this.webSocketManager.sendMessage(s)},onMessage:e=>{switch(!this.firstMessageReceived&&(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMar
2ks()),e.type){case"Transition":{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case"MutationResponse":{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);null!==t&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case"ActionResponse":this.requestManager.onResponse(e);break;case"AuthError":this.authenticationManager.onAuthError(e);break;case"FatalError":{var t,s;let i,n=(t=this.logger,s=e.error,i=`[CONVEX FATAL ERROR] ${s}`,t.error(i),Error(i));throw this.webSocketManager.terminate(),n}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},o,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&f()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(let[e,i]of t){let t=this.state.queryToken(e);if(null!==t){let n={result:i,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,n)}}let i=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:i.map(e=>{let t=this.optimisticQueryResults.rawQueryResult(e);return{token:e,modification:{kind:"Updated",result:t}}}),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&"User"===e.tokenType){try{t=e?et(e.value):{}}catch{t={}}return{token:e.value,decoded:t}}}setAuth(e,t){this.authenticationManager.setConfig(e,t)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){let i=(0,O.parseArgs)(t),{modification:n,queryToken:r,unsubscribe:o}=this.state.subscribe(e,i,s?.journal,s?.componentPath);return null!==n&&this.webSocketManager.sendMessage(n),{queryToken:r,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let s=p(e,(0,O.parseArgs)(t));return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let s=p(e,(0,O.parseArgs)(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=p(e,(0,O.parseArgs)(t));return this.state.queryJournal(s)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){let i=await this.mutationInternal(e,t,s);if(!i.success){if(void 0!==i.errorData)throw f(i,new M.ConvexError(d("mutation",e,i)));throw Error(d("mutation",e,i))}return i.value}async mutationInternal(e,t,s,i){let{mutationPromise:n}=this.enqueueMutation(e,t,s,i);return n}enqueueMutation(e,t,s,i){let n=(0,O.parseArgs)(t);this.tryReportLongDisconnect();let o=this.nextRequestId;if(this._nextRequestId++,void 0!==s){let e=s.optimisticUpdate;if(void 0!==e){let t=t=>{e(t,n)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},s=this.optimisticQueryResults.applyOptimisticUpdate(t,o).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:"Updated",result:void 0===t?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:s,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let a={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[(0,r.convexToJson)(n)]},u=this.webSocketManager.sendMessage(a);return{requestId:o,mutationPromise:this.requestManager.request(a,u)}}async action(e,t){let s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw f(s,new M.ConvexError(d("action",e,s)));throw Error(d("action",e,s))}return s.value}async actionInternal(e,t,s){let i=(0,O.parseArgs)(t),n=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let o={type:"Action",requestId:n,udfPath:e,componentPath:s,args:[(0,r.convexToJson)(i)]},a=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,a)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}
2reportMarks(){if(this.debug){let e=function(e){if("u"<typeof performance||!performance.getEntriesByName)return[];let t=[];for(let s of er){let i=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...i)}return t.map(eo)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;null===e||Date.now()-e.getTime()<=6e4||fetch(`${this.address}/api/debug_event`,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${n.version}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(e=>{e.ok||this.logger.warn("Analytics request failed with response:",e.body)}).catch(e=>{this.logger.warn("Analytics response failed with error:",e)})}}function el(e){if("object"!=typeof e||null===e||!Array.isArray(e.page)||"boolean"!=typeof e.isDone||"string"!=typeof e.continueCursor)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var ec=Object.defineProperty,ed=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ec(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class ef{constructor(e,t){this.client=e,this.onTransition=t,ed(this,"paginatedQuerySet",new Map),ed(this,"lastTransitionTs"),this.lastTransitionTs=L.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){let i=g(e),n=y(i,t,s),r=()=>this.removePaginatedQuerySubscriber(n),o=this.paginatedQuerySet.get(n);return o?o.numSubscribers+=1:(this.paginatedQuerySet.set(n,{token:n,canonicalizedUdfPath:i,args:t,numSubscribers:1,options:{initialNumItems:s.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:s.id}),this.addPageToPaginatedQuery(n,null,s.initialNumItems)),{paginatedQueryToken:n,unsubscribe:r}}localQueryResult(e,t,s){let i=y(g(e),t,s);return this.localQueryResultByToken(i)}localQueryResultByToken(e){let t,s=this.paginatedQuerySet.get(e);if(!s)return;let i=this.activePageQueryTokens(s);if(0===i.length)return{results:[],status:"LoadingFirstPage",loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let n=[],r=!1,o=!1;for(let e of i){let t=this.client.localQueryResultByToken(e);if(void 0===t){r=!0,o=!1;continue}let s=el(t);n=n.concat(s.page),o=!!s.isDone}return t=r?0===n.length?"LoadingFirstPage":"LoadingMore":o?"Exhausted":"CanLoadMore",{results:n,status:t,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),s=this.queriesContainingTokens(t),i=[];s.length>0&&(this.processPaginatedQuerySplits(s,e=>this.client.localQueryResultByToken(e)),i=s.map(e=>({token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}})));let n={...e,paginatedQueries:i};this.onTransition(n)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let s=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(s);if(!i)return!1;let n=el(i);if(n.isDone)return!1;this.addPageToPaginatedQuery(e,n.continueCursor,t);let r={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(r),!0}queriesContainingTokens(e){if(0===e.length)return[];let t=[],s=new Set(e);for(let[e,i]of this.paginatedQuerySet)for(let n of this.allQueryTokens(i))if(s.has(n)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let s of e){let e=this.mustGetPaginatedQuery(s),{ongoingSplits:i,pageKeyToQuery:n,pageKeys:r}=e;for(let[s,[r,o]]of i)void 0!==t(n.get(r).queryToken)&&void 0!==t(n.get(o).queryToken)&&this.completePaginatedQuerySplit(e,s,r,o);for(let s of r){if(i.has(s))continue;let r=t(n.get(s).queryToken);if(!r)continue;let o=el(r);o.splitCursor&&("SplitRecommended"===o.pageStatus||"SplitRequired"===o.pageStatus||o.page.length>2*e.options.initialNumItems)&&this.splitPaginatedQueryPage(e,s,o.splitCursor,o.continueCursor)}}}splitPaginatedQueryPage(e,t,s,i){let n=e.nextPageKey++,r=e.nextPageKey++,o={cursor:i,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...o,cursor:null,endCursor:s}});e.pageKeyToQuery.set(n,a);let u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...o,cursor:s,endCursor:i}});e.pageKeyToQuery.set(r,u),e.ongoingSplits.set(t,[n,r])}addPageToPaginatedQuery(e,t,s){let i=this.mustGetPaginatedQuery(e),n=i.nextPageKey++,r={cursor:t,numItems:s,id:i.id},o={...i.args,paginationOpts:r},a=this.client.subscribe(i.canonicalizedUdfPath,o);return i.pageKeys.push(n),i.pageKeyToQuery.set(n,a),a}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(t.numSubscribers-=1,!(t.numSubscribers>
20))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,s,i){let n=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let r=e.pageKeys.indexOf(t);e.pageKeys.splice(r,1,s,i),e.ongoingSplits.delete(t),n.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),s=t.pageKeys[t.pageKeys.length-1];if(void 0===s)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(s).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error("paginated query no longer exists for token "+e);return t}}var eg=Object.defineProperty,ep=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eg(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function ey(e,t){return t.data=(0,r.jsonToConvex)(e),t}e.s(["ConvexHttpClient",0,class{constructor(e,t){if(ep(this,"address"),ep(this,"auth"),ep(this,"adminAuth"),ep(this,"encodedTsPromise"),ep(this,"debug"),ep(this,"fetchOptions"),ep(this,"fetch"),ep(this,"logger"),ep(this,"mutationQueue",[]),ep(this,"isProcessingQueue",!1),"boolean"==typeof t)throw Error("skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.");!0!==(t??{}).skipConvexDeploymentUrlCheck&&(0,O.validateDeploymentUrl)(e),this.logger=t?.logger===!1?function(e){return new h(e)}({verbose:!1}):t?.logger!==!0&&t?.logger?t.logger:l({verbose:!1}),this.address=e,this.debug=!0,this.auth=void 0,this.adminAuth=void 0,this.fetch=t?.fetch,t?.auth&&this.setAuth(t.auth)}backendUrl(){return`${this.address}/api`}get url(){return this.address}setAuth(e){this.clearAuth(),this.auth=e}setAdminAuth(e,t){if(this.clearAuth(),void 0!==t){let s=btoa(String.fromCodePoint(...new TextEncoder().encode(JSON.stringify(t))));this.adminAuth=`${e}:${s}`}else this.adminAuth=e}clearAuth(){this.auth=void 0,this.adminAuth=void 0}setDebug(e){this.debug=e}setFetchOptions(e){this.fetchOptions=e}async consistentQuery(e,...t){let s=(0,O.parseArgs)(t[0]),i=this.getTimestamp();return await this.queryInner(e,s,{timestampPromise:i})}async getTimestamp(){return this.encodedTsPromise?this.encodedTsPromise:this.encodedTsPromise=this.getTimestampInner()}async getTimestampInner(){let e=this.fetch||s||fetch,t={"Content-Type":"application/json","Convex-Client":`npm-${n.version}`},i=await e(`${this.address}/api/query_ts`,{...this.fetchOptions,method:"POST",headers:t});if(!i.ok)throw Error(await i.text());let{ts:r}=await i.json();return r}async query(e,...t){let s=(0,O.parseArgs)(t[0]);return await this.queryInner(e,s,{})}async queryInner(e,t,i){let o=A(e),a=[(0,r.convexToJson)(t)],u={"Content-Type":"application/json","Convex-Client":`npm-${n.version}`};this.adminAuth?u.Authorization=`Convex ${this.adminAuth}`:this.auth&&(u.Authorization=`Bearer ${this.auth}`);let h=this.fetch||s||fetch,l=i.timestampPromise?await i.timestampPromise:void 0,d=JSON.stringify({path:o,format:"convex_encoded_json",args:a,...l?{ts:l}:{}}),f=l?`${this.address}/api/query_at_ts`:`${this.address}/api/query`,g=await h(f,{...this.fetchOptions,body:d,method:"POST",headers:u});if(!g.ok&&560!==g.status)throw Error(await g.text());let p=await g.json();if(this.debug)for(let e of p.logLines??[])c(this.logger,"info","query",o,e);switch(p.status){case"success":return(0,r.jsonToConvex)(p.value);case"error":if(void 0!==p.errorData)throw ey(p.errorData,new M.ConvexError(p.errorMessage));throw Error(p.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(p)}`)}}async mutationInner(e,t){let i=A(e),o=JSON.stringify({path:i,format:"convex_encoded_json",args:[(0,r.convexToJson)(t)]}),a={"Content-Type":"application/json","Convex-Client":`npm-${n.version}`};this.adminAuth?a.Authorization=`Convex ${this.adminAuth}`:this.auth&&(a.Authorization=`Bearer ${this.auth}`);let u=this.fetch||s||fetch,h=await u(`${this.address}/api/mutation`,{...this.fetchOptions,body:o,method:"POST",headers:a});if(!h.ok&&560!==h.status)throw Error(await h.text());let l=await h.json();if(this.debug)for(let e of l.logLines??[])c(this.logger,"info","mutation",i,e);switch(l.status){case"success":return(0,r.jsonToConvex)(l.value);case"error":if(void 0!==l.errorData)throw ey(l.errorData,new M.ConvexError(l.errorMessage));throw Error(l.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(l)}`)}}async processMutationQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;
2this.mutationQueue.length>0;){let{mutation:e,args:t,resolve:s,reject:i}=this.mutationQueue.shift();try{let i=await this.mutationInner(e,t);s(i)}catch(e){i(e)}}this.isProcessingQueue=!1}}enqueueMutation(e,t){return new Promise((s,i)=>{this.mutationQueue.push({mutation:e,args:t,resolve:s,reject:i}),this.processMutationQueue()})}async mutation(e,...t){let[s,i]=t,n=(0,O.parseArgs)(s);return i?.skipQueue?await this.mutationInner(e,n):await this.enqueueMutation(e,n)}async action(e,...t){let i=(0,O.parseArgs)(t[0]),o=A(e),a=JSON.stringify({path:o,format:"convex_encoded_json",args:[(0,r.convexToJson)(i)]}),u={"Content-Type":"application/json","Convex-Client":`npm-${n.version}`};this.adminAuth?u.Authorization=`Convex ${this.adminAuth}`:this.auth&&(u.Authorization=`Bearer ${this.auth}`);let h=this.fetch||s||fetch,l=await h(`${this.address}/api/action`,{...this.fetchOptions,body:a,method:"POST",headers:u});if(!l.ok&&560!==l.status)throw Error(await l.text());let d=await l.json();if(this.debug)for(let e of d.logLines??[])c(this.logger,"info","action",o,e);switch(d.status){case"success":return(0,r.jsonToConvex)(d.value);case"error":if(void 0!==d.errorData)throw ey(d.errorData,new M.ConvexError(d.errorMessage));throw Error(d.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(d)}`)}}async function(e,t,...i){let o=(0,O.parseArgs)(i[0]),a="string"==typeof e?e:A(e),u=JSON.stringify({componentPath:t,path:a,format:"convex_encoded_json",args:(0,r.convexToJson)(o)}),h={"Content-Type":"application/json","Convex-Client":`npm-${n.version}`};this.adminAuth?h.Authorization=`Convex ${this.adminAuth}`:this.auth&&(h.Authorization=`Bearer ${this.auth}`);let l=this.fetch||s||fetch,d=await l(`${this.address}/api/function`,{...this.fetchOptions,body:u,method:"POST",headers:h});if(!d.ok&&560!==d.status)throw Error(await d.text());let f=await d.json();if(this.debug)for(let e of f.logLines??[])c(this.logger,"info","any",a,e);switch(f.status){case"success":return(0,r.jsonToConvex)(f.value);case"error":if(void 0!==f.errorData)throw ey(f.errorData,new M.ConvexError(f.errorMessage));throw Error(f.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(f)}`)}}}],71482);var em=Object.defineProperty,ev=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?em(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};if(void 0===i.default)throw Error("Required dependency 'react' not found");class eb{constructor(e,t){if(ev(this,"address"),ev(this,"cachedSync"),ev(this,"cachedPaginatedQueryClient"),ev(this,"listeners"),ev(this,"options"),ev(this,"closed",!1),ev(this,"_logger"),ev(this,"adminAuth"),ev(this,"fakeUserIdentity"),void 0===e)throw Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if("string"!=typeof e)throw Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=t?.logger===!1?function(e){return new h(e)}({verbose:t?.verbose??!1}):t?.logger!==!0&&t?.logger?t.logger:l({verbose:t?.verbose??!1}),this.options={...t,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw Error("ConvexReactClient has already been closed.");return this.cachedSync||(this.cachedSync=new eh(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new ef(this.cachedSync,e=>this.handleTransition(e))),this.cachedSync}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw Error("Should already be instantiated")}setAuth(e,t){if("string"==typeof e)throw Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,t??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,t){if(this.adminAuth=e,this.fakeUserIdentity=t,this.closed)throw Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,t)}watchQuery(e,...t){let[s,i]=t,n=A(e);return{onUpdate:e=>{let{queryToken:t,unsubscribe:r}=this.sync.subscribe(n,s,i),o=this.listeners.get(t);return void 0!==o?o.add(e):this.listeners.set(t,new Set([e])),()=>{if(this.closed)return;let s=this.listeners.get(t);s.delete(e),0===s.size&&this.listeners.delete(t),r()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(n,s)},localQueryLogs:()=>
2{if(this.cachedSync)return this.cachedSync.localQueryLogs(n,s)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(n,s)}}}prewarmQuery(e){let t=e.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(e.query,e.args||{}).onUpdate(()=>{}),t)}watchPaginatedQuery(e,t,s){let i=A(e);return{onUpdate:e=>{let{paginatedQueryToken:n,unsubscribe:r}=this.paginatedQueryClient.subscribe(i,t||{},s),o=this.listeners.get(n);return void 0!==o?o.add(e):this.listeners.set(n,new Set([e])),()=>{if(this.closed)return;let t=this.listeners.get(n);t.delete(e),0===t.size&&this.listeners.delete(n),r()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,t,s)}}mutation(e,...t){let[s,i]=t,n=A(e);return this.sync.mutation(n,s,i)}action(e,...t){let s=A(e);return this.sync.action(s,...t)}query(e,...t){let s=this.watchQuery(e,...t),i=s.localQueryResult();return void 0!==i?Promise.resolve(i):new Promise((e,t)=>{let i=s.onUpdate(()=>{i();try{e(s.localQueryResult())}catch(e){t(e)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){let e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){let t=e.queries.map(e=>e.token),s=e.paginatedQueries.map(e=>e.token);this.transition([...t,...s])}transition(e){for(let t of e){let e=this.listeners.get(t);if(e)for(let t of e)t()}}}let ew=i.default.createContext(void 0);function ek(){return(0,i.useContext)(ew)}let eS=({client:e,children:t})=>i.default.createElement(ew.Provider,{value:e},t);function eC(e,...t){let s="skip"===t[0],n="skip"===t[0]?{}:(0,O.parseArgs)(t[0]),o="string"==typeof e?x(e):e,a=A(o),u=function(e){let t=ek();if(void 0===t)throw Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return function(e,t){let[s]=(0,i.useState)(()=>new eq(t));return s.createWatch!==t&&s.setCreateWatch(t),(0,i.useEffect)(()=>()=>s.destroy(),[s]),function({getCurrentValue:e,subscribe:t}){let[s,n]=(0,i.useState)(()=>({getCurrentValue:e,subscribe:t,value:e()})),r=s.value;return(s.getCurrentValue!==e||s.subscribe!==t)&&(r=e(),n({getCurrentValue:e,subscribe:t,value:r})),(0,i.useEffect)(()=>{let s=!1,i=()=>{s||n(s=>{if(s.getCurrentValue!==e||s.subscribe!==t)return s;let i=e();return s.value===i?s:{...s,value:i}})},r=t(i);return i(),()=>{s=!0,r()}},[e,t]),r}((0,i.useMemo)(()=>({getCurrentValue:()=>s.getLocalResults(e),subscribe:t=>(s.setQueries(e),s.subscribe(t))}),[s,e]))}(e,(0,i.useMemo)(()=>(e,s,{journal:i,paginationOptions:n})=>n?t.watchPaginatedQuery(e,s,n):t.watchQuery(e,s,i?{journal:i}:{}),[t]))}((0,i.useMemo)(()=>s?{}:{query:{query:o,args:n}},[JSON.stringify((0,r.convexToJson)(n)),a,s])).query;if(u instanceof Error)throw u;return u}function eT(e){let t="string"==typeof e?x(e):e,s=(0,i.useContext)(ew);if(void 0===s)throw Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return(0,i.useMemo)(()=>(function e(t,s,i){function n(e){return function(e){if("object"==typeof e&&null!==e&&"bubbles"in e&&"persist"in e&&"isDefaultPrevented"in e)throw Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}(e),s.mutation(t,e,{optimisticUpdate:i})}return n.withOptimisticUpdate=function(n){if(void 0!==i)throw Error(`Already specified optimistic update for mutation ${A(t)}`);return e(t,s,n)},n})(t,s),[s,A(t)])}function eR(e){let t=(0,i.useContext)(ew),s="string"==typeof e?x(e):e;if(void 0===t)throw Error("Could not find Convex client! `useAction` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return(0,i.useMemo)(()=>function(e){return t.action(s,e)},[t,A(s)])}var eA=Object.defineProperty,ex=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eA(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eq{constructor(e){ex(this,"createWatch"),ex(this,"queries"),ex(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(let t of Object.keys(e)){let{query:s,args:i,paginationOptions:n}=e[t];if(A(s),void 0===this.queries[t])this.addQuery(t,s,i,n?{paginationOptions:n}:{});else{let e=this.queries[t];(A(s)!==A(e.query)||JSON.stringify((0,r.convexToJson)(i))!==JSON.stringify((0,r.convexToJson)(e.args))||JSON.stringify(n)!==JSON.stringify(e.paginationOptions))&&(this.removeQuery(t),this.addQuery(t,s,i,n?{paginationOptions:n}:{}))}}for(let t of Object.keys(this.queries))void 0===e[t]&&this.removeQuery(t)}
2subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){let t={};for(let s of Object.keys(e)){let i,{query:n,args:r}=e[s],o=e[s].paginationOptions;A(n);let a=this.createWatch(n,r,o?{paginationOptions:o}:{});try{i=a.localQueryResult()}catch(e){if(e instanceof Error)i=e;else throw e}t[s]=i}return t}setCreateWatch(e){for(let t of(this.createWatch=e,Object.keys(this.queries))){let{query:e,args:s,watch:i,paginationOptions:n}=this.queries[t],r="journal"in i?i.journal():void 0;this.removeQuery(t),this.addQuery(t,e,s,{...r?{journal:r}:[],...n?{paginationOptions:n}:{}})}}destroy(){for(let e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,t,s,{paginationOptions:i,journal:n}){if(void 0!==this.queries[e])throw Error(`Tried to add a new query with identifier ${e} when it already exists.`);let r=this.createWatch(t,s,{...n?{journal:n}:[],...i?{paginationOptions:i}:{}}),o=r.onUpdate(()=>this.notifyListeners());this.queries[e]={query:t,args:s,watch:r,unsubscribe:o,...i?{paginationOptions:i}:{}}}removeQuery(e){let t=this.queries[e];if(void 0===t)throw Error(`No query found with identifier ${e}.`);t.unsubscribe(),delete this.queries[e]}notifyListeners(){for(let e of this.listeners)e()}}e.i(6689),Symbol("includePageKeys"),Symbol("page");let eO=(0,i.createContext)(void 0);function eM(){let e=(0,i.useContext)(eO);if(void 0===e)throw Error("Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project.");return e}function eE({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:n,setIsConvexAuthenticated:r}){return(0,i.useEffect)(()=>{let s=!0;if(e)return n.setAuth(t,e=>{s&&r(()=>e)}),()=>{s=!1,r(e=>!e&&null)}},[e,t,s,n,r]),null}function e$({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:n,setIsConvexAuthenticated:r}){return(0,i.useEffect)(()=>{if(e)return()=>{n.clearAuth(),r(()=>null)}},[e,t,s,n,r]),null}e.s(["ConvexProviderWithAuth",0,function({children:e,client:t,useAuth:s}){let{isLoading:n,isAuthenticated:r,fetchAccessToken:o}=s(),[a,u]=(0,i.useState)(null);return n&&null!==a&&u(null),n||r||!1===a||u(!1),i.default.createElement(eO.Provider,{value:{isLoading:null===a,isAuthenticated:r&&(a??!1)}},i.default.createElement(eE,{authProviderAuthenticated:r,fetchAccessToken:o,authProviderLoading:n,client:t,setIsConvexAuthenticated:u}),i.default.createElement(eS,{client:t},e),i.default.createElement(e$,{authProviderAuthenticated:r,fetchAccessToken:o,authProviderLoading:n,client:t,setIsConvexAuthenticated:u}))},"useConvexAuth",0,eM],81958),e.s(["AuthLoading",0,function({children:e}){let{isLoading:t}=eM();return t?i.default.createElement(i.default.Fragment,null,e):null},"Authenticated",0,function({children:e}){let{isLoading:t,isAuthenticated:s}=eM();return t||!s?null:i.default.createElement(i.default.Fragment,null,e)},"Unauthenticated",0,function({children:e}){let{isLoading:t,isAuthenticated:s}=eM();return t||s?null:i.default.createElement(i.default.Fragment,null,e)}],82295),e.s([],50711)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.