@communecter/cocolight-api-client 1.0.121 → 1.0.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/203.cocolight-api-client.cjs +1 -0
  2. package/dist/278.cocolight-api-client.browser.js +1 -0
  3. package/dist/278.cocolight-api-client.cjs +1 -0
  4. package/dist/278.cocolight-api-client.mjs.js +1 -0
  5. package/dist/401.cocolight-api-client.mjs.js +1 -1
  6. package/dist/407.cocolight-api-client.browser.js +1 -0
  7. package/dist/407.cocolight-api-client.mjs.js +1 -0
  8. package/dist/499.cocolight-api-client.browser.js +1 -0
  9. package/dist/499.cocolight-api-client.cjs +1 -0
  10. package/dist/499.cocolight-api-client.mjs.js +1 -0
  11. package/dist/556.cocolight-api-client.browser.js +1 -0
  12. package/dist/556.cocolight-api-client.cjs +1 -0
  13. package/dist/556.cocolight-api-client.mjs.js +1 -0
  14. package/dist/588.cocolight-api-client.mjs.js +1 -1
  15. package/dist/593.cocolight-api-client.mjs.js +1 -1
  16. package/dist/839.cocolight-api-client.mjs.js +1 -1
  17. package/dist/85.cocolight-api-client.browser.js +1 -0
  18. package/dist/85.cocolight-api-client.cjs +1 -0
  19. package/dist/85.cocolight-api-client.mjs.js +1 -0
  20. package/dist/906.cocolight-api-client.browser.js +1 -0
  21. package/dist/906.cocolight-api-client.cjs +1 -0
  22. package/dist/906.cocolight-api-client.mjs.js +1 -0
  23. package/dist/cocolight-api-client.browser.js +3 -3
  24. package/dist/cocolight-api-client.cjs +1 -1
  25. package/dist/cocolight-api-client.mjs.js +1 -1
  26. package/dist/cocolight-api-client.vite.mjs.js +1 -1
  27. package/dist/cocolight-api-client.vite.mjs.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/Api.ts +21 -2
  30. package/src/api/BaseEntity.ts +145 -4
  31. package/src/api/EndpointApi.ts +125 -1
  32. package/src/api/EndpointApi.types.ts +210 -1
  33. package/src/api/EntityRegistry.ts +11 -3
  34. package/src/api/Form.ts +60 -0
  35. package/src/api/User.ts +2 -0
  36. package/src/api/UserApi.ts +3 -2
  37. package/src/api/serverDataType/Form.ts +56 -0
  38. package/src/endpoints.module.ts +1 -1
  39. package/src/index.ts +3 -1
  40. package/src/types/entities.ts +3 -2
  41. package/types/Api.d.ts +7 -0
  42. package/types/api/BaseEntity.d.ts +99 -3
  43. package/types/api/EndpointApi.d.ts +77 -1
  44. package/types/api/EndpointApi.types.d.ts +194 -1
  45. package/types/api/EntityRegistry.d.ts +1 -1
  46. package/types/api/Form.d.ts +23 -0
  47. package/types/api/Organization.d.ts +1 -1
  48. package/types/api/User.d.ts +1 -0
  49. package/types/api/serverDataType/Form.d.ts +51 -0
  50. package/types/endpoints.module.d.ts +2994 -168
  51. package/types/index.d.ts +3 -1
  52. package/types/types/entities.d.ts +3 -2
@@ -0,0 +1 @@
1
+ "use strict";exports.id=203,exports.ids=[203],exports.modules={203:(e,t,s)=>{s.d(t,{ConvexClient:()=>ConvexClient});const n="1.32.0";for(var i=[],r=[],o=Uint8Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0;c<64;++c)i[c]=a[c],r[a.charCodeAt(c)]=c;function h(e){var t,s,n=function(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}(e),i=n[0],a=n[1],c=new o(function(e,t,s){return 3*(t+s)/4-s}(0,i,a)),h=0,u=a>0?i-4:i;for(s=0;s<u;s+=4)t=r[e.charCodeAt(s)]<<18|r[e.charCodeAt(s+1)]<<12|r[e.charCodeAt(s+2)]<<6|r[e.charCodeAt(s+3)],c[h++]=t>>16&255,c[h++]=t>>8&255,c[h++]=255&t;return 2===a&&(t=r[e.charCodeAt(s)]<<2|r[e.charCodeAt(s+1)]>>4,c[h++]=255&t),1===a&&(t=r[e.charCodeAt(s)]<<10|r[e.charCodeAt(s+1)]<<4|r[e.charCodeAt(s+2)]>>2,c[h++]=t>>8&255,c[h++]=255&t),c}function u(e){return i[e>>18&63]+i[e>>12&63]+i[e>>6&63]+i[63&e]}function l(e,t,s){for(var n,i=[],r=t;r<s;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),i.push(u(n));return i.join("")}function d(e){for(var t,s=e.length,n=s%3,r=[],o=16383,a=0,c=s-n;a<c;a+=o)r.push(l(e,a,a+o>c?c:a+o));return 1===n?(t=e[s-1],r.push(i[t>>2]+i[t<<4&63]+"==")):2===n&&(t=(e[s-2]<<8)+e[s-1],r.push(i[t>>10]+i[t>>4&63]+i[t<<2&63]+"=")),r.join("")}function f(e){if(void 0===e)return{};if(!g(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function p(e){if(void 0===e)throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof e)throw new Error(`Invalid deployment address: found ${e}".`);if(!e.startsWith("http:")&&!e.startsWith("https:"))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw new 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 new 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 g(e){const t="object"==typeof e,s=Object.getPrototypeOf(e),n=null===s||s===Object.prototype||"Object"===s?.constructor?.name;return t&&n}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63;const m=!0,y=BigInt("-9223372036854775808"),b=BigInt("9223372036854775807"),_=BigInt("0"),v=BigInt("8"),w=BigInt("256");function S(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}const k=DataView.prototype.setBigInt64?function(e){if(e<y||b<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);const t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),d(new Uint8Array(t))}:function(e){e<_&&(e-=y+y);let t=e.toString(16);t.length%2==1&&(t="0"+t);const s=new Uint8Array(new ArrayBuffer(8));let n=0;for(const i of t.match(/.{2}/g).reverse())s.set([parseInt(i,16)],n++),e>>=v;return d(s)},T=DataView.prototype.getBigInt64?function(e){const t=h(e);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){const t=h(e);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=_,n=_;for(const e of t)s+=BigInt(e)*w**n,n++;return s>b&&(s+=y+y),s};function C(e){if(e.length>1024)throw new Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw new Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s<32||s>=127)throw new Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function E(e){if(null===e)return e;if("boolean"==typeof e)return e;if("number"==typeof e)return e;if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>E(e));if("object"!=typeof e)throw new Error(`Unexpected type of ${e}`);const t=Object.entries(e);if(1===t.length){const s=t[0][0];if("$bytes"===s){if("string"!=typeof e.$bytes)throw new Error(`Malformed $bytes field on ${e}`);return h(e.$bytes).buffer}if("$integer"===s){if("string"!=typeof e.$integer)throw new Error(`Malformed $integer field on ${e}`);return T(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw new Error(`Malformed $float field on ${e}`);const t=h(e.$float);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $float`);const s=new DataView(t.buffer).getFloat64(0,m);if(!S(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if("$set"===s)throw new Error("Received a Set which is no longer supported as a Convex type.");if("$map"===s)throw new Error("Received a Map which is no longer supported as a Convex type.")}const s={};for(const[t,n]of Object.entries(e))C(t),s[t]=E(n);return s}function x(e){const t=JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t);if(t.length>16384){const e="[...truncated]";let s=16384-e.length;const n=t.codePointAt(s-1);return void 0!==n&&n>65535&&(s-=1),t.substring(0,s)+e}return t}function R(e,t,s,n){if(void 0===e){const e=s&&` (present at path ${s} in original object ${x(t)})`;throw new 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<y||b<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:k(e)}}if("number"==typeof e){if(S(e)){const t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,m),{$float:d(new Uint8Array(t))}}return e}if("boolean"==typeof e)return e;if("string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:d(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,n)=>R(e,t,s+`[${n}]`,!1));if(e instanceof Set)throw new Error(O(s,"Set",[...e],t));if(e instanceof Map)throw new Error(O(s,"Map",[...e],t));if(!g(e)){const n=e?.constructor?.name;throw new Error(O(s,n?`${n} `:"",e,t))}const i={},r=Object.entries(e);r.sort(([e,t],[s,n])=>e===s?0:e<s?-1:1);for(const[e,o]of r)void 0!==o?(C(e),i[e]=R(o,t,s+`.${e}`,!1)):n&&(C(e),i[e]=L(o,t,s+`.${e}`));return i}function O(e,t,s,n){return e?`${t}${x(s)} is not a supported Convex type (present at path ${e} in original object ${x(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(s)} is not a supported Convex type.`}function L(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw new Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return R(e,t,s,!1)}function I(e){return R(e,e,"",!1)}Object.defineProperty;var A,P,M=Object.defineProperty,q=(e,t,s)=>((e,t,s)=>t in e?M(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const N=Symbol.for("ConvexError");class errors_ConvexError extends(P=Error,A=N,P){constructor(e){super("string"==typeof e?e:x(e)),q(this,"name","ConvexError"),q(this,"data"),q(this,A,!0),this.data=e}}const $=()=>Array.from({length:4},()=>0);$(),$();var B=Object.defineProperty,V=(e,t,s)=>((e,t,s)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function U(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class DefaultLogger{constructor(e){V(this,"_onLogLineFuncs"),V(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(const t of Object.values(this._onLogLineFuncs))t("debug",`${(new Date).toISOString()}`,...e)}log(...e){for(const t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(const t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(const t of Object.values(this._onLogLineFuncs))t("error",...e)}}function Q(e,t,s,n,i){const r=U(s);if("object"==typeof i&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),"info"===t){const t=i.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${n})] Could not parse console.log`);const 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 D(e,t,s){return`[CONVEX ${U(e)}(${t})] ${s.errorMessage}\n Called by client`}function W(e,t){return t.data=e.errorData,t}function j(e){const t=e.split(":");let s,n;return 1===t.length?(s=t[0],n="default"):(s=t.slice(0,t.length-1).join(":"),n=t[t.length-1]),s.endsWith(".js")&&(s=s.slice(0,-3)),`${s}:${n}`}function F(e,t){return JSON.stringify({udfPath:j(e),args:I(t)})}function G(e,t,s){const{initialNumItems:n,id:i}=s;return JSON.stringify({type:"paginated",udfPath:j(e),args:I(t),options:I({initialNumItems:n,id:i})})}function z(e){return"paginated"===JSON.parse(e).type}var H=Object.defineProperty,K=(e,t,s)=>((e,t,s)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class LocalSyncState{constructor(){K(this,"nextQueryId"),K(this,"querySetVersion"),K(this,"querySet"),K(this,"queryIdToToken"),K(this,"identityVersion"),K(this,"auth"),K(this,"outstandingQueriesOlderThanRestart"),K(this,"outstandingAuthOlderThanRestart"),K(this,"paused"),K(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){const i=j(e),r=F(i,t),o=this.querySet.get(r);if(void 0!==o)return o.numSubscribers+=1,{queryToken:r,modification:null,unsubscribe:()=>this.removeSubscriber(r)};{const e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:s,componentPath:n};this.querySet.set(r,o),this.queryIdToToken.set(e,r);const a=this.querySetVersion,c=this.querySetVersion+1,h={type:"Add",queryId:e,udfPath:i,args:[I(t)],journal:s,componentPath:n};return this.paused?this.pendingQuerySetModifications.set(e,h):this.querySetVersion=c,{queryToken:r,modification:{type:"ModifyQuerySet",baseVersion:a,newVersion:c,modifications:[h]},unsubscribe:()=>this.removeSubscriber(r)}}}transition(e){for(const t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);const e=t.journal;if(void 0!==e){const 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 new Error(`Invalid modification ${t.type}`)}}queryId(e,t){const s=F(j(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};const t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){const s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const 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){const t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){const t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const t=[];for(const s of this.querySet.values()){const n={type:"Add",queryId:s.id,udfPath:s.canonicalizedUdfPath,args:[I(s.args)],journal:s.journal,componentPath:s.componentPath};t.push(n),e.has(s.id)||this.outstandingQueriesOlderThanRestart.add(s.id)}this.querySetVersion=1;const s={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:t};if(!this.auth)return this.identityVersion=0,[s,void 0];this.outstandingAuthOlderThanRestart=!0;const n={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[s,n]}pause(){this.paused=!0}resume(){const 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){const 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);const 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 J=Object.defineProperty,Y=(e,t,s)=>((e,t,s)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class RequestManager{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,Y(this,"inflightRequests"),Y(this,"requestsOlderThanRestart"),Y(this,"inflightMutationsCount",0),Y(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){const s=new Promise(s=>{const n=t?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:n,requestedAt:new Date,onResult:s}}),"Mutation"===e.type?this.inflightMutationsCount++:"Action"===e.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),s}onResponse(e){const t=this.inflightRequests.get(e.requestId);if(void 0===t)return null;if("Completed"===t.status.status)return null;const s="Mutation"===t.message.type?"mutation":"action",n=t.message.udfPath;for(const t of e.logLines)Q(this.logger,"info",s,n,t);const i=t.status;let r,o;if(e.success)r={success:!0,logLines:e.logLines,value:E(e.result)},o=()=>i.onResult(r);else{const t=e.result,{errorData:a}=e;Q(this.logger,"error",s,n,t),r={success:!1,errorMessage:t,errorData:void 0!==a?E(a):void 0,logLines:e.logLines},o=()=>i.onResult(r)}return"ActionResponse"!==e.type&&e.success?(t.status={status:"Completed",result:r,ts:e.ts,onResolve:o},null):(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===t.message.type?this.inflightActionsCount--:"Mutation"===t.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:r})}removeCompleted(e){const t=new Map;for(const[s,n]of this.inflightRequests.entries()){const 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());const e=[];for(const[t,s]of this.inflightRequests)if("NotSent"!==s.status.status){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 new Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}else s.status.status="Requested",e.push(s.message);return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,t]of this.inflightRequests)"NotSent"!==t.status.status||(t.status.status="Requested",e.push(t.message));return e}hasIncompleteRequests(){for(const 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(const 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}}const X=Symbol.for("functionName"),Z=Symbol.for("toReferencePath");function ee(e){const t=function(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[X])t={name:e[X]};else{const s=e[Z]??null;if(!s)throw new Error(`${e} is not a functionReference`);t={reference:s}}return t}(e);if(void 0===t.name){if(void 0!==t.functionHandle)throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(void 0!==t.reference)throw new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`);throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`)}if("string"==typeof e)return e;const s=e[X];if(!s)throw new Error(`${e} is not a functionReference`);return s}!function e(t=[]){return new Proxy({},{get(s,n){if("string"==typeof n)return e([...t,n]);if(n===X){if(t.length<2){const e=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${e}\``)}const 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 te=Object.defineProperty,se=(e,t,s)=>((e,t,s)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class OptimisticLocalStoreImpl{constructor(e){se(this,"queryResults"),se(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){const s=f(t[0]),n=ee(e),i=this.queryResults.get(F(n,s));if(void 0!==i)return OptimisticLocalStoreImpl.queryValue(i.result)}getAllQueries(e){const t=[],s=ee(e);for(const e of this.queryResults.values())e.udfPath===j(s)&&t.push({args:e.args,value:OptimisticLocalStoreImpl.queryValue(e.result)});return t}setQuery(e,t,s){const n=f(t),i=ee(e),r=F(i,n);let o;o=void 0===s?void 0:{success:!0,value:s,logLines:[]};const a={udfPath:i,args:n,result:o};this.queryResults.set(r,a),this.modifiedQueries.push(r)}static queryValue(e){return void 0===e?void 0:e.success?e.value:void 0}}class OptimisticQueryResults{constructor(){se(this,"queryResults"),se(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));const s=this.queryResults;this.queryResults=new Map(e);const n=new OptimisticLocalStoreImpl(this.queryResults);for(const e of this.optimisticUpdates)e.update(n);const i=[];for(const[e,t]of this.queryResults){const 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});const s=new OptimisticLocalStoreImpl(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){const t=this.queryResults.get(e);if(void 0!==t)return t.result}queryResult(e){const t=this.queryResults.get(e);if(void 0===t)return;const s=t.result;if(void 0!==s){if(s.success)return s.value;if(void 0!==s.errorData)throw W(s,new errors_ConvexError(D("query",t.udfPath,s)));throw new Error(D("query",t.udfPath,s))}}hasQueryResult(e){return void 0!==this.queryResults.get(e)}queryLogs(e){const t=this.queryResults.get(e);return t?.result?.logLines}}var ne=Object.defineProperty,ie=(e,t,s)=>((e,t,s)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Long{constructor(e,t){ie(this,"low"),ie(this,"high"),ie(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 Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const 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?re:e>=ae?ce:new Long(e%oe|0,e/oe|0)}toString(){return(BigInt(this.high)*BigInt(oe)+BigInt(this.low)).toString()}equals(e){return Long.isLong(e)||(e=Long.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 Long.isLong(e)||(e=Long.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 this.comp(e)<=0}static fromValue(e){return"number"==typeof e?Long.fromNumber(e):new Long(e.low,e.high)}}const re=new Long(0,0),oe=4294967296,ae=oe*oe,ce=new Long(-1,-1);var he=Object.defineProperty,ue=(e,t,s)=>((e,t,s)=>t in e?he(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class RemoteQuerySet{constructor(e,t){ue(this,"version"),ue(this,"remoteQuerySet"),ue(this,"queryPath"),ue(this,"logger"),this.version={querySet:0,ts:Long.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){const t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw new Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const t of e.modifications)switch(t.type){case"QueryUpdated":{const e=this.queryPath(t.queryId);if(e)for(const s of t.logLines)Q(this.logger,"info","query",e,s);const s=E(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:s,logLines:t.logLines});break}case"QueryFailed":{const e=this.queryPath(t.queryId);if(e)for(const s of t.logLines)Q(this.logger,"info","query",e,s);const{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?E(s):void 0,logLines:t.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(t.queryId);break;default:throw new Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function le(e){const t=h(e);return Long.fromBytesLE(Array.from(t))}function de(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":return e.success?{...e,ts:le(e.ts)}:{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:le(e.startVersion.ts)},endVersion:{...e.endVersion,ts:le(e.endVersion.ts)}}}}var fe=Object.defineProperty,pe=(e,t,s)=>((e,t,s)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let ge;function me(){return void 0===ge&&(ge=Date.now()),"undefined"!=typeof performance&&performance.now?Math.round(ge+performance.now()):Date.now()}function ye(){return`t=${Math.round((me()-ge)/100)/10}s`}const be={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 WebSocketManager{constructor(e,t,s,n,i,r){this.markConnectionStateDirty=i,this.debug=r,pe(this,"socket"),pe(this,"connectionCount"),pe(this,"_hasEverConnected",!1),pe(this,"lastCloseReason"),pe(this,"transitionChunkBuffer",null),pe(this,"defaultInitialBackoff"),pe(this,"maxBackoff"),pe(this,"retries"),pe(this,"serverInactivityThreshold"),pe(this,"reconnectDueToServerInactivityTimeout"),pe(this,"scheduledReconnect",null),pe(this,"networkOnlineHandler",null),pe(this,"pendingNetworkRecoveryInfo",null),pe(this,"uri"),pe(this,"onOpen"),pe(this,"onResume"),pe(this,"onMessage"),pe(this,"webSocketConstructor"),pe(this,"logger"),pe(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(){"undefined"!=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&&"undefined"!=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,new Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new 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){const e=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const t=de(JSON.parse(e));if("Transition"!==t.type)throw new 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 new Error("Didn't start connection from disconnected state: "+this.socket.state);const 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 new 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:me()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",ye(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",ye())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){const{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;const t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();const t=e.data.length;let s=de(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${s.type}`),"Ping"!==s.type){if("TransitionChunk"===s.type){const 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)}const t=function(e){if(void 0===e)return"Unknown";for(const t of Object.keys(be))if(e.startsWith(t))return t;return"Unknown"}(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){const t={type:e.type,..."Authenticate"===e.type&&"User"===e.tokenType?{value:`...${e.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){const s=function(e){switch(e.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...e};case"Connect":return void 0!==e.maxObservedTimestamp?{...e,maxObservedTimestamp:(t=e.maxObservedTimestamp,d(new Uint8Array(t.toBytesLE())))}:{...e,maxObservedTimestamp:void 0}}var t}(e),n=JSON.stringify(s);let i=!1;try{this.socket.ws.send(n),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);const s=me(),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":return this.lastCloseReason=e,this.close(),void this.scheduleReconnect("client");default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const 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");const e=this.socket.ws;e.onmessage=e=>{this._logVerbose("Ignoring message received after close")};const 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":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new 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();const 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":return void this.logger.logVerbose("Restart called without stopping first");default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":return void(this.socket={...this.socket,paused:"yes"});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){const t=me()-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":return void(this.socket={...this.socket,paused:"no"});case"ready":return void("uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:me()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume()));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){const t=("client"===e?100:"Unknown"===e?this.defaultInitialBackoff:be[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const s=Math.min(t,this.maxBackoff);return s+s*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;const s=me()-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}) 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 InvalidTokenError extends Error{}function _e(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const s=!0===t.header?0:1,n=e.split(".")[s];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${s+1}`);let i;try{i=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 new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return atob(t)}}(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${s+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${s+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var ve=Object.defineProperty,we=(e,t,s)=>((e,t,s)=>t in e?ve(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class AuthenticationManager{constructor(e,t,s){we(this,"authState",{state:"noAuth"}),we(this,"configVersion",0),we(this,"syncState"),we(this,"authenticate"),we(this,"stopSocket"),we(this,"tryRestartSocket"),we(this,"pauseSocket"),we(this,"resumeSocket"),we(this,"clearAuth"),we(this,"logger"),we(this,"refreshTokenLeewaySeconds"),we(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();const 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))return"waitingForServerConfirmationOfCachedToken"===this.authState.state?(this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),void this.authState.config.onAuthChange(!0)):void("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");const{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)return this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),void("noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange));"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const 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");const 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;const t=this.decodeToken(e);if(!t)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");const{iat:s,exp:n}=t;if(!s||!n)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");const 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,1e3*(i-this.refreshTokenLeewaySeconds));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);const 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){const s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);const n=await e(t);return 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){const t="waitingForServerConfirmationOfFreshToken"===e.state?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return _e(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}]`)}}const Se=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function ke(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}var Te=Object.defineProperty,Ce=(e,t,s)=>((e,t,s)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class BaseConvexClient{constructor(e,t,s){if(Ce(this,"address"),Ce(this,"state"),Ce(this,"requestManager"),Ce(this,"webSocketManager"),Ce(this,"authenticationManager"),Ce(this,"remoteQuerySet"),Ce(this,"optimisticQueryResults"),Ce(this,"_transitionHandlerCounter",0),Ce(this,"_nextRequestId"),Ce(this,"_onTransitionFns",new Map),Ce(this,"_sessionId"),Ce(this,"firstMessageReceived",!1),Ce(this,"debug"),Ce(this,"logger"),Ce(this,"maxObservedTimestamp"),Ce(this,"connectionStateSubscribers",new Map),Ce(this,"nextConnectionStateSubscriberId",0),Ce(this,"_lastPublishedConnectionState"),Ce(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(const t of this.connectionStateSubscribers.values())t(e)}})}),Ce(this,"mark",e=>{this.debug&&function(e,t){const s={sessionId:t};"undefined"!=typeof performance&&performance.mark&&performance.mark(e,{detail:s})}(e,this.sessionId)}),"object"==typeof e)throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");!0!==s?.skipConvexDeploymentUrlCheck&&p(e);const i=(s={...s}).authRefreshTokenLeewaySeconds??10;let r=s.webSocketConstructor;if(!r&&"undefined"==typeof WebSocket)throw new 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 DefaultLogger(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:function(e){const t=new DefaultLogger(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}({verbose:s.verbose??!1});const o=e.search("://");if(-1===o)throw new Error("Provided address was not an absolute URL.");const a=e.substring(o+3),c=e.substring(0,o);let h;if("http"===c)h="ws";else{if("https"!==c)throw new Error(`Unknown parent protocol ${c}`);h="wss"}const u=`${h}://${a}/api/${n}/sync`;this.state=new LocalSyncState,this.remoteQuerySet=new RemoteQuerySet(e=>this.state.queryPath(e),this.logger),this.requestManager=new RequestManager(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new AuthenticationManager(this.state,{authenticate:e=>{const t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new OptimisticQueryResults,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});const{unsavedChangesWarning:d}=s;if("undefined"==typeof window||void 0===window.addEventListener){if(!0===d)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==d&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();const t="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=t,t}});this.webSocketManager=new WebSocketManager(u,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const t=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new RemoteQuerySet(e=>this.state.queryPath(e),this.logger);const[s,n]=this.state.restart(t);n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(s);for(const e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{const[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(const e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},onMessage:e=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),e.type){case"Transition":{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);const t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case"MutationResponse":{e.success&&this.observedTimestamp(e.ts);const 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":{const t=function(e,t){const s=`[CONVEX FATAL ERROR] ${t}`;return e.error(s),new Error(s)}(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},r,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&l()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(const[e,n]of t){const t=this.state.queryToken(e);if(null!==t){const i={result:n,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,i)}}const n=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:n.map(e=>({token:e,modification:{kind:"Updated",result:this.optimisticQueryResults.rawQueryResult(e)}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){const t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){const e=this.state.getAuth();let t={};if(e&&"User"===e.tokenType){try{t=e?_e(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){const s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){const n=f(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:()=>{const e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){const s=F(e,f(t));return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){const s=F(e,f(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){const s=F(e,f(t));return this.state.queryJournal(s)}connectionState(){const 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){const t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){const n=await this.mutationInternal(e,t,s);if(!n.success){if(void 0!==n.errorData)throw W(n,new errors_ConvexError(D("mutation",e,n)));throw new Error(D("mutation",e,n))}return n.value}async mutationInternal(e,t,s,n){const{mutationPromise:i}=this.enqueueMutation(e,t,s,n);return i}enqueueMutation(e,t,s,n){const i=f(t);this.tryReportLongDisconnect();const r=this.nextRequestId;if(this._nextRequestId++,void 0!==s){const e=s.optimisticUpdate;if(void 0!==e){const 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=>{const 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()})}}const o={type:"Mutation",requestId:r,udfPath:e,componentPath:n,args:[I(i)]},a=this.webSocketManager.sendMessage(o);return{requestId:r,mutationPromise:this.requestManager.request(o,a)}}async action(e,t){const s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw W(s,new errors_ConvexError(D("action",e,s)));throw new Error(D("action",e,s))}return s.value}async actionInternal(e,t,s){const n=f(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const r={type:"Action",requestId:i,udfPath:e,componentPath:s,args:[I(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}reportMarks(){if(this.debug){const e=function(e){if("undefined"==typeof performance||!performance.getEntriesByName)return[];const t=[];for(const s of Se){const n=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...n)}return t.map(ke)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(null===e||Date.now()-e.getTime()<=6e4)return;const t=`${this.address}/api/debug_event`;fetch(t,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${n}`},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)})}}var Ee=s(339),xe=s(3);function Re(e){if("object"!=typeof e||null===e||!Array.isArray(e.page)||"boolean"!=typeof e.isDone||"string"!=typeof e.continueCursor)throw new Error(`Not a valid paginated query result: ${e?.toString()}`);return e}Object.defineProperty;var Oe=Object.defineProperty,Le=(e,t,s)=>((e,t,s)=>t in e?Oe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class PaginatedQueryClient{constructor(e,t){this.client=e,this.onTransition=t,Le(this,"paginatedQuerySet",new Map),Le(this,"lastTransitionTs"),this.lastTransitionTs=Long.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){const n=j(e),i=G(n,t,s),r=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:r}):(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){const n=G(j(e),t,s);return this.localQueryResultByToken(n)}localQueryResultByToken(e){const t=this.paginatedQuerySet.get(e);if(!t)return;const s=this.activePageQueryTokens(t);if(0===s.length)return{results:[],status:"LoadingFirstPage",loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let n,i=[],r=!1,o=!1;for(const e of s){const t=this.client.localQueryResultByToken(e);if(void 0===t){r=!0,o=!1;continue}const s=Re(t);i=i.concat(s.page),o=!!s.isDone}return n=r?0===i.length?"LoadingFirstPage":"LoadingMore":o?"Exhausted":"CanLoadMore",{results:i,status:n,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){const t=e.queries.map(e=>e.token),s=this.queriesContainingTokens(t);let 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)}})));const i={...e,paginatedQueries:n};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);const s=this.queryTokenForLastPageOfPaginatedQuery(e),n=this.client.localQueryResultByToken(s);if(!n)return!1;const i=Re(n);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);const 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[];const t=[],s=new Set(e);for(const[e,n]of this.paginatedQuerySet)for(const i of this.allQueryTokens(n))if(s.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(const s of e){const e=this.mustGetPaginatedQuery(s),{ongoingSplits:n,pageKeyToQuery:i,pageKeys:r}=e;for(const[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(const s of r){if(n.has(s))continue;const r=t(i.get(s).queryToken);if(!r)continue;const o=Re(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){const 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);const c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...o,cursor:s,endCursor:n}});e.pageKeyToQuery.set(r,c),e.ongoingSplits.set(t,[i,r])}addPageToPaginatedQuery(e,t,s){const 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){const t=this.paginatedQuerySet.get(e);if(t&&(t.numSubscribers-=1,!(t.numSubscribers>0))){for(const e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,s,n){const i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);const 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){const t=this.mustGetPaginatedQuery(e),s=t.pageKeys[t.pageKeys.length-1];if(void 0===s)throw new Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(s).queryToken}mustGetPaginatedQuery(e){const t=this.paginatedQuerySet.get(e);if(!t)throw new Error("paginated query no longer exists for token "+e);return t}}var Ie=Object.defineProperty,Ae=(e,t,s)=>((e,t,s)=>t in e?Ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let Pe;class ConvexClient{constructor(e,t={}){Ae(this,"listeners"),Ae(this,"_client"),Ae(this,"_paginatedClient"),Ae(this,"callNewListenersWithCurrentValuesTimer"),Ae(this,"_closed"),Ae(this,"_disabled"),!0!==t.skipConvexDeploymentUrlCheck&&p(e);const{disabled:s,...n}=t;this._closed=!1,this._disabled=!!s,Pe&&!("webSocketConstructor"in n)&&"undefined"==typeof WebSocket&&(n.webSocketConstructor=Pe),"undefined"!=typeof window||"unsavedChangesWarning"in n||(n.unsavedChangesWarning=!1),this.disabled||(this._client=new BaseConvexClient(e,()=>{},n),this._paginatedClient=new PaginatedQueryClient(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw new Error("ConvexClient is disabled")}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw new Error("ConvexClient is disabled")}get disabled(){return this._disabled}onUpdate(e,t,s,n){if(this.disabled)return this.createDisabledUnsubscribe();const{queryToken:i,unsubscribe:r}=this.client.subscribe(ee(e),t),o={queryToken:i,callback:s,onError:n,unsubscribe:r,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&void 0===this.callNewListenersWithCurrentValuesTimer&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));const a={unsubscribe:()=>{this.closed||(this.listeners.delete(o),r())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=a.unsubscribe;return Object.assign(c,a),c}onPaginatedUpdate_experimental(e,t,s,n,i){if(this.disabled)return this.createDisabledUnsubscribe();const r={initialNumItems:s.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:a}=this.paginatedClient.subscribe(ee(e),t,r),c={queryToken:o,callback:n,onError:i,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:r};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&void 0===this.callNewListenersWithCurrentValuesTimer&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));const h={unsubscribe:()=>{this.closed||(this.listeners.delete(c),a())},getCurrentValue:()=>this.paginatedClient.localQueryResult(ee(e),t,r),getQueryLogs:()=>[]},u=h.unsubscribe;return Object.assign(u,h),u}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){const e=()=>{},t={unsubscribe:e,getCurrentValue:()=>{},getQueryLogs:()=>{}};return Object.assign(e,t),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw new Error("ConvexClient has already been closed.");this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},s=!1){const n=[...e.map(e=>e.token),...t.map(e=>e.token)];for(const e of this.listeners){const{callback:t,queryToken:i,onError:r,hasEverRun:o}=e,a=z(i),c=a?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(n.includes(i)||s&&!o&&c){let s;e.hasEverRun=!0;try{s=a?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;r?r(e,"Second argument to onUpdate onError is reserved for later use"):Promise.reject(e);continue}t(s,"Second argument to onUpdate callback is reserved for later use")}}}async mutation(e,t,s){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.mutation(ee(e),t,s)}async action(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.action(ee(e),t)}async query(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");const s=this.client.localQueryResult(ee(e),t);return void 0!==s?Promise.resolve(s):new Promise((s,n)=>{const{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),s(e)},e=>{i(),n(e)})})}connectionState(){if(this.disabled)throw new Error("ConvexClient is disabled");return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}}const Me=(0,Ee.createRequire)((0,xe.resolve)("."));var qe=Object.create,Ne=Object.defineProperty,$e=Object.getOwnPropertyDescriptor,Be=Object.getOwnPropertyNames,Ve=Object.getPrototypeOf,Ue=Object.prototype.hasOwnProperty,Qe=(e=>void 0!==Me?Me:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>(void 0!==Me?Me:e)[t]}):e)(function(e){if(void 0!==Me)return Me.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),De=(e,t)=>function(){return t||(0,e[Be(e)[0]])((t={exports:{}}).exports,t),t.exports},We=(e,t,s)=>(s=null!=e?qe(Ve(e)):{},((e,t,s,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let s of Be(t))Ue.call(e,s)||undefined===s||Ne(e,s,{get:()=>t[s],enumerable:!(n=$e(t,s))||n.enumerable});return e})(!t&&e&&e.__esModule?s:Ne(s,"default",{value:e,enumerable:!0}),e)),je=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/stream.js"(e,t){var{Duplex:s}=Qe("stream");function n(e){e.emit("close")}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function r(e){this.removeListener("error",r),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}t.exports=function(e,t){let o=!0;const a=new s({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,s){const n=!s&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()}),e.once("error",function(e){a.destroyed||(o=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,s){if(e.readyState===e.CLOSED)return s(t),void process.nextTick(n,a);let i=!1;e.once("error",function(e){i=!0,s(e)}),e.once("close",function(){i||s(t),process.nextTick(n,a)}),o&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close())):e.once("open",function(){a._final(t)})},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,s,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",function(){a._write(t,s,n)})},a.on("end",i),a.on("error",r),a}}}),Fe=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/constants.js"(e,t){var s=["nodebuffer","arraybuffer","fragments"],n="undefined"!=typeof Blob;n&&s.push("blob"),t.exports={BINARY_TYPES:s,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:n,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}}}),Ge=De({"../common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js"(e,t){var s=Qe("fs"),n=Qe("path"),i=Qe("os"),r=Me,o=process.config&&process.config.variables||{},a=!!process.env.PREBUILDS_ONLY,c=process.versions.modules,h=process.versions&&process.versions.electron||process.env.ELECTRON_RUN_AS_NODE||"undefined"!=typeof window&&window.process&&"renderer"===window.process.type?"electron":process.versions&&process.versions.nw?"node-webkit":"node",u=process.env.npm_config_arch||i.arch(),l=process.env.npm_config_platform||i.platform(),d=process.env.LIBC||("linux"===l&&s.existsSync("/etc/alpine-release")?"musl":"glibc"),f=process.env.ARM_VERSION||("arm64"===u?"8":o.arm_version)||"",p=(process.versions.uv||"").split(".")[0];function g(e){return r(g.resolve(e))}function m(e){try{return s.readdirSync(e)}catch(e){return[]}}function y(e,t){var s=m(e).filter(t);return s[0]&&n.join(e,s[0])}function b(e){return/\.node$/.test(e)}function _(e){var t=e.split("-");if(2===t.length){var s=t[0],n=t[1].split("+");if(s&&n.length&&n.every(Boolean))return{name:e,platform:s,architectures:n}}}function v(e,t){return function(s){return null!=s&&s.platform===e&&s.architectures.includes(t)}}function w(e,t){return e.architectures.length-t.architectures.length}function S(e){var t=e.split("."),s={file:e,specificity:0};if("node"===t.pop()){for(var n=0;n<t.length;n++){var i=t[n];if("node"===i||"electron"===i||"node-webkit"===i)s.runtime=i;else if("napi"===i)s.napi=!0;else if("abi"===i.slice(0,3))s.abi=i.slice(3);else if("uv"===i.slice(0,2))s.uv=i.slice(2);else if("armv"===i.slice(0,4))s.armv=i.slice(4);else{if("glibc"!==i&&"musl"!==i)continue;s.libc=i}s.specificity++}return s}}function k(e,t){return function(s){return!(null==s||s.runtime&&s.runtime!==e&&!function(e){return"node"===e.runtime&&e.napi}(s)||s.abi&&s.abi!==t&&!s.napi||s.uv&&s.uv!==p||s.armv&&s.armv!==f||s.libc&&s.libc!==d)}}function T(e){return function(t,s){return t.runtime!==s.runtime?t.runtime===e?-1:1:t.abi!==s.abi?t.abi?-1:1:t.specificity!==s.specificity?t.specificity>s.specificity?-1:1:0}}t.exports=g,g.resolve=g.path=function(e){e=n.resolve(e||".");try{var t=r(n.join(e,"package.json")).name.toUpperCase().replace(/-/g,"_");process.env[t+"_PREBUILD"]&&(e=process.env[t+"_PREBUILD"])}catch(e){}if(!a){var s=y(n.join(e,"build/Release"),b);if(s)return s;var i=y(n.join(e,"build/Debug"),b);if(i)return i}var o=E(e);if(o)return o;var g=E(n.dirname(process.execPath));if(g)return g;var C=["platform="+l,"arch="+u,"runtime="+h,"abi="+c,"uv="+p,f?"armv="+f:"","libc="+d,"node="+process.versions.node,process.versions.electron?"electron="+process.versions.electron:"","webpack=true"].filter(Boolean).join(" ");throw new Error("No native build was found for "+C+"\n loaded from: "+e+"\n");function E(e){var t=m(n.join(e,"prebuilds")).map(_).filter(v(l,u)).sort(w)[0];if(t){var s=n.join(e,"prebuilds",t.name),i=m(s).map(S).filter(k(h,c)).sort(T(h))[0];return i?n.join(s,i.file):void 0}}},g.parseTags=S,g.matchTags=k,g.compareTags=T,g.parseTuple=_,g.matchTuple=v,g.compareTuples=w}}),ze=De({"../common/temp/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js"(e,t){var s=Me;"function"==typeof s.addon?t.exports=s.addon.bind(s):t.exports=Ge()}}),He=De({"../common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js"(e,t){t.exports={mask:(e,t,s,n,i)=>{for(var r=0;r<i;r++)s[n+r]=e[r]^t[3&r]},unmask:(e,t)=>{const s=e.length;for(var n=0;n<s;n++)e[n]^=t[3&n]}}}}),Ke=De({"../common/temp/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js"(e,t){try{t.exports=ze()(__dirname)}catch(e){t.exports=He()}}}),Je=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/buffer-util.js"(e,t){var{EMPTY_BUFFER:s}=Fe(),n=Buffer[Symbol.species];function i(e,t,s,n,i){for(let r=0;r<i;r++)s[n+r]=e[r]^t[3&r]}function r(e,t){for(let s=0;s<e.length;s++)e[s]^=t[3&s]}if(t.exports={concat:function(e,t){if(0===e.length)return s;if(1===e.length)return e[0];const i=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const s=e[t];i.set(s,r),r+=s.length}return r<t?new n(i.buffer,i.byteOffset,r):i},mask:i,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let s;return t instanceof ArrayBuffer?s=new n(t):ArrayBuffer.isView(t)?s=new n(t.buffer,t.byteOffset,t.byteLength):(s=Buffer.from(t),e.readOnly=!1),s},unmask:r},!process.env.WS_NO_BUFFER_UTIL)try{const e=Ke();t.exports.mask=function(t,s,n,r,o){o<48?i(t,s,n,r,o):e.mask(t,s,n,r,o)},t.exports.unmask=function(t,s){t.length<32?r(t,s):e.unmask(t,s)}}catch(e){}}}),Ye=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/limiter.js"(e,t){var s=Symbol("kDone"),n=Symbol("kRun");t.exports=class{constructor(e){this[s]=()=>{this.pending--,this[n]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[n]()}[n](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[s])}}}}}),Xe=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/permessage-deflate.js"(e,t){var s,n=Qe("zlib"),i=Je(),r=Ye(),{kStatusCode:o}=Fe(),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),h=Symbol("permessage-deflate"),u=Symbol("total-length"),l=Symbol("callback"),d=Symbol("buffers"),f=Symbol("error");function p(e){this[d].push(e),this[u]+=e.length}function g(e){this[u]+=e.length,this[h]._maxPayload<1||this[u]<=this[h]._maxPayload?this[d].push(e):(this[f]=new RangeError("Max payload size exceeded"),this[f].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[f][o]=1009,this.removeListener("data",g),this.reset())}function m(e){this[h]._inflate=null,e[o]=1007,this[l](e)}t.exports=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!s){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;s=new r(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[l];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,s=e.find(e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:!0!==s.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete s.client_max_window_bits,s}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let s=e[t];if(s.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==s)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}e[t]=s})}),e}decompress(e,t,n){s.add(s=>{this._decompress(e,t,(e,t)=>{s(),n(e,t)})})}compress(e,t,n){s.add(s=>{this._compress(e,t,(e,t)=>{s(),n(e,t)})})}_decompress(e,t,s){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[h]=this,this._inflate[u]=0,this._inflate[d]=[],this._inflate.on("error",m),this._inflate.on("data",g)}this._inflate[l]=s,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{const e=this._inflate[f];if(e)return this._inflate.close(),this._inflate=null,void s(e);const n=i.concat(this._inflate[d],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[d]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,n)})}_compress(e,t,s){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[d]=[],this._deflate.on("data",p)}this._deflate[l]=s,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[d],this._deflate[u]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[l]=null,this._deflate[u]=0,this._deflate[d]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,e)})}}}}),Ze=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/validation.js"(e,t){var{isUtf8:s}=Qe("buffer"),{hasBlob:n}=Fe();function i(e){const t=e.length;let s=0;for(;s<t;)if(128&e[s])if(192==(224&e[s])){if(s+1===t||128!=(192&e[s+1])||192==(254&e[s]))return!1;s+=2}else if(224==(240&e[s])){if(s+2>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||224===e[s]&&128==(224&e[s+1])||237===e[s]&&160==(224&e[s+1]))return!1;s+=3}else{if(240!=(248&e[s]))return!1;if(s+3>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||128!=(192&e[s+3])||240===e[s]&&128==(240&e[s+1])||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}else s++;return!0}if(t.exports={isBlob:function(e){return n&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:i,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},s)t.exports.isValidUTF8=function(e){return e.length<24?i(e):s(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=Qe("utf-8-validate");t.exports.isValidUTF8=function(t){return t.length<32?i(t):e(t)}}catch(e){}}}),et=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/receiver.js"(e,t){var{Writable:s}=Qe("stream"),n=Xe(),{BINARY_TYPES:i,EMPTY_BUFFER:r,kStatusCode:o,kWebSocket:a}=Fe(),{concat:c,toArrayBuffer:h,unmask:u}=Je(),{isValidStatusCode:l,isValidUTF8:d}=Ze(),f=Buffer[Symbol.species];t.exports=class extends s{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[a]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0],n=t.length-e;e>=s.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new f(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0])return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));const s=!(64&~t[0]);if(!s||this._extensions[n.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=s}else{if(!(this._opcode>7&&this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(s)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),s=t.readUInt32BE(0);s>Math.pow(2,21)-1?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=r;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&u(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[n.extensionName].decompress(e,this._fin,(e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(s)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?c(s,t):"arraybuffer"===this._binaryType?h(c(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)}))}else{const n=c(s,t);if(!this._skipUTF8Validation&&!d(n)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,r),this.end();else{const s=e.readUInt16BE(0);if(!l(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!d(n)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",s,n),this.end()}this._state=0}}createError(e,t,s,n,i){this._loop=!1,this._errored=!0;const r=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(r,this.createError),r.code=i,r[o]=n,r}}}}),tt=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/sender.js"(e,t){var s,{Duplex:n}=Qe("stream"),{randomFillSync:i}=Qe("crypto"),r=Xe(),{EMPTY_BUFFER:o,kWebSocket:a,NOOP:c}=Fe(),{isBlob:h,isValidStatusCode:u}=Ze(),{mask:l,toBuffer:d}=Je(),f=Symbol("kByteLength"),p=Buffer.alloc(4),g=8192,m=g;function y(e,t,s){"function"==typeof s&&s(t);for(let s=0;s<e._queue.length;s++){const n=e._queue[s],i=n[n.length-1];"function"==typeof i&&i(t)}}function b(e,t,s){y(e,t,s),e.onerror(t)}t.exports=class _Sender{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[a]=void 0}static frame(e,t){let n,r,o=!1,a=2,c=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(m===g&&(void 0===s&&(s=Buffer.alloc(g)),i(s,0,g),m=0),n[0]=s[m++],n[1]=s[m++],n[2]=s[m++],n[3]=s[m++]),c=0===(n[0]|n[1]|n[2]|n[3]),a=6),"string"==typeof e?r=t.mask&&!c||void 0===t[f]?(e=Buffer.from(e)).length:t[f]:(r=e.length,o=t.mask&&t.readOnly&&!c);let h=r;r>=65536?(a+=8,h=127):r>125&&(a+=2,h=126);const u=Buffer.allocUnsafe(o?r+a:a);return u[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(u[0]|=64),u[1]=h,126===h?u.writeUInt16BE(r,2):127===h&&(u[2]=u[3]=0,u.writeUIntBE(r,4,6)),t.mask?(u[1]|=128,u[a-4]=n[0],u[a-3]=n[1],u[a-2]=n[2],u[a-1]=n[3],c?[u,e]:o?(l(e,n,u,a,r),[u]):(l(e,n,e,0,r),[u,e])):[u,e]}close(e,t,s,n){let i;if(void 0===e)i=o;else{if("number"!=typeof e||!u(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const s=Buffer.byteLength(t);if(s>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+s),i.writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0)}const r={[f]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,r,n]):this.sendFrame(_Sender.frame(i,r),n)}ping(e,t,s){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):h(e)?(n=e.size,i=!1):(n=(e=d(e)).length,i=d.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const r={[f]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,r,s]):this.getBlobData(e,!1,r,s):0!==this._state?this.enqueue([this.dispatch,e,!1,r,s]):this.sendFrame(_Sender.frame(e,r),s)}pong(e,t,s){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):h(e)?(n=e.size,i=!1):(n=(e=d(e)).length,i=d.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const r={[f]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,r,s]):this.getBlobData(e,!1,r,s):0!==this._state?this.enqueue([this.dispatch,e,!1,r,s]):this.sendFrame(_Sender.frame(e,r),s)}send(e,t,s){const n=this._extensions[r.extensionName];let i,o,a=t.binary?2:1,c=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):h(e)?(i=e.size,o=!1):(i=(e=d(e)).length,o=d.readOnly),this._firstFragment?(this._firstFragment=!1,c&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(c=i>=n._threshold),this._compress=c):(c=!1,a=0),t.fin&&(this._firstFragment=!0);const u={[f]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:o,rsv1:c};h(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,s]):this.getBlobData(e,this._compress,u,s):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,s]):this.dispatch(e,this._compress,u,s)}getBlobData(e,t,s,n){this._bufferedBytes+=s[f],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(y,this,e,n)}this._bufferedBytes-=s[f];const i=d(e);t?this.dispatch(i,t,s,n):(this._state=0,this.sendFrame(_Sender.frame(i,s),n),this.dequeue())}).catch(e=>{process.nextTick(b,this,e,n)})}dispatch(e,t,s,n){if(!t)return void this.sendFrame(_Sender.frame(e,s),n);const i=this._extensions[r.extensionName];this._bufferedBytes+=s[f],this._state=1,i.compress(e,s.fin,(e,t)=>{this._socket.destroyed?y(this,new Error("The socket was closed while data was being compressed"),n):(this._bufferedBytes-=s[f],this._state=0,s.readOnly=!1,this.sendFrame(_Sender.frame(t,s),n),this.dequeue())})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}}}),st=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/event-target.js"(e,t){var{kForOnEventAttribute:s,kListener:n}=Fe(),i=Symbol("kCode"),r=Symbol("kData"),o=Symbol("kError"),a=Symbol("kMessage"),c=Symbol("kReason"),h=Symbol("kTarget"),u=Symbol("kType"),l=Symbol("kWasClean"),d=class{constructor(e){this[h]=null,this[u]=e}get target(){return this[h]}get type(){return this[u]}};Object.defineProperty(d.prototype,"target",{enumerable:!0}),Object.defineProperty(d.prototype,"type",{enumerable:!0});var f=class extends d{constructor(e,t={}){super(e),this[i]=void 0===t.code?0:t.code,this[c]=void 0===t.reason?"":t.reason,this[l]=void 0!==t.wasClean&&t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[l]}};Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});var p=class extends d{constructor(e,t={}){super(e),this[o]=void 0===t.error?null:t.error,this[a]=void 0===t.message?"":t.message}get error(){return this[o]}get message(){return this[a]}};Object.defineProperty(p.prototype,"error",{enumerable:!0}),Object.defineProperty(p.prototype,"message",{enumerable:!0});var g=class extends d{constructor(e,t={}){super(e),this[r]=void 0===t.data?null:t.data}get data(){return this[r]}};Object.defineProperty(g.prototype,"data",{enumerable:!0});var m={addEventListener(e,t,i={}){for(const r of this.listeners(e))if(!i[s]&&r[n]===t&&!r[s])return;let r;if("message"===e)r=function(e,s){const n=new g("message",{data:s?e:e.toString()});n[h]=this,y(t,this,n)};else if("close"===e)r=function(e,s){const n=new f("close",{code:e,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[h]=this,y(t,this,n)};else if("error"===e)r=function(e){const s=new p("error",{error:e,message:e.message});s[h]=this,y(t,this,s)};else{if("open"!==e)return;r=function(){const e=new d("open");e[h]=this,y(t,this,e)}}r[s]=!!i[s],r[n]=t,i.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const i of this.listeners(e))if(i[n]===t&&!i[s]){this.removeListener(e,i);break}}};function y(e,t,s){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,s):e.call(t,s)}t.exports={CloseEvent:f,ErrorEvent:p,Event:d,EventTarget:m,MessageEvent:g}}}),nt=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/extension.js"(e,t){var{tokenChars:s}=Ze();function n(e,t,s){void 0===e[t]?e[t]=[s]:e[t].push(s)}t.exports={format:function(e){return Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>[t].concat(Object.keys(e).map(t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){const t=Object.create(null);let i,r,o=Object.create(null),a=!1,c=!1,h=!1,u=-1,l=-1,d=-1,f=0;for(;f<e.length;f++)if(l=e.charCodeAt(f),void 0===i)if(-1===d&&1===s[l])-1===u&&(u=f);else if(0===f||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f);const s=e.slice(u,d);44===l?(n(t,s,o),o=Object.create(null)):i=s,u=d=-1}}else-1===d&&-1!==u&&(d=f);else if(void 0===r)if(-1===d&&1===s[l])-1===u&&(u=f);else if(32===l||9===l)-1===d&&-1!==u&&(d=f);else if(59===l||44===l){if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f),n(o,e.slice(u,d),!0),44===l&&(n(t,i,o),o=Object.create(null),i=void 0),u=d=-1}else{if(61!==l||-1===u||-1!==d)throw new SyntaxError(`Unexpected character at index ${f}`);r=e.slice(u,f),u=d=-1}else if(c){if(1!==s[l])throw new SyntaxError(`Unexpected character at index ${f}`);-1===u?u=f:a||(a=!0),c=!1}else if(h)if(1===s[l])-1===u&&(u=f);else if(34===l&&-1!==u)h=!1,d=f;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${f}`);c=!0}else if(34===l&&61===e.charCodeAt(f-1))h=!0;else if(-1===d&&1===s[l])-1===u&&(u=f);else if(-1===u||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${f}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${f}`);-1===d&&(d=f);let s=e.slice(u,d);a&&(s=s.replace(/\\/g,""),a=!1),n(o,r,s),44===l&&(n(t,i,o),o=Object.create(null),i=void 0),r=void 0,u=d=-1}}else-1===d&&(d=f);if(-1===u||h||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===d&&(d=f);const p=e.slice(u,d);return void 0===i?n(t,p,o):(void 0===r?n(o,p,!0):n(o,r,a?p.replace(/\\/g,""):p),n(t,i,o)),t}}}}),it=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/websocket.js"(e,t){var s=Qe("events"),n=Qe("https"),i=Qe("http"),r=Qe("net"),o=Qe("tls"),{randomBytes:a,createHash:c}=Qe("crypto"),{Duplex:h,Readable:u}=Qe("stream"),{URL:l}=Qe("url"),d=Xe(),f=et(),p=tt(),{isBlob:g}=Ze(),{BINARY_TYPES:m,EMPTY_BUFFER:y,GUID:b,kForOnEventAttribute:_,kListener:v,kStatusCode:w,kWebSocket:S,NOOP:k}=Fe(),{EventTarget:{addEventListener:T,removeEventListener:C}}=st(),{format:E,parse:x}=nt(),{toBuffer:R}=Je(),O=Symbol("kAborted"),L=[8,13],I=["CONNECTING","OPEN","CLOSING","CLOSED"],A=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,P=class _WebSocket extends s{constructor(e,t,s){super(),this._binaryType=m[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=_WebSocket.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(s=t,t=[]):t=[t]),M(this,e,t,s)):(this._autoPong=s.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){m.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,s){const n=new f({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new p(e,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[S]=this,i[S]=this,e[S]=this,n.on("conclude",U),n.on("drain",Q),n.on("error",D),n.on("message",j),n.on("ping",F),n.on("pong",G),i.onerror=H,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",J),e.on("data",Y),e.on("end",X),e.on("error",Z),this._readyState=_WebSocket.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=_WebSocket.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[d.extensionName]&&this._extensions[d.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=_WebSocket.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return void B(this,this._req,e)}this.readyState!==_WebSocket.CLOSING?(this._readyState=_WebSocket.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),K(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==_WebSocket.CONNECTING&&this.readyState!==_WebSocket.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===_WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||y,t,s)):V(this,e,s)}pong(e,t,s){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===_WebSocket.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||y,t,s)):V(this,e,s)}resume(){this.readyState!==_WebSocket.CONNECTING&&this.readyState!==_WebSocket.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===_WebSocket.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==_WebSocket.OPEN)return void V(this,e,s);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[d.extensionName]||(n.compress=!1),this._sender.send(e||y,n,s)}terminate(){if(this.readyState!==_WebSocket.CLOSED){if(this.readyState===_WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return void B(this,this._req,e)}this._socket&&(this._readyState=_WebSocket.CLOSING,this._socket.destroy())}}};function M(e,t,s,r){const o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:L[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!L.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${L.join(", ")})`);let h;if(t instanceof l)h=t;else try{h=new l(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===h.protocol?h.protocol="ws:":"https:"===h.protocol&&(h.protocol="wss:"),e._url=h.href;const u="wss:"===h.protocol,f="ws+unix:"===h.protocol;let p;if("ws:"===h.protocol||u||f?f&&!h.pathname?p="The URL's pathname is empty":h.hash&&(p="The URL contains a fragment identifier"):p='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',p){const t=new SyntaxError(p);if(0===e._redirects)throw t;return void q(e,t)}const g=u?443:80,m=a(16).toString("base64"),y=u?n.request:i.request,_=new Set;let v,w;if(o.createConnection=o.createConnection||(u?$:N),o.defaultPort=o.defaultPort||g,o.port=h.port||g,o.host=h.hostname.startsWith("[")?h.hostname.slice(1,-1):h.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},o.path=h.pathname+h.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(v=new d(!0!==o.perMessageDeflate?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=E({[d.extensionName]:v.offer()})),s.length){for(const e of s){if("string"!=typeof e||!A.test(e)||_.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");_.add(e)}o.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(h.username||h.password)&&(o.auth=`${h.username}:${h.password}`),f){const e=o.path.split(":");o.socketPath=e[0],o.path=e[1]}if(o.followRedirects){if(0===e._redirects){e._originalIpc=f,e._originalSecure=u,e._originalHostOrSocketPath=f?o.socketPath:h.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,s]of Object.entries(t))r.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=f?!!e._originalIpc&&o.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&h.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),w=e._req=y(o),e._redirects&&e.emit("redirect",e.url,w)}else w=e._req=y(o);o.timeout&&w.on("timeout",()=>{B(e,w,"Opening handshake has timed out")}),w.on("error",t=>{null===w||w[O]||(w=e._req=null,q(e,t))}),w.on("response",n=>{const i=n.headers.location,a=n.statusCode;if(i&&o.followRedirects&&a>=300&&a<400){if(++e._redirects>o.maxRedirects)return void B(e,w,"Maximum redirects exceeded");let n;w.abort();try{n=new l(i,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${i}`);return void q(e,s)}M(e,n,s,r)}else e.emit("unexpected-response",w,n)||B(e,w,`Unexpected server response: ${n.statusCode}`)}),w.on("upgrade",(t,s,n)=>{if(e.emit("upgrade",t),e.readyState!==P.CONNECTING)return;w=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void B(e,s,"Invalid Upgrade header");const r=c("sha1").update(m+b).digest("base64");if(t.headers["sec-websocket-accept"]!==r)return void B(e,s,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let h;if(void 0!==a?_.size?_.has(a)||(h="Server sent an invalid subprotocol"):h="Server sent a subprotocol but none was requested":_.size&&(h="Server sent no subprotocol"),h)return void B(e,s,h);a&&(e._protocol=a);const u=t.headers["sec-websocket-extensions"];if(void 0!==u){if(!v)return void B(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let t;try{t=x(u)}catch(t){return void B(e,s,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==d.extensionName)return void B(e,s,"Server indicated an extension that was not requested");try{v.accept(t[d.extensionName])}catch(t){return void B(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[d.extensionName]=v}e.setSocket(s,n,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(w,e):w.end()}function q(e,t){e._readyState=P.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function N(e){return e.path=e.socketPath,r.connect(e)}function $(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=r.isIP(e.host)?"":e.host),o.connect(e)}function B(e,t,s){e._readyState=P.CLOSING;const n=new Error(s);Error.captureStackTrace(n,B),t.setHeader?(t[O]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(q,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function V(e,t,s){if(t){const s=g(t)?t.size:R(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${I[e.readyState]})`);process.nextTick(s,t)}}function U(e,t){const s=this[S];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[S]&&(s._socket.removeListener("data",Y),process.nextTick(z,s._socket),1005===e?s.close():s.close(e,t))}function Q(){const e=this[S];e.isPaused||e._socket.resume()}function D(e){const t=this[S];void 0!==t._socket[S]&&(t._socket.removeListener("data",Y),process.nextTick(z,t._socket),t.close(e[w])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function W(){this[S].emitClose()}function j(e,t){this[S].emit("message",e,t)}function F(e){const t=this[S];t._autoPong&&t.pong(e,!this._isServer,k),t.emit("ping",e)}function G(e){this[S].emit("pong",e)}function z(e){e.resume()}function H(e){const t=this[S];t.readyState!==P.CLOSED&&(t.readyState===P.OPEN&&(t._readyState=P.CLOSING,K(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function K(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function J(){const e=this[S];let t;this.removeListener("close",J),this.removeListener("data",Y),this.removeListener("end",X),e._readyState=P.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",W),e._receiver.on("finish",W))}function Y(e){this[S]._receiver.write(e)||this.pause()}function X(){const e=this[S];e._readyState=P.CLOSING,e._receiver.end(),this.end()}function Z(){const e=this[S];this.removeListener("error",Z),this.on("error",k),e&&(e._readyState=P.CLOSING,this.destroy())}Object.defineProperty(P,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")}),Object.defineProperty(P.prototype,"CONNECTING",{enumerable:!0,value:I.indexOf("CONNECTING")}),Object.defineProperty(P,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")}),Object.defineProperty(P.prototype,"OPEN",{enumerable:!0,value:I.indexOf("OPEN")}),Object.defineProperty(P,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")}),Object.defineProperty(P.prototype,"CLOSING",{enumerable:!0,value:I.indexOf("CLOSING")}),Object.defineProperty(P,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")}),Object.defineProperty(P.prototype,"CLOSED",{enumerable:!0,value:I.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(P.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(P.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[_])return t[v];return null},set(t){for(const t of this.listeners(e))if(t[_]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[_]:!0})}})}),P.prototype.addEventListener=T,P.prototype.removeEventListener=C,t.exports=P}}),rt=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/subprotocol.js"(e,t){var{tokenChars:s}=Ze();t.exports={parse:function(e){const t=new Set;let n=-1,i=-1,r=0;for(;r<e.length;r++){const o=e.charCodeAt(r);if(-1===i&&1===s[o])-1===n&&(n=r);else if(0===r||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${r}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${r}`);-1===i&&(i=r);const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=i=-1}}else-1===i&&-1!==n&&(i=r)}if(-1===n||-1!==i)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}}}}),ot=De({"../common/temp/node_modules/.pnpm/ws@8.18.0_bufferutil@4.0.9/node_modules/ws/lib/websocket-server.js"(e,t){var s=Qe("events"),n=Qe("http"),{Duplex:i}=Qe("stream"),{createHash:r}=Qe("crypto"),o=nt(),a=Xe(),c=rt(),h=it(),{GUID:u,kWebSocket:l}=Fe(),d=/^[+/0-9A-Za-z]{22}==$/;function f(e){e._state=2,e.emit("close")}function p(){this.destroy()}function g(e,t,s,i){s=s||n.STATUS_CODES[t],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...i},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${n.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join("\r\n")+"\r\n\r\n"+s)}function m(e,t,s,n,i){if(e.listenerCount("wsClientError")){const n=new Error(i);Error.captureStackTrace(n,m),e.emit("wsClientError",n,s,t)}else g(s,n,i)}t.exports=class extends s{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:h,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=n.createServer((e,t)=>{const s=n.STATUS_CODES[426];t.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),t.end(s)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const s of Object.keys(t))e.on(s,t[s]);return function(){for(const s of Object.keys(t))e.removeListener(s,t[s])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,s,n)=>{this.handleUpgrade(t,s,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",()=>{e(new Error("The server is not running"))}),void process.nextTick(f,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(f,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{f(this)})}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,n){t.on("error",p);const i=e.headers["sec-websocket-key"],r=e.headers.upgrade,h=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void m(this,e,t,405,"Invalid HTTP method");if(void 0===r||"websocket"!==r.toLowerCase())return void m(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!d.test(i))return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==h&&13!==h)return void m(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void g(t,400);const u=e.headers["sec-websocket-protocol"];let l=new Set;if(void 0!==u)try{l=c.parse(u)}catch(s){return void m(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const f=e.headers["sec-websocket-extensions"],y={};if(this.options.perMessageDeflate&&void 0!==f){const s=new a(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=o.parse(f);e[a.extensionName]&&(s.accept(e[a.extensionName]),y[a.extensionName]=s)}catch(s){return void m(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const r={origin:e.headers[8===h?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(r,(r,o,a,c)=>{if(!r)return g(t,o||401,a,c);this.completeUpgrade(y,i,l,e,t,s,n)});if(!this.options.verifyClient(r))return g(t,401)}this.completeUpgrade(y,i,l,e,t,s,n)}completeUpgrade(e,t,s,n,i,c,h){if(!i.readable||!i.writable)return i.destroy();if(i[l])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return g(i,503);const d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${r("sha1").update(t+u).digest("base64")}`],m=new this.options.WebSocket(null,void 0,this.options);if(s.size){const e=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;e&&(d.push(`Sec-WebSocket-Protocol: ${e}`),m._protocol=e)}if(e[a.extensionName]){const t=e[a.extensionName].params,s=o.format({[a.extensionName]:[t]});d.push(`Sec-WebSocket-Extensions: ${s}`),m._extensions=e}this.emit("headers",d,n),i.write(d.concat("\r\n").join("\r\n")),i.removeListener("error",p),m.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(m),m.on("close",()=>{this.clients.delete(m),this._shouldEmitClose&&!this.clients.size&&process.nextTick(f,this)})),h(m,n)}}}}),at=(We(je(),1),We(et(),1),We(tt(),1),We(it(),1)),ct=(We(ot(),1),at.default);Pe=ct}};
@@ -0,0 +1 @@
1
+ "use strict";(this.webpackChunkCocolightApiClient=this.webpackChunkCocolightApiClient||[]).push([[278],{2278:(s,t,i)=>{i.d(t,{ConvexReactivityBridge:()=>ConvexReactivityBridge});var r=i(2188);class ConvexReactivityBridge{_transport;_normalizer;_subscriptions=new Map;constructor(s,t){this._transport=s,this._normalizer=t}async subscribe(s,t,i){if(!this._transport.subscribe)throw new Error("Le transport ne supporte pas les subscriptions. Utilisez un TransportAdapter avec subscribe() (ex: ConvexTransportAdapter).");const e=await this._transport.subscribe(s,t,s=>{try{(0,r.batch)(()=>{const t=this._normalizer.normalizeEntity(s);i(t)})}catch(s){console.error("[ConvexReactivityBridge] Erreur dans le callback real-time :",s)}}),n=`${s}:${JSON.stringify(t)}`;return this._subscriptions.has(n)&&this._subscriptions.get(n)(),this._subscriptions.set(n,e),()=>{e(),this._subscriptions.delete(n)}}disposeAll(){for(const s of this._subscriptions.values())s();this._subscriptions.clear()}get activeSubscriptionCount(){return this._subscriptions.size}}}}]);
@@ -0,0 +1 @@
1
+ "use strict";exports.id=278,exports.ids=[278],exports.modules={278:(s,t,r)=>{r.d(t,{ConvexReactivityBridge:()=>ConvexReactivityBridge});var i=r(188);class ConvexReactivityBridge{_transport;_normalizer;_subscriptions=new Map;constructor(s,t){this._transport=s,this._normalizer=t}async subscribe(s,t,r){if(!this._transport.subscribe)throw new Error("Le transport ne supporte pas les subscriptions. Utilisez un TransportAdapter avec subscribe() (ex: ConvexTransportAdapter).");const e=await this._transport.subscribe(s,t,s=>{try{(0,i.batch)(()=>{const t=this._normalizer.normalizeEntity(s);r(t)})}catch(s){console.error("[ConvexReactivityBridge] Erreur dans le callback real-time :",s)}}),o=`${s}:${JSON.stringify(t)}`;return this._subscriptions.has(o)&&this._subscriptions.get(o)(),this._subscriptions.set(o,e),()=>{e(),this._subscriptions.delete(o)}}disposeAll(){for(const s of this._subscriptions.values())s();this._subscriptions.clear()}get activeSubscriptionCount(){return this._subscriptions.size}}}};
@@ -0,0 +1 @@
1
+ export const __webpack_esm_id__=278;export const __webpack_esm_ids__=[278];export const __webpack_esm_modules__={278:(s,t,r)=>{r.d(t,{ConvexReactivityBridge:()=>ConvexReactivityBridge});var i=r(188);class ConvexReactivityBridge{_transport;_normalizer;_subscriptions=new Map;constructor(s,t){this._transport=s,this._normalizer=t}async subscribe(s,t,r){if(!this._transport.subscribe)throw new Error("Le transport ne supporte pas les subscriptions. Utilisez un TransportAdapter avec subscribe() (ex: ConvexTransportAdapter).");const e=await this._transport.subscribe(s,t,s=>{try{(0,i.batch)(()=>{const t=this._normalizer.normalizeEntity(s);r(t)})}catch(s){console.error("[ConvexReactivityBridge] Erreur dans le callback real-time :",s)}}),o=`${s}:${JSON.stringify(t)}`;return this._subscriptions.has(o)&&this._subscriptions.get(o)(),this._subscriptions.set(o,e),()=>{e(),this._subscriptions.delete(o)}}disposeAll(){for(const s of this._subscriptions.values())s();this._subscriptions.clear()}get activeSubscriptionCount(){return this._subscriptions.size}}}};
@@ -1 +1 @@
1
- export const __webpack_id__=401;export const __webpack_ids__=[401];export const __webpack_modules__={401:(e,o,n)=>{async function s(e){const{Readable:o}=await Promise.resolve().then(n.bind(n,702));return o.from(e)}async function t(){const{PassThrough:e}=await Promise.resolve().then(n.bind(n,702));return new e}n.d(o,{bufferToReadable:()=>s,createPassThrough:()=>t})}};
1
+ export const __webpack_esm_id__=401;export const __webpack_esm_ids__=[401];export const __webpack_esm_modules__={401:(e,s,o)=>{async function n(e){const{Readable:s}=await Promise.resolve().then(o.bind(o,702));return s.from(e)}async function _(){const{PassThrough:e}=await Promise.resolve().then(o.bind(o,702));return new e}o.d(s,{bufferToReadable:()=>n,createPassThrough:()=>_})}};
@@ -0,0 +1 @@
1
+ "use strict";(this.webpackChunkCocolightApiClient=this.webpackChunkCocolightApiClient||[]).push([[407],{3407:(e,t,s)=>{s.d(t,{s:()=>BaseConvexClient,ConvexClient:()=>ConvexClient});const n="1.32.0";for(var i=[],r=[],o=Uint8Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0;u<64;++u)i[u]=a[u],r[a.charCodeAt(u)]=u;function c(e){var t,s,n=function(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}(e),i=n[0],a=n[1],u=new o(function(e,t,s){return 3*(t+s)/4-s}(0,i,a)),c=0,h=a>0?i-4:i;for(s=0;s<h;s+=4)t=r[e.charCodeAt(s)]<<18|r[e.charCodeAt(s+1)]<<12|r[e.charCodeAt(s+2)]<<6|r[e.charCodeAt(s+3)],u[c++]=t>>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===a&&(t=r[e.charCodeAt(s)]<<2|r[e.charCodeAt(s+1)]>>4,u[c++]=255&t),1===a&&(t=r[e.charCodeAt(s)]<<10|r[e.charCodeAt(s+1)]<<4|r[e.charCodeAt(s+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u}function h(e){return i[e>>18&63]+i[e>>12&63]+i[e>>6&63]+i[63&e]}function l(e,t,s){for(var n,i=[],r=t;r<s;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),i.push(h(n));return i.join("")}function d(e){for(var t,s=e.length,n=s%3,r=[],o=16383,a=0,u=s-n;a<u;a+=o)r.push(l(e,a,a+o>u?u:a+o));return 1===n?(t=e[s-1],r.push(i[t>>2]+i[t<<4&63]+"==")):2===n&&(t=(e[s-2]<<8)+e[s-1],r.push(i[t>>10]+i[t>>4&63]+i[t<<2&63]+"=")),r.join("")}function g(e){if(void 0===e)return{};if(!y(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function f(e){if(void 0===e)throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof e)throw new Error(`Invalid deployment address: found ${e}".`);if(!e.startsWith("http:")&&!e.startsWith("https:"))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw new 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 new 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 y(e){const t="object"==typeof e,s=Object.getPrototypeOf(e),n=null===s||s===Object.prototype||"Object"===s?.constructor?.name;return t&&n}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63;const p=!0,m=BigInt("-9223372036854775808"),b=BigInt("9223372036854775807"),v=BigInt("0"),w=BigInt("8"),k=BigInt("256");function S(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}const C=DataView.prototype.setBigInt64?function(e){if(e<m||b<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);const t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),d(new Uint8Array(t))}:function(e){e<v&&(e-=m+m);let t=e.toString(16);t.length%2==1&&(t="0"+t);const s=new Uint8Array(new ArrayBuffer(8));let n=0;for(const i of t.match(/.{2}/g).reverse())s.set([parseInt(i,16)],n++),e>>=w;return d(s)},T=DataView.prototype.getBigInt64?function(e){const t=c(e);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){const t=c(e);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=v,n=v;for(const e of t)s+=BigInt(e)*k**n,n++;return s>b&&(s+=m+m),s};function R(e){if(e.length>1024)throw new Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw new Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){const s=e.charCodeAt(t);if(s<32||s>=127)throw new Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function q(e){if(null===e)return e;if("boolean"==typeof e)return e;if("number"==typeof e)return e;if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>q(e));if("object"!=typeof e)throw new Error(`Unexpected type of ${e}`);const t=Object.entries(e);if(1===t.length){const s=t[0][0];if("$bytes"===s){if("string"!=typeof e.$bytes)throw new Error(`Malformed $bytes field on ${e}`);return c(e.$bytes).buffer}if("$integer"===s){if("string"!=typeof e.$integer)throw new Error(`Malformed $integer field on ${e}`);return T(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw new Error(`Malformed $float field on ${e}`);const t=c(e.$float);if(8!==t.byteLength)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $float`);const s=new DataView(t.buffer).getFloat64(0,p);if(!S(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if("$set"===s)throw new Error("Received a Set which is no longer supported as a Convex type.");if("$map"===s)throw new Error("Received a Map which is no longer supported as a Convex type.")}const s={};for(const[t,n]of Object.entries(e))R(t),s[t]=q(n);return s}function A(e){const t=JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t);if(t.length>16384){const e="[...truncated]";let s=16384-e.length;const n=t.codePointAt(s-1);return void 0!==n&&n>65535&&(s-=1),t.substring(0,s)+e}return t}function M(e,t,s,n){if(void 0===e){const e=s&&` (present at path ${s} in original object ${A(t)})`;throw new 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<m||b<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:C(e)}}if("number"==typeof e){if(S(e)){const t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,p),{$float:d(new Uint8Array(t))}}return e}if("boolean"==typeof e)return e;if("string"==typeof e)return e;if(e instanceof ArrayBuffer)return{$bytes:d(new Uint8Array(e))};if(Array.isArray(e))return e.map((e,n)=>M(e,t,s+`[${n}]`,!1));if(e instanceof Set)throw new Error(I(s,"Set",[...e],t));if(e instanceof Map)throw new Error(I(s,"Map",[...e],t));if(!y(e)){const n=e?.constructor?.name;throw new Error(I(s,n?`${n} `:"",e,t))}const i={},r=Object.entries(e);r.sort(([e,t],[s,n])=>e===s?0:e<s?-1:1);for(const[e,o]of r)void 0!==o?(R(e),i[e]=M(o,t,s+`.${e}`,!1)):n&&(R(e),i[e]=O(o,t,s+`.${e}`));return i}function I(e,t,s,n){return e?`${t}${A(s)} is not a supported Convex type (present at path ${e} in original object ${A(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${A(s)} is not a supported Convex type.`}function O(e,t,s){if(void 0===e)return{$undefined:null};if(void 0===t)throw new Error(`Programming error. Current value is ${A(e)} but original value is undefined`);return M(e,t,s,!1)}function Q(e){return M(e,e,"",!1)}Object.defineProperty;var L,x,E=Object.defineProperty,$=(e,t,s)=>((e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const V=Symbol.for("ConvexError");class errors_ConvexError extends(x=Error,L=V,x){constructor(e){super("string"==typeof e?e:A(e)),$(this,"name","ConvexError"),$(this,"data"),$(this,L,!0),this.data=e}}const P=()=>Array.from({length:4},()=>0);P(),P();var _=Object.defineProperty,N=(e,t,s)=>((e,t,s)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function B(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class DefaultLogger{constructor(e){N(this,"_onLogLineFuncs"),N(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(const t of Object.values(this._onLogLineFuncs))t("debug",`${(new Date).toISOString()}`,...e)}log(...e){for(const t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(const t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(const t of Object.values(this._onLogLineFuncs))t("error",...e)}}function F(e,t,s,n,i){const r=B(s);if("object"==typeof i&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),"info"===t){const t=i.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${n})] Could not parse console.log`);const 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 D(e,t,s){return`[CONVEX ${B(e)}(${t})] ${s.errorMessage}\n Called by client`}function U(e,t){return t.data=e.errorData,t}function j(e){const t=e.split(":");let s,n;return 1===t.length?(s=t[0],n="default"):(s=t.slice(0,t.length-1).join(":"),n=t[t.length-1]),s.endsWith(".js")&&(s=s.slice(0,-3)),`${s}:${n}`}function W(e,t){return JSON.stringify({udfPath:j(e),args:Q(t)})}function K(e,t,s){const{initialNumItems:n,id:i}=s;return JSON.stringify({type:"paginated",udfPath:j(e),args:Q(t),options:Q({initialNumItems:n,id:i})})}function J(e){return"paginated"===JSON.parse(e).type}var H=Object.defineProperty,z=(e,t,s)=>((e,t,s)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class LocalSyncState{constructor(){z(this,"nextQueryId"),z(this,"querySetVersion"),z(this,"querySet"),z(this,"queryIdToToken"),z(this,"identityVersion"),z(this,"auth"),z(this,"outstandingQueriesOlderThanRestart"),z(this,"outstandingAuthOlderThanRestart"),z(this,"paused"),z(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){const i=j(e),r=W(i,t),o=this.querySet.get(r);if(void 0!==o)return o.numSubscribers+=1,{queryToken:r,modification:null,unsubscribe:()=>this.removeSubscriber(r)};{const e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:s,componentPath:n};this.querySet.set(r,o),this.queryIdToToken.set(e,r);const a=this.querySetVersion,u=this.querySetVersion+1,c={type:"Add",queryId:e,udfPath:i,args:[Q(t)],journal:s,componentPath:n};return this.paused?this.pendingQuerySetModifications.set(e,c):this.querySetVersion=u,{queryToken:r,modification:{type:"ModifyQuerySet",baseVersion:a,newVersion:u,modifications:[c]},unsubscribe:()=>this.removeSubscriber(r)}}}transition(e){for(const t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);const e=t.journal;if(void 0!==e){const 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 new Error(`Invalid modification ${t.type}`)}}queryId(e,t){const s=W(j(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};const t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){const s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const 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){const t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){const t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const t=[];for(const s of this.querySet.values()){const n={type:"Add",queryId:s.id,udfPath:s.canonicalizedUdfPath,args:[Q(s.args)],journal:s.journal,componentPath:s.componentPath};t.push(n),e.has(s.id)||this.outstandingQueriesOlderThanRestart.add(s.id)}this.querySetVersion=1;const s={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:t};if(!this.auth)return this.identityVersion=0,[s,void 0];this.outstandingAuthOlderThanRestart=!0;const n={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[s,n]}pause(){this.paused=!0}resume(){const 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){const 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);const 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 G=Object.defineProperty,X=(e,t,s)=>((e,t,s)=>t in e?G(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class RequestManager{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,X(this,"inflightRequests"),X(this,"requestsOlderThanRestart"),X(this,"inflightMutationsCount",0),X(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){const s=new Promise(s=>{const n=t?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:n,requestedAt:new Date,onResult:s}}),"Mutation"===e.type?this.inflightMutationsCount++:"Action"===e.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),s}onResponse(e){const t=this.inflightRequests.get(e.requestId);if(void 0===t)return null;if("Completed"===t.status.status)return null;const s="Mutation"===t.message.type?"mutation":"action",n=t.message.udfPath;for(const t of e.logLines)F(this.logger,"info",s,n,t);const i=t.status;let r,o;if(e.success)r={success:!0,logLines:e.logLines,value:q(e.result)},o=()=>i.onResult(r);else{const t=e.result,{errorData:a}=e;F(this.logger,"error",s,n,t),r={success:!1,errorMessage:t,errorData:void 0!==a?q(a):void 0,logLines:e.logLines},o=()=>i.onResult(r)}return"ActionResponse"!==e.type&&e.success?(t.status={status:"Completed",result:r,ts:e.ts,onResolve:o},null):(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===t.message.type?this.inflightActionsCount--:"Mutation"===t.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:r})}removeCompleted(e){const t=new Map;for(const[s,n]of this.inflightRequests.entries()){const 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());const e=[];for(const[t,s]of this.inflightRequests)if("NotSent"!==s.status.status){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 new Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}else s.status.status="Requested",e.push(s.message);return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,t]of this.inflightRequests)"NotSent"!==t.status.status||(t.status.status="Requested",e.push(t.message));return e}hasIncompleteRequests(){for(const 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(const 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}}const Y=Symbol.for("functionName"),Z=Symbol.for("toReferencePath");function ee(e){const t=function(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[Y])t={name:e[Y]};else{const s=e[Z]??null;if(!s)throw new Error(`${e} is not a functionReference`);t={reference:s}}return t}(e);if(void 0===t.name){if(void 0!==t.functionHandle)throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(void 0!==t.reference)throw new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`);throw new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`)}if("string"==typeof e)return e;const s=e[Y];if(!s)throw new Error(`${e} is not a functionReference`);return s}!function e(t=[]){return new Proxy({},{get(s,n){if("string"==typeof n)return e([...t,n]);if(n===Y){if(t.length<2){const e=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${e}\``)}const 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 te=Object.defineProperty,se=(e,t,s)=>((e,t,s)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class OptimisticLocalStoreImpl{constructor(e){se(this,"queryResults"),se(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){const s=g(t[0]),n=ee(e),i=this.queryResults.get(W(n,s));if(void 0!==i)return OptimisticLocalStoreImpl.queryValue(i.result)}getAllQueries(e){const t=[],s=ee(e);for(const e of this.queryResults.values())e.udfPath===j(s)&&t.push({args:e.args,value:OptimisticLocalStoreImpl.queryValue(e.result)});return t}setQuery(e,t,s){const n=g(t),i=ee(e),r=W(i,n);let o;o=void 0===s?void 0:{success:!0,value:s,logLines:[]};const a={udfPath:i,args:n,result:o};this.queryResults.set(r,a),this.modifiedQueries.push(r)}static queryValue(e){return void 0===e?void 0:e.success?e.value:void 0}}class OptimisticQueryResults{constructor(){se(this,"queryResults"),se(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));const s=this.queryResults;this.queryResults=new Map(e);const n=new OptimisticLocalStoreImpl(this.queryResults);for(const e of this.optimisticUpdates)e.update(n);const i=[];for(const[e,t]of this.queryResults){const 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});const s=new OptimisticLocalStoreImpl(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){const t=this.queryResults.get(e);if(void 0!==t)return t.result}queryResult(e){const t=this.queryResults.get(e);if(void 0===t)return;const s=t.result;if(void 0!==s){if(s.success)return s.value;if(void 0!==s.errorData)throw U(s,new errors_ConvexError(D("query",t.udfPath,s)));throw new Error(D("query",t.udfPath,s))}}hasQueryResult(e){return void 0!==this.queryResults.get(e)}queryLogs(e){const t=this.queryResults.get(e);return t?.result?.logLines}}var ne=Object.defineProperty,ie=(e,t,s)=>((e,t,s)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class Long{constructor(e,t){ie(this,"low"),ie(this,"high"),ie(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 Long(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const 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?re:e>=ae?ue:new Long(e%oe|0,e/oe|0)}toString(){return(BigInt(this.high)*BigInt(oe)+BigInt(this.low)).toString()}equals(e){return Long.isLong(e)||(e=Long.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 Long.isLong(e)||(e=Long.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 this.comp(e)<=0}static fromValue(e){return"number"==typeof e?Long.fromNumber(e):new Long(e.low,e.high)}}const re=new Long(0,0),oe=4294967296,ae=oe*oe,ue=new Long(-1,-1);var ce=Object.defineProperty,he=(e,t,s)=>((e,t,s)=>t in e?ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class RemoteQuerySet{constructor(e,t){he(this,"version"),he(this,"remoteQuerySet"),he(this,"queryPath"),he(this,"logger"),this.version={querySet:0,ts:Long.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){const t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw new Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const t of e.modifications)switch(t.type){case"QueryUpdated":{const e=this.queryPath(t.queryId);if(e)for(const s of t.logLines)F(this.logger,"info","query",e,s);const s=q(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:s,logLines:t.logLines});break}case"QueryFailed":{const e=this.queryPath(t.queryId);if(e)for(const s of t.logLines)F(this.logger,"info","query",e,s);const{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 new Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function le(e){const t=c(e);return Long.fromBytesLE(Array.from(t))}function de(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":return e.success?{...e,ts:le(e.ts)}:{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:le(e.startVersion.ts)},endVersion:{...e.endVersion,ts:le(e.endVersion.ts)}}}}var ge=Object.defineProperty,fe=(e,t,s)=>((e,t,s)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);let ye;function pe(){return void 0===ye&&(ye=Date.now()),"undefined"!=typeof performance&&performance.now?Math.round(ye+performance.now()):Date.now()}function me(){return`t=${Math.round((pe()-ye)/100)/10}s`}const be={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 WebSocketManager{constructor(e,t,s,n,i,r){this.markConnectionStateDirty=i,this.debug=r,fe(this,"socket"),fe(this,"connectionCount"),fe(this,"_hasEverConnected",!1),fe(this,"lastCloseReason"),fe(this,"transitionChunkBuffer",null),fe(this,"defaultInitialBackoff"),fe(this,"maxBackoff"),fe(this,"retries"),fe(this,"serverInactivityThreshold"),fe(this,"reconnectDueToServerInactivityTimeout"),fe(this,"scheduledReconnect",null),fe(this,"networkOnlineHandler",null),fe(this,"pendingNetworkRecoveryInfo",null),fe(this,"uri"),fe(this,"onOpen"),fe(this,"onResume"),fe(this,"onMessage"),fe(this,"webSocketConstructor"),fe(this,"logger"),fe(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(){"undefined"!=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&&"undefined"!=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,new Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new 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){const e=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const t=de(JSON.parse(e));if("Transition"!==t.type)throw new 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 new Error("Didn't start connection from disconnected state: "+this.socket.state);const 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 new 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:pe()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",me(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",me())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){const{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;const t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();const t=e.data.length;let s=de(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${s.type}`),"Ping"!==s.type){if("TransitionChunk"===s.type){const 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)}const t=function(e){if(void 0===e)return"Unknown";for(const t of Object.keys(be))if(e.startsWith(t))return t;return"Unknown"}(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){const t={type:e.type,..."Authenticate"===e.type&&"User"===e.tokenType?{value:`...${e.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){const s=function(e){switch(e.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...e};case"Connect":return void 0!==e.maxObservedTimestamp?{...e,maxObservedTimestamp:(t=e.maxObservedTimestamp,d(new Uint8Array(t.toBytesLE())))}:{...e,maxObservedTimestamp:void 0}}var t}(e),n=JSON.stringify(s);let i=!1;try{this.socket.ws.send(n),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);const s=pe(),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":return this.lastCloseReason=e,this.close(),void this.scheduleReconnect("client");default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const 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");const e=this.socket.ws;e.onmessage=e=>{this._logVerbose("Ignoring message received after close")};const 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":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new 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();const 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":return void this.logger.logVerbose("Restart called without stopping first");default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":return void(this.socket={...this.socket,paused:"yes"});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){const t=pe()-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":return void(this.socket={...this.socket,paused:"no"});case"ready":return void("uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:pe()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume()));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){const t=("client"===e?100:"Unknown"===e?this.defaultInitialBackoff:be[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const s=Math.min(t,this.maxBackoff);return s+s*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;const s=pe()-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}) 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 InvalidTokenError extends Error{}function ve(e,t){if("string"!=typeof e)throw new InvalidTokenError("Invalid token specified: must be a string");t||(t={});const s=!0===t.header?0:1,n=e.split(".")[s];if("string"!=typeof n)throw new InvalidTokenError(`Invalid token specified: missing part #${s+1}`);let i;try{i=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 new Error("base64 string is not of the correct length")}try{return function(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return atob(t)}}(n)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid base64 for part #${s+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new InvalidTokenError(`Invalid token specified: invalid json for part #${s+1} (${e.message})`)}}InvalidTokenError.prototype.name="InvalidTokenError";var we=Object.defineProperty,ke=(e,t,s)=>((e,t,s)=>t in e?we(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class AuthenticationManager{constructor(e,t,s){ke(this,"authState",{state:"noAuth"}),ke(this,"configVersion",0),ke(this,"syncState"),ke(this,"authenticate"),ke(this,"stopSocket"),ke(this,"tryRestartSocket"),ke(this,"pauseSocket"),ke(this,"resumeSocket"),ke(this,"clearAuth"),ke(this,"logger"),ke(this,"refreshTokenLeewaySeconds"),ke(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();const 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))return"waitingForServerConfirmationOfCachedToken"===this.authState.state?(this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),void this.authState.config.onAuthChange(!0)):void("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");const{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)return this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),void("noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange));"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const 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");const 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;const t=this.decodeToken(e);if(!t)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");const{iat:s,exp:n}=t;if(!s||!n)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");const 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,1e3*(i-this.refreshTokenLeewaySeconds));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);const 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){const s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);const n=await e(t);return 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){const t="waitingForServerConfirmationOfFreshToken"===e.state?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return ve(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}]`)}}const Se=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Ce(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}var Te=Object.defineProperty,Re=(e,t,s)=>((e,t,s)=>t in e?Te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class BaseConvexClient{constructor(e,t,s){if(Re(this,"address"),Re(this,"state"),Re(this,"requestManager"),Re(this,"webSocketManager"),Re(this,"authenticationManager"),Re(this,"remoteQuerySet"),Re(this,"optimisticQueryResults"),Re(this,"_transitionHandlerCounter",0),Re(this,"_nextRequestId"),Re(this,"_onTransitionFns",new Map),Re(this,"_sessionId"),Re(this,"firstMessageReceived",!1),Re(this,"debug"),Re(this,"logger"),Re(this,"maxObservedTimestamp"),Re(this,"connectionStateSubscribers",new Map),Re(this,"nextConnectionStateSubscriberId",0),Re(this,"_lastPublishedConnectionState"),Re(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(const t of this.connectionStateSubscribers.values())t(e)}})}),Re(this,"mark",e=>{this.debug&&function(e,t){const s={sessionId:t};"undefined"!=typeof performance&&performance.mark&&performance.mark(e,{detail:s})}(e,this.sessionId)}),"object"==typeof e)throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");!0!==s?.skipConvexDeploymentUrlCheck&&f(e);const i=(s={...s}).authRefreshTokenLeewaySeconds??10;let r=s.webSocketConstructor;if(!r&&"undefined"==typeof WebSocket)throw new 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 DefaultLogger(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:function(e){const t=new DefaultLogger(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}({verbose:s.verbose??!1});const o=e.search("://");if(-1===o)throw new Error("Provided address was not an absolute URL.");const a=e.substring(o+3),u=e.substring(0,o);let c;if("http"===u)c="ws";else{if("https"!==u)throw new Error(`Unknown parent protocol ${u}`);c="wss"}const h=`${c}://${a}/api/${n}/sync`;this.state=new LocalSyncState,this.remoteQuerySet=new RemoteQuerySet(e=>this.state.queryPath(e),this.logger),this.requestManager=new RequestManager(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new AuthenticationManager(this.state,{authenticate:e=>{const t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new OptimisticQueryResults,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});const{unsavedChangesWarning:d}=s;if("undefined"==typeof window||void 0===window.addEventListener){if(!0===d)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==d&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();const t="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=t,t}});this.webSocketManager=new WebSocketManager(h,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const t=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new RemoteQuerySet(e=>this.state.queryPath(e),this.logger);const[s,n]=this.state.restart(t);n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(s);for(const e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{const[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(const e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},onMessage:e=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),e.type){case"Transition":{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);const t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case"MutationResponse":{e.success&&this.observedTimestamp(e.ts);const 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":{const t=function(e,t){const s=`[CONVEX FATAL ERROR] ${t}`;return e.error(s),new Error(s)}(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},r,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&l()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(const[e,n]of t){const t=this.state.queryToken(e);if(null!==t){const i={result:n,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,i)}}const n=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:n.map(e=>({token:e,modification:{kind:"Updated",result:this.optimisticQueryResults.rawQueryResult(e)}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){const t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){const e=this.state.getAuth();let t={};if(e&&"User"===e.tokenType){try{t=e?ve(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){const s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){const n=g(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:()=>{const e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){const s=W(e,g(t));return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){const s=W(e,g(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){const s=W(e,g(t));return this.state.queryJournal(s)}connectionState(){const 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){const t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){const n=await this.mutationInternal(e,t,s);if(!n.success){if(void 0!==n.errorData)throw U(n,new errors_ConvexError(D("mutation",e,n)));throw new Error(D("mutation",e,n))}return n.value}async mutationInternal(e,t,s,n){const{mutationPromise:i}=this.enqueueMutation(e,t,s,n);return i}enqueueMutation(e,t,s,n){const i=g(t);this.tryReportLongDisconnect();const r=this.nextRequestId;if(this._nextRequestId++,void 0!==s){const e=s.optimisticUpdate;if(void 0!==e){const 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=>{const 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()})}}const o={type:"Mutation",requestId:r,udfPath:e,componentPath:n,args:[Q(i)]},a=this.webSocketManager.sendMessage(o);return{requestId:r,mutationPromise:this.requestManager.request(o,a)}}async action(e,t){const s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw U(s,new errors_ConvexError(D("action",e,s)));throw new Error(D("action",e,s))}return s.value}async actionInternal(e,t,s){const n=g(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const r={type:"Action",requestId:i,udfPath:e,componentPath:s,args:[Q(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}reportMarks(){if(this.debug){const e=function(e){if("undefined"==typeof performance||!performance.getEntriesByName)return[];const t=[];for(const s of Se){const n=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...n)}return t.map(Ce)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(null===e||Date.now()-e.getTime()<=6e4)return;const t=`${this.address}/api/debug_event`;fetch(t,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${n}`},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 qe(e){if("object"!=typeof e||null===e||!Array.isArray(e.page)||"boolean"!=typeof e.isDone||"string"!=typeof e.continueCursor)throw new Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var Ae=Object.defineProperty,Me=(e,t,s)=>((e,t,s)=>t in e?Ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class PaginatedQueryClient{constructor(e,t){this.client=e,this.onTransition=t,Me(this,"paginatedQuerySet",new Map),Me(this,"lastTransitionTs"),this.lastTransitionTs=Long.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){const n=j(e),i=K(n,t,s),r=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:r}):(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){const n=K(j(e),t,s);return this.localQueryResultByToken(n)}localQueryResultByToken(e){const t=this.paginatedQuerySet.get(e);if(!t)return;const s=this.activePageQueryTokens(t);if(0===s.length)return{results:[],status:"LoadingFirstPage",loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let n,i=[],r=!1,o=!1;for(const e of s){const t=this.client.localQueryResultByToken(e);if(void 0===t){r=!0,o=!1;continue}const s=qe(t);i=i.concat(s.page),o=!!s.isDone}return n=r?0===i.length?"LoadingFirstPage":"LoadingMore":o?"Exhausted":"CanLoadMore",{results:i,status:n,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){const t=e.queries.map(e=>e.token),s=this.queriesContainingTokens(t);let 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)}})));const i={...e,paginatedQueries:n};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);const s=this.queryTokenForLastPageOfPaginatedQuery(e),n=this.client.localQueryResultByToken(s);if(!n)return!1;const i=qe(n);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);const 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[];const t=[],s=new Set(e);for(const[e,n]of this.paginatedQuerySet)for(const i of this.allQueryTokens(n))if(s.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(const s of e){const e=this.mustGetPaginatedQuery(s),{ongoingSplits:n,pageKeyToQuery:i,pageKeys:r}=e;for(const[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(const s of r){if(n.has(s))continue;const r=t(i.get(s).queryToken);if(!r)continue;const o=qe(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){const 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);const 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){const 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){const t=this.paginatedQuerySet.get(e);if(t&&(t.numSubscribers-=1,!(t.numSubscribers>0))){for(const e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,s,n){const i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);const 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){const t=this.mustGetPaginatedQuery(e),s=t.pageKeys[t.pageKeys.length-1];if(void 0===s)throw new Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(s).queryToken}mustGetPaginatedQuery(e){const t=this.paginatedQuerySet.get(e);if(!t)throw new Error("paginated query no longer exists for token "+e);return t}}var Ie=Object.defineProperty,Oe=(e,t,s)=>((e,t,s)=>t in e?Ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class ConvexClient{constructor(e,t={}){Oe(this,"listeners"),Oe(this,"_client"),Oe(this,"_paginatedClient"),Oe(this,"callNewListenersWithCurrentValuesTimer"),Oe(this,"_closed"),Oe(this,"_disabled"),!0!==t.skipConvexDeploymentUrlCheck&&f(e);const{disabled:s,...n}=t;this._closed=!1,this._disabled=!!s,"undefined"!=typeof window||"unsavedChangesWarning"in n||(n.unsavedChangesWarning=!1),this.disabled||(this._client=new BaseConvexClient(e,()=>{},n),this._paginatedClient=new PaginatedQueryClient(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw new Error("ConvexClient is disabled")}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw new Error("ConvexClient is disabled")}get disabled(){return this._disabled}onUpdate(e,t,s,n){if(this.disabled)return this.createDisabledUnsubscribe();const{queryToken:i,unsubscribe:r}=this.client.subscribe(ee(e),t),o={queryToken:i,callback:s,onError:n,unsubscribe:r,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&void 0===this.callNewListenersWithCurrentValuesTimer&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));const a={unsubscribe:()=>{this.closed||(this.listeners.delete(o),r())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},u=a.unsubscribe;return Object.assign(u,a),u}onPaginatedUpdate_experimental(e,t,s,n,i){if(this.disabled)return this.createDisabledUnsubscribe();const r={initialNumItems:s.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:a}=this.paginatedClient.subscribe(ee(e),t,r),u={queryToken:o,callback:n,onError:i,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:r};this.listeners.add(u),this.paginatedClient.localQueryResultByToken(o)&&void 0===this.callNewListenersWithCurrentValuesTimer&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));const c={unsubscribe:()=>{this.closed||(this.listeners.delete(u),a())},getCurrentValue:()=>this.paginatedClient.localQueryResult(ee(e),t,r),getQueryLogs:()=>[]},h=c.unsubscribe;return Object.assign(h,c),h}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){const e=()=>{},t={unsubscribe:e,getCurrentValue:()=>{},getQueryLogs:()=>{}};return Object.assign(e,t),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw new Error("ConvexClient has already been closed.");this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},s=!1){const n=[...e.map(e=>e.token),...t.map(e=>e.token)];for(const e of this.listeners){const{callback:t,queryToken:i,onError:r,hasEverRun:o}=e,a=J(i),u=a?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(n.includes(i)||s&&!o&&u){let s;e.hasEverRun=!0;try{s=a?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;r?r(e,"Second argument to onUpdate onError is reserved for later use"):Promise.reject(e);continue}t(s,"Second argument to onUpdate callback is reserved for later use")}}}async mutation(e,t,s){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.mutation(ee(e),t,s)}async action(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");return await this.client.action(ee(e),t)}async query(e,t){if(this.disabled)throw new Error("ConvexClient is disabled");const s=this.client.localQueryResult(ee(e),t);return void 0!==s?Promise.resolve(s):new Promise((s,n)=>{const{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),s(e)},e=>{i(),n(e)})})}connectionState(){if(this.disabled)throw new Error("ConvexClient is disabled");return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}}Object.defineProperty}}]);