@01.works/visual-review 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{i as e,r as t,t as n}from"./review-repository-B3NZ_Tqo.js";for(var r=[],i=[],a=Uint8Array,o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,s=0,c=o.length;s<c;++s)r[s]=o[s],i[o.charCodeAt(s)]=s;i[45]=62,i[95]=63;function l(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function u(e,t,n){return(t+n)*3/4-n}function d(e){var t,n=l(e),r=n[0],o=n[1],s=new a(u(e,r,o)),c=0,d=o>0?r-4:r,f;for(f=0;f<d;f+=4)t=i[e.charCodeAt(f)]<<18|i[e.charCodeAt(f+1)]<<12|i[e.charCodeAt(f+2)]<<6|i[e.charCodeAt(f+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=i[e.charCodeAt(f)]<<2|i[e.charCodeAt(f+1)]>>4,s[c++]=t&255),o===1&&(t=i[e.charCodeAt(f)]<<10|i[e.charCodeAt(f+1)]<<4|i[e.charCodeAt(f+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function f(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[e&63]}function ee(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(f(r));return i.join(``)}function p(e){for(var t,n=e.length,i=n%3,a=[],o=16383,s=0,c=n-i;s<c;s+=o)a.push(ee(e,s,s+o>c?c:s+o));return i===1?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+`==`)):i===2&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+`=`)),a.join(``)}function m(e){if(e===void 0)return{};if(!ne(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function te(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith(`http:`)||e.startsWith(`https:`)))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(`.convex.site`))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function ne(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}const h=BigInt(`-9223372036854775808`),g=BigInt(`9223372036854775807`),_=BigInt(`0`),re=BigInt(`8`),ie=BigInt(`256`),v=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var ae=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(v)}valueOf(){throw Error(v)}toJSON(){throw Error(v)}toString(){return`[unresolved commit timestamp]`}};const oe=new ae;function se(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function ce(e){e<_&&(e-=h+h);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=re;return p(n)}function le(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=_,r=_;for(let e of t)n+=BigInt(e)*ie**r,r++;return n>g&&(n+=h+h),n}function ue(e){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),p(new Uint8Array(t))}function de(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}const fe=DataView.prototype.setBigInt64?ue:ce,pe=DataView.prototype.getBigInt64?de:le,me=1024;function y(e){if(e.length>me)throw Error(`Field name ${e} exceeds maximum field name length ${me}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function b(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>b(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return d(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return pe(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=d(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!se(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return oe}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))y(t),n[t]=b(r);return n}const he=16384;function x(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>he){let e=he-14,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function S(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${x(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e==`bigint`){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:fe(e)}}if(typeof e==`number`)if(se(e)){let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:p(new Uint8Array(t))}}else return e;if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:p(new Uint8Array(e))};if(e instanceof ae)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>S(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(C(n,`Set`,[...e],t));if(e instanceof Map)throw Error(C(n,`Map`,[...e],t));if(!ne(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(C(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(y(e),i[e]=ge(o,t,n+`.${e}`)):(y(e),i[e]=S(o,t,n+`.${e}`,!1));return i}function C(e,t,n,r){return e?`${t}${x(n)} is not a supported Convex type (present at path ${e} in original object ${x(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(n)} is not a supported Convex type.`}function ge(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return S(e,t,n,!1)}function w(e){return S(e,e,``,!1)}var _e=Object.defineProperty,ve=(e,t,n)=>t in e?_e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,T=(e,t,n)=>ve(e,typeof t==`symbol`?t:t+``,n),E,ye;const be=Symbol.for(`ConvexError`);var D=class extends (ye=Error,E=be,ye){constructor(e){super(typeof e==`string`?e:x(e)),T(this,`name`,`ConvexError`),T(this,`data`),T(this,E,!0),this.data=e}};const O=`1.45.0`;var xe=Object.defineProperty,Se=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t,n)=>Se(e,typeof t==`symbol`?t:t+``,n);function Ce(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var we=class{constructor(e){k(this,`_onLogLineFuncs`),k(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&&this._onLogLineFuncs[t]!==void 0;e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t(`debug`,`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t(`info`,...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t(`warn`,...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t(`error`,...e)}};function Te(e){let t=new we(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function Ee(e){return new we(e)}function A(e,t,n,r,i){let a=Ce(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function De(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function j(e,t,n){return`[CONVEX ${Ce(e)}(${t})] ${n.errorMessage}
2
- Called by client`}function M(e,t){return t.data=e.errorData,t}function N(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function P(e,t){return JSON.stringify({udfPath:N(e),args:w(t)})}function Oe(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:N(e),args:w(t),options:w({initialNumItems:r,id:i})})}function ke(e){return JSON.parse(e).type===`paginated`}var Ae=Object.defineProperty,je=(e,t,n)=>t in e?Ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,F=(e,t,n)=>je(e,typeof t==`symbol`?t:t+``,n),Me=class{constructor(){F(this,`nextQueryId`),F(this,`querySetVersion`),F(this,`querySet`),F(this,`queryIdToToken`),F(this,`identityVersion`),F(this,`auth`),F(this,`outstandingQueriesOlderThanRestart`),F(this,`outstandingAuthOlderThanRestart`),F(this,`paused`),F(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 this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=N(e),a=P(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[w(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(let t of e.modifications)switch(t.type){case`QueryUpdated`:case`QueryFailed`:{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=P(N(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:`User`,value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:`Authenticate`,baseVersion:t,...this.auth}}setAdminAuth(e,t){let n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:`Authenticate`,tokenType:`None`,baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[w(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:`ModifyQuerySet`,baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return--t.numSubscribers,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=this.querySetVersion,r=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=r,{type:`ModifyQuerySet`,baseVersion:n,newVersion:r,modifications:[i]}}}},Ne=Object.defineProperty,Pe=(e,t,n)=>t in e?Ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,I=(e,t,n)=>Pe(e,typeof t==`symbol`?t:t+``,n),Fe=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,I(this,`inflightRequests`),I(this,`requestsOlderThanRestart`),I(this,`inflightMutationsCount`,0),I(this,`inflightActionsCount`,0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)A(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:b(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;A(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:b(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.status.onResult({success:!1,errorMessage:`Connection lost while action was in flight`,logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},Ie=Object.defineProperty,Le=(e,t,n)=>t in e?Ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,L=(e,t,n)=>Le(e,typeof t==`symbol`?t:t+``,n),Re=class t{constructor(e){L(this,`queryResults`),L(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(n,...r){let i=m(r[0]),a=e(n),o=this.queryResults.get(P(a,i));if(o!==void 0)return t.queryValue(o.result)}getAllQueries(n){let r=[],i=e(n);for(let e of this.queryResults.values())e.udfPath===N(i)&&r.push({args:e.args,value:t.queryValue(e.result)});return r}setQuery(t,n,r){let i=m(n),a=e(t),o=P(a,i),s;s=r===void 0?void 0:{success:!0,value:r,logLines:[]};let c={udfPath:a,args:i,result:s};this.queryResults.set(o,c),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},ze=class{constructor(){L(this,`queryResults`),L(this,`optimisticUpdates`),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new Re(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new Re(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(j(`query`,t.udfPath,n)):M(n,new D(j(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},Be=Object.defineProperty,Ve=(e,t,n)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t,n)=>Ve(e,typeof t==`symbol`?t:t+``,n),z=class e{constructor(e,t){R(this,`low`),R(this,`high`),R(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?He:t>=Ue?We:new e(t%V|0,t/V|0)}toString(){return(BigInt(this.high)*BigInt(V)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};const He=new z(0,0),B=65536,V=B*B,Ue=V*V,We=new z(-1,-1);var Ge=Object.defineProperty,Ke=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t,n)=>Ke(e,typeof t==`symbol`?t:t+``,n),U=class{constructor(e,t){H(this,`version`),H(this,`remoteQuerySet`),H(this,`queryPath`),H(this,`logger`),this.version={querySet:0,ts:z.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case`QueryUpdated`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let n=b(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:b(n),logLines:t.logLines});break}case`QueryRemoved`:this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function W(e){let t=d(e);return z.fromBytesLE(Array.from(t))}function qe(e){return p(new Uint8Array(e.toBytesLE()))}function Je(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:W(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:W(e.startVersion.ts)},endVersion:{...e.endVersion,ts:W(e.endVersion.ts)}};default:}}function Ye(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:qe(e.maxObservedTimestamp)};default:}}var Xe=Object.defineProperty,Ze=(e,t,n)=>t in e?Xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G=(e,t,n)=>Ze(e,typeof t==`symbol`?t:t+``,n);let K;function q(){return K===void 0&&(K=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(K+performance.now())}function Qe(){return`t=${Math.round((q()-K)/100)/10}s`}const $e={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}};function et(e){if(e===void 0)return`Unknown`;for(let t of Object.keys($e))if(e.startsWith(t))return t;return`Unknown`}var tt=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,G(this,`socket`),G(this,`connectionCount`),G(this,`_hasEverConnected`,!1),G(this,`lastCloseReason`),G(this,`transitionChunkBuffer`,null),G(this,`defaultInitialBackoff`),G(this,`maxBackoff`),G(this,`retries`),G(this,`serverInactivityThreshold`),G(this,`reconnectDueToServerInactivityTimeout`),G(this,`scheduledReconnect`,null),G(this,`networkOnlineHandler`,null),G(this,`pendingNetworkRecoveryInfo`,null),G(this,`uri`),G(this,`onOpen`),G(this,`onResume`),G(this,`onMessage`),G(this,`webSocketConstructor`),G(this,`logger`),G(this,`onServerDisconnectError`),this.webSocketConstructor=n,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=r,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(){typeof window>`u`||typeof window.addEventListener!=`function`||this.networkOnlineHandler===null&&(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&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(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||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join(``);this.transitionChunkBuffer=null;let t=Je(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)throw Error(`Didn't start connection from disconnected state: `+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose(`constructed WebSocket`),this.setSocketState({state:`connecting`,ws:e,paused:`no`}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose(`begin ws.onopen`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:q()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,Qe(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,Qe())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,n=Je(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=et(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=Ye(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),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(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=q(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return;case`connecting`:case`ready`:this.lastCloseReason=e,this.close(),this.scheduleReconnect(`client`);return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return Promise.resolve();case`connecting`:{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)},new Promise(t=>{e.onclose=()=>{this._logVerbose(`Closed after connecting`),t()},e.onopen=()=>{this._logVerbose(`Opened after connecting`),e.close()}})}case`ready`:{this._logVerbose(`ws.close called`);let e=this.socket.ws;e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.cleanupNetworkListener(),this.socket.state){case`terminated`:case`stopped`:case`disconnected`:case`connecting`:case`ready`:{let e=this.close();return this.setSocketState({state:`terminated`}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case`terminated`:return Promise.resolve();case`connecting`:case`stopped`:case`disconnected`:case`ready`:{this.cleanupNetworkListener();let e=this.close();return this.socket={state:`stopped`},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case`stopped`:break;case`terminated`:case`connecting`:case`ready`:case`disconnected`:this.logger.logVerbose(`Restart called without stopping first`);return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case`disconnected`:case`stopped`:case`terminated`:return;case`connecting`:case`ready`:this.socket={...this.socket,paused:`yes`};return;default:this.socket;return}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=q()-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=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:q()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:$e[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=q()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} 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`):n>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:`Event`,eventType:`ClientReceivedTransition`,event:{transitionTransitTime:n,messageLength:t}})}};function nt(){return rt()}function rt(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var J=class extends Error{};J.prototype.name=`InvalidTokenError`;function it(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function at(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return it(t)}catch{return atob(t)}}function Y(e,t){if(typeof e!=`string`)throw new J(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new J(`Invalid token specified: missing part #${n+1}`);let i;try{i=at(r)}catch(e){throw new J(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new J(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var ot=Object.defineProperty,st=(e,t,n)=>t in e?ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,X=(e,t,n)=>st(e,typeof t==`symbol`?t:t+``,n),ct=class{constructor(e,t,n){X(this,`authState`,{state:`noAuth`}),X(this,`configVersion`,0),X(this,`syncState`),X(this,`authenticate`),X(this,`stopSocket`),X(this,`tryRestartSocket`),X(this,`pauseSocket`),X(this,`resumeSocket`),X(this,`clearAuth`),X(this,`logger`),X(this,`refreshTokenLeewaySeconds`),X(this,`initialAuthTokenReuse`),X(this,`lastRefreshChange`),X(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=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),await this.refetchToken()),this._logVerbose(`resuming WS after auth token fetch`),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,config:this.authState.config,token:t.value,hadAuth:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(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(this.authState.state===`noAuth`)return;this._logVerbose(`refetching auth token`);let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:`notRefetching`,config:this.authState.config}):(this._logVerbose(`refetching token failed`),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose(`restarting WS after auth token fetch (if currently stopped)`),this.tryRestartSocket())}scheduleTokenRefetch(e,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{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;break;case`waitingForServerConfirmationOfFreshToken`:case`waitingForServerConfirmationOfCachedToken`:case`initialRefetch`:break;default:}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return Y(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 lt=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function ut(e,t){let n={sessionId:t};typeof performance>`u`||!performance.mark||performance.mark(e,{detail:n})}function dt(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function ft(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of lt){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(dt)}var pt=Object.defineProperty,mt=(e,t,n)=>t in e?pt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Z=(e,t,n)=>mt(e,typeof t==`symbol`?t:t+``,n),ht=class{constructor(e,t,n){if(Z(this,`address`),Z(this,`state`),Z(this,`requestManager`),Z(this,`webSocketManager`),Z(this,`authenticationManager`),Z(this,`remoteQuerySet`),Z(this,`optimisticQueryResults`),Z(this,`_transitionHandlerCounter`,0),Z(this,`_nextRequestId`),Z(this,`_onTransitionFns`,new Map),Z(this,`_sessionId`),Z(this,`firstMessageReceived`,!1),Z(this,`debug`),Z(this,`logger`),Z(this,`maxObservedTimestamp`),Z(this,`connectionStateSubscribers`,new Map),Z(this,`nextConnectionStateSubscriberId`,0),Z(this,`_lastPublishedConnectionState`),Z(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),Z(this,`mark`,e=>{this.debug&&ut(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&te(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)throw Error(`No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient`);i||=WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?Ee({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Te({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${O}/sync`;this.state=new Me,this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger),this.requestManager=new Fe(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ct(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new ze,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=nt();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&window.addEventListener(`beforeunload`,e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t=`Are you sure you want to leave? Your changes may not be saved.`;return(e||window.event).returnValue=t,t}});this.webSocketManager=new tt(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let 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);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case`MutationResponse`:{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);t!==null&&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`:{let t=De(this.logger,e.error);throw this.webSocketManager.terminate(),t}default:}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.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(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType===`User`)try{t=e?Y(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=m(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=P(e,m(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=P(e,m(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=P(e,m(t));return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(j(`mutation`,e,r)):M(r,new D(j(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=m(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[w(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(j(`action`,e,n)):M(n,new D(j(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=m(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[w(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,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){let e=ft(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${O}`},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 Q(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var gt=Object.defineProperty,_t=(e,t,n)=>t in e?gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>_t(e,typeof t==`symbol`?t:t+``,n),yt=class{constructor(e,t){this.client=e,this.onTransition=t,vt(this,`paginatedQuerySet`,new Map),vt(this,`lastTransitionTs`),this.lastTransitionTs=z.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=N(e),i=Oe(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=Oe(N(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=Q(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=Q(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=Q(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},bt=Object.defineProperty,xt=(e,t,n)=>t in e?bt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$=(e,t,n)=>xt(e,typeof t==`symbol`?t:t+``,n),St=class{constructor(e,t={}){$(this,`listeners`),$(this,`_client`),$(this,`_paginatedClient`),$(this,`callNewListenersWithCurrentValuesTimer`),$(this,`_closed`),$(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&te(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new ht(e,()=>{},r),this._paginatedClient=new yt(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:a,unsubscribe:o}=this.client.subscribe(e(t),n),s={queryToken:a,callback:r,onError:i,unsubscribe:o,hasEverRun:!1,query:t,args:n,paginationOptions:void 0};this.listeners.add(s),this.queryResultReady(a)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let c={unsubscribe:()=>{this.closed||(this.listeners.delete(s),o())},getCurrentValue:()=>this.client.localQueryResultByToken(a),getQueryLogs:()=>this.client.localQueryLogs(a)},l=c.unsubscribe;return Object.assign(l,c),l}onPaginatedUpdate_experimental(t,n,r,i,a){if(this.disabled)return this.createDisabledUnsubscribe();let o={initialNumItems:r.initialNumItems,id:-1},{paginatedQueryToken:s,unsubscribe:c}=this.paginatedClient.subscribe(e(t),n,o),l={queryToken:s,callback:i,onError:a,unsubscribe:c,hasEverRun:!1,query:t,args:n,paginationOptions:o};this.listeners.add(l),this.paginatedClient.localQueryResultByToken(s)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let u={unsubscribe:()=>{this.closed||(this.listeners.delete(l),c())},getCurrentValue:()=>this.paginatedClient.localQueryResult(e(t),n,o),getQueryLogs:()=>[]},d=u.unsubscribe;return Object.assign(d,u),d}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,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 Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=ke(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(t,n,r){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(e(t),n,r)}async action(t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(e(t),n)}async query(t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);let r=this.client.localQueryResult(e(t),n);return r===void 0?new Promise((e,r)=>{let{unsubscribe:i}=this.onUpdate(t,n,t=>{i(),e(t)},e=>{i(),r(e)})}):Promise.resolve(r)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}};function Ct(e,t){let n=e.trim();if(!/^https:\/\/[^/]+$/.test(n))throw Error(`A valid HTTPS Convex deployment URL is required`);let r=new St(n);return r.setAuth(t),r}function wt(e,n){let r=e.trim();if(!r)throw Error(`Convex deployment URL is required`);return{async resolve(e){let i=await n.fetchAccessToken(kt(e,!1));if(!i)throw Error(`Convex review authentication is required`);let a=i,o=(n.clientFactory??Ct)(r,async({forceRefreshToken:t})=>{if(!t&&a){let e=a;return a=null,e}return n.fetchAccessToken({...kt(e,t),signal:new AbortController().signal})}),s=await o.mutation(t.resolveSession,{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.routeKey===void 0?{}:{routeKey:e.routeKey}}),c=At(s.session,e.invitationId),l=0;return Tt({client:o,session:c,request:e,pageId:s.pageId,resolvePage:async n=>{if(n.location.origin!==e.location.origin)throw Error(`Convex review session cannot move to another origin`);let r=++l,i=await o.mutation(t.resolveSession,{invitationId:e.invitationId,origin:n.location.origin,pathname:n.location.pathname,...n.routeKey===void 0?{}:{routeKey:n.routeKey}});if(n.signal.aborted||r!==l)throw jt();return{pageId:i.pageId,...n.cursorChat?{cursorChatRoomId:Ot(i.pageId)}:{}}},cursorChatRepositoryFactory:n.cursorChatRepositoryFactory})}}}async function Tt(e){let t=new n(e.client,e.session,{origin:e.request.location.origin}),r;if(e.request.cursorChat)try{r=await Et(e.client,e.session,e.request.location.origin,e.cursorChatRepositoryFactory)}catch{}return{pageId:e.pageId,session:e.session,repository:t,...r?{cursorChatRepository:r,cursorChatRoomId:Ot(e.pageId)}:{},resolvePage:e.resolvePage,allowedStagingHosts:[e.request.location.hostname]}}async function Et(e,t,n,r=Dt){return r(e,t,n)}async function Dt(e,t,n){let{ConvexReviewCursorChatRepository:r}=await import(`./cursor-chat-repository-Cjy9pxGa.js`);return new r(e,t,{origin:n})}function Ot(e){return`cursor-chat:${e}`}function kt(e,t){return{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.emailToken===void 0?{}:{emailToken:e.emailToken},forceRefreshToken:t,signal:e.signal}}function At(e,t){if(!e||e.invitationId!==t||!e.authUserId||!e.reviewerId||!e.projectId)throw Error(`Convex returned an invalid reviewer session`);return structuredClone(e)}function jt(){return Object.assign(Error(`Review page resolution was superseded`),{code:`PAGE_SWAP_SUPERSEDED`})}export{wt as createConvexReviewRuntime};
1
+ import{i as e,r as t,t as n}from"./review-repository-DJTt7aZR.js";for(var r=[],i=[],a=Uint8Array,o=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,s=0,c=o.length;s<c;++s)r[s]=o[s],i[o.charCodeAt(s)]=s;i[45]=62,i[95]=63;function l(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function u(e,t,n){return(t+n)*3/4-n}function d(e){var t,n=l(e),r=n[0],o=n[1],s=new a(u(e,r,o)),c=0,d=o>0?r-4:r,f;for(f=0;f<d;f+=4)t=i[e.charCodeAt(f)]<<18|i[e.charCodeAt(f+1)]<<12|i[e.charCodeAt(f+2)]<<6|i[e.charCodeAt(f+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=i[e.charCodeAt(f)]<<2|i[e.charCodeAt(f+1)]>>4,s[c++]=t&255),o===1&&(t=i[e.charCodeAt(f)]<<10|i[e.charCodeAt(f+1)]<<4|i[e.charCodeAt(f+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function f(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[e&63]}function ee(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(f(r));return i.join(``)}function p(e){for(var t,n=e.length,i=n%3,a=[],o=16383,s=0,c=n-i;s<c;s+=o)a.push(ee(e,s,s+o>c?c:s+o));return i===1?(t=e[n-1],a.push(r[t>>2]+r[t<<4&63]+`==`)):i===2&&(t=(e[n-2]<<8)+e[n-1],a.push(r[t>>10]+r[t>>4&63]+r[t<<2&63]+`=`)),a.join(``)}function m(e){if(e===void 0)return{};if(!ne(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function te(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith(`http:`)||e.startsWith(`https:`)))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(`.convex.site`))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function ne(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}const h=BigInt(`-9223372036854775808`),g=BigInt(`9223372036854775807`),_=BigInt(`0`),re=BigInt(`8`),ie=BigInt(`256`),v=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var ae=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(v)}valueOf(){throw Error(v)}toJSON(){throw Error(v)}toString(){return`[unresolved commit timestamp]`}};const oe=new ae;function se(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function ce(e){e<_&&(e-=h+h);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=re;return p(n)}function le(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=_,r=_;for(let e of t)n+=BigInt(e)*ie**r,r++;return n>g&&(n+=h+h),n}function ue(e){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),p(new Uint8Array(t))}function de(e){let t=d(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}const fe=DataView.prototype.setBigInt64?ue:ce,pe=DataView.prototype.getBigInt64?de:le,me=1024;function y(e){if(e.length>me)throw Error(`Field name ${e} exceeds maximum field name length ${me}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function b(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>b(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return d(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return pe(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=d(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!se(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return oe}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))y(t),n[t]=b(r);return n}const he=16384;function x(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>he){let e=he-14,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function S(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${x(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e==`bigint`){if(e<h||g<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:fe(e)}}if(typeof e==`number`)if(se(e)){let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:p(new Uint8Array(t))}}else return e;if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:p(new Uint8Array(e))};if(e instanceof ae)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>S(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(C(n,`Set`,[...e],t));if(e instanceof Map)throw Error(C(n,`Map`,[...e],t));if(!ne(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(C(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(y(e),i[e]=ge(o,t,n+`.${e}`)):(y(e),i[e]=S(o,t,n+`.${e}`,!1));return i}function C(e,t,n,r){return e?`${t}${x(n)} is not a supported Convex type (present at path ${e} in original object ${x(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${x(n)} is not a supported Convex type.`}function ge(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${x(e)} but original value is undefined`);return S(e,t,n,!1)}function w(e){return S(e,e,``,!1)}var _e=Object.defineProperty,ve=(e,t,n)=>t in e?_e(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,T=(e,t,n)=>ve(e,typeof t==`symbol`?t:t+``,n),E,ye;const be=Symbol.for(`ConvexError`);var D=class extends (ye=Error,E=be,ye){constructor(e){super(typeof e==`string`?e:x(e)),T(this,`name`,`ConvexError`),T(this,`data`),T(this,E,!0),this.data=e}};const O=`1.45.0`;var xe=Object.defineProperty,Se=(e,t,n)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,k=(e,t,n)=>Se(e,typeof t==`symbol`?t:t+``,n);function Ce(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var we=class{constructor(e){k(this,`_onLogLineFuncs`),k(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&&this._onLogLineFuncs[t]!==void 0;e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t(`debug`,`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t(`info`,...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t(`warn`,...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t(`error`,...e)}};function Te(e){let t=new we(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function Ee(e){return new we(e)}function A(e,t,n,r,i){let a=Ce(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function De(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function j(e,t,n){return`[CONVEX ${Ce(e)}(${t})] ${n.errorMessage}
2
+ Called by client`}function M(e,t){return t.data=e.errorData,t}function N(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function P(e,t){return JSON.stringify({udfPath:N(e),args:w(t)})}function Oe(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:N(e),args:w(t),options:w({initialNumItems:r,id:i})})}function ke(e){return JSON.parse(e).type===`paginated`}var Ae=Object.defineProperty,je=(e,t,n)=>t in e?Ae(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,F=(e,t,n)=>je(e,typeof t==`symbol`?t:t+``,n),Me=class{constructor(){F(this,`nextQueryId`),F(this,`querySetVersion`),F(this,`querySet`),F(this,`queryIdToToken`),F(this,`identityVersion`),F(this,`auth`),F(this,`outstandingQueriesOlderThanRestart`),F(this,`outstandingAuthOlderThanRestart`),F(this,`paused`),F(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 this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=N(e),a=P(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[w(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(let t of e.modifications)switch(t.type){case`QueryUpdated`:case`QueryFailed`:{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=P(N(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:`User`,value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:`Authenticate`,baseVersion:t,...this.auth}}setAdminAuth(e,t){let n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:`Authenticate`,tokenType:`None`,baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[w(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:`ModifyQuerySet`,baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return--t.numSubscribers,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=this.querySetVersion,r=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=r,{type:`ModifyQuerySet`,baseVersion:n,newVersion:r,modifications:[i]}}}},Ne=Object.defineProperty,Pe=(e,t,n)=>t in e?Ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,I=(e,t,n)=>Pe(e,typeof t==`symbol`?t:t+``,n),Fe=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,I(this,`inflightRequests`),I(this,`requestsOlderThanRestart`),I(this,`inflightMutationsCount`,0),I(this,`inflightActionsCount`,0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)A(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:b(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;A(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:b(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.status.onResult({success:!1,errorMessage:`Connection lost while action was in flight`,logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},Ie=Object.defineProperty,Le=(e,t,n)=>t in e?Ie(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,L=(e,t,n)=>Le(e,typeof t==`symbol`?t:t+``,n),Re=class t{constructor(e){L(this,`queryResults`),L(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(n,...r){let i=m(r[0]),a=e(n),o=this.queryResults.get(P(a,i));if(o!==void 0)return t.queryValue(o.result)}getAllQueries(n){let r=[],i=e(n);for(let e of this.queryResults.values())e.udfPath===N(i)&&r.push({args:e.args,value:t.queryValue(e.result)});return r}setQuery(t,n,r){let i=m(n),a=e(t),o=P(a,i),s;s=r===void 0?void 0:{success:!0,value:r,logLines:[]};let c={udfPath:a,args:i,result:s};this.queryResults.set(o,c),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},ze=class{constructor(){L(this,`queryResults`),L(this,`optimisticUpdates`),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new Re(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new Re(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(j(`query`,t.udfPath,n)):M(n,new D(j(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},Be=Object.defineProperty,Ve=(e,t,n)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t,n)=>Ve(e,typeof t==`symbol`?t:t+``,n),z=class e{constructor(e,t){R(this,`low`),R(this,`high`),R(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?He:t>=Ue?We:new e(t%V|0,t/V|0)}toString(){return(BigInt(this.high)*BigInt(V)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};const He=new z(0,0),B=65536,V=B*B,Ue=V*V,We=new z(-1,-1);var Ge=Object.defineProperty,Ke=(e,t,n)=>t in e?Ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t,n)=>Ke(e,typeof t==`symbol`?t:t+``,n),U=class{constructor(e,t){H(this,`version`),H(this,`remoteQuerySet`),H(this,`queryPath`),H(this,`logger`),this.version={querySet:0,ts:z.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case`QueryUpdated`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let n=b(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:b(n),logLines:t.logLines});break}case`QueryRemoved`:this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function W(e){let t=d(e);return z.fromBytesLE(Array.from(t))}function qe(e){return p(new Uint8Array(e.toBytesLE()))}function Je(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:W(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:W(e.startVersion.ts)},endVersion:{...e.endVersion,ts:W(e.endVersion.ts)}};default:}}function Ye(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:qe(e.maxObservedTimestamp)};default:}}var Xe=Object.defineProperty,Ze=(e,t,n)=>t in e?Xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G=(e,t,n)=>Ze(e,typeof t==`symbol`?t:t+``,n);let K;function q(){return K===void 0&&(K=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(K+performance.now())}function Qe(){return`t=${Math.round((q()-K)/100)/10}s`}const $e={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}};function et(e){if(e===void 0)return`Unknown`;for(let t of Object.keys($e))if(e.startsWith(t))return t;return`Unknown`}var tt=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,G(this,`socket`),G(this,`connectionCount`),G(this,`_hasEverConnected`,!1),G(this,`lastCloseReason`),G(this,`transitionChunkBuffer`,null),G(this,`defaultInitialBackoff`),G(this,`maxBackoff`),G(this,`retries`),G(this,`serverInactivityThreshold`),G(this,`reconnectDueToServerInactivityTimeout`),G(this,`scheduledReconnect`,null),G(this,`networkOnlineHandler`,null),G(this,`pendingNetworkRecoveryInfo`,null),G(this,`uri`),G(this,`onOpen`),G(this,`onResume`),G(this,`onMessage`),G(this,`webSocketConstructor`),G(this,`logger`),G(this,`onServerDisconnectError`),this.webSocketConstructor=n,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=r,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(){typeof window>`u`||typeof window.addEventListener!=`function`||this.networkOnlineHandler===null&&(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&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(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||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join(``);this.transitionChunkBuffer=null;let t=Je(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)throw Error(`Didn't start connection from disconnected state: `+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose(`constructed WebSocket`),this.setSocketState({state:`connecting`,ws:e,paused:`no`}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose(`begin ws.onopen`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:q()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,Qe(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,Qe())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,n=Je(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=et(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=Ye(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),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(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=q(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return;case`connecting`:case`ready`:this.lastCloseReason=e,this.close(),this.scheduleReconnect(`client`);return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return Promise.resolve();case`connecting`:{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)},new Promise(t=>{e.onclose=()=>{this._logVerbose(`Closed after connecting`),t()},e.onopen=()=>{this._logVerbose(`Opened after connecting`),e.close()}})}case`ready`:{this._logVerbose(`ws.close called`);let e=this.socket.ws;e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.cleanupNetworkListener(),this.socket.state){case`terminated`:case`stopped`:case`disconnected`:case`connecting`:case`ready`:{let e=this.close();return this.setSocketState({state:`terminated`}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case`terminated`:return Promise.resolve();case`connecting`:case`stopped`:case`disconnected`:case`ready`:{this.cleanupNetworkListener();let e=this.close();return this.socket={state:`stopped`},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case`stopped`:break;case`terminated`:case`connecting`:case`ready`:case`disconnected`:this.logger.logVerbose(`Restart called without stopping first`);return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case`disconnected`:case`stopped`:case`terminated`:return;case`connecting`:case`ready`:this.socket={...this.socket,paused:`yes`};return;default:this.socket;return}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=q()-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=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:q()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:$e[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=q()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} 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`):n>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:`Event`,eventType:`ClientReceivedTransition`,event:{transitionTransitTime:n,messageLength:t}})}};function nt(){return rt()}function rt(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var J=class extends Error{};J.prototype.name=`InvalidTokenError`;function it(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function at(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return it(t)}catch{return atob(t)}}function Y(e,t){if(typeof e!=`string`)throw new J(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new J(`Invalid token specified: missing part #${n+1}`);let i;try{i=at(r)}catch(e){throw new J(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new J(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var ot=Object.defineProperty,st=(e,t,n)=>t in e?ot(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,X=(e,t,n)=>st(e,typeof t==`symbol`?t:t+``,n),ct=class{constructor(e,t,n){X(this,`authState`,{state:`noAuth`}),X(this,`configVersion`,0),X(this,`syncState`),X(this,`authenticate`),X(this,`stopSocket`),X(this,`tryRestartSocket`),X(this,`pauseSocket`),X(this,`resumeSocket`),X(this,`clearAuth`),X(this,`logger`),X(this,`refreshTokenLeewaySeconds`),X(this,`initialAuthTokenReuse`),X(this,`lastRefreshChange`),X(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=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),await this.refetchToken()),this._logVerbose(`resuming WS after auth token fetch`),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,config:this.authState.config,token:t.value,hadAuth:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(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(this.authState.state===`noAuth`)return;this._logVerbose(`refetching auth token`);let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:`notRefetching`,config:this.authState.config}):(this._logVerbose(`refetching token failed`),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose(`restarting WS after auth token fetch (if currently stopped)`),this.tryRestartSocket())}scheduleTokenRefetch(e,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{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;break;case`waitingForServerConfirmationOfFreshToken`:case`waitingForServerConfirmationOfCachedToken`:case`initialRefetch`:break;default:}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return Y(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 lt=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function ut(e,t){let n={sessionId:t};typeof performance>`u`||!performance.mark||performance.mark(e,{detail:n})}function dt(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function ft(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of lt){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(dt)}var pt=Object.defineProperty,mt=(e,t,n)=>t in e?pt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Z=(e,t,n)=>mt(e,typeof t==`symbol`?t:t+``,n),ht=class{constructor(e,t,n){if(Z(this,`address`),Z(this,`state`),Z(this,`requestManager`),Z(this,`webSocketManager`),Z(this,`authenticationManager`),Z(this,`remoteQuerySet`),Z(this,`optimisticQueryResults`),Z(this,`_transitionHandlerCounter`,0),Z(this,`_nextRequestId`),Z(this,`_onTransitionFns`,new Map),Z(this,`_sessionId`),Z(this,`firstMessageReceived`,!1),Z(this,`debug`),Z(this,`logger`),Z(this,`maxObservedTimestamp`),Z(this,`connectionStateSubscribers`,new Map),Z(this,`nextConnectionStateSubscriberId`,0),Z(this,`_lastPublishedConnectionState`),Z(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),Z(this,`mark`,e=>{this.debug&&ut(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&te(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)throw Error(`No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient`);i||=WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?Ee({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Te({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${O}/sync`;this.state=new Me,this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger),this.requestManager=new Fe(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new ct(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new ze,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=nt();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&window.addEventListener(`beforeunload`,e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t=`Are you sure you want to leave? Your changes may not be saved.`;return(e||window.event).returnValue=t,t}});this.webSocketManager=new tt(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new U(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let 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);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case`MutationResponse`:{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);t!==null&&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`:{let t=De(this.logger,e.error);throw this.webSocketManager.terminate(),t}default:}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.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(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType===`User`)try{t=e?Y(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=m(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=P(e,m(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=P(e,m(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=P(e,m(t));return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(j(`mutation`,e,r)):M(r,new D(j(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=m(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[w(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(j(`action`,e,n)):M(n,new D(j(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=m(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[w(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,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){let e=ft(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${O}`},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 Q(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var gt=Object.defineProperty,_t=(e,t,n)=>t in e?gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,vt=(e,t,n)=>_t(e,typeof t==`symbol`?t:t+``,n),yt=class{constructor(e,t){this.client=e,this.onTransition=t,vt(this,`paginatedQuerySet`,new Map),vt(this,`lastTransitionTs`),this.lastTransitionTs=z.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=N(e),i=Oe(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=Oe(N(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=Q(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=Q(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=Q(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},bt=Object.defineProperty,xt=(e,t,n)=>t in e?bt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$=(e,t,n)=>xt(e,typeof t==`symbol`?t:t+``,n),St=class{constructor(e,t={}){$(this,`listeners`),$(this,`_client`),$(this,`_paginatedClient`),$(this,`callNewListenersWithCurrentValuesTimer`),$(this,`_closed`),$(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&te(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new ht(e,()=>{},r),this._paginatedClient=new yt(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:a,unsubscribe:o}=this.client.subscribe(e(t),n),s={queryToken:a,callback:r,onError:i,unsubscribe:o,hasEverRun:!1,query:t,args:n,paginationOptions:void 0};this.listeners.add(s),this.queryResultReady(a)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let c={unsubscribe:()=>{this.closed||(this.listeners.delete(s),o())},getCurrentValue:()=>this.client.localQueryResultByToken(a),getQueryLogs:()=>this.client.localQueryLogs(a)},l=c.unsubscribe;return Object.assign(l,c),l}onPaginatedUpdate_experimental(t,n,r,i,a){if(this.disabled)return this.createDisabledUnsubscribe();let o={initialNumItems:r.initialNumItems,id:-1},{paginatedQueryToken:s,unsubscribe:c}=this.paginatedClient.subscribe(e(t),n,o),l={queryToken:s,callback:i,onError:a,unsubscribe:c,hasEverRun:!1,query:t,args:n,paginationOptions:o};this.listeners.add(l),this.paginatedClient.localQueryResultByToken(s)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let u={unsubscribe:()=>{this.closed||(this.listeners.delete(l),c())},getCurrentValue:()=>this.paginatedClient.localQueryResult(e(t),n,o),getQueryLogs:()=>[]},d=u.unsubscribe;return Object.assign(d,u),d}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,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 Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=ke(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(t,n,r){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(e(t),n,r)}async action(t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(e(t),n)}async query(t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);let r=this.client.localQueryResult(e(t),n);return r===void 0?new Promise((e,r)=>{let{unsubscribe:i}=this.onUpdate(t,n,t=>{i(),e(t)},e=>{i(),r(e)})}):Promise.resolve(r)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}};function Ct(e,t){let n=e.trim();if(!/^https:\/\/[^/]+$/.test(n))throw Error(`A valid HTTPS Convex deployment URL is required`);let r=new St(n);return r.setAuth(t),r}function wt(e,n){let r=e.trim();if(!r)throw Error(`Convex deployment URL is required`);return{async resolve(e){let i=await n.fetchAccessToken(kt(e,!1));if(!i)throw Error(`Convex review authentication is required`);let a=i,o=(n.clientFactory??Ct)(r,async({forceRefreshToken:t})=>{if(!t&&a){let e=a;return a=null,e}return n.fetchAccessToken({...kt(e,t),signal:new AbortController().signal})}),s=await o.mutation(t.resolveSession,{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.routeKey===void 0?{}:{routeKey:e.routeKey}}),c=At(s.session,e.invitationId),l=0;return Tt({client:o,session:c,request:e,pageId:s.pageId,resolvePage:async n=>{if(n.location.origin!==e.location.origin)throw Error(`Convex review session cannot move to another origin`);let r=++l,i=await o.mutation(t.resolveSession,{invitationId:e.invitationId,origin:n.location.origin,pathname:n.location.pathname,...n.routeKey===void 0?{}:{routeKey:n.routeKey}});if(n.signal.aborted||r!==l)throw jt();return{pageId:i.pageId,...n.cursorChat?{cursorChatRoomId:Ot(i.pageId)}:{}}},cursorChatRepositoryFactory:n.cursorChatRepositoryFactory})}}}async function Tt(e){let t=new n(e.client,e.session,{origin:e.request.location.origin}),r;if(e.request.cursorChat)try{r=await Et(e.client,e.session,e.request.location.origin,e.cursorChatRepositoryFactory)}catch{}return{pageId:e.pageId,session:e.session,repository:t,...r?{cursorChatRepository:r,cursorChatRoomId:Ot(e.pageId)}:{},resolvePage:e.resolvePage,allowedStagingHosts:[e.request.location.hostname]}}async function Et(e,t,n,r=Dt){return r(e,t,n)}async function Dt(e,t,n){let{ConvexReviewCursorChatRepository:r}=await import(`./cursor-chat-repository-B2hY4vVl.js`);return new r(e,t,{origin:n})}function Ot(e){return`cursor-chat:${e}`}function kt(e,t){return{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname,...e.emailToken===void 0?{}:{emailToken:e.emailToken},forceRefreshToken:t,signal:e.signal}}function At(e,t){if(!e||e.invitationId!==t||!e.authUserId||!e.reviewerId||!e.projectId)throw Error(`Convex returned an invalid reviewer session`);return structuredClone(e)}function jt(){return Object.assign(Error(`Review page resolution was superseded`),{code:`PAGE_SWAP_SUPERSEDED`})}export{wt as createConvexReviewRuntime};
@@ -1 +1 @@
1
- import{n as e,r as t}from"./review-repository-B3NZ_Tqo.js";var n=class{client;#e=new Map;#t;#n;#r;#i;#a;#o;constructor(e,t,n){this.client=e,this.#t=t.invitationId.trim(),this.#n=new URL(n.origin).origin,this.#r=i(n.cursorThrottleMs??80,40,1e3),this.#i=i(n.heartbeatMs??1e4,2e3,2e4),this.#a=n.now??Date.now,this.#o=n.sessionId??(()=>globalThis.crypto.randomUUID())}subscribe(n,r,i,a){let o=!1,s=[],c=this.#s(n,r.roomId,a),l=()=>{o||i({pageId:n,peers:structuredClone(s)})},u;try{u=this.client.onUpdate(t.presenceList,{...this.#d(),pageId:n,roomId:r.roomId},e=>{let t=this.#a();s=e.filter(({peerId:e,expiresAt:n})=>e!==c.sessionId&&n>t).map(({expiresAt:e,...t})=>t).sort((e,t)=>e.displayName.localeCompare(t.displayName)||e.peerId.localeCompare(t.peerId)),l()},t=>a?.(e(t)))}catch(e){throw this.#u(c),e}return queueMicrotask(l),()=>{o||(o=!0,u(),this.#u(c))}}publishPresence(e,t,n){let i=this.#e.get(r(e,t));!i||i.stopped||(i.current={...n},i.latest={...i.current},this.#c(i))}#s(e,t,n){let i=r(e,t),a=this.#e.get(i);a&&this.#u(a);let o={pageId:e,roomId:t,sessionId:this.#o(),stopped:!1,lastSentAt:-1/0,inFlight:!1,onFailure:n};return o.heartbeatTimer=setInterval(()=>{o.stopped||!o.current||(o.latest??={...o.current},this.#c(o))},this.#i),this.#e.set(i,o),o}#c(e){if(e.inFlight||e.flushTimer||e.stopped)return;let t=Math.max(0,this.#r-(this.#a()-e.lastSentAt));if(t===0){this.#l(e);return}e.flushTimer=setTimeout(()=>{e.flushTimer=void 0,this.#l(e)},t)}async#l(n){if(n.stopped||n.inFlight||!n.latest)return;n.inFlight=!0;let r=n.latest;n.latest=void 0;try{await this.client.mutation(t.presenceUpdate,{...this.#d(),pageId:n.pageId,roomId:n.roomId,sessionId:n.sessionId,active:r.active,...r.pathname===void 0?{}:{pathname:r.pathname},...r.cursorX===void 0?{}:{cursorX:r.cursorX},...r.cursorY===void 0?{}:{cursorY:r.cursorY},...r.viewportWidth===void 0?{}:{viewportWidth:r.viewportWidth},...r.viewportHeight===void 0?{}:{viewportHeight:r.viewportHeight},...r.cursorChat===void 0?{}:{cursorChat:r.cursorChat}}),n.lastSentAt=this.#a()}catch(t){n.onFailure?.(e(t))}finally{n.inFlight=!1,n.latest&&this.#c(n)}}#u(e){e.stopped||(e.stopped=!0,e.current=void 0,e.latest=void 0,e.flushTimer&&clearTimeout(e.flushTimer),e.heartbeatTimer&&clearInterval(e.heartbeatTimer),this.#e.delete(r(e.pageId,e.roomId)),this.client.mutation(t.presenceDisconnect,{...this.#d(),sessionId:e.sessionId}).catch(()=>void 0))}#d(){return{invitationId:this.#t,origin:this.#n}}};function r(e,t){return`${e}\u0000${t}`}function i(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):t}export{n as ConvexReviewCursorChatRepository};
1
+ import{n as e,r as t}from"./review-repository-DJTt7aZR.js";var n=class{client;#e=new Map;#t;#n;#r;#i;#a;#o;constructor(e,t,n){this.client=e,this.#t=t.invitationId.trim(),this.#n=new URL(n.origin).origin,this.#r=i(n.cursorThrottleMs??80,40,1e3),this.#i=i(n.heartbeatMs??1e4,2e3,2e4),this.#a=n.now??Date.now,this.#o=n.sessionId??(()=>globalThis.crypto.randomUUID())}subscribe(n,r,i,a){let o=!1,s=[],c=this.#s(n,r.roomId,a),l=()=>{o||i({pageId:n,peers:structuredClone(s)})},u;try{u=this.client.onUpdate(t.presenceList,{...this.#d(),pageId:n,roomId:r.roomId},e=>{let t=this.#a();s=e.filter(({peerId:e,expiresAt:n})=>e!==c.sessionId&&n>t).map(({expiresAt:e,...t})=>t).sort((e,t)=>e.displayName.localeCompare(t.displayName)||e.peerId.localeCompare(t.peerId)),l()},t=>a?.(e(t)))}catch(e){throw this.#u(c),e}return queueMicrotask(l),()=>{o||(o=!0,u(),this.#u(c))}}publishPresence(e,t,n){let i=this.#e.get(r(e,t));!i||i.stopped||(i.current={...n},i.latest={...i.current},this.#c(i))}#s(e,t,n){let i=r(e,t),a=this.#e.get(i);a&&this.#u(a);let o={pageId:e,roomId:t,sessionId:this.#o(),stopped:!1,lastSentAt:-1/0,inFlight:!1,onFailure:n};return o.heartbeatTimer=setInterval(()=>{o.stopped||!o.current||(o.latest??={...o.current},this.#c(o))},this.#i),this.#e.set(i,o),o}#c(e){if(e.inFlight||e.flushTimer||e.stopped)return;let t=Math.max(0,this.#r-(this.#a()-e.lastSentAt));if(t===0){this.#l(e);return}e.flushTimer=setTimeout(()=>{e.flushTimer=void 0,this.#l(e)},t)}async#l(n){if(n.stopped||n.inFlight||!n.latest)return;n.inFlight=!0;let r=n.latest;n.latest=void 0;try{await this.client.mutation(t.presenceUpdate,{...this.#d(),pageId:n.pageId,roomId:n.roomId,sessionId:n.sessionId,active:r.active,...r.pathname===void 0?{}:{pathname:r.pathname},...r.cursorX===void 0?{}:{cursorX:r.cursorX},...r.cursorY===void 0?{}:{cursorY:r.cursorY},...r.viewportWidth===void 0?{}:{viewportWidth:r.viewportWidth},...r.viewportHeight===void 0?{}:{viewportHeight:r.viewportHeight},...r.cursorChat===void 0?{}:{cursorChat:r.cursorChat}}),n.lastSentAt=this.#a()}catch(t){n.onFailure?.(e(t))}finally{n.inFlight=!1,n.latest&&this.#c(n)}}#u(e){e.stopped||(e.stopped=!0,e.current=void 0,e.latest=void 0,e.flushTimer&&clearTimeout(e.flushTimer),e.heartbeatTimer&&clearInterval(e.heartbeatTimer),this.#e.delete(r(e.pageId,e.roomId)),this.client.mutation(t.presenceDisconnect,{...this.#d(),sessionId:e.sessionId}).catch(()=>void 0))}#d(){return{invitationId:this.#t,origin:this.#n}}};function r(e,t){return`${e}\u0000${t}`}function i(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):t}export{n as ConvexReviewCursorChatRepository};
@@ -0,0 +1,13 @@
1
+ import{r as e}from"./install-DAqwiYRg.js";var t=class extends Error{code;constructor(e,t){super(t),this.code=e,this.name=`ReviewBootstrapError`}};function n(e,t,n=``,r){if(t.aborted)return Promise.reject(d());let i=o(e);i.replaceChildren(s(i,r),c(i));let a=i.querySelector(`form`),l=a.elements.namedItem(`displayName`),u=i.querySelector(`button`),p=i.querySelector(`.error`);return l.value=n.trim().slice(0,120),l.focus(),l.select(),new Promise((e,n)=>{let r=!1,o=e=>{r||(r=!0,t.removeEventListener(`abort`,s),i.removeEventListener(`keydown`,h),a.removeEventListener(`submit`,m),e())},s=()=>o(()=>n(d())),c=()=>{let t=l.value.trim();if(!t){p.textContent=`이름을 입력해 주세요.`,l.focus();return}if(t.length>120){p.textContent=`이름은 120자 이하여야 합니다.`,l.focus();return}p.textContent=``,u.disabled=!0,a.setAttribute(`aria-busy`,`true`),o(()=>e(t))},m=e=>{e.preventDefault(),c()},h=e=>{let t=e;if(t.key===`Escape`){t.preventDefault(),s();return}if(t.key===`Tab`){f(i,t);return}t.key===`Enter`&&!t.isComposing&&t.target===l&&(t.preventDefault(),c())};t.addEventListener(`abort`,s,{once:!0}),i.addEventListener(`keydown`,h),a.addEventListener(`submit`,m)})}function r(e,t,n){if(t.aborted)return Promise.reject(d());let r=o(e);r.replaceChildren(s(r,n),l(r));let i=r.querySelector(`form`),a=r.querySelector(`button`);return a.focus(),new Promise((e,n)=>{let o=!1,s=e=>{o||(o=!0,t.removeEventListener(`abort`,c),r.removeEventListener(`keydown`,u),i.removeEventListener(`submit`,l),e())},c=()=>s(()=>n(d())),l=t=>{t.preventDefault(),a.disabled=!0,i.setAttribute(`aria-busy`,`true`),s(e)},u=e=>{let t=e;t.key===`Escape`?(t.preventDefault(),c()):t.key===`Tab`&&f(r,t)};t.addEventListener(`abort`,c,{once:!0}),r.addEventListener(`keydown`,u),i.addEventListener(`submit`,l)})}function i(e,t,n,r){if(t.aborted)return Promise.reject(d());let i=o(e),a=s(i,r);return new Promise((e,r)=>{let o=!1,s=null,c=null,l=()=>{s&&c&&s.removeEventListener(`submit`,c),s=null,c=null},p=e=>{o||(o=!0,t.removeEventListener(`abort`,m),i.removeEventListener(`keydown`,h),l(),e())},m=()=>p(()=>r(d())),h=e=>{let t=e;t.key===`Escape`?(t.preventDefault(),m()):t.key===`Tab`&&f(i,t)},g=(e,t)=>{l(),s=e,c=t,e.addEventListener(`submit`,t),i.replaceChildren(a,e)},_=(t,r)=>{let a=i.ownerDocument,o=a.createElement(`form`);o.setAttribute(`role`,`dialog`),o.setAttribute(`aria-modal`,`true`);let s=u(a,`p`,`01.works`,`eyebrow`),c=u(a,`h2`,`이메일 확인`),l=u(a,`p`,`${r.emailHint}로 보낸 6자리 코드를 입력하세요.`,`description`),d=u(a,`label`,`인증 코드`),f=a.createElement(`input`);f.name=`code`,f.inputMode=`numeric`,f.autocomplete=`one-time-code`,f.pattern=`[0-9]{6}`,f.maxLength=6,f.required=!0;let m=u(a,`p`,``,`error`);m.setAttribute(`role`,`alert`);let h=u(a,`button`,`리뷰 시작`);h.type=`submit`,d.append(f),o.append(s,c,l,d,m,h),g(o,i=>{i.preventDefault();let a=f.value.trim();if(!/^\d{6}$/u.test(a)){m.textContent=`6자리 숫자를 입력해 주세요.`;return}h.disabled=!0,o.setAttribute(`aria-busy`,`true`),m.textContent=``,n.verifyCode(r.challengeId,r.attemptId,t,a).then(t=>p(()=>e(t)),e=>{h.disabled=!1,o.removeAttribute(`aria-busy`),m.textContent=e instanceof Error?e.message:`인증 코드를 확인하지 못했습니다.`,f.select()})}),f.focus()},v=i.ownerDocument,y=v.createElement(`form`);y.setAttribute(`role`,`dialog`),y.setAttribute(`aria-modal`,`true`);let b=u(v,`p`,`01.works`,`eyebrow`),x=u(v,`h2`,`리뷰 로그인`),S=u(v,`p`,`초대받은 이메일로 인증 코드를 보내드립니다.`,`description`),C=u(v,`label`,`이메일`),w=v.createElement(`input`);w.name=`email`,w.type=`email`,w.autocomplete=`email`,w.required=!0;let T=u(v,`p`,``,`error`);T.setAttribute(`role`,`alert`);let E=u(v,`button`,`인증 코드 받기`);E.type=`submit`,C.append(w),y.append(b,x,S,C,T,E),g(y,e=>{e.preventDefault();let t=w.value.trim().toLowerCase();if(t.length>320||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)){T.textContent=`유효한 이메일을 입력해 주세요.`;return}E.disabled=!0,y.setAttribute(`aria-busy`,`true`),T.textContent=``,n.requestCode(t).then(e=>_(t,e),e=>{E.disabled=!1,y.removeAttribute(`aria-busy`),T.textContent=e instanceof Error?e.message:`인증 코드를 보내지 못했습니다.`})}),t.addEventListener(`abort`,m,{once:!0}),i.addEventListener(`keydown`,h),i.replaceChildren(a,y),w.focus()})}async function a(e,t,n,r){if(t.aborted)throw d();let i=await n.requestCode();if(t.aborted)throw d();let a=o(e),c=a.ownerDocument.createElement(`form`);c.setAttribute(`role`,`dialog`),c.setAttribute(`aria-modal`,`true`);let l=u(a.ownerDocument,`p`,`01.works`,`eyebrow`),p=u(a.ownerDocument,`h2`,`리뷰 접속 복구`),m=u(a.ownerDocument,`p`,`${i.emailHint}로 보낸 6자리 코드를 입력하세요.`,`description`),h=u(a.ownerDocument,`label`,`복구 코드`),g=a.ownerDocument.createElement(`input`);g.name=`code`,g.inputMode=`numeric`,g.autocomplete=`one-time-code`,g.pattern=`[0-9]{6}`,g.maxLength=6,g.required=!0;let _=u(a.ownerDocument,`p`,``,`error`);_.setAttribute(`role`,`alert`);let v=u(a.ownerDocument,`button`,`접속 복구`);return v.type=`submit`,h.append(g),c.append(l,p,m,h,_,v),a.replaceChildren(s(a,r),c),g.focus(),new Promise((e,r)=>{let o=!1,s=e=>{o||(o=!0,t.removeEventListener(`abort`,l),a.removeEventListener(`keydown`,u),c.removeEventListener(`submit`,p),e())},l=()=>s(()=>r(d())),u=e=>{let t=e;t.key===`Escape`?(t.preventDefault(),l()):t.key===`Tab`&&f(a,t)},p=t=>{t.preventDefault();let r=g.value.trim();if(!/^\d{6}$/.test(r)){_.textContent=`6자리 숫자를 입력해 주세요.`;return}v.disabled=!0,c.setAttribute(`aria-busy`,`true`),_.textContent=``,n.verifyCode(i.challengeId,r).then(t=>s(()=>e(t)),e=>{v.disabled=!1,c.removeAttribute(`aria-busy`),_.textContent=e instanceof Error?e.message:`복구 코드를 확인하지 못했습니다.`,g.select()})};t.addEventListener(`abort`,l,{once:!0}),a.addEventListener(`keydown`,u),c.addEventListener(`submit`,p)})}function o(e){return e.shadowRoot??e.attachShadow({mode:`open`})}function s(e,t){let n=e.ownerDocument.createElement(`style`);return t&&(n.nonce=t),n.textContent=p,n}function c(e){let t=e.ownerDocument,n=t.createElement(`form`);n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-labelledby`,`visual-review-name-title`),n.setAttribute(`aria-describedby`,`visual-review-name-description`);let r=u(t,`p`,`01.works`,`eyebrow`),i=u(t,`h2`,`표시 이름`);i.id=`visual-review-name-title`;let a=u(t,`p`,`피드백에 이 이름이 표시됩니다.`,`description`);a.id=`visual-review-name-description`;let o=u(t,`label`,`이름`);o.htmlFor=`visual-review-display-name`;let s=t.createElement(`input`);s.id=`visual-review-display-name`,s.name=`displayName`,s.autocomplete=`name`,s.maxLength=120,s.required=!0;let c=u(t,`p`,``,`error`);c.setAttribute(`role`,`alert`);let l=u(t,`button`,`리뷰 시작`);return l.type=`submit`,n.append(r,i,a,o,s,c,l),n}function l(e){let t=e.ownerDocument,n=t.createElement(`form`);n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-modal`,`true`),n.setAttribute(`aria-labelledby`,`visual-review-invitation-title`),n.setAttribute(`aria-describedby`,`visual-review-invitation-description`);let r=u(t,`p`,`01.works`,`eyebrow`),i=u(t,`h2`,`리뷰 초대`);i.id=`visual-review-invitation-title`;let a=u(t,`p`,`초대받은 프로젝트를 열고 화면에 피드백을 남길 수 있습니다.`,`description`);a.id=`visual-review-invitation-description`;let o=u(t,`button`,`리뷰 시작`);return o.type=`submit`,n.append(r,i,a,o),n}function u(e,t,n,r){let i=e.createElement(t);return i.textContent=n,r&&(i.className=r),i}function d(){return new t(`AUTH_CANCELLED`,`리뷰 로그인이 취소되었습니다.`)}function f(e,t){let n=Array.from(e.querySelectorAll(`input:not([disabled]),button:not([disabled])`)).filter(e=>!e.closest(`[hidden]`));if(n.length===0)return;let r=n[0],i=n.at(-1);t.shiftKey&&e.activeElement===r?(t.preventDefault(),i.focus()):!t.shiftKey&&e.activeElement===i&&(t.preventDefault(),r.focus())}const p=`
2
+ :host{all:initial;--vr-panel:#fff;--vr-text:#161616;--vr-muted:#707070;--vr-label:#3f3f3f;--vr-control:#fff;--vr-border:#d9d9d9;--vr-action:#161616;--vr-action-text:#fff;position:fixed;inset:0;z-index:2147483646;display:grid;place-items:center;overflow:auto;padding:8px;box-sizing:border-box;background:rgba(15,15,15,.34);font-family:Inter,ui-sans-serif,system-ui,sans-serif;color:var(--vr-text)}
3
+ form{box-sizing:border-box;width:min(320px,calc(100vw - 16px));padding:20px;border:0;border-radius:14px;background:var(--vr-panel);box-shadow:0 18px 56px rgba(0,0,0,.18)}
4
+ .eyebrow{margin:0 0 10px;color:var(--vr-muted);font-size:10px;font-weight:700;letter-spacing:.09em;text-transform:uppercase}
5
+ h2{margin:0 0 5px;font-size:16px;line-height:1.3;letter-spacing:-.01em}.description{margin:0 0 18px;color:var(--vr-muted);font-size:13px;line-height:1.45}
6
+ [hidden]{display:none!important}label{display:grid;gap:6px;margin-top:12px;color:var(--vr-label);font-size:12px;font-weight:600}input{box-sizing:border-box;width:100%;height:40px;margin-top:6px;padding:0 11px;border:1px solid var(--vr-border);border-radius:9px;background:var(--vr-control);color:var(--vr-text);font:400 13px/1 Inter,ui-sans-serif,system-ui,sans-serif}
7
+ label input{margin-top:0}input:focus{border-color:#999;outline:0;box-shadow:0 0 0 3px rgba(127,127,127,.16)}.error{min-height:17px;margin:8px 0 0;color:#d92d20;font-size:11px;line-height:1.45}
8
+ button{width:100%;height:40px;margin-top:7px;border:0;border-radius:9px;background:var(--vr-action);color:var(--vr-action-text);font:650 13px/1 Inter,ui-sans-serif,system-ui,sans-serif;cursor:pointer}button:focus-visible{outline:2px solid var(--vr-action);outline-offset:2px}button:disabled{opacity:.55;cursor:wait}
9
+ @media (prefers-color-scheme:dark){:host{--vr-panel:#161616;--vr-text:#fff;--vr-muted:#a7a7a7;--vr-label:#d6d6d6;--vr-control:#222;--vr-border:#3a3a3a;--vr-action:#fff;--vr-action-text:#171717}}
10
+ @media (pointer:coarse){input,button{height:44px}}
11
+ @media (max-width:480px){form{padding:18px}input{font-size:16px}}
12
+ @media (prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
13
+ `;function m(e){let t=[`01works-reviewer-device-proof-v1`,e.purpose,e.deviceSessionId,e.challengeId,e.challenge,String(e.counter),String(e.expiresAt),e.invitationId,e.origin,e.pathname];return new TextEncoder().encode(t.map(e=>`${e.length}:${e}`).join(``))}const h=`reviewer-device-credentials-v1`;function g(){try{return globalThis.indexedDB?new y(globalThis.indexedDB):null}catch{return null}}async function _(e=globalThis.crypto){if(!e?.subtle||typeof e.randomUUID!=`function`)throw Error(`Visual Review device authentication requires Web Crypto`);let t=await e.subtle.generateKey({name:`ECDSA`,namedCurve:`P-256`},!1,[`sign`,`verify`]);if(!(t instanceof Object)||!(`privateKey`in t)||!(`publicKey`in t)||t.privateKey.extractable)throw Error(`Visual Review could not create a non-extractable device key`);let n=await e.subtle.exportKey(`jwk`,t.publicKey);if(n.kty!==`EC`||n.crv!==`P-256`||typeof n.x!=`string`||typeof n.y!=`string`)throw Error(`Visual Review received an invalid device public key`);return{deviceSessionId:e.randomUUID(),privateKey:t.privateKey,publicKey:{kty:`EC`,crv:`P-256`,x:n.x,y:n.y}}}async function v(e,t,n=globalThis.crypto){if(e.extractable||e.type!==`private`||e.algorithm.name!==`ECDSA`||!e.usages.includes(`sign`))throw Error(`Visual Review device key is invalid`);let r=await n.subtle.sign({name:`ECDSA`,hash:`SHA-256`},e,m(t));return C(new Uint8Array(r))}var y=class{factory;constructor(e){this.factory=e}async get(e){let t=await this.open();try{return b(await x(t.transaction(h,`readonly`).objectStore(h).get(e)))}finally{t.close()}}async set(e,t){let n=await this.open();try{await S(n.transaction(h,`readwrite`),n=>{n.put(t,e)})}finally{n.close()}}async delete(e){let t=await this.open();try{await S(t.transaction(h,`readwrite`),t=>{t.delete(e)})}finally{t.close()}}open(){return new Promise((e,t)=>{let n=this.factory.open(`01works-visual-review`,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(h)||n.result.createObjectStore(h)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??Error(`IndexedDB open failed`)),n.onblocked=()=>t(Error(`IndexedDB upgrade blocked`))})}};function b(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;return typeof t.deviceSessionId!=`string`||!Number.isSafeInteger(t.expiresAt)||(t.expiresAt??0)<=Date.now()||t.invitationId!==void 0&&typeof t.invitationId!=`string`||!t.privateKey||t.privateKey.type!==`private`||t.privateKey.extractable||t.privateKey.algorithm.name!==`ECDSA`||!t.privateKey.usages.includes(`sign`)?null:t}function x(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??Error(`IndexedDB request failed`))})}function S(e,t){return new Promise((n,r)=>{e.oncomplete=()=>n(),e.onerror=()=>r(e.error??Error(`IndexedDB transaction failed`)),e.onabort=()=>r(e.error??Error(`IndexedDB transaction aborted`)),t(e.objectStore(h))})}function C(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replaceAll(`+`,`-`).replaceAll(`/`,`_`).replace(/=+$/u,``)}var w=class extends Error{code;status;constructor(e,t,n){super(t),this.code=e,this.status=n,this.name=`HostedBootstrapError`}};function T(e={}){return E(e)}function E(t={},n={}){let r=e(t.serviceUrl??`https://review.01.works`),i=globalThis.fetch,a=t.fetch??(typeof i==`function`?i.bind(globalThis):void 0),o=n.now??Date.now,s=new Map,c=n.reviewerDeviceStore===void 0?g():n.reviewerDeviceStore,l=n.crypto??globalThis.crypto,u=n.reviewerSessionStorage===void 0?q(ae(),oe()):q(n.reviewerSessionStorage);if(typeof a!=`function`)throw Error(`Visual Review bootstrap requires the Fetch API`);return{async resolve(e){let t=H(e),i=await U(r,a,t,e.signal),d=o(),f=await ee({config:i,convexRuntimeFactory:n.convexRuntimeFactory??(await import(`./convex-runtime-Bkk8o32N.js`)).createConvexReviewRuntime,fetcher:a,memorySessions:s,navigateToAccountBridge:n.navigateToAccountBridge,reviewerDeviceStore:c,cryptoProvider:l,request:e,legacySessionStorages:u,serviceUrl:r}),p=f.resolvePage;if(!p)return f;let m=async t=>{await U(r,a,{invitationId:e.invitationId,origin:t.location.origin,pathname:t.location.pathname},t.signal),d=o()};return{...f,resolvePage:async e=>(o()-d>=3e5&&await m(e),p(e))}}}}async function ee(e){let t=e.config.accessScope?.kind===`project`?e.config.accessScope:null,n=K(e.serviceUrl,e.request.location.origin,t?.locator??e.config.sessionLocator??e.request.invitationId),i=K(e.serviceUrl,e.request.location.origin,e.request.invitationId);X(e.legacySessionStorages,n),i!==n&&X(e.legacySessionStorages,i);let a;if(t){if(a=await J(e.reviewerDeviceStore,e.memorySessions,n),a&&!a.invitationId&&(await Y(e.reviewerDeviceStore,e.memorySessions,n),a=null),!a){let n=await _(e.cryptoProvider);a=e.request.accountToken?await ne(e,e.request.accountToken,n).catch(r=>{if(!(r instanceof w))throw r;if(r.code===`INVITATION_NOT_FOUND`&&t.mode===`email`)return D(e,t.locator,n);if(r.code===`INVITATION_TOKEN_USED`||r.code===`INVITATION_TOKEN_INVALID`||r.code===`ACCOUNT_ASSERTION_EXPIRED`||r.code===`AUTH_REQUIRED`||r.code===`INVALID_INPUT`)return O(e,t.locator);throw r}):e.request.accountBridgeAttempted?t.mode===`link`?await te(e,t.locator,n):await D(e,t.locator,n):await O(e,t.locator)}}else if(e.request.emailToken){await r(e.request.authHost,e.request.signal,e.request.styleNonce);let t=await _(e.cryptoProvider);try{a=await P(e.serviceUrl,e.fetcher,{invitationId:e.request.invitationId,emailToken:e.request.emailToken,origin:e.request.location.origin,pathname:e.request.location.pathname,signal:e.request.signal,device:t})}catch(n){if(!(n instanceof w)||n.code!==`INVITATION_TOKEN_USED`)throw n;a=await A(e,t)}}else a=await J(e.reviewerDeviceStore,e.memorySessions,n),!a&&i!==n&&(a=await J(e.reviewerDeviceStore,e.memorySessions,i),a&&await Y(e.reviewerDeviceStore,e.memorySessions,i));a||=await A(e,await _(e.cryptoProvider));let o=t?a.invitationId:e.request.invitationId;if(!o)throw new w(`INVALID_PROJECT_ACCESS_RESPONSE`,`프로젝트 리뷰 인증 응답이 올바르지 않습니다.`,502);a={...a,invitationId:o},await se(e.reviewerDeviceStore,e.memorySessions,n,a);let{expiresAt:s}=a,c={...e.request,invitationId:o,emailToken:void 0,accountToken:void 0,accountBridgeAttempted:void 0};return{...await e.convexRuntimeFactory(e.config.convexUrl,{fetchAccessToken:t=>j(e.serviceUrl,e.fetcher,a,t,e.cryptoProvider,()=>Y(e.reviewerDeviceStore,e.memorySessions,n))}).resolve(c),sessionScope:`browser`,sessionExpiresAt:s??e.config.invitationExpiresAt,clearLocalSession:()=>{Y(e.reviewerDeviceStore,e.memorySessions,n);let t=new AbortController,r=setTimeout(()=>t.abort(),5e3);N(e.serviceUrl,e.fetcher,a,{invitationId:o,origin:e.request.location.origin,pathname:e.request.location.pathname,forceRefreshToken:!1,signal:t.signal},e.cryptoProvider).catch(()=>void 0).finally(()=>clearTimeout(r))}}}async function D(e,t,n){let r={reviewLocator:t,pathname:e.request.location.pathname,signal:e.request.signal};return i(e.request.authHost,e.request.signal,{requestCode:t=>I(e.serviceUrl,e.fetcher,{...r,email:t}),verifyCode:(t,i,a,o)=>L(e.serviceUrl,e.fetcher,{...r,challengeId:t,attemptId:i,email:a,code:o,device:n})},e.request.styleNonce)}async function te(e,t,r){let i=await n(e.request.authHost,e.request.signal,``,e.request.styleNonce),a=await e.fetcher(`${e.serviceUrl}/v1/reviewer/link/start`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({reviewLocator:t,displayName:i,pathname:e.request.location.pathname,deviceSessionId:r.deviceSessionId,devicePublicKey:r.publicKey}),cache:`no-store`,credentials:`omit`,signal:e.request.signal}),o=await Z(a),s=Q(o,`invitationId`),c=Q(o,`deviceSessionId`),l=G($(o,`expiresAt`));if(!a.ok||c!==r.deviceSessionId||!s||l==null)throw new w(Q(o,`error`)??`LINK_ACCESS_FAILED`,Q(o,`message`)??`링크 리뷰를 시작하지 못했습니다.`,a.status);return{deviceSessionId:c,privateKey:r.privateKey,invitationId:s,expiresAt:l}}async function O(e,t){let n=await e.fetcher(`${e.serviceUrl}/v1/reviewer/account/start`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({reviewLocator:t,pathname:e.request.location.pathname,returnPath:`${e.request.location.pathname}${e.request.location.search??``}`,returnHash:e.request.location.hash??``}),cache:`no-store`,credentials:`omit`,signal:e.request.signal}),r=await Z(n),i=Q(r,`continueUrl`);throw!n.ok||!i||!k(i,e.serviceUrl)?new w(Q(r,`error`)??`ACCOUNT_BRIDGE_FAILED`,Q(r,`message`)??`로그인 상태를 확인하지 못했습니다.`,n.status):((e.navigateToAccountBridge??(e=>{globalThis.location.assign(e)}))(i),new w(`ACCOUNT_BRIDGE_REDIRECT`,`로그인 상태를 확인하는 중입니다.`,0))}async function ne(e,t,n){let r=await e.fetcher(`${e.serviceUrl}/v1/reviewer/account/redeem`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({assertionToken:t,pathname:e.request.location.pathname,deviceSessionId:n.deviceSessionId,devicePublicKey:n.publicKey}),cache:`no-store`,credentials:`omit`,signal:e.request.signal}),i=await Z(r),a=Q(i,`invitationId`),o=Q(i,`deviceSessionId`),s=G($(i,`expiresAt`));if(!r.ok||o!==n.deviceSessionId||!a||s==null)throw new w(Q(i,`error`)??`ACCOUNT_BRIDGE_FAILED`,Q(i,`message`)??`로그인 계정으로 리뷰를 시작하지 못했습니다.`,r.status);return{deviceSessionId:o,privateKey:n.privateKey,invitationId:a,expiresAt:s}}function k(e,t){try{let n=new URL(e),r=new URL(`${t}/v1/reviewer/account/continue`);return n.origin===r.origin&&n.pathname===r.pathname&&n.searchParams.has(`state`)&&n.hash===``}catch{return!1}}async function A(e,t){let n={invitationId:e.request.invitationId,pathname:e.request.location.pathname,signal:e.request.signal};return a(e.request.authHost,e.request.signal,{requestCode:()=>F(e.serviceUrl,e.fetcher,n),verifyCode:(r,i)=>R(e.serviceUrl,e.fetcher,{...n,challengeId:r,code:i,device:t})},e.request.styleNonce)}async function j(e,t,n,r,i,a){let o;try{o=await M(e,t,n.deviceSessionId,r)}catch(e){throw e instanceof w&&[401,403,409,410].includes(e.status)&&await a(),e}let s=await v(n.privateKey,{purpose:`token`,deviceSessionId:n.deviceSessionId,...o,invitationId:r.invitationId,origin:r.origin,pathname:r.pathname},i),c=await t(`${e}/v1/convex/token`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({invitationId:r.invitationId,origin:r.origin,pathname:r.pathname,deviceSessionId:n.deviceSessionId,proof:{deviceSessionId:n.deviceSessionId,...o,signature:s}}),cache:`no-store`,credentials:`omit`,signal:r.signal}),l=await Z(c),u=Q(l,`token`);if(!c.ok||!u||u.length>16e3)throw[401,403,409,410].includes(c.status)&&await a(),new w(Q(l,`error`)??`CONVEX_AUTH_FAILED`,Q(l,`message`)??`리뷰 인증을 갱신하지 못했습니다.`,c.status);return u}async function M(e,t,n,r,i=`token`){let a=await t(`${e}/v1/convex/token/challenge`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({deviceSessionId:n,invitationId:r.invitationId,origin:r.origin,pathname:r.pathname,purpose:i}),cache:`no-store`,credentials:`omit`,signal:r.signal}),o=await Z(a),s=Q(o,`challengeId`),c=Q(o,`challenge`),l=$(o,`counter`),u=G($(o,`expiresAt`));if(!a.ok||!s||!c||!Number.isSafeInteger(l)||l<1||u==null)throw new w(Q(o,`error`)??`DEVICE_CHALLENGE_FAILED`,Q(o,`message`)??`리뷰 기기 인증을 시작하지 못했습니다.`,a.status);return{challengeId:s,challenge:c,counter:l,expiresAt:u}}async function N(e,t,n,r,i){let a=await M(e,t,n.deviceSessionId,r,`revoke`),o=await v(n.privateKey,{purpose:`revoke`,deviceSessionId:n.deviceSessionId,...a,invitationId:r.invitationId,origin:r.origin,pathname:r.pathname},i);if(!(await t(`${e}/v1/convex/session/revoke`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({deviceSessionId:n.deviceSessionId,invitationId:r.invitationId,origin:r.origin,pathname:r.pathname,proof:{deviceSessionId:n.deviceSessionId,...a,signature:o}}),cache:`no-store`,credentials:`omit`,keepalive:!0,signal:r.signal})).ok)throw Error(`Reviewer device revocation failed`)}async function P(e,t,n){let r=await t(`${e}/v1/invitations/redeem-email`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({invitationId:n.invitationId,emailToken:n.emailToken,pathname:n.pathname,deviceSessionId:n.device.deviceSessionId,devicePublicKey:n.device.publicKey}),cache:`no-store`,credentials:`omit`,signal:n.signal}),i=await Z(r);if(!r.ok)throw new w(Q(i,`error`)??`INVITATION_REDEEM_FAILED`,Q(i,`message`)??`리뷰 초대를 시작하지 못했습니다.`,r.status);let a=Q(i,`deviceSessionId`);if(!a||a!==n.device.deviceSessionId)throw new w(`INVALID_INVITATION_REDEEM_RESPONSE`,`잘못된 초대 인증 응답입니다.`,502);let o=G($(i,`expiresAt`));if(o===null)throw new w(`INVALID_INVITATION_REDEEM_RESPONSE`,`잘못된 초대 인증 응답입니다.`,502);if(o===void 0)throw new w(`INVALID_INVITATION_REDEEM_RESPONSE`,`device session 만료 시각이 필요합니다.`,502);return{deviceSessionId:a,privateKey:n.device.privateKey,expiresAt:o}}async function F(e,t,n){let r=await z(e,t,`start`,n),i=Q(r,`challengeId`),a=Q(r,`emailHint`);if(!i||!a)throw new w(`INVALID_RECOVERY_RESPONSE`,`잘못된 복구 응답입니다.`,502);return{challengeId:i,emailHint:a}}async function I(e,t,n){let r=await B(e,t,`start`,n),i=Q(r,`challengeId`),a=Q(r,`attemptId`),o=Q(r,`emailHint`);if(!i||!a||!o)throw new w(`INVALID_PROJECT_ACCESS_RESPONSE`,`프로젝트 리뷰 인증 응답이 올바르지 않습니다.`,502);return{challengeId:i,attemptId:a,emailHint:o}}async function L(e,t,n){let r=await B(e,t,`verify`,n),i=Q(r,`deviceSessionId`),a=Q(r,`invitationId`),o=G($(r,`expiresAt`));if(i!==n.device.deviceSessionId||!a||o==null)throw new w(`INVALID_PROJECT_ACCESS_RESPONSE`,`프로젝트 리뷰 인증 응답이 올바르지 않습니다.`,502);return{deviceSessionId:i,privateKey:n.device.privateKey,invitationId:a,expiresAt:o}}async function R(e,t,n){let r=await z(e,t,`verify`,n),i=Q(r,`deviceSessionId`);if(!i||i!==n.device.deviceSessionId)throw new w(`INVALID_RECOVERY_RESPONSE`,`잘못된 복구 응답입니다.`,502);let a=G($(r,`expiresAt`));if(a===null)throw new w(`INVALID_RECOVERY_RESPONSE`,`잘못된 복구 응답입니다.`,502);if(a===void 0)throw new w(`INVALID_RECOVERY_RESPONSE`,`device session 만료 시각이 필요합니다.`,502);return{deviceSessionId:i,privateKey:n.device.privateKey,expiresAt:a}}async function z(e,t,n,r){let{signal:i,...a}=r,o=a;if(`device`in a&&V(a.device)){let{device:e,...t}=a;o={...t,deviceSessionId:e.deviceSessionId,devicePublicKey:e.publicKey}}let s=await t(`${e}/v1/invitations/recovery/${n}`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify(o),cache:`no-store`,credentials:`omit`,signal:i}),c=await Z(s);if(!s.ok)throw new w(Q(c,`error`)??`RECOVERY_FAILED`,Q(c,`message`)??`리뷰 접속을 복구하지 못했습니다.`,s.status);if(!c||typeof c!=`object`||Array.isArray(c))throw new w(`INVALID_RECOVERY_RESPONSE`,`잘못된 복구 응답입니다.`,502);return c}async function B(e,t,n,r){let{signal:i,...a}=r,o=a;if(`device`in a&&V(a.device)){let{device:e,...t}=a;o={...t,deviceSessionId:e.deviceSessionId,devicePublicKey:e.publicKey}}let s=await t(`${e}/v1/reviewer/access/${n}`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify(o),cache:`no-store`,credentials:`omit`,signal:i}),c=await Z(s);if(!s.ok)throw new w(Q(c,`error`)??`PROJECT_ACCESS_FAILED`,Q(c,`message`)??`프로젝트 리뷰에 로그인하지 못했습니다.`,s.status);if(!c||typeof c!=`object`||Array.isArray(c))throw new w(`INVALID_PROJECT_ACCESS_RESPONSE`,`프로젝트 리뷰 인증 응답이 올바르지 않습니다.`,502);return c}function V(e){return!!(e&&typeof e==`object`&&`deviceSessionId`in e&&`privateKey`in e&&`publicKey`in e)}function H(e){return{invitationId:e.invitationId,origin:e.location.origin,pathname:e.location.pathname}}async function U(e,t,n,r){let i=await t(`${e}/v1/bootstrap`,{method:`POST`,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify(n),cache:`no-store`,credentials:`omit`,signal:r}),a=await Z(i);if(!i.ok)throw new w(Q(a,`error`)??`BOOTSTRAP_FAILED`,Q(a,`message`)??`Visual Review bootstrap에 실패했습니다.`,i.status);return W(a)}function W(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);let t=e;if(typeof t.apiVersion==`number`&&t.apiVersion!==2)throw new w(`UNSUPPORTED_SERVICE_VERSION`,`이 Visual Review 위젯 버전은 더 이상 지원되지 않습니다. 사이트의 @01.works/visual-review를 업데이트해 주세요.`,502);if(t.apiVersion!==2)throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);let n=ce(t.convexUrl),r=G(t.invitationExpiresAt),i=re(t.accessScope),a=ie(t.sessionLocator);if(t.provider!==`convex`||!n||r===null)throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);return{apiVersion:2,provider:`convex`,convexUrl:n,...r===void 0?{}:{invitationExpiresAt:r},...i===void 0?{}:{accessScope:i},...a===void 0?{}:{sessionLocator:a}}}function re(e){if(e===void 0)return;if(!e||typeof e!=`object`||Array.isArray(e))throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);let t=e,n=Q(t,`locator`);if(t.kind!==`project`||!n||n.length>200||t.mode!==void 0&&t.mode!==`email`&&t.mode!==`link`)throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);return{kind:`project`,locator:n,...t.mode===void 0?{}:{mode:t.mode}}}function ie(e){if(e!==void 0){if(typeof e!=`string`||!e.trim()||e.length>200)throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`잘못된 bootstrap 응답입니다.`,502);return e.trim()}}function G(e){if(e!==void 0)return Number.isSafeInteger(e)&&e>0?e:null}function K(e,t,n){return`01works.visual-review.convex-session.v1:${JSON.stringify([e,t,n])}`}function q(...e){return e.filter(e=>e!==null)}function ae(){try{return globalThis.localStorage??null}catch{return null}}function oe(){try{return globalThis.sessionStorage??null}catch{return null}}async function J(e,t,n){try{let t=await e?.get(n);if(t)return t}catch{}let r=t.get(n)??null;return r&&r.expiresAt<=Date.now()?(t.delete(n),null):r}async function se(e,t,n,r){t.set(n,r);try{await e?.set(n,r)}catch{}}async function Y(e,t,n){t.delete(n);try{await e?.delete(n)}catch{}}function X(e,t){for(let n of e)try{n.removeItem(t)}catch{}}function ce(e){if(typeof e!=`string`||!e.trim())return null;try{let t=new URL(e.trim());return t.origin!==e.trim()||t.protocol!==`https:`||!t.hostname.endsWith(`.convex.cloud`)?null:t.origin}catch{return null}}async function Z(e){try{return await e.json()}catch{throw new w(`INVALID_BOOTSTRAP_RESPONSE`,`JSON bootstrap 응답이 필요합니다.`,502)}}function Q(e,t){let n=$(e,t);return typeof n==`string`&&n.trim()?n.trim():null}function $(e,t){if(!(!e||typeof e!=`object`||Array.isArray(e)))return e[t]}export{T as createHostedReviewRuntime};
package/dist/index.d.ts CHANGED
@@ -126,12 +126,20 @@ export interface VisualReviewComment {
126
126
  pageNumber?: number;
127
127
  authorId: string;
128
128
  authorName: string;
129
+ /** How the initial feedback was created. Omitted legacy rows are human-authored. */
130
+ authorKind?: 'human' | 'agent';
129
131
  body: string;
130
132
  anchor: VisualReviewAnchor;
133
+ /** Latest reviewer-authored position override for a movable pin. */
134
+ pinAnchor?: VisualReviewAnchor;
135
+ /** Compare-and-set revision for concurrent pin moves. */
136
+ pinRevision?: number;
131
137
  target: VisualReviewAnnotationTarget;
132
138
  scope?: Record<string, string | number | boolean | null>;
133
139
  status: 'open' | 'resolved';
134
140
  workflowRevision?: number;
141
+ /** Monotonic CAS token for replies and workflow changes; pin moves do not advance it. */
142
+ threadRevision?: number;
135
143
  createdAt: number;
136
144
  updatedAt: number;
137
145
  resolvedAt?: number;
@@ -180,7 +188,11 @@ export interface VisualReviewSnapshotWindow {
180
188
  export type VisualReviewMutation =
181
189
  | { type: 'comment.upsert'; comment: VisualReviewComment }
182
190
  | { type: 'comment.delete'; commentId: string }
183
- | { type: 'reply.upsert'; reply: VisualReviewReply }
191
+ | {
192
+ type: 'reply.upsert';
193
+ reply: VisualReviewReply;
194
+ requestReopen?: boolean;
195
+ }
184
196
  | { type: 'reply.delete'; commentId: string; replyId: string };
185
197
 
186
198
  export type VisualReviewSubscriptionFailure =
@@ -211,6 +223,12 @@ export interface VisualReviewRepository {
211
223
  onFailure?: (failure: VisualReviewSubscriptionFailure) => void,
212
224
  ): () => void;
213
225
  mutate(pageId: string, mutation: VisualReviewMutation): Promise<void>;
226
+ moveCommentPin?(
227
+ pageId: string,
228
+ commentId: string,
229
+ anchor: VisualReviewAnchor,
230
+ expectedRevision: number,
231
+ ): Promise<{ pinRevision: number; updatedAt: number }>;
214
232
  attachScreenshot?(
215
233
  pageId: string,
216
234
  commentId: string,
@@ -334,6 +352,87 @@ export interface VisualReviewInactiveState {
334
352
  origin: string;
335
353
  }
336
354
 
355
+ export interface VisualReviewAgentPoint {
356
+ clientX: number;
357
+ clientY: number;
358
+ }
359
+
360
+ export interface VisualReviewCommentableTarget {
361
+ index: number;
362
+ tagName: string;
363
+ role: string | null;
364
+ /** Sanitized but still untrusted text from the reviewed page. */
365
+ label: string | null;
366
+ /** Diagnostic evidence only; no mutation accepts this selector. */
367
+ selector: string;
368
+ selectorTruncated: boolean;
369
+ rect: VisualReviewAgentPoint & { width: number; height: number };
370
+ /** Pass this point to createFeedbackAtPoint() after checking the live page. */
371
+ point: VisualReviewAgentPoint;
372
+ }
373
+
374
+ export interface VisualReviewCommentableTargetInventory {
375
+ schemaVersion: 1;
376
+ trustBoundary: string;
377
+ /** Origin and pathname only; query and fragment credentials are omitted. */
378
+ pageUrl: string;
379
+ viewport: { width: number; height: number };
380
+ /** Fixed at 100 in this protocol version. */
381
+ maxTargets: 100;
382
+ truncated: boolean;
383
+ targets: VisualReviewCommentableTarget[];
384
+ }
385
+
386
+ export interface VisualReviewCreateFeedbackRequest extends VisualReviewAgentPoint {
387
+ body: string;
388
+ endClientX?: number;
389
+ endClientY?: number;
390
+ }
391
+
392
+ export interface VisualReviewCreateFeedbackResult {
393
+ commentId: string;
394
+ target: VisualReviewAnnotationTarget;
395
+ }
396
+
397
+ export interface VisualReviewPagePortableArchive {
398
+ schemaVersion: 1;
399
+ archiveId: string;
400
+ pageUrl: string;
401
+ exportedAt: string;
402
+ feedback: Array<{
403
+ id: string;
404
+ body: string;
405
+ target: VisualReviewAnnotationTarget;
406
+ scope?: Record<string, string | number | boolean | null>;
407
+ replies: Array<{ id: string; body: string }>;
408
+ }>;
409
+ }
410
+
411
+ export interface VisualReviewPageImportResult {
412
+ importedComments: number;
413
+ importedReplies: number;
414
+ commentIds: string[];
415
+ }
416
+
417
+ /** Authenticated, staging-only browser automation surface. */
418
+ export interface VisualReviewAgentBridge extends HTMLElement {
419
+ readonly mode: 'view' | 'comment' | 'review';
420
+ setMode(mode: 'view' | 'comment' | 'review'): void;
421
+ listCommentableTargets(): VisualReviewCommentableTargetInventory;
422
+ createFeedbackAtPoint(
423
+ request: VisualReviewCreateFeedbackRequest,
424
+ ): Promise<VisualReviewCreateFeedbackResult>;
425
+ exportPageFeedback(format: 'json'): VisualReviewPagePortableArchive;
426
+ exportPageFeedback(format: 'markdown'): string;
427
+ importPageFeedback(value: unknown): Promise<VisualReviewPageImportResult>;
428
+ }
429
+
430
+ declare global {
431
+ interface HTMLElementTagNameMap {
432
+ 'agency-review-widget': VisualReviewAgentBridge;
433
+ }
434
+ }
435
+
337
436
  export interface InstallVisualReviewOptions {
338
437
  /** Override only for local development or self-hosted integration tests. */
339
438
  serviceUrl?: string;
@@ -342,11 +441,11 @@ export interface InstallVisualReviewOptions {
342
441
  runtime?: VisualReviewRuntime;
343
442
  /** Emergency kill switch. Omit for invitation-driven activation. */
344
443
  enabled?: boolean;
345
- /** @deprecated Retained as a no-op for 0.11 consumers. */
444
+ /** Development-only integrations that never persist or transmit copied content. */
346
445
  developerTools?: {
347
- /** @deprecated Code-context copying was removed in 0.12. */
446
+ /** Show a dedicated React Grab action that copies immediately after element selection. */
348
447
  codeContextCopy?: boolean;
349
- /** @deprecated Code-context copying was removed in 0.12. */
448
+ /** @deprecated Use `codeContextCopy`. Retained for 0.11 consumers. */
350
449
  reactGrab?: boolean;
351
450
  };
352
451
  /** Opt in to ephemeral Convex-backed reviewer cursors and cursor chat. */
@@ -364,19 +463,19 @@ export interface InstallVisualReviewOptions {
364
463
  /** Called when the launcher can safely identify why it stayed inactive. */
365
464
  onInactive?: (state: VisualReviewInactiveState) => void;
366
465
  /** Called once for each successful mount owned by this installation. */
367
- onReady?: (widget: HTMLElement) => void;
466
+ onReady?: (widget: VisualReviewAgentBridge) => void;
368
467
  /** Optional host-router adapter for opening feedback on another page. */
369
468
  navigateToFeedback?: (url: string) => void | Promise<void>;
370
469
  }
371
470
 
372
471
  export interface VisualReviewInstallation {
373
- ready: Promise<HTMLElement | null>;
472
+ ready: Promise<VisualReviewAgentBridge | null>;
374
473
  /**
375
474
  * Re-resolve the current route after a framework router changes it in place,
376
475
  * and re-anchor the widget to it even when the route did not change. A widget
377
476
  * the host detached is remounted; a healthy one is never torn down.
378
477
  */
379
- refresh(): Promise<HTMLElement | null>;
478
+ refresh(): Promise<VisualReviewAgentBridge | null>;
380
479
  dispose(): void;
381
480
  }
382
481
 
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./install-CxzNo7RN.js";export{e as installVisualReview};
1
+ import{t as e}from"./install-DAqwiYRg.js";export{e as installVisualReview};