1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,15697,e=>{"use strict";let t,s;for(var n,i,r=e.i(43476),o=e.i(71645),a=[],u=[],l=Uint8Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,d=h.length;c<d;++c)a[c]=h[c],u[h.charCodeAt(c)]=c;function f(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 n=s===t?0:4-s%4;return[s,n]}function g(e){var t,s,n=f(e),i=n[0],r=n[1],o=new l((i+r)*3/4-r),a=0,h=r>0?i-4:i;for(s=0;s<h;s+=4)t=u[e.charCodeAt(s)]<<18|u[e.charCodeAt(s+1)]<<12|u[e.charCodeAt(s+2)]<<6|u[e.charCodeAt(s+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===r&&(t=u[e.charCodeAt(s)]<<2|u[e.charCodeAt(s+1)]>>4,o[a++]=255&t),1===r&&(t=u[e.charCodeAt(s)]<<10|u[e.charCodeAt(s+1)]<<4|u[e.charCodeAt(s+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o}function y(e){for(var t,s=e.length,n=s%3,i=[],r=0,o=s-n;r<o;r+=16383)i.push(function(e,t,s){for(var n,i=[],r=t;r<s;r+=3)n=(e[r]<<16&0xff0000)+(e[r+1]<<8&65280)+(255&e[r+2]),i.push(a[n>>18&63]+a[n>>12&63]+a[n>>6&63]+a[63&n]);return i.join("")}(e,r,r+16383>o?o:r+16383));return 1===n?i.push(a[(t=e[s-1])>>2]+a[t<<4&63]+"=="):2===n&&i.push(a[(t=(e[s-2]<<8)+e[s-1])>>10]+a[t>>4&63]+a[t<<2&63]+"="),i.join("")}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),n=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&n}u[45]=62,u[95]=63,e.s(["byteLength",0,function(e){var t=f(e),s=t[0],n=t[1];return(s+n)*3/4-n},"fromByteArray",0,y,"fromByteArrayUrlSafeNoPadding",0,function(e){return y(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},"toByteArray",0,g],95543);let b=BigInt("-9223372036854775808"),w=BigInt("9223372036854775807"),k=BigInt("0"),S=BigInt("8"),x=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),y(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)),n=0;for(let i of t.match(/.{2}/g).reverse())s.set([parseInt(i,16)],n++),e>>=S;return y(s)},R=DataView.prototype.getBigInt64?function(e){let t=g(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=g(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=k,n=k;for(let e of t)s+=BigInt(e)*x**n,n++;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 q(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>q(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 g(e.$bytes).buffer}
1if("$integer"===s){if("string"!=typeof e.$integer)throw Error(`Malformed $integer field on ${e}`);return R(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw Error(`Malformed $float field on ${e}`);let t=g(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,n]of Object.entries(e))A(t),s[t]=q(n);return s}function O(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,n=t.codePointAt(s-1);return void 0!==n&&n>65535&&(s-=1),t.substring(0,s)+e}return t}function I(e,t,s,n){if(void 0===e){let e=s&&` (present at path ${s} in original object ${O(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:y(new Uint8Array(t))}}if("boolean"==typeof e||"string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:y(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,n)=>I(e,t,s+`[${n}]`,!1));if(e instanceof Set)throw Error(E(s,"Set",[...e],t));if(e instanceof Map)throw Error(E(s,"Map",[...e],t));if(!v(e)){let n=e?.constructor?.name;throw Error(E(s,n?`${n} `:"",e,t))}let i={},r=Object.entries(e);for(let[e,o]of(r.sort(([e,t],[s,n])=>e===s?0:e<s?-1:1),r))void 0!==o?(A(e),i[e]=I(o,t,s+`.${e}`,!1)):n&&(A(e),i[e]=$(o,t,s+`.${e}`));return i}function E(e,t,s,n){return e?`${t}${O(s)} is not a supported Convex type (present at path ${e} in original object ${O(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${O(s)} is not a supported Convex type.`}function $(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw Error(`Programming error. Current value is ${O(e)} but original value is undefined`);return I(e,t,s,!1)}function M(e){return I(e,e,"",!1)}function j(e){return $(e,e,"")}var _=Object.defineProperty,Q=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?_(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};function P(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 N{constructor({isOptional:e}){Q(this,"type"),Q(this,"fieldPaths"),Q(this,"isOptional"),Q(this,"isConvexValidator"),this.isOptional=e,this.isConvexValidator=!0}}class L extends N{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 L({isOptional:"optional",tableName:this.tableName})}}class V extends N{constructor(){super(...arguments),Q(this,"kind","float64")}get json(){return{type:"number"}}asOptional(){return new V({isOptional:"optional"})}}class F extends N{constructor(){super(...arguments),Q(this,"kind","int64")}get json(){return{type:"bigint"}}asOptional(){return new F({isOptional:"optional"})}}class U extends N{constructor(){super(...arguments),Q(this,"kind","boolean")}get json(){return{type:this.kind}}asOptional(){return new U({isOptional:"optional"})}}class D extends N{constructor(){super(...arguments),Q(this,"kind","bytes")}get json(){return{type:this.kind}}asOptional(){return new D({isOptional:"optional"})}}class B extends N{constructor(){super(...arguments),Q(this,"kind","string")}get json(){return{type:this.kind}}asOptional(){return new B({isOptional:"optional"})}}class W extends N{constructor(){super(...arguments),Q(this,"kind","null")}get json(){return{type:this.kind}}asOptional(){return new W({isOptional:"optional"})}}class K extends N{constructor(){super(...arguments),Q(this,"kind","any")}get json(){return{type:this.kind}}asOptional(){return new K({isOptional:"optional"})}}class J extends N{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&&P("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 J({isOptional:"optional",fields:this.fields})}omit(...e){let t={...this.fields};for(let s of e)delete t[s];return new J({isOptional:this.isOptional,fields:t})}pick(...e){let t={};for(let s of e)t[s]=this.fields[s];return new J({isOptional:this.isOptional,fields:t})}partial(){let e={};for(let[t,s]of globalThis.Object.entries(this.fields))e[t]=s.asOptional();return new J({isOptional:this.isOptional,fields:e})}extend(e){return new J({isOptional:this.isOptional,fields:{...this.fields,...e}})}}class z extends N{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:M(this.value)}}asOptional(){return new z({isOptional:"optional",value:this.value})}}class H extends N{constructor({isOptional:e,element:t}){super({isOptional:e}),Q(this,"element"),Q(this,"kind","array"),void 0===t&&P("v.array()"),this.element=t}get json(){return{type:this.kind,value:this.element.json}}asOptional(){return new H({isOptional:"optional",element:this.element})}}class G extends N{constructor({isOptional:e,key:t,value:s}){if(super({isOptional:e}),Q(this,"key"),Q(this,"value"),Q(this,"kind","record"),void 0===t&&P("v.record()","key"),void 0===s&&P("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 G({isOptional:"optional",key:this.key,value:this.value})}}class X extends N{constructor({isOptional:e,members:t}){super({isOptional:e}),Q(this,"members"),Q(this,"kind","union"),t.forEach((e,t)=>{if(void 0===e&&P("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 X({isOptional:"optional",members:this.members})}}let Y={id:e=>new L({isOptional:"required",tableName:e}),null:()=>new W({isOptional:"required"}),number:()=>new V({isOptional:"required"}),float64:()=>new V({isOptional:"required"}),bigint:()=>new F({isOptional:"required"}),int64:()=>new F({isOptional:"required"}),boolean:()=>new U({isOptional:"required"}),string:()=>new B({isOptional:"required"}),bytes:()=>new D({isOptional:"required"}),literal:e=>new z({isOptional:"required",value:e}),array:e=>new H({isOptional:"required",element:e}),object:e=>new J({isOptional:"required",fields:e}),record:(e,t)=>new G({isOptional:"required",key:e,value:t}),union:(...e)=>new X({isOptional:"required",members:e}),any:()=>new K({isOptional:"required"}),optional:e=>e.asOptional(),nullable:e=>Y.union(e,Y.null())};var Z=e.i(95543),ee=Object.defineProperty,et=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?ee(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};let es=Symbol.for("ConvexError");class en extends(i=Error,n=es,i){constructor(e){super("string"==typeof e?e:O(e)),et(this,"name","ConvexError"),et(this,"data"),et(this,n,!0),this.data=e}}let ei=()=>Array.from({length:4},()=>0);ei(),ei();let er="1.37.0";var eo=Object.defineProperty,ea=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eo(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};function eu(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}
1class el{constructor(e){ea(this,"_onLogLineFuncs"),ea(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 eh(e){let t=new el(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 ec(e,t,s,n,i){let r=eu(s);if("object"==typeof i&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),"info"===t){let t=i.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${n})] Could not parse console.log`);let s=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${r}(${n})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${r}(${n})] ${i}`)}function ed(e,t,s){let n=eu(e);return`[CONVEX ${n}(${t})] ${s.errorMessage} 2 Called by client`}function ef(e,t){return t.data=e.errorData,t}function eg(e){let t,s,n=e.split(":");return 1===n.length?(t=n[0],s="default"):(t=n.slice(0,n.length-1).join(":"),s=n[n.length-1]),t.endsWith(".js")&&(t=t.
2slice(0,-3)),`${t}:${s}`}function ey(e,t){return JSON.stringify({udfPath:eg(e),args:M(t)})}function ep(e,t,s){let{initialNumItems:n,id:i}=s;return JSON.stringify({type:"paginated",udfPath:eg(e),args:M(t),options:M({initialNumItems:n,id:i})})}var em=Object.defineProperty,ev=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?em(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eb{constructor(){ev(this,"nextQueryId"),ev(this,"querySetVersion"),ev(this,"querySet"),ev(this,"queryIdToToken"),ev(this,"identityVersion"),ev(this,"auth"),ev(this,"outstandingQueriesOlderThanRestart"),ev(this,"outstandingAuthOlderThanRestart"),ev(this,"paused"),ev(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,n){let i=eg(e),r=ey(i,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:i,args:t,numSubscribers:1,journal:s,componentPath:n}),this.queryIdToToken.set(e,r);let o=this.querySetVersion,a=this.querySetVersion+1,u={type:"Add",queryId:e,udfPath:i,args:[M(t)],journal:s,componentPath:n};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=ey(eg(e),t),n=this.querySet.get(s);return void 0!==n?n.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 n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...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:[M(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,n=this.querySetVersion+1,i={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=n,{type:"ModifyQuerySet",baseVersion:s,newVersion:n,modifications:[i]}}}}var ew=Object.defineProperty,ek=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?ew(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eS{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,ek(this,"inflightRequests"),ek(this,"requestsOlderThanRestart"),ek(this,"inflightMutationsCount",0),ek(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,n=this.inflightRequests.get(e.requestId);if(void 0===n||"Completed"===n.status.status)return null;let i="Mutation"===n.message.type?"mutation":"action",r=n.message.udfPath;for(let t of e.logLines)ec(this.logger,"info",i,r,t);let o=n.status;if(e.success)t={success:!0,logLines:e.logLines,value:q(e.result)},s=()=>o.onResult(t);else{let n=e.result,{errorData:a}=e;ec(this.logger,"error",i,r,n),t={success:!1,errorMessage:n,errorData:void 0!==a?q(a):void 0,logLines:e.logLines},s=()=>o.onResult(t)}return"ActionResponse"!==e.type&&e.success?(n.status={status:"Completed",result:t,ts:e.ts,onRes
2olve:s},null):(s(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===n.message.type?this.inflightActionsCount--:"Mutation"===n.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:t})}removeCompleted(e){let t=new Map;for(let[s,n]of this.inflightRequests.entries()){let i=n.status;"Completed"===i.status&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(s,i.result),"Mutation"===n.message.type?this.inflightMutationsCount--:"Action"===n.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 ex=Symbol.for("functionName"),eC=Symbol.for("toReferencePath");function eT(e){let t=function(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[ex])t={name:e[ex]};else{let s=e[eC]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}(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[ex];if(!s)throw Error(`${e} is not a functionReference`);return s}let eR=function e(t=[]){return new Proxy({},{get(s,n){if("string"==typeof n)return e([...t,n]);if(n===ex){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 n===Symbol.toStringTag?"FunctionReference":void 0}})}();var eA=Object.defineProperty,eq=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eA(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eO{constructor(e){eq(this,"queryResults"),eq(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=p(t[0]),n=eT(e),i=this.queryResults.get(ey(n,s));if(void 0!==i)return eO.queryValue(i.result)}getAllQueries(e){let t=[],s=eT(e);for(let e of this.queryResults.values())e.udfPath===eg(s)&&t.push({args:e.args,value:eO.queryValue(e.result)});return t}setQuery(e,t,s){let n=p(t),i=eT(e),r=ey(i,n);this.queryResults.set(r,{udfPath:i,args:n,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 eI{constructor(){eq(this,"queryResults"),eq(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 n=new eO(this.queryResults);for(let e of this.optimisticUpdates)e.update(n);let i=[];for(let[e,t]of this.queryResults){let n=s.get(e);(void 0===n||n.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new eO(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 ef(s,new en(ed("query",t.udfPath,s)));throw Error(ed("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 eE=Object.defineProperty,e$=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eE(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eM{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 eM(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?ej:e>=eQ?eP:new eM(e%e_|0,e/e_|0)}toString(){return(BigInt(this.high)*BigInt(e_)+BigInt(this.low)).toString()}equals(e){return eM.isLong(e)||(e=eM.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(eM.isLong(e)||(e=eM.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?eM.fromNumber(e):new eM(e.low,e.high)}}let ej=new eM(0,0),e_=0x100000000,eQ=0xffffffffffffffff,eP=new eM(-1,-1);var eN=Object.defineProperty,eL=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eN(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eV{constructor(e,t){eL(this,"version"),eL(this,"remoteQuerySet"),eL(this,"queryPath"),eL(this,"logger"),this.version={querySet:0,ts:eM.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)ec(this.logger,"info","query",e,s);let s=q(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)ec(this.logger,"info","query",e,s);let{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?q(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 eF(e){let t=Z.toByteArray(e);return eM.fromBytesLE(Array.from(t))}function eU(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:eF(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:eF(e.startVersion.ts)},endVersion:{...e.endVersion,ts:eF(e.endVersion.ts)}}}}var eD=Object.defineProperty,eB=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eD(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};function eW(){return(void 0===t&&(t=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(t+performance.now())}function eK(){return`t=${Math.round((eW()-t)/100)/10}s`}let eJ={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 ez{constructor(e,t,s,n,i,r){this.markConnectionStateDirty=i,this.debug=r,eB(this,"socket"),eB(this,"connectionCount"),eB(this,"_hasEverConnected",!1),eB(this,"lastCloseReason"),eB(this,"transitionChunkBuffer",null),eB(this,"defaultInitialBackoff"),eB(this,"maxBackoff"),eB(this,"retries"),eB(this,"serverInactivityThreshold"),eB(this,"reconnectDueToServerInactivityTimeout"),eB(this,"scheduledReconnect",null),eB(this,"networkOnlineHandler",null),eB(this,"pendingNetworkRecoveryInfo",null),eB(this,"uri"),eB(this,"onOpen"),eB(this,"onResume"),eB(this,"onMessage"),eB(this,"webSocketConstructor"),eB(this,"logger"),eB(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=n,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=eU(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:eW()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",eK(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",eK())),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=eU(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(eJ))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()),Z.fromByteArray(t))}}}(e)),n=!1;try{this.socket.ws.send(s),n=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${n?"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=eW(),n=setTimeout(()=>{this.scheduledReconnect?.timeout===n&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:n,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=eW()-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._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:eW()})):"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:eJ[e].timeout)*Math.pow(2,this.retries);this.retries+=1;let s=Math.min(t,this.maxBackoff),n=s*(Math.random()-.5);return s+n}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;let s=eW()-e.clientClockSkew-e.serverTs/1e6,n=`${Math.round(s)}ms`,i=`${Math.round(t/1e4)/100}MB`,r=t/(s/1e3),o=`${Math.round(r/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${n} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}
2) which will take a long time to download on slower connections`):s>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${n})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:s,messageLength:t}})}}class eH extends Error{}function eG(e,t){let s;if("string"!=typeof e)throw new eH("Invalid token specified: must be a string");t||(t={});let n=+(!0!==t.header),i=e.split(".")[n];if("string"!=typeof i)throw new eH(`Invalid token specified: missing part #${n+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)}}(i)}catch(e){throw new eH(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new eH(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}eH.prototype.name="InvalidTokenError";var eX=Object.defineProperty,eY=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?eX(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class eZ{constructor(e,t,s){eY(this,"authState",{state:"noAuth"}),eY(this,"configVersion",0),eY(this,"syncState"),eY(this,"authenticate"),eY(this,"stopSocket"),eY(this,"tryRestartSocket"),eY(this,"pauseSocket"),eY(this,"resumeSocket"),eY(this,"clearAuth"),eY(this,"logger"),eY(this,"refreshTokenLeewaySeconds"),eY(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:n}=t;if(!s||!n)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let i=n-s;if(i<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");let r=Math.min(1728e6,(i-this.refreshTokenLeewaySeconds)*1e3);r<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${i}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 n=await e(t);
2return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:n}}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 eG(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 e0=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function e1(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var e3=Object.defineProperty,e2=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?e3(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class e6{constructor(e,t,s){let n;if(e2(this,"address"),e2(this,"state"),e2(this,"requestManager"),e2(this,"webSocketManager"),e2(this,"authenticationManager"),e2(this,"remoteQuerySet"),e2(this,"optimisticQueryResults"),e2(this,"_transitionHandlerCounter",0),e2(this,"_nextRequestId"),e2(this,"_onTransitionFns",new Map),e2(this,"_sessionId"),e2(this,"firstMessageReceived",!1),e2(this,"debug"),e2(this,"logger"),e2(this,"maxObservedTimestamp"),e2(this,"connectionStateSubscribers",new Map),e2(this,"nextConnectionStateSubscriberId",0),e2(this,"_lastPublishedConnectionState"),e2(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)})}),e2(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 i=(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 el(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:eh({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)n="ws";else if("https"===u)n="wss";else throw Error(`Unknown parent protocol ${u}`);const l=`${n}://${a}/api/${er}/sync`;this.state=new eb,this.remoteQuerySet=new eV(e=>this.state.queryPath(e),this.logger),this.requestManager=new eS(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new eZ(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:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new eI,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 ez(l,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new eV(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 n,i=(t=this.logger,s=e.error,n=`[CONVEX FATAL ERROR] ${s}`,t.error(n),Error(n));throw this.webSocketManager.terminate(),i}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},r,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&h()}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,n]of t){let t=this.state.queryToken(e);if(null!==t){let i={result:n,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,i)}}let n=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:n.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?eG(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 n=p(t),{modification:i,queryToken:r,unsubscribe:o}=this.state.subscribe(e,n,s?.journal,s?.componentPath);return null!==i&&this.webSocketManager.sendMessage(i),{queryToken:r,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let s=ey(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=ey(e,p(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=ey(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 n=await this.mutationInternal(e,t,s);if(!n.success){if(void 0!==n.errorData)throw ef(n,new en(ed("mutation",e,n)));throw Error(ed("mutation",e,n))}return n.value}async mutationInternal(e,t,s,n){let{mutationPromise:i}=this.enqueueMutation(e,t,s,n);return i}enqueueMutation(e,t,s,n){let i=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,i)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:n,args:[M(i)]},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 ef(s,new en(ed("action",e,s)));throw Error(ed("action",e,s))}return s.value}async actionInternal(e,t,s){let n=p(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let r={type:"Action",requestId:i,udfPath:e,componentPath:s,args:[M(n)]},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 e0){let n=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...n)}return t.map(e1)}(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-${er}`},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 e5(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 e4=Object.defineProperty,e8=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?e4(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class e7{constructor(e,t){this.client=e,this.onTransition=t,e8(this,"paginatedQuerySet",new Map),e8(this,"lastTransitionTs"),this.lastTransitionTs=eM.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){let n=eg(e),i=ep(n,t,s),r=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?o.numSubscribers+=1:(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:n,args:t,numSubscribers:1,options:{initialNumItems:s.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:s.id}),this.addPageToPaginatedQuery(i,null,s.initialNumItems)),{paginatedQueryToken:i,unsubscribe:r}}localQueryResult(e,t,s){let n=ep(eg(e),t,s);return this.localQueryResultByToken(n)}localQueryResultByToken(e){let t,s=this.paginatedQuerySet.get(e);if(!s)return;let n=this.activePageQueryTokens(s);if(0===n.length)return{results:[],status:"LoadingFirstPage",loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let i=[],r=!1,o=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(void 0===t){r=!0,o=!1;continue}let s=e5(t);i=i.concat(s.page),o=!!s.isDone}return t=r?0===i.length?"LoadingFirstPage":"LoadingMore":o?"Exhausted":"CanLoadMore",{results:i,status:t,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),s=this.queriesContainingTokens(t),n=[];s.length>0&&(this.processPaginatedQuerySplits(s,e=>this.client.localQueryResultByToken(e)),n=s.map(e=>({token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:n};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let s=this.queryTokenForLastPageOfPaginatedQuery(e),n=this.client.localQueryResultByToken(s);if(!n)return!1;let i=e5(n);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.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,n]of this.paginatedQuerySet)for(let i of this.allQueryTokens(n))if(s.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let s of e){let e=this.mustGetPaginatedQuery(s),{ongoingSplits:n,pageKeyToQuery:i,pageKeys:r}=e;for(let[s,[r,o]]of n)void 0!==t(i.get(r).queryToken)&&void 0!==t(i.get(o).queryToken)&&this.completePaginatedQuerySplit(e,s,r,o);for(let s of r){if(n.has(s))continue;let r=t(i.get(s).queryToken);if(!r)continue;let o=e5(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,n){let i=e.nextPageKey++,r=e.nextPageKey++,o={cursor:n,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...o,cursor:null,endCursor:s}});e.pageKeyToQuery.set(i,a);let u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...o,cursor:s,endCursor:n}});e.pageKeyToQuery.set(r,u),e.ongoingSplits.set(t,[i,r])}addPageToPaginatedQuery(e,t,s){let n=this.mustGetPaginatedQuery(e),i=n.nextPageKey++,r={cursor:t,numItems:s,id:n.id},o={...n.args,paginationOpts:r},a=this.client.subscribe(n.canonicalizedUdfPath,o);return n.pageKeys.push(i),n.pageKeyToQuery.set(i,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,n){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let r=e.pageKeys.indexOf(t);e.pageKeys.splice(r,1,s,n),e.ongoingSplits.delete(t),i.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 e9=Object.defineProperty,te=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?e9(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class tt{constructor(e,t){if(te(this,"address"),te(this,"auth"),te(this,"adminAuth"),te(this,"encodedTsPromise"),te(this,"debug"),te(this,"fetchOptions"),te(this,"fetch"),te(this,"logger"),te(this,"mutationQueue",[]),te(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&&m(e),this.logger=t?.logger===!1?function(e){return new el(e)}({verbose:!1}):t?.logger!==!0&&t?.logger?t.logger:eh({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=p(t[0]),n=this.getTimestamp();return await this.queryInner(e,s,{timestampPromise:n})}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-${er}`},n=await e(`${this.address}/api/query_ts`,{...this.fetchOptions,method:"POST",headers:t});if(!n.ok)throw Error(await n.text());let{ts:i}=await n.json();return i}async query(e,...t){let s=p(t[0]);return await this.queryInner(e,s,{})}async queryInner(e,t,n){let i=eT(e),r=[M(t)],o={"Content-Type":"application/json","Convex-Client":`npm-${er}`};this.adminAuth?o.Authorization=`Convex ${this.adminAuth}`:this.auth&&(o.Authorization=`Bearer ${this.auth}`);let a=this.fetch||s||fetch,u=n.timestampPromise?await n.timestampPromise:void 0,l=JSON.stringify({path:i,format:"convex_encoded_json",args:r,...u?{ts:u}:{}}),h=u?`${this.address}/api/query_at_ts`:`${this.address}/api/query`,c=await a(h,{...this.fetchOptions,body:l,method:"POST",headers:o});if(!c.ok&&560!==c.status)throw Error(await c.text());let d=await c.json();if(this.debug)for(let e of d.logLines??[])ec(this.logger,"info","query",i,e);switch(d.status){case"success":return q(d.value);case"error":if(void 0!==d.errorData)throw ts(d.errorData,new en(d.errorMessage));throw Error(d.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(d)}`)}}async mutationInner(e,t){let n=eT(e),i=JSON.stringify({path:n,format:"convex_encoded_json",args:[M(t)]}),r={"Content-Type":"application/json","Convex-Client":`npm-${er}`};this.adminAuth?r.Authorization=`Convex ${this.adminAuth}`:this.auth&&(r.Authorization=`Bearer ${this.auth}`);let o=this.fetch||s||fetch,a=await o(`${this.address}/api/mutation`,{...this.fetchOptions,body:i,method:"POST",headers:r});if(!a.ok&&560!==a.status)throw Error(await a.text());let u=await a.json();if(this.debug)for(let e of u.logLines??[])ec(this.logger,"info","mutation",n,e);switch(u.status){case"success":return q(u.value);case"error":if(void 0!==u.errorData)throw ts(u.errorData,new en(u.errorMessage));throw Error(u.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(u)}`)}}async processMutationQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;
2this.mutationQueue.length>0;){let{mutation:e,args:t,resolve:s,reject:n}=this.mutationQueue.shift();try{let n=await this.mutationInner(e,t);s(n)}catch(e){n(e)}}this.isProcessingQueue=!1}}enqueueMutation(e,t){return new Promise((s,n)=>{this.mutationQueue.push({mutation:e,args:t,resolve:s,reject:n}),this.processMutationQueue()})}async mutation(e,...t){let[s,n]=t,i=p(s);return n?.skipQueue?await this.mutationInner(e,i):await this.enqueueMutation(e,i)}async action(e,...t){let n=p(t[0]),i=eT(e),r=JSON.stringify({path:i,format:"convex_encoded_json",args:[M(n)]}),o={"Content-Type":"application/json","Convex-Client":`npm-${er}`};this.adminAuth?o.Authorization=`Convex ${this.adminAuth}`:this.auth&&(o.Authorization=`Bearer ${this.auth}`);let a=this.fetch||s||fetch,u=await a(`${this.address}/api/action`,{...this.fetchOptions,body:r,method:"POST",headers:o});if(!u.ok&&560!==u.status)throw Error(await u.text());let l=await u.json();if(this.debug)for(let e of l.logLines??[])ec(this.logger,"info","action",i,e);switch(l.status){case"success":return q(l.value);case"error":if(void 0!==l.errorData)throw ts(l.errorData,new en(l.errorMessage));throw Error(l.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(l)}`)}}async function(e,t,...n){let i=p(n[0]),r="string"==typeof e?e:eT(e),o=JSON.stringify({componentPath:t,path:r,format:"convex_encoded_json",args:M(i)}),a={"Content-Type":"application/json","Convex-Client":`npm-${er}`};this.adminAuth?a.Authorization=`Convex ${this.adminAuth}`:this.auth&&(a.Authorization=`Bearer ${this.auth}`);let u=this.fetch||s||fetch,l=await u(`${this.address}/api/function`,{...this.fetchOptions,body:o,method:"POST",headers:a});if(!l.ok&&560!==l.status)throw Error(await l.text());let h=await l.json();if(this.debug)for(let e of h.logLines??[])ec(this.logger,"info","any",r,e);switch(h.status){case"success":return q(h.value);case"error":if(void 0!==h.errorData)throw ts(h.errorData,new en(h.errorMessage));throw Error(h.errorMessage);default:throw Error(`Invalid response: ${JSON.stringify(h)}`)}}}function ts(e,t){return t.data=q(e),t}var tn=Object.defineProperty,ti=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tn(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};if(void 0===o.default)throw Error("Required dependency 'react' not found");class tr{constructor(e,t){if(ti(this,"address"),ti(this,"cachedSync"),ti(this,"cachedPaginatedQueryClient"),ti(this,"listeners"),ti(this,"options"),ti(this,"closed",!1),ti(this,"_logger"),ti(this,"adminAuth"),ti(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 el(e)}({verbose:t?.verbose??!1}):t?.logger!==!0&&t?.logger?t.logger:eh({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 e6(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new e7(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,n]=t,i=eT(e);return{onUpdate:e=>{let{queryToken:t,unsubscribe:r}=this.sync.subscribe(i,s,n),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(i,s)},localQueryLogs:()=>
2{if(this.cachedSync)return this.cachedSync.localQueryLogs(i,s)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(i,s)}}}prewarmQuery(e){let t=e.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(e.query,e.args||{}).onUpdate(()=>{}),t)}watchPaginatedQuery(e,t,s){let n=eT(e);return{onUpdate:e=>{let{paginatedQueryToken:i,unsubscribe:r}=this.paginatedQueryClient.subscribe(n,t||{},s),o=this.listeners.get(i);return void 0!==o?o.add(e):this.listeners.set(i,new Set([e])),()=>{if(this.closed)return;let t=this.listeners.get(i);t.delete(e),0===t.size&&this.listeners.delete(i),r()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(n,t,s)}}mutation(e,...t){let[s,n]=t,i=eT(e);return this.sync.mutation(i,s,n)}action(e,...t){let s=eT(e);return this.sync.action(s,...t)}query(e,...t){let s=this.watchQuery(e,...t),n=s.localQueryResult();return void 0!==n?Promise.resolve(n):new Promise((e,t)=>{let n=s.onUpdate(()=>{n();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 to=o.default.createContext(void 0),ta=({client:e,children:t})=>o.default.createElement(to.Provider,{value:e},t);var tu=Object.defineProperty,tl=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tu(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class th{constructor(e){tl(this,"createWatch"),tl(this,"queries"),tl(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(let t of Object.keys(e)){let{query:s,args:n,paginationOptions:i}=e[t];if(eT(s),void 0===this.queries[t])this.addQuery(t,s,n,i?{paginationOptions:i}:{});else{let e=this.queries[t];(eT(s)!==eT(e.query)||JSON.stringify(M(n))!==JSON.stringify(M(e.args))||JSON.stringify(i)!==JSON.stringify(e.paginationOptions))&&(this.removeQuery(t),this.addQuery(t,s,n,i?{paginationOptions:i}:{}))}}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 n,{query:i,args:r}=e[s],o=e[s].paginationOptions;eT(i);let a=this.createWatch(i,r,o?{paginationOptions:o}:{});try{n=a.localQueryResult()}catch(e){if(e instanceof Error)n=e;else throw e}t[s]=n}return t}setCreateWatch(e){for(let t of(this.createWatch=e,Object.keys(this.queries))){let{query:e,args:s,watch:n,paginationOptions:i}=this.queries[t],r="journal"in n?n.journal():void 0;this.removeQuery(t),this.addQuery(t,e,s,{...r?{journal:r}:[],...i?{paginationOptions:i}:{}})}}destroy(){for(let e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,t,s,{paginationOptions:n,journal:i}){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,{...i?{journal:i}:[],...n?{paginationOptions:n}:{}}),o=r.onUpdate(()=>this.notifyListeners());this.queries[e]={query:t,args:s,watch:r,unsubscribe:o,...n?{paginationOptions:n}:{}}}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 tc=(0,o.createContext)(void 0);function td(){let e=(0,o.useContext)(tc);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 tf({children:e,client:t,useAuth:s}){let{isLoading:n,isAuthenticated:i,fetchAccessToken:r}=s(),[a,u]=(0,o.useState)(null);return n&&null!==a&&u(null),n||i||!1===a||u(!1),o.default.createElement(tc.Provider,{value:{isLoading:null===a,isAuthenticated:i&&(a??!1)}},o.default.createElement(tg,{authProviderAuthenticated:i,fetchAccessToken:r,authProviderLoading:n,client:t,setIsConvexAuthenticated:u}),o.default.createElement(ta,{client:t},e),o.default.createElement(ty,{authProviderAuthenticated:i,fetchAccessToken:r,authProviderLoading:n,client:t,setIsConvexAuthenticated:u}))}function tg({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:n,setIsConvexAuthenticated:i}){return(0,o.useEffect)(()=>{let s=!0;if(e)return n.setAuth(t,e=>{s&&i(()=>e)}
2),()=>{s=!1,i(e=>!e&&null)}},[e,t,s,n,i]),null}function ty({authProviderAuthenticated:e,fetchAccessToken:t,authProviderLoading:s,client:n,setIsConvexAuthenticated:i}){return(0,o.useEffect)(()=>{if(e)return()=>{n.clearAuth(),i(()=>null)}},[e,t,s,n,i]),null}function tp({children:e}){let{isLoading:t,isAuthenticated:s}=td();return t||!s?null:o.default.createElement(o.default.Fragment,null,e)}function tm({children:e}){let{isLoading:t,isAuthenticated:s}=td();return t||s?null:o.default.createElement(o.default.Fragment,null,e)}let tv=Object.prototype.toString,tb=new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]),tw=[500,2e3],tk=(0,o.createContext)(void 0),tS=(0,o.createContext)(void 0);function tx(){return(0,o.useContext)(tS)}let tC=(0,o.createContext)(null),tT="__convexAuthOAuthVerifier",tR="__convexAuthJWT",tA="__convexAuthRefreshToken",tq="__convexAuthServerStateFetchTime";function tO({client:e,serverState:t,onChange:s,shouldHandleCode:n,storage:i,storageNamespace:a,replaceURL:u,children:l}){var h,c;let d,f,g,y,p=(0,o.useRef)(t?._state.token??null),[m,v]=(0,o.useState)(null===p.current),[b,w]=(0,o.useState)(p.current),k=e.verbose??!1,S=(0,o.useCallback)(t=>{k&&(console.debug(`${new Date().toISOString()} ${t}`),e.logger?.logVerbose(t))},[k]),{storageSet:x,storageGet:C,storageRemove:T,storageKey:R}=(h=i,c=a,d=function(){let[e,t]=(0,o.useState)({});return()=>({getItem:t=>e[t],setItem:(e,s)=>{t(t=>({...t,[e]:s}))},removeItem:e=>{t(t=>{let{[e]:s,...n}=t;return n})}})}(),f=(0,o.useMemo)(()=>h??d(),[h]),g=c.replace(/[^a-zA-Z0-9]/g,""),y=(0,o.useCallback)(e=>`${e}_${g}`,[c]),{storageSet:(0,o.useCallback)((e,t)=>f.setItem(y(e),t),[f,y]),storageGet:(0,o.useCallback)(e=>f.getItem(y(e)),[f,y]),storageRemove:(0,o.useCallback)(e=>f.removeItem(y(e)),[f,y]),storageKey:y}),[A,q]=(0,o.useState)(!1),O=(0,o.useCallback)(async e=>{let t,n=null!==p.current;if(null===e.tokens)p.current=null,e.shouldStore&&(await T(tR),await T(tA)),t=null;else{let{token:s}=e.tokens;if(p.current=s,e.shouldStore){let{refreshToken:t}=e.tokens;await x(tR,s),await x(tA,t)}t=s}n!==(null!==t)&&await s?.(),w(t),v(!1)},[x,T]);(0,o.useEffect)(()=>{let e=async e=>{if(A)return e.preventDefault(),e.returnValue=!0,"Are you sure you want to leave? Your changes may not be saved."};return t_("beforeunload",e),()=>{tQ("beforeunload",e)}}),(0,o.useEffect)(()=>{let e=e=>{(async()=>{if(e.storageArea===i&&e.key===R(tR)){let t=e.newValue;S(`synced access token, is null: ${null===t}`),await O({shouldStore:!1,tokens:null===t?null:{token:t}})}})()};return t_("storage",e),()=>tQ("storage",e)},[O]);let I=(0,o.useCallback)(async t=>{let s,n=0;for(;n<tw.length;)try{return await e.unauthenticatedCall("auth:signIn","code"in t?{params:{code:t.code},verifier:t.verifier}:t)}catch(t){if(s=t,!function(e){if(!(e&&"[object Error]"===tv.call(e)&&"TypeError"===e.name&&"string"==typeof e.message))return!1;let{message:t,stack:s}=e;return"Load failed"===t?void 0===s||"__sentry_captured__"in e:!!(t.startsWith("error sending request for url")||"Failed to fetch"===t||t.startsWith("Failed to fetch (")&&t.endsWith(")"))||tb.has(t)}(t))break;let e=tw[n]+100*Math.random();n++,S(`verifyCode failed with network error, retry ${n} of ${tw.length} in ${e}ms`),await new Promise(t=>setTimeout(t,e))}throw s},[e]),E=(0,o.useCallback)(async e=>{let{tokens:t}=await I(e);return S(`retrieved tokens, is null: ${null===t}`),await O({shouldStore:!0,tokens:t??null}),null!==t},[e,O]),$=(0,o.useCallback)(async(t,s)=>{let n=s instanceof FormData?Array.from(s.entries()).reduce((e,[t,s])=>(e[t]=s,e),{}):s??{},i=await C(tT)??void 0;await T(tT);let r=await e.authenticatedCall("auth:signIn",{provider:t,params:n,verifier:i});if(void 0!==r.redirect){let e=new URL(r.redirect);return await x(tT,r.verifier),"ReactNative"!==navigator.product&&(window.location.href=e.toString()),{signingIn:!1,redirect:e}}if(void 0!==r.tokens){let{tokens:e}=r;return S(`signed in and got tokens, is null: ${null===e}`),await O({shouldStore:!0,tokens:e}),{signingIn:null!==r.tokens}}return{signingIn:!1}},[e,O,C]),M=(0,o.useCallback)(async()=>{try{await e.authenticatedCall("auth:signOut")}catch(e){}S("signed out, erasing tokens"),await O({shouldStore:!0,tokens:null})},[O,e]),j=(0,o.useCallback)(async({forceRefreshToken:e})=>
2{if(e){let e=p.current;return await tI(tA,async()=>{let t=p.current;if(t!==e)return S(`returning synced token, is null: ${null===t}`),t;let s=await C(tA)??null;return null!==s?(q(!0),await E({refreshToken:s}).finally(()=>{q(!1)}),S(`returning retrieved token, is null: ${null===t}`),p.current):(q(!1),S("returning null, there is no refresh token"),null)})}return p.current},[E,M,C]),_=(0,o.useRef)(!1);(0,o.useEffect)(()=>{if(void 0===i)throw Error("`localStorage` is not available in this environment, set the `storage` prop on `ConvexAuthProvider`!");let e=async()=>{let e=await C(tR)??null;S(`retrieved token from storage, is null: ${null===e}`),await O({shouldStore:!1,tokens:null===e?null:{token:e}})};if(void 0!==t){let s=C(tq),n=s=>{if(!s||t._timeFetched>+s){let{token:e,refreshToken:s}=t._state;x(tq,t._timeFetched.toString()),O({tokens:null===e||null===s?null:{token:e,refreshToken:s},shouldStore:!0})}else e()};s instanceof Promise?s.then(n):n(s);return}let s=void 0!==window?.location?.search?new URLSearchParams(window.location.search).get("code"):null;if(_.current);else if(s&&(void 0===n||("function"==typeof n?n():n))){_.current=!0;let e=new URL(window.location.href);e.searchParams.delete("code"),(async()=>{await u(e.pathname+e.search+e.hash),await $(void 0,{code:s}),_.current=!1})()}else e()},[e,C]);let Q=(0,o.useMemo)(()=>({signIn:$,signOut:M}),[$,M]),P=null!==b,N=(0,o.useMemo)(()=>({isLoading:m,isAuthenticated:P,fetchAccessToken:j}),[j,m,P]);return(0,r.jsx)(tS.Provider,{value:N,children:(0,r.jsx)(tk.Provider,{value:Q,children:(0,r.jsx)(tC.Provider,{value:b,children:l})})})}async function tI(e,t){let s=window?.navigator?.locks;return void 0!==s?await s.request(e,t):await tj(e,t)}function tE(e){void 0===globalThis.__convexAuthMutexes&&(globalThis.__convexAuthMutexes={});let t=globalThis.__convexAuthMutexes[e];return void 0===t&&(globalThis.__convexAuthMutexes[e]={currentlyRunning:null,waiting:[]}),t=globalThis.__convexAuthMutexes[e]}function t$(e,t){globalThis.__convexAuthMutexes[e]=t}async function tM(e,t){let s=tE(e);null===s.currentlyRunning?t$(e,{currentlyRunning:t().finally(()=>{let t=tE(e).waiting.shift();tE(e).currentlyRunning=null,t$(e,{...tE(e),currentlyRunning:void 0===t?null:tM(e,t)})}),waiting:[]}):t$(e,{...s,waiting:[...s.waiting,t]})}async function tj(e,t){return new Promise((s,n)=>{tM(e,()=>t().then(e=>s(e)).catch(e=>n(e)))})}function t_(e,t,s){"u">typeof window&&window.addEventListener?.(e,t,s)}function tQ(e,t,s){"u">typeof window&&window.removeEventListener?.(e,t,s)}function tP(){return(0,o.useContext)(tk)}function tN(e){let{client:t,storage:s,storageNamespace:n,replaceURL:i,shouldHandleCode:a,children:u}=e,l=(0,o.useMemo)(()=>({authenticatedCall:(e,s)=>t.action(e,s),unauthenticatedCall:(e,s)=>new tt(t.address,{logger:t.logger}).action(e,s),verbose:t.options?.verbose,logger:t.logger}),[t]);return(0,r.jsx)(tO,{client:l,storage:s??("u"<typeof window?void 0:window?.localStorage),storageNamespace:n??t.address,replaceURL:i??(e=>{window.history.replaceState({},"",e)}),shouldHandleCode:a,children:(0,r.jsx)(tf,{client:t,useAuth:tx,children:u})})}function tL(e,t){if("u"<typeof Convex||void 0===Convex.syscall)throw Error("The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?");return JSON.parse(Convex.syscall(e,JSON.stringify(t)))}async function tV(e,t){let s;if("u"<typeof Convex||void 0===Convex.asyncSyscall)throw Error("The Convex database and auth objects are being used outside of a Convex backend. Did you mean to use `useQuery` or `useMutation` to call a Convex function?");try{s=await Convex.asyncSyscall(e,JSON.stringify(t))}catch(e){if(void 0!==e.data){let t=new en(e.message);throw t.data=q(e.data),t}throw Error(e.message)}return JSON.parse(s)}function tF(e,t,s,n){if(void 0===e)throw TypeError(`Must provide arg ${t} \`${n}\` to \`${s}\``)}var tU=Object.defineProperty,tD=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tU(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class tB{constructor(){tD(this,"_isExpression"),tD(this,"_value")}}var tW=Object.defineProperty;class tK extends tB{constructor(e){super(),((e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tW(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s})(this,"inner"),this.inner=e}serialize(){return this.inner}}function tJ(e){return e instanceof tK?e.serialize():{$literal:j(e)}}let tz={eq:(e,t)=>
2new tK({$eq:[tJ(e),tJ(t)]}),neq:(e,t)=>new tK({$neq:[tJ(e),tJ(t)]}),lt:(e,t)=>new tK({$lt:[tJ(e),tJ(t)]}),lte:(e,t)=>new tK({$lte:[tJ(e),tJ(t)]}),gt:(e,t)=>new tK({$gt:[tJ(e),tJ(t)]}),gte:(e,t)=>new tK({$gte:[tJ(e),tJ(t)]}),add:(e,t)=>new tK({$add:[tJ(e),tJ(t)]}),sub:(e,t)=>new tK({$sub:[tJ(e),tJ(t)]}),mul:(e,t)=>new tK({$mul:[tJ(e),tJ(t)]}),div:(e,t)=>new tK({$div:[tJ(e),tJ(t)]}),mod:(e,t)=>new tK({$mod:[tJ(e),tJ(t)]}),neg:e=>new tK({$neg:tJ(e)}),and:(...e)=>new tK({$and:e.map(tJ)}),or:(...e)=>new tK({$or:e.map(tJ)}),not:e=>new tK({$not:tJ(e)}),field:e=>new tK({$field:e})};var tH=Object.defineProperty,tG=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tH(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};function tX(e){throw Error("consumed"===e?"This query is closed and can't emit any more values.":"This query has been chained with another operator and can't be reused.")}class tY{constructor(e){tG(this,"state"),tG(this,"tableNameForErrorMessages"),this.state={type:"preparing",query:e},"FullTableScan"===e.source.type?this.tableNameForErrorMessages=e.source.tableName:this.tableNameForErrorMessages=e.source.indexName.split(".")[0]}takeQuery(){if("preparing"!==this.state.type)throw Error("A query can only be chained once and can't be chained after iteration begins.");let e=this.state.query;return this.state={type:"closed"},e}startQuery(){if("executing"===this.state.type)throw Error("Iteration can only begin on a query once.");("closed"===this.state.type||"consumed"===this.state.type)&&tX(this.state.type);let{queryId:e}=tL("1.0/queryStream",{query:this.state.query,version:er});return this.state={type:"executing",queryId:e},e}closeQuery(){"executing"===this.state.type&&tL("1.0/queryCleanup",{queryId:this.state.queryId}),this.state={type:"consumed"}}order(e){tF(e,1,"order","order");let t=this.takeQuery();if("Search"===t.source.type)throw Error("Search queries must always be in relevance order. Can not set order manually.");if(null!==t.source.order)throw Error("Queries may only specify order at most once");return t.source.order=e,new tY(t)}filter(e){tF(e,1,"filter","predicate");let t=this.takeQuery();if(t.operators.length>=256)throw Error("Can't construct query with more than 256 operators");return t.operators.push({filter:tJ(e(tz))}),new tY(t)}limit(e){tF(e,1,"limit","n");let t=this.takeQuery();return t.operators.push({limit:e}),new tY(t)}[Symbol.asyncIterator](){return this.startQuery(),this}async next(){("closed"===this.state.type||"consumed"===this.state.type)&&tX(this.state.type);let e="preparing"===this.state.type?this.startQuery():this.state.queryId,{value:t,done:s}=await tV("1.0/queryStreamNext",{queryId:e});return s&&this.closeQuery(),{value:q(t),done:s}}return(){return this.closeQuery(),Promise.resolve({done:!0,value:void 0})}async paginate(e){if(tF(e,1,"paginate","options"),"number"!=typeof e?.numItems||e.numItems<0)throw Error(`\`options.numItems\` must be a positive number. Received \`${e?.numItems}\`.`);let t=this.takeQuery(),s=e.numItems,n=e.cursor,i=e?.endCursor??null,r=e.maximumRowsRead??null,{page:o,isDone:a,continueCursor:u,splitCursor:l,pageStatus:h}=await tV("1.0/queryPage",{query:t,cursor:n,endCursor:i,pageSize:s,maximumRowsRead:r,maximumBytesRead:e.maximumBytesRead,version:er});return{page:o.map(e=>q(e)),isDone:a,continueCursor:u,splitCursor:l,pageStatus:h}}async collect(){let e=[];for await(let t of this)e.push(t);return e}async take(e){tF(e,1,"take","n");if(!Number.isInteger(e)||e<0)throw TypeError("Arg 1 `n` to `take` must be a non-negative integer");return this.limit(e).collect()}async first(){let e=await this.take(1);return 0===e.length?null:e[0]}async unique(){let e=await this.take(2);if(0===e.length)return null;if(2===e.length)throw Error(`unique() query returned more than one result from table ${this.tableNameForErrorMessages}: 3 [${e[0]._id}, ${e[1]._id}, ...]`);return e[0]}}Y.object({numItems:Y.number(),cursor:Y.union(Y.string(),Y.null()),endCursor:Y.optional(Y.union(Y.string(),Y.null())),id:Y.optional(Y.number()),maximumRowsRead:Y.optional(Y.number()),maximumBytesRead:Y.optional(Y.number())});Symbol("var.requestId"),Symbol("var.ip"),Symbol("var.userAgent"),Symbol("var.now");var tZ=Object.defineProperty,t0=(e,t,s)=>{let n;return(n="symbol"!=typeof t?t+"":t)in e?tZ(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s};class t1{constructor(e){t0(this,"indexes"),t0(this,"stagedDbIndexes"),t0(this,"searchIndexes"),t0(this,"stagedSearchIndexes"),t0(this,"vectorIndexes"),t0(this,"stagedVectorIndexes"),t0(this,"validator"),this.indexes=[],this.stagedDbIndexes=[],this.searchIndexes=[],this.stagedSearchIndexes=[],this.vectorIndexes=[],this.stagedVectorIndexes=[],this.validator=e}" indexes"(){return this.indexes}index(e,t){return Array.isArray(t)?this.indexes.push({indexDescriptor:e,fields:t}):t.staged?this.stagedDbIndexes.push({indexDescriptor:e,fields:t.fields}):this.indexes.push({indexDescriptor:e,fields:t.fields}),this}searchIndex(e,t){return t.staged?this.stagedSearchIndexes.push({indexDescriptor:e,searchField:t.searchField,filterFields:t.filterFields||[]}):this.searchIndexes.push({indexDescriptor:e,searchField:t.searchField,filterFields:t.filterFields||[]}),this}
3vectorIndex(e,t){return t.staged?this.stagedVectorIndexes.push({indexDescriptor:e,vectorField:t.vectorField,dimensions:t.dimensions,filterFields:t.filterFields||[]}):this.vectorIndexes.push({indexDescriptor:e,vectorField:t.vectorField,dimensions:t.dimensions,filterFields:t.filterFields||[]}),this}self(){return this}export(){let e=this.validator.json;if("object"!=typeof e)throw Error("Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)");return{indexes:this.indexes,stagedDbIndexes:this.stagedDbIndexes,searchIndexes:this.searchIndexes,stagedSearchIndexes:this.stagedSearchIndexes,vectorIndexes:this.vectorIndexes,stagedVectorIndexes:this.stagedVectorIndexes,documentType:e}}}function t3(e){return new t1(e.isConvexValidator?e:Y.object(e))}new class e{constructor(e,t){t0(this,"tables"),t0(this,"strictTableNameTypes"),t0(this,"schemaValidation"),this.tables=e,this.schemaValidation=t?.schemaValidation===void 0||t.schemaValidation}export(){return JSON.stringify({tables:Object.entries(this.tables).map(([e,t])=>{let{indexes:s,stagedDbIndexes:n,searchIndexes:i,stagedSearchIndexes:r,vectorIndexes:o,stagedVectorIndexes:a,documentType:u}=t.export();return{tableName:e,indexes:s,stagedDbIndexes:n,searchIndexes:i,stagedSearchIndexes:r,vectorIndexes:o,stagedVectorIndexes:a,documentType:u}}),schemaValidation:this.schemaValidation})}}({_scheduled_functions:t3({name:Y.string(),args:Y.array(Y.any()),scheduledTime:Y.float64(),completedTime:Y.optional(Y.float64()),state:Y.union(Y.object({kind:Y.literal("pending")}),Y.object({kind:Y.literal("inProgress")}),Y.object({kind:Y.literal("success")}),Y.object({kind:Y.literal("failed"),error:Y.string()}),Y.object({kind:Y.literal("canceled")}))}),_storage:t3({sha256:Y.string(),size:Y.float64(),contentType:Y.optional(Y.string())})},void 0),!function e(t,s){return new Proxy({},{get(n,i){if("string"==typeof i)return e(t,[...s,i]);if(i===eC){if(s.length<1){let e=[t,...s].join(".");throw Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${e}\``)}return"_reference/childComponent/"+s.join("/")}}})}("components",[]);var t2=e.i(83266),t6=e.i(60450);function t5({message:e}){return(0,r.jsx)("main",{className:"shell",children:(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"Account is not configured."}),(0,r.jsx)("p",{className:"notice error",children:e})]})})}function t4(e){let t=e?.message||"Something went wrong. Try again.";return t.includes("Could not send sign-in email")?"Could not send sign-in email. Please check your email address and try again.":t.includes("[CONVEX")?"Something went wrong. Try again.":t}function t8(){return(0,r.jsx)("span",{className:"spinner","aria-hidden":"true"})}function t7(){let{signIn:e}=tP(),[t,s]=(0,o.useState)(""),[n,i]=(0,o.useState)(""),[a,u]=(0,o.useState)(!1),[l,h]=(0,o.useState)(null),[c,d]=(0,o.useState)(!1);async function f(s){s.preventDefault(),h(null),d(!0),(0,t2.track)("account_sign_in_code_requested");try{let s=new URL(window.location.href);s.searchParams.delete("linkCode"),await e("email",{email:t,redirectTo:s.toString()}),u(!0),h({type:"success",text:"Code sent. Check your inbox or spam folder."}),(0,t2.track)("account_sign_in_code_sent")}catch(e){h({type:"error",text:t4(e)}),(0,t2.track)("account_sign_in_code_failed")}finally{d(!1)}}async function g(s){s.preventDefault(),h(null),d(!0),(0,t2.track)("account_sign_in_code_submitted");try{let s=await e("email",{email:t,code:n});s.signingIn||h({type:"error",text:"Could not verify that code."}),(0,t2.track)(s.signingIn?"account_sign_in_code_accepted":"account_sign_in_code_rejected")}catch(e){h({type:"error",text:t4(e)}),(0,t2.track)("account_sign_in_code_failed")}finally{d(!1)}}return(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"Sign in with a one-time code."}),(0,r.jsx)("p",{className:"muted",children:"Enter your email and we'll send a code so you can link your browser extension."}
3),(0,r.jsxs)("form",{onSubmit:a?g:f,className:"form",onChange:e=>{e.target?.name==="email"&&(u(!1),i(""))},children:[(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{children:"Email"}),(0,r.jsx)("input",{name:"email",value:t,onChange:e=>s(e.target.value),type:"email",autoComplete:"email",required:!0})]}),a?(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{children:"Code"}),(0,r.jsx)("input",{value:n,onChange:e=>i(e.target.value),inputMode:"numeric",autoComplete:"one-time-code",required:!0})]}):null,(0,r.jsxs)("button",{type:"submit",disabled:c,children:[c?(0,r.jsx)(t8,{}):null,a?"Verify Code":"Send Code"]})]}),l?(0,r.jsx)("p",{className:`notice ${l.type}`,children:l.text}):null]})}function t9(){let{signOut:e}=tP(),t=function(e,...t){let s="skip"===t[0],n="skip"===t[0]?{}:p(t[0]),i="string"==typeof e?{[ex]:e}:e,r=eT(i),a=function(e){let t=(0,o.useContext)(to);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,o.useState)(()=>new th(t));return s.createWatch!==t&&s.setCreateWatch(t),(0,o.useEffect)(()=>()=>s.destroy(),[s]),function({getCurrentValue:e,subscribe:t}){let[s,n]=(0,o.useState)(()=>({getCurrentValue:e,subscribe:t,value:e()})),i=s.value;return(s.getCurrentValue!==e||s.subscribe!==t)&&(i=e(),n({getCurrentValue:e,subscribe:t,value:i})),(0,o.useEffect)(()=>{let s=!1,i=()=>{s||n(s=>{if(s.getCurrentValue!==e||s.subscribe!==t)return s;let n=e();return s.value===n?s:{...s,value:n}})},r=t(i);return i(),()=>{s=!0,r()}},[e,t]),i}((0,o.useMemo)(()=>({getCurrentValue:()=>s.getLocalResults(e),subscribe:t=>(s.setQueries(e),s.subscribe(t))}),[s,e]))}(e,(0,o.useMemo)(()=>(e,s,{journal:n,paginationOptions:i})=>i?t.watchPaginatedQuery(e,s,i):t.watchQuery(e,s,n?{journal:n}:{}),[t]))}((0,o.useMemo)(()=>s?{}:{query:{query:i,args:n}},[JSON.stringify(M(n)),r,s])).query;if(a instanceof Error)throw a;return a}(eR.entitlements.current),s=function(e){let t="string"==typeof e?{[ex]:e}:e,s=(0,o.useContext)(to);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,o.useMemo)(()=>(function e(t,s,n){function i(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:n})}return i.withOptimisticUpdate=function(i){if(void 0!==n)throw Error(`Already specified optimistic update for mutation ${eT(t)}`);return e(t,s,i)},i})(t,s),[s,eT(t)])}(eR.entitlements.completeCurrentUserExtensionLink),[n,i]=(0,o.useState)(""),[a,u]=(0,o.useState)(!0),[l,h]=(0,o.useState)(!1),[c,d]=(0,o.useState)(null),[f,g]=(0,o.useState)(!1),y=(0,o.useRef)(!1),m=(0,o.useMemo)(()=>(function(e){if(!t6.WEB_CONFIG.checkoutUrl)return"";let t=new URL(t6.WEB_CONFIG.checkoutUrl);return e&&t.searchParams.set("prefilled_email",e),t.toString()})(t?.email),[t?.email]),v=t?.plan==="pro"&&["active","trialing"].includes(t?.status);async function b(){d(null),g(!0),(0,t2.track)("extension_link_submitted",{mode:a?"manual":"auto"});try{let e=await s({code:n});e.ok?(h(!0),d({type:"success",text:"Extension linked. Return to Kept; it should update automatically."}),(0,t2.track)("extension_link_succeeded",{mode:a?"manual":"auto"})):(d({type:"error",text:e.error||"Could not link that code."}),(0,t2.track)("extension_link_failed",{mode:a?"manual":"auto"}))}catch(e){d({type:"error",text:t4(e)}),(0,t2.track)("extension_link_failed",{mode:a?"manual":"auto"})}finally{g(!1)}}return((0,o.useEffect)(()=>{let e=new URLSearchParams(window.location.search).get("linkCode")||"";e&&(i(e),u(!1))},[]),(0,o.useEffect)(()=>{a||!n||l||f||y.current||(y.current=!0,b())},[a,n,l,f]),void 0===t)?(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"Loading account."}),(0,r.jsxs)("p",{className:"notice",children:[(0,r.jsx)(t8,{}),"Checking your session"]})]}):a||c?.type!=="error"?l?(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"Extension linked."}),(0,r.jsxs)("p",{className:"muted",children:["Signed in as ",t?.email||"
3your Kept account","."]}),c?(0,r.jsx)("p",{className:`notice ${c.type}`,children:c.text}):null,(0,r.jsxs)("div",{className:"actions",children:[!v&&m?(0,r.jsx)("a",{className:"button-link",href:m,onClick:()=>(0,t2.track)("checkout_clicked",{source:"linked_account"}),children:"Buy Kept"}):null,(0,r.jsx)("button",{className:"ghost",type:"button",onClick:()=>void e(),children:"Sign Out"})]})]}):v&&!n?(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"Kept is unlocked."}),(0,r.jsxs)("p",{className:"muted",children:["Signed in as ",t?.email||"your Kept account","."]}),(0,r.jsx)("div",{className:"actions",children:(0,r.jsx)("button",{className:"ghost",type:"button",onClick:()=>void e(),children:"Sign Out"})})]}):(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:a?"Link this browser extension.":"Linking this browser extension."}),(0,r.jsxs)("p",{className:"muted",children:["Signed in as ",t?.email||"your Kept account","."]}),(0,r.jsxs)("form",{onSubmit:function(e){e.preventDefault(),b()},className:"form",children:[a?(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{children:"Extension code"}),(0,r.jsx)("input",{value:n,onChange:e=>i(e.target.value.toUpperCase()),placeholder:"KPT-ABC123",required:!0})]}):null,a?(0,r.jsxs)("button",{type:"submit",disabled:f,children:[f?(0,r.jsx)(t8,{}):null,"Link Extension"]}):(0,r.jsxs)("p",{className:"notice",children:[(0,r.jsx)(t8,{}),"Finishing extension link"]})]}),c?(0,r.jsx)("p",{className:`notice ${c.type}`,children:c.text}):null,(0,r.jsx)("div",{className:"actions",children:(0,r.jsx)("button",{className:"ghost",type:"button",onClick:()=>void e(),children:"Sign Out"})})]}):(0,r.jsxs)("section",{className:"panel",children:[(0,r.jsx)("p",{className:"eyebrow",children:"Kept Account"}),(0,r.jsx)("h1",{children:"This extension link expired."}),(0,r.jsxs)("p",{className:"muted",children:["Signed in as ",t?.email||"your Kept account","."]}),(0,r.jsx)("p",{className:"notice error",children:c.text}),(0,r.jsx)("p",{className:"muted",children:"Return to Kept and start sign-in again to create a fresh browser link."}),(0,r.jsx)("div",{className:"actions",children:(0,r.jsx)("button",{className:"ghost",type:"button",onClick:()=>void e(),children:"Sign Out"})})]})}function se(){return(0,r.jsxs)("main",{className:"shell",children:[(0,r.jsx)(tp,{children:(0,r.jsx)(t9,{})}),(0,r.jsx)(tm,{children:(0,r.jsx)(t7,{})})]})}e.s(["default",0,function(){let e=function(){if(!t6.WEB_CONFIG.convexUrl)return"NEXT_PUBLIC_CONVEX_URL is not configured.";try{let e=new URL(t6.WEB_CONFIG.convexUrl);if("https:"!==e.protocol&&"localhost"!==e.hostname&&"127.0.0.1"!==e.hostname)return"NEXT_PUBLIC_CONVEX_URL must use HTTPS outside local development.";if(e.hostname.endsWith(".convex.site"))return"NEXT_PUBLIC_CONVEX_URL must use the Convex cloud URL, not the Convex site URL."}catch{return"NEXT_PUBLIC_CONVEX_URL is not a valid URL."}return""}(),t=(0,o.useMemo)(()=>e?null:new tr(t6.WEB_CONFIG.convexUrl),[e]);return e?(0,r.jsx)(t5,{message:e}):(0,r.jsx)(tN,{client:t,children:(0,r.jsx)(se,{})})}],15697)}]);
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.