PageSourceSearch

https://www.maced.ai/_next/static/chunks/0658291e5372e6da.js?dpl=dpl_26WZQQSTTQdkWEyQCAmdkaepMrrW

js maced.ai collected 2026-10-05 12:13:53 UTC 76,054 bytes, 2 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,528972,650322,871560,351321,185855,922991,84674,953584,558380,230588,338419,423395,e=>{"use strict";let t;for(var s,i,n=e.i(488182),r=[],o=[],a=Uint8Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0,l=u.length;h<l;++h)r[h]=u[h],o[u.charCodeAt(h)]=h;function c(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 d(e){var t=c(e),s=t[0],i=t[1];return(s+i)*3/4-i}function f(e){var t,s,i=c(e),n=i[0],r=i[1],u=new a((n+r)*3/4-r),h=0,l=r>0?n-4:n;for(s=0;s<l;s+=4)t=o[e.charCodeAt(s)]<<18|o[e.charCodeAt(s+1)]<<12|o[e.charCodeAt(s+2)]<<6|o[e.charCodeAt(s+3)],u[h++]=t>>16&255,u[h++]=t>>8&255,u[h++]=255&t;return 2===r&&(t=o[e.charCodeAt(s)]<<2|o[e.charCodeAt(s+1)]>>4,u[h++]=255&t),1===r&&(t=o[e.charCodeAt(s)]<<10|o[e.charCodeAt(s+1)]<<4|o[e.charCodeAt(s+2)]>>2,u[h++]=t>>8&255,u[h++]=255&t),u}function g(e){for(var t,s=e.length,i=s%3,n=[],o=0,a=s-i;o<a;o+=16383)n.push(function(e,t,s){for(var i,n=[],o=t;o<s;o+=3)i=(e[o]<<16&0xff0000)+(e[o+1]<<8&65280)+(255&e[o+2]),n.push(r[i>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return n.join("")}(e,o,o+16383>a?a:o+16383));return 1===i?n.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===i&&n.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),n.join("")}function y(e){return g(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function p(e){if(void 0===e)return{};if(!v(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function m(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.`)}function v(e){let t="object"==typeof e,s=Object.getPrototypeOf(e),i=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&i}o[45]=62,o[95]=63,e.s(["byteLength",()=>d,"fromByteArray",()=>g,"fromByteArrayUrlSafeNoPadding",()=>y,"toByteArray",()=>f],89718),e.s(["isSimpleObject",()=>v,"parseArgs",()=>p,"validateDeploymentUrl",()=>m],650322);let b=BigInt("-9223372036854775808"),w=BigInt("9223372036854775807"),k=BigInt("0"),S=BigInt("8"),R=BigInt("256");function C(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}let T=DataView.prototype.setBigInt64?function(e){if(e<b||w<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),g(new Uint8Array(t))}:function(e){e<k&&(e-=b+b);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>>=S;return g(s)},q=DataView.prototype.getBigInt64?function(e){let t=f(e);
1if(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=f(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=k,i=k;for(let e of t)s+=BigInt(e)*R**i,i++;return s>w&&(s+=b+b),s};function A(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} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function O(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>O(e));if("object"!=typeof e)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(1===t.length){let s=t[0][0];if("$bytes"===s){if("string"!=typeof e.$bytes)throw Error(`Malformed $bytes field on ${e}`);return f(e.$bytes).buffer}if("$integer"===s){if("string"!=typeof e.$integer)throw Error(`Malformed $integer field on ${e}`);return q(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw Error(`Malformed $float field on ${e}`);let t=f(e.$float);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let s=new DataView(t.buffer).getFloat64(0,!0);if(!C(s))throw Error(`Float ${s} should be encoded as a number`);return s}if("$set"===s)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===s)throw Error("Received a Map which is no longer supported as a Convex type.")}let s={};for(let[t,i]of Object.entries(e))A(t),s[t]=O(i);return s}function x(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 M(e,t,s,i){if(void 0===e){let e=s&&` (present at path ${s} in original object ${x(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<b||w<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:T(e)}}if("number"==typeof e)if(!C(e))return e;else{let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:g(new Uint8Array(t))}}if("boolean"==typeof e||"string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:g(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,i)=>M(e,t,s+`[${i}]`,!1));if(e instanceof Set)throw Error(Q(s,"Set",[...e],t));if(e instanceof Map)throw Error(Q(s,"Map",[...e],t));if(!v(e)){let i=e?.constructor?.name;throw Error(Q(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?(A(e),n[e]=M(o,t,s+`.${e}`,!1)):i&&(A(e),n[e]=E(o,t,s+`.${e}`));return n}function Q(e,t,s,i){return e?`${t}${x(s)} is not a supported Convex type (present at path ${e} in original object ${x(i)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(s)} is not a supported Convex type.`}function E(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return M(e,t,s,!1)}function $(e){return M(e,e,"",!1)}function I(e){return E(e,e,"")}function P(e){return M(e,e,"",!0)}e.s(["convexOrUndefinedToJson",()=>I,"convexToJson",()=>$,"jsonToConvex",()=>O,"patchValueToJson",()=>P,"stringifyValueForError",()=>x],871560);var V=Object.defineProperty,L=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?V(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function _(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 j{constructor({isOptional:e}){L(this,"type"),L(this,"fieldPaths"),L(this,"isOptional"),L(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}}class N extends j{constructor({isOptional:e,tableName:t}){if(super({isOptional:e}),L(this,"tableName"),L(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 N({isOptional:"optional",tableName:this.tableName})}}class F extends j{constructor(){super(...arguments),L(this,"kind","float64")}get json(){return{type:"number"}}asOptional(){return new F({isOptional:"optional"})}}class B extends j{constructor(){super(...arguments),L(this,"kind","int64")}get json(){return{type:"bigint"}}asOptional(){return new B({isOptional:"optional"})}}class U extends j{constructor(){super(...arguments),L(this,"kind","boolean")}get json(){return{type:this.kind}}asOptional(){return new U({isOptional:"optional"})}}class D extends j{constructor(){super(...arguments),L(this,"kind","bytes")}get json(){return{type:this.kind}}asOptional(){return new D({isOptional:"optional"})}}class W extends j{constructor(){super(...arguments),L(this,"kind","string")}get json(){return{type:this.kind}}asOptional(){return new W({isOptional:"optional"})}}class J extends j{constructor(){super(...arguments),L(this,"kind","null")}get json(){return{type:this.kind}}
1asOptional(){return new J({isOptional:"optional"})}}class K extends j{constructor(){super(...arguments),L(this,"kind","any")}get json(){return{type:this.kind}}asOptional(){return new K({isOptional:"optional"})}}class H extends j{constructor({isOptional:e,fields:t}){super({isOptional:e}),L(this,"fields"),L(this,"kind","object"),globalThis.Object.entries(t).forEach(([e,t])=>{if(void 0===t&&_("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 H({isOptional:"optional",fields:this.fields})}omit(...e){let t={...this.fields};for(let s of e)delete t[s];return new H({isOptional:this.isOptional,fields:t})}pick(...e){let t={};for(let s of e)t[s]=this.fields[s];return new H({isOptional:this.isOptional,fields:t})}partial(){let e={};for(let[t,s]of globalThis.Object.entries(this.fields))e[t]=s.asOptional();return new H({isOptional:this.isOptional,fields:e})}extend(e){return new H({isOptional:this.isOptional,fields:{...this.fields,...e}})}}class z extends j{constructor({isOptional:e,value:t}){if(super({isOptional:e}),L(this,"value"),L(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:$(this.value)}}asOptional(){return new z({isOptional:"optional",value:this.value})}}class G extends j{constructor({isOptional:e,element:t}){super({isOptional:e}),L(this,"element"),L(this,"kind","array"),void 0===t&&_("v.array()"),this.element=t}get json(){return{type:this.kind,value:this.element.json}}asOptional(){return new G({isOptional:"optional",element:this.element})}}class X extends j{constructor({isOptional:e,key:t,value:s}){if(super({isOptional:e}),L(this,"key"),L(this,"value"),L(this,"kind","record"),void 0===t&&_("v.record()","key"),void 0===s&&_("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 X({isOptional:"optional",key:this.key,value:this.value})}}class Y extends j{constructor({isOptional:e,members:t}){super({isOptional:e}),L(this,"members"),L(this,"kind","union"),t.forEach((e,t)=>{if(void 0===e&&_("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 Y({isOptional:"optional",members:this.members})}}function Z(e){return!!e.isConvexValidator}function ee(e){return Z(e)?e:et.object(e)}let et={id:e=>new N({isOptional:"required",tableName:e}),null:()=>new J({isOptional:"required"}),number:()=>new F({isOptional:"required"}),float64:()=>new F({isOptional:"required"}),bigint:()=>new B({isOptional:"required"}),int64:()=>new B({isOptional:"required"}),boolean:()=>new U({isOptional:"required"}),string:()=>new W({isOptional:"required"}),bytes:()=>new D({isOptional:"required"}),literal:e=>new z({isOptional:"required",value:e}),array:e=>new G({isOptional:"required",element:e}),object:e=>new H({isOptional:"required",fields:e}),record:(e,t)=>new X({isOptional:"required",key:e,value:t}),union:(...e)=>new Y({isOptional:"required",members:e}),any:()=>new K({isOptional:"required"}),optional:e=>e.asOptional(),nullable:e=>et.union(e,et.null())};e.s(["asObjectValidator",()=>ee,"isValidator",()=>Z,"v",0,et],351321);var es=e.i(89718),ei=Object.defineProperty,en=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ei(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};let er=Symbol.for("ConvexError");class eo extends(i=Error,s=er,i){constructor(e){super("string"==typeof e?e:
1x(e)),en(this,"name","ConvexError"),en(this,"data"),en(this,s,!0),this.data=e}}e.s(["ConvexError",()=>eo],185855);let ea=()=>Array.from({length:4},()=>0);ea(),ea(),e.s([],922991),e.s(["ConvexProvider",()=>tl,"ConvexReactClient",()=>ta,"useConvex",()=>th,"useQuery",()=>tc],230588);let eu="1.35.1";e.s(["version",0,eu],84674);var eh=Object.defineProperty,el=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eh(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function ec(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class ed{constructor(e){el(this,"_onLogLineFuncs"),el(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 ef(e){let t=new ed(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 eg(e,t,s,i,n){let r=ec(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 ey(e,t,s){let i=ec(e);return`[CONVEX ${i}(${t})] ${s.errorMessage}
2  Called by client`}function ep(e,t){return t.data=e.errorData,t}function em(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 ev(e,t){return JSON.stringify({udfPath:em(e),args:$(t)})}function eb(e,t,s){let{initialNumItems:i,id:n}=s;return JSON.stringify({type:"paginated",udfPath:em(e),args:$(t),options:$({initialNumItems:i,id:n})})}var ew=Object.defineProperty,ek=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ew(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eS{constructor(){ek(this,"nextQueryId"),ek(this,"querySetVersion"),ek(this,"querySet"),ek(this,"queryIdToToken"),ek(this,"identityVersion"),ek(this,"auth"),ek(this,"outstandingQueriesOlderThanRestart"),ek(this,"outstandingAuthOlderThanRestart"),ek(this,"paused"),ek(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=em(e),r=ev(n,t),o=this.querySet.get(r);if(void 0!==o)return o.numSubscribers+=1,{queryToken:r,modification:null,unsubscribe:()=>this.removeSubscriber(r)};{let e=this.nextQueryId++;this.querySet.set(r,{id:e,canonicalizedUdfPath:n,args:t,numSubscribers:1,journal:s,componentPath:i}),this.queryIdToToken.set(e,r);let o=this.querySetVersion,a=this.querySetVersion+1,u={type:"Add",queryId:e,udfPath:n,args:[$(t)],journal:s,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(e,u):this.querySetVersion=a,{queryToken:r,modification:{type:"ModifyQuerySet",baseVersion:o,newVersion:a,modifications:[u]},unsubscribe:()=>this.removeSubscriber(r)}}}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=ev(em(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(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let s={type:"Add",queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[$(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(s),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let s={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[t,s]}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 eR=Object.defineProperty,eC=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eR(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eT{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,eC(this,"inflightRequests"),eC(this,"requestsOlderThanRestart"),eC(this,"inflightMutationsCount",0),eC(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",r=i.message.udfPath;
2for(let t of e.logLines)eg(this.logger,"info",n,r,t);let o=i.status;if(e.success)t={success:!0,logLines:e.logLines,value:O(e.result)},s=()=>o.onResult(t);else{let i=e.result,{errorData:a}=e;eg(this.logger,"error",n,r,i),t={success:!1,errorMessage:i,errorData:void 0!==a?O(a):void 0,logLines:e.logLines},s=()=>o.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 eq=Symbol.for("functionName"),eA=Symbol.for("toReferencePath");function eO(e,t){e[eA]=t}function ex(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[eq])t={name:e[eq]};else{let s=e[eA]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}function eM(e){let t=ex(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[eq];if(!s)throw Error(`${e} is not a functionReference`);return s}function eQ(e){return{[eq]:e}}e.s(["getFunctionAddress",()=>ex,"setReferencePath",()=>eO,"toReferencePath",0,eA],953584);let eE=function e(t=[]){return new Proxy({},{get(s,i){if("string"==typeof i)return e([...t,i]);if(i===eq){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,eE,"getFunctionName",()=>eM,"makeFunctionReference",()=>eQ],558380);var e$=Object.defineProperty,eI=(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 eP{constructor(e){eI(this,"queryResults"),eI(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=p(t[0]),i=eM(e),n=this.queryResults.get(ev(i,s));if(void 0!==n)return eP.queryValue(n.result)}getAllQueries(e){let t=[],s=eM(e);for(let e of this.queryResults.values())e.udfPath===em(s)&&t.push({args:e.args,value:eP.queryValue(e.result)});return t}setQuery(e,t,s){let i=p(t),n=eM(e),r=ev(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 eV{constructor(){eI(this,"queryResults"),eI(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 eP(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 eP(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 ep(s,new eo(ey("query",t.udfPath,s)));throw Error(ey("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 eL=Object.defineProperty,e_=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eL(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class ej{constructor(e,t){e_(this,"low"),e_(this,"high"),e_(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 ej(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?eN:e>=eB?eU:new ej(e%eF|0,e/eF|0)}toString(){return(BigInt(this.high)*BigInt(eF)+BigInt(this.low)).toString()}equals(e){return ej.isLong(e)||(e=ej.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(ej.isLong(e)||(e=ej.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?ej.fromNumber(e):new ej(e.low,e.high)}}let eN=new ej(0,0),eF=0x100000000,eB=0xffffffffffffffff,eU=new ej(-1,-1);var eD=Object.defineProperty,eW=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eD(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eJ{constructor(e,t){eW(this,"version"),eW(this,"remoteQuerySet"),eW(this,"queryPath"),eW(this,"logger"),this.version={querySet:0,ts:ej.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)eg(this.logger,"info","query",e,s);let s=O(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)eg(this.logger,"info","query",e,s);let{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?O(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}}function eK(e){let t=es.toByteArray(e);return ej.fromBytesLE(Array.from(t))}function eH(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:eK(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:eK(e.startVersion.ts)},endVersion:{...e.endVersion,ts:eK(e.endVersion.ts)}}}}var ez=Object.defineProperty,eG=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ez(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function eX(){return(void 0===t&&(t=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(t+performance.now())}function eY(){return`t=${Math.round((eX()-t)/100)/10}s`}let eZ={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 e0{constructor(e,t,s,i,n,r){this.markConnectionStateDirty=n,this.debug=r,eG(this,"socket"),eG(this,"connectionCount"),eG(this,"_hasEverConnected",!1),eG(this,"lastCloseReason"),eG(this,"transitionChunkBuffer",null),eG(this,"defaultInitialBackoff"),eG(this,"maxBackoff"),eG(this,"retries"),eG(this,"serverInactivityThreshold"),eG(this,"reconnectDueToServerInactivityTimeout"),eG(this,"scheduledReconnect",null),eG(this,"networkOnlineHandler",null),eG(this,"pendingNetworkRecoveryInfo",null),eG(this,"uri"),eG(this,"onOpen"),eG(this,"onResume"),eG(this,"onMessage"),eG(this,"webSocketConstructor"),eG(this,"logger"),eG(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=eH(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:eX()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",eY(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",eY())),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=eH(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(eZ))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()),es.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=eX(),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=eX()-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:eX()})):"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:eZ[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=eX()-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 e1 extends Error{}function e3(e,t){let s;if("string"!=typeof e)throw new e1("Invalid token specified: must be a string");t||(t={});let i=+(!0!==t.header),n=e.split(".")[i];if("string"!=typeof n)throw new e1(`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 e1(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new e1(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}e1.prototype.name="InvalidTokenError";var e2=Object.defineProperty,e5=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?e2(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class e8{constructor(e,t,s){e5(this,"authState",{state:"noAuth"}),e5(this,"configVersion",0),e5(this,"syncState"),e5(this,"authenticate"),e5(this,"stopSocket"),e5(this,"tryRestartSocket"),e5(this,"pauseSocket"),e5(this,"resumeSocket"),e5(this,"clearAuth"),e5(this,"logger"),e5(this,"refreshTokenLeewaySeconds"),e5(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(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),"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.authState=e}decodeToken(e){try{return e3(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 e6=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function e4(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var e7=Object.defineProperty,e9=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?e7(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class te{constructor(e,t,s){let i;if(e9(this,"address"),e9(this,"state"),e9(this,"requestManager"),e9(this,"webSocketManager"),e9(this,"authenticationManager"),e9(this,"remoteQuerySet"),e9(this,"optimisticQueryResults"),e9(this,"_transitionHandlerCounter",0),e9(this,"_nextRequestId"),e9(this,"_onTransitionFns",new Map),e9(this,"_sessionId"),e9(this,"firstMessageReceived",!1),e9(this,"debug"),e9(this,"logger"),e9(this,"maxObservedTimestamp"),e9(this,"connectionStateSubscribers",new Map),e9(this,"nextConnectionStateSubscriberId",0),e9(this,"_lastPublishedConnectionState"),e9(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)})}),e9(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&&m(e);const n=(s={...s}).authRefreshTokenLeewaySeconds??10;let r=s.webSocketConstructor;if(!r&&"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");r=r||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=!1===s.logger?function(e){return new ed(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:ef({verbose:s.verbose??!1});const o=e.search("://");if(-1===o)throw Error("Provided address was not an absolute URL.");const a=e.substring(o+3),u=e.substring(0,o);if("http"===u)i="ws";else if("https"===u)i="wss";else throw Error(`Unknown parent protocol ${u}`);const h=`${i}://${a}/api/${eu}/sync`;this.state=new eS,this.remoteQuerySet=new eJ(e=>this.state.queryPath(e),this.logger),this.requestManager=new eT(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new e8(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:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:n}),this.optimisticQueryResults=new eV,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:c}=s;if("u"<typeof window||void 0===window.addEventListener){if(!0===c)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==c&&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 e0(h,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new eJ(e=>this.state.queryPath(e),this.logger);let[t,s]=this.state.restart();for(let e of(s&&this.webSocketManager.sendMessage(s),this.webSocketManager.sendMessage(t),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},r,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&l()}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?e3(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=p(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=ev(e,p(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=ev(e,p(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=ev(e,p(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 ep(i,new eo(ey("mutation",e,i)));throw Error(ey("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=p(t);this.tryReportLongDisconnect();let r=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,r).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 o={type:"Mutation",requestId:r,udfPath:e,componentPath:i,args:[$(n)]},a=this.webSocketManager.sendMessage(o);return{requestId:r,mutationPromise:this.requestManager.request(o,a)}}async action(e,t){let s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw ep(s,new eo(ey("action",e,s)));throw Error(ey("action",e,s))}return s.value}async actionInternal(e,t,s){let i=p(t),n=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let r={type:"Action",requestId:n,udfPath:e,componentPath:s,args:[$(i)]},o=this.webSocketManager.sendMessage(r);return this.requestManager.request(r,o)}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 e6){let i=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...i)}return t.map(e4)}(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-${eu}`},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 tt(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 ts=Object.defineProperty,ti=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ts(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class tn{constructor(e,t){this.client=e,this.onTransition=t,ti(this,"paginatedQuerySet",new Map),ti(this,"lastTransitionTs"),this.lastTransitionTs=ej.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){let i=em(e),n=eb(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=eb(em(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=tt(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=tt(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=tt(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 tr=Object.defineProperty,to=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?tr(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};if(void 0===n.default)throw Error("Required dependency 'react' not found");class ta{constructor(e,t){if(to(this,"address"),to(this,"cachedSync"),to(this,"cachedPaginatedQueryClient"),to(this,"listeners"),to(this,"options"),to(this,"closed",!1),to(this,"_logger"),to(this,"adminAuth"),to(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 ed(e)}({verbose:t?.verbose??!1}):t?.logger!==!0&&t?.logger?t.logger:ef({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 te(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new tn(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=eM(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:()=>{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=eM(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=eM(e);return this.sync.mutation(n,s,i)}action(e,...t){let s=eM(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)=>
2{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 tu=n.default.createContext(void 0);function th(){return(0,n.useContext)(tu)}let tl=({client:e,children:t})=>n.default.createElement(tu.Provider,{value:e},t);function tc(e,...t){let s="skip"===t[0],i="skip"===t[0]?{}:p(t[0]),r="string"==typeof e?eQ(e):e,o=eM(r),a=function(e){let t=th();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,n.useState)(()=>new tg(t));return s.createWatch!==t&&s.setCreateWatch(t),(0,n.useEffect)(()=>()=>s.destroy(),[s]),function({getCurrentValue:e,subscribe:t}){let[s,i]=(0,n.useState)(()=>({getCurrentValue:e,subscribe:t,value:e()})),r=s.value;return(s.getCurrentValue!==e||s.subscribe!==t)&&(r=e(),i({getCurrentValue:e,subscribe:t,value:r})),(0,n.useEffect)(()=>{let s=!1,n=()=>{s||i(s=>{if(s.getCurrentValue!==e||s.subscribe!==t)return s;let i=e();return s.value===i?s:{...s,value:i}})},r=t(n);return n(),()=>{s=!0,r()}},[e,t]),r}((0,n.useMemo)(()=>({getCurrentValue:()=>s.getLocalResults(e),subscribe:t=>(s.setQueries(e),s.subscribe(t))}),[s,e]))}(e,(0,n.useMemo)(()=>(e,s,{journal:i,paginationOptions:n})=>n?t.watchPaginatedQuery(e,s,n):t.watchQuery(e,s,i?{journal:i}:{}),[t]))}((0,n.useMemo)(()=>s?{}:{query:{query:r,args:i}},[JSON.stringify($(i)),o,s])).query;if(a instanceof Error)throw a;return a}var td=Object.defineProperty,tf=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?td(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class tg{constructor(e){tf(this,"createWatch"),tf(this,"queries"),tf(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(eM(s),void 0===this.queries[t])this.addQuery(t,s,i,n?{paginationOptions:n}:{});else{let e=this.queries[t];(eM(s)!==eM(e.query)||JSON.stringify($(i))!==JSON.stringify($(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)}subscribe(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;eM(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()}}Symbol("includePageKeys"),Symbol("page");let ty=(0,n.createContext)(void 0);function tp(){let e=(0,n.useContext)(ty);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 tm({children:e,client:t,useAuth:s}){let{isLoading:i,isAuthenticated:r,fetchAccessToken:o}
2=s(),[a,u]=(0,n.useState)(null);return i&&null!==a&&u(null),i||r||!1===a||u(!1),n.default.createElement(ty.Provider,{value:{isLoading:null===a,isAuthenticated:r&&(a??!1)}},n.default.createElement(tv,{authProviderAuthenticated:r,fetchAccessToken:o,authProviderLoading:i,client:t,setIsConvexAuthenticated:u}),n.default.createElement(tl,{client:t},e),n.default.createElement(tb,{authProviderAuthenticated:r,fetchAccessToken:o,authProviderLoading:i,client:t,setIsConvexAuthenticated:u}))}function tv({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:i,setIsConvexAuthenticated:r}){return(0,n.useEffect)(()=>{let s=!0;if(e)return i.setAuth(t,e=>{s&&r(()=>e)}),()=>{s=!1,r(e=>!e&&null)}},[e,t,s,i,r]),null}function tb({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:i,setIsConvexAuthenticated:r}){return(0,n.useEffect)(()=>{if(e)return()=>{i.clearAuth(),r(()=>null)}},[e,t,s,i,r]),null}function tw({children:e}){let{isLoading:t,isAuthenticated:s}=tp();return t||!s?null:n.default.createElement(n.default.Fragment,null,e)}e.s(["ConvexProviderWithAuth",()=>tm,"useConvexAuth",()=>tp],338419),e.s(["Authenticated",()=>tw],423395),e.s([],528972)}]);

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.