@roughapp/feature 0.4.2 → 0.5.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.
- package/README.md +37 -17
- package/index.d.ts +20 -23
- package/index.js +61 -45
- package/package.json +3 -3
package/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{z as e}from"zod";import{errorBoundary as t,errorListBoundary as n}from"@stayradiated/error-boundary";import{z as r}from"zod/mini";import{getContext as i,mount as a,onDestroy as o,onMount as s,unmount as c}from"svelte";import"svelte/internal/disclose-version";import"svelte/internal/flags/async";import*as l from"svelte/internal/client";import{SvelteMap as u,SvelteSet as d}from"svelte/reactivity";import{newMessagePortRpcSession as f}from"capnweb";import"@andypf/json-viewer";var p=Object.create,m=Object.defineProperty,h=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyNames,_=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty,y=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),b=(e,t)=>{let n={};for(var r in e)m(n,r,{get:e[r],enumerable:!0});return t||m(n,Symbol.toStringTag,{value:`Module`}),n},ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=g(t),a=0,o=i.length,s;a<o;a++)s=i[a],!v.call(e,s)&&s!==n&&m(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=h(t,s))||r.enumerable});return e},x=(e,t,n)=>(n=e==null?{}:p(_(e)),ee(t||!e||!e.__esModule||!v.call(e,`default`)?m(n,`default`,{value:e,enumerable:!0}):n,e)),te=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,t=>e.call(t)];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup(),i=await e.subscribe(r,t);return async()=>{i(),r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),ne=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,async t=>e.outputSample];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup();return r(e.outputSample),async()=>{r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),re=e=>({type:e.type,id:e.id,name:e.name,description:e.description,inputSchema:e.inputSchema.toJSONSchema(),outputSchema:e.outputSchema.toJSONSchema(),outputSample:e.outputSample}),ie=class t{type=`mutation`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},ae=class t{type=`query`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},oe=class t{type=`subscription`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async subscribe(t,n){let r=this.inputSchema.safeParse(n);if(!r.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(r.error)}`);return await this.implementation(n=>{let r=this.outputSchema.safeParse(n);if(!r.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(r.error)}`);t(r.data)},r.data)}},se=e=>{let t=new URL(e.path,e.baseUrl);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,String(r));return t.toString()},ce=async e=>{let{replicache:n,projectId:r,signal:i}=e;return i?.aborted?Error(`Ping project aborted`):t(async()=>{await n.mutate.project_ping_v1({projectPublicId:r,context:{actionedAt:Date.now()}}),await n.push({now:!0})})},le=`/`,S=e=>{let t=`${e}${le}`,n=t.length;return()=>({name:e,value:t=>({name:e,idA:t,idB:void 0}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:e=>`${t}${e}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n)},decodeWithoutPrefix:e=>e})},C=e=>{let t=`${e}${le}`,n=t.length;return()=>({name:e,value:(t,n)=>({name:e,idA:t,idB:n}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}${le}`;case 2:return`${t}${e[0]}${le}${e[1]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:(e,n)=>`${t}${e}${le}${n}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n).split(le)},decodeWithoutPrefix:e=>e.split(le)})},w={internal:S(`__internal`)(),apiToken:S(`apiToken`)(),asset:S(`asset`)(),backlogTask:S(`backlogTask`)(),block:S(`block`)(),comment:S(`comment`)(),commentThread:S(`commentThread`)(),content:S(`content`)(),document:S(`document`)(),draftContent:S(`draftContent`)(),event:S(`event`)(),filter:S(`filter`)(),filterRule:S(`filterRule`)(),fizzyAccount:S(`fizzyAccount`)(),fizzyBoard:S(`fizzyBoard`)(),fizzyIntegration:S(`fizzyIntegration`)(),invitation:S(`invitation`)(),inviteLink:S(`inviteLink`)(),label:S(`label`)(),llmModel:S(`llmModel`)(),llmModelDefault:S(`llmModelDefault`)(),llmProvider:S(`llmProvider`)(),note:S(`note`)(),notification:S(`notification`)(),person:S(`person`)(),project:S(`project`)(),projectAccount:S(`projectAccount`)(),reaction:S(`reaction`)(),reference:S(`reference`)(),sequence:S(`sequence`)(),signingKey:S(`signingKey`)(),sprite:S(`sprite`)(),spriteBuild:S(`spriteBuild`)(),spriteBuildEvent:S(`spriteBuildEvent`)(),surface:S(`surface`)(),task:S(`task`)(),vcsBranch:S(`vcsBranch`)(),vcsCommit:S(`vcsCommit`)(),vcsIntegration:S(`vcsIntegration`)(),vcsRepo:S(`vcsRepo`)(),vcsUser:S(`vcsUser`)(),watch:S(`watch`)(),workspace:S(`workspace`)(),blockUser:C(`blockUser`)(),documentUser:C(`documentUser`)(),sequenceDocument:C(`sequenceDocument`)(),signingKeyProject:C(`signingKeyProject`)(),vcsCommitDocument:C(`vcsCommitDocument`)(),noteLabel:C(`noteLabel`)(),spriteProjectAccount:C(`spriteProjectAccount`)(),taskLabel:C(`taskLabel`)(),relatedDocumentNote:C(`relatedDocumentNote`)(),relatedDocumentPair:C(`relatedDocumentPair`)(),relatedNotePair:C(`relatedNotePair`)(),relatedSpritePair:C(`relatedSpritePair`)(),stackTask:C(`stackTask`)(),workspaceUser:S(`workspaceUser`)()},ue=(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e]?.push(r):Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:[r],writable:!0})}return n},de=class{#e=0;#t=new Map;#n=new Map;#r;#i;#a;constructor(e){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge==`number`&&e.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#r=e.maxSize,this.#i=e.maxAge??1/0,this.#a=e.onEviction,Object.defineProperty(this,Symbol.for(`nodejs.util.inspect.custom`),{value:()=>this.toString()})}get __oldCache(){return this.#n}#o(e){if(typeof this.#a==`function`)for(let[t,n]of e)this.#a(t,n.value)}#s(e,t){return typeof t.expiry==`number`&&t.expiry<=Date.now()&&(this.#a?.(e,t.value),this.delete(e))}#c(e,t){if(!this.#s(e,t))return t.value}#l(e,t){if(t)return t.expiry?this.#c(e,t):t.value}#u(e,t){return this.#l(e,t.get(e))}#d(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#r&&(this.#e=0,this.#o(this.#n),this.#n=this.#t,this.#t=new Map)}#f(e,t){this.#n.delete(e),this.#d(e,t)}*#p(){for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t]);for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t])}get(e){if(this.#t.has(e))return this.#l(e,this.#t.get(e));if(this.#n.has(e)){let t=this.#n.get(e);if(t&&!this.#s(e,t))return this.#f(e,t),t.value}}set(e,t,{maxAge:n=this.#i}={}){let r={value:t,expiry:typeof n==`number`&&n!==1/0?Date.now()+n:void 0};return this.#t.has(e)?this.#t.set(e,r):this.#d(e,r),this}has(e){if(this.#t.has(e)){let t=this.#t.get(e);return t?!this.#s(e,t):!1}if(this.#n.has(e)){let t=this.#n.get(e);return t?!this.#s(e,t):!1}return!1}peek(e){if(this.#t.has(e))return this.#u(e,this.#t);if(this.#n.has(e))return this.#u(e,this.#n)}expiresIn(e){let t=this.#t.get(e)??this.#n.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#n.delete(e)||t}clear(){this.#t.clear(),this.#n.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw TypeError("`maxSize` must be a number greater than 0");let t=[...this.#p()],n=t.length-e;n<0?(this.#t=new Map(t),this.#n=new Map,this.#e=t.length):(n>0&&this.#o(t.slice(0,n)),this.#n=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#r=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#p()],r=Math.trunc(Math.min(t,Math.max(n.length-1,0)));r<=0||(this.#o(n.slice(0,r)),this.#n=new Map(n.slice(r)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t.value]);for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t.value])}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;this.#s(r,i)||(yield[r,i.value])}e=[...this.#n];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;!this.#t.has(r)&&!this.#s(r,i)&&(yield[r,i.value])}}*entriesAscending(){for(let[e,t]of this.#p())yield[e,t.value]}get size(){if(!this.#e)return this.#n.size;let e=0;for(let t of this.#n.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#r)}get maxSize(){return this.#r}get maxAge(){return this.#i}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,r]of this.entriesAscending())e.call(t,r,n,this)}get[Symbol.toStringTag](){return`QuickLRU`}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}},fe=class{arraySize=0;array=Array(8);set=null;get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw Error(`no set or array`)}add(e){if(this.array)return this.array.indexOf(e)===-1?this.arraySize<8?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0):!1;if(this.set)return!this.set.has(e)&&(this.set.add(e),!0);throw Error(`no set or array`)}remove(e){if(this.array){let t=this.array.indexOf(e);return t!==-1&&(this.array[t]=void 0,this.arraySize--,t!==this.arraySize&&(this.array[t]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw Error(`no set or array`)}visit(e){if(this.array){for(let t=0;t<this.arraySize;t++){let n=this.array[t];n!==void 0&&e(n)}return}if(this.set){this.set.forEach(e);return}throw Error(`no set or array`)}};function T(e){return e&&typeof e==`object`&&`parents`in e}function pe(e){for(let t=0,n=e.parents.length;t<n;t++)if(e.parents[t].__unsafe__getWithoutCapture(),e.parents[t].lastChangedEpoch!==e.parentEpochs[t])return!0;return!1}var me=(e,t)=>{if(e.children.remove(t)&&e.children.isEmpty&&T(e))for(let t=0,n=e.parents.length;t<n;t++)me(e.parents[t],e)},he=(e,t)=>{if(e.children.add(t)&&T(e))for(let t=0,n=e.parents.length;t<n;t++)he(e.parents[t],e)};function ge(e,t){return e===t||Object.is(e,t)||!!(e&&t&&typeof e.equals==`function`&&e.equals(t))}var _e=Object.freeze([]),ve=Symbol.for(`__signia__`),ye=globalThis;ye[ve]?console.error(`Multiple versions of signia detected. This will cause unexpected behavior. Please add "resolutions" (yarn/pnpm) or "overrides" (npm) in your package.json to ensure only one version of signia is loaded.`):ye[ve]=!0;var be=class{constructor(e,t){this.below=e,this.child=t}offset=0;numNewParents=0;maybeRemoved},E=null;function xe(e){E=new be(E,e)}function Se(){let e=E;if(E=e.below,e.numNewParents>0||e.offset!==e.child.parents.length){for(let t=e.offset;t<e.child.parents.length;t++){let n=e.child.parents[t];e.child.parents.indexOf(n)>=e.offset&&me(n,e.child)}if(e.child.parents.length=e.offset,e.child.parentEpochs.length=e.offset,E?.maybeRemoved)for(let t=0;t<E.maybeRemoved.length;t++){let n=E.maybeRemoved[t];e.child.parents.indexOf(n)===-1&&me(n,e.child)}}}function Ce(e){if(E){let t=E.child.parents.indexOf(e);if(t<0&&(E.numNewParents++,E.child.isActivelyListening&&he(e,E.child)),t<0||t>=E.offset){if(t!==E.offset&&t>0){let e=E.child.parents[E.offset];E.maybeRemoved?E.maybeRemoved.indexOf(e)===-1&&E.maybeRemoved.push(e):E.maybeRemoved=[e]}E.child.parents[E.offset]=e,E.child.parentEpochs[E.offset]=e.lastChangedEpoch,E.offset++}}}var we=Symbol(`RESET_VALUE`),Te=class{constructor(e){this.capacity=e,this.buffer=Array(e)}index=0;buffer;pushEntry(e,t,n){if(n!==void 0){if(n===we){this.clear();return}this.buffer[this.index]=[e,t,n],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){let{index:t,capacity:n,buffer:r}=this;for(let i=0;i<n;i++){let a=(t-1+n-i)%n,o=r[a];if(!o)return we;let[s,c]=o;if(i===0&&e>=c)return[];if(s<=e&&e<c){let e=i+1,t=Array(e);for(let i=0;i<e;i++)t[i]=r[(a+i)%n][2];return t}}return we}},D=0,Ee=!1;function De(){D++}function Oe(e){if(Ee)throw Error(`cannot change atoms during reaction cycle`);try{Ee=!0;let t=new Set,n=e=>{e.lastTraversedEpoch!==D&&(e.lastTraversedEpoch=D,`maybeScheduleEffect`in e?t.add(e):e.children.visit(n))};for(let t of e)t.children.visit(n);for(let e of t)e.maybeScheduleEffect()}finally{Ee=!1}}function ke(e,t){Ae?Ae.initialAtomValues.has(e)||Ae.initialAtomValues.set(e,t):Oe([e])}var Ae=null,je=class{constructor(e,t,n){this.name=e,this.current=t,this.isEqual=n?.isEqual??null,n&&(n.historyLength&&(this.historyBuffer=new Te(n.historyLength)),this.computeDiff=n.computeDiff)}isEqual;computeDiff;lastChangedEpoch=D;children=new fe;historyBuffer;__unsafe__getWithoutCapture(){return this.current}get value(){return Ce(this),this.current}set(e,t){if(this.isEqual?.(this.current,e)??ge(this.current,e))return this.current;De(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,D,t??this.computeDiff?.(this.current,e,this.lastChangedEpoch,D)??we),this.lastChangedEpoch=D;let n=this.current;return this.current=e,ke(this,n),e}update(e){return this.set(e(this.current))}getDiffSince(e){return Ce(this),e>=this.lastChangedEpoch?_e:this.historyBuffer?.getChangesSince(e)??we}};function Me(e,t,n){return new je(e,t,n)}var Ne=Symbol(`UNINITIALIZED`),Pe=e=>e===Ne,Fe=class{constructor(e,t){this.value=e,this.diff=t}},Ie=class{constructor(e,t,n){this.name=e,this.derive=t,n?.historyLength&&(this.historyBuffer=new Te(n.historyLength)),this.computeDiff=n?.computeDiff,this.isEqual=n?.isEqual??ge}lastChangedEpoch=-1;lastTraversedEpoch=-1;lastCheckedEpoch=-1;parents=[];parentEpochs=[];children=new fe;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=Ne;computeDiff;isEqual;__unsafe__getWithoutCapture(){let e=this.lastChangedEpoch===-1;if(!e&&(this.lastCheckedEpoch===D||!pe(this)))return this.lastCheckedEpoch=D,this.state;try{xe(this);let t=this.derive(this.state,this.lastCheckedEpoch),n=t instanceof Fe?t.value:t;if(this.state===Ne||!this.isEqual(n,this.state)){if(this.historyBuffer&&!e){let e=t instanceof Fe?t.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,D,e??this.computeDiff?.(this.state,n,this.lastCheckedEpoch,D)??we)}this.lastChangedEpoch=D,this.state=n}return this.lastCheckedEpoch=D,this.state}finally{Se()}}get value(){let e=this.__unsafe__getWithoutCapture();return Ce(this),e}getDiffSince(e){return this.value,e>=this.lastChangedEpoch?_e:this.historyBuffer?.getChangesSince(e)??we}};function Le(e={},t,n,r){let i=r.get,a=Symbol.for(`__signia__computed__`+n);return r.get=function(){let t=this[a];return t||(t=new Ie(n,i.bind(this),e),Object.defineProperty(this,a,{enumerable:!1,configurable:!1,writable:!1,value:t})),t.value},r}function Re(){if(arguments.length===1){let e=arguments[0];return(t,n,r)=>Le(e,t,n,r)}return typeof arguments[0]==`string`?new Ie(arguments[0],arguments[1],arguments[2]):Le(void 0,arguments[0],arguments[1],arguments[2])}var ze=class{constructor(e,t,n){this.name=e,this.runEffect=t,this._scheduleEffect=n?.scheduleEffect}_isActivelyListening=!1;get isActivelyListening(){return this._isActivelyListening}lastTraversedEpoch=-1;lastReactedEpoch=-1;_scheduleCount=0;get scheduleCount(){return this._scheduleCount}parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==D){if(this.parents.length&&!pe(this)){this.lastReactedEpoch=D;return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}maybeExecute=()=>{this._isActivelyListening&&this.execute()};attach(){this._isActivelyListening=!0;for(let e=0,t=this.parents.length;e<t;e++)he(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)me(this.parents[e],this)}execute(){try{xe(this);let e=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=D,e}finally{Se()}}};function Be(e,t,n){let r=new ze(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}var Ve=e=>{let{diffList:t,source:n,mapKey:r,mapValue:i}=e;if(t.length===0)return;let a={...n.__unsafe__getWithoutCapture()},o=[];for(let e of t)switch(e.op){case`add`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`add`,key:t,value:n});break}case`change`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`replace`,key:t,value:n});break}case`del`:{let t=r(e.key);delete a[t],o.push({op:`remove`,key:t});break}default:throw Error(`Unhandled diff op: ${JSON.stringify(e)}`)}n.set(a,o)},He=e=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];for(let e=i.length-1;e>=0;e--){let r=i[e];t.has(r.key)||(t.add(r.key),n.push(r))}}return n.reverse(),n},Ue=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))t(i)&&(r[n]=i);return Object.values(r)};return Re(`${e.name}:filter`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:t(e.value)&&(r[e.key]=e.value);break;case`remove`:delete r[e.key];break;case`replace`:t(e.value)?r[e.key]=e.value:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},We=(e,t,n)=>{let r=new Set,i,a=()=>{r.clear(),i=void 0;let n=!1,a;for(let[o,s]of Object.entries(e.value))n?r.add(o):t(s)&&(n=!0,a=s,i=o);return a},o=()=>{for(let n of r){r.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return i=n,a}i=void 0};return Re(`${e.name}:find`,(n,s)=>{if(Pe(n))return a();let c=e.getDiffSince(s);if(c===we)return a();let l=He(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:i===void 0?t(e.value)&&(i=e.key):r.add(e.key);break;case`remove`:e.key===i?o():r.delete(e.key);break;case`replace`:e.key===i||i===void 0?t(e.value)?i=e.key:o():r.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return i===void 0?void 0:e.value[i]},{...n})},Ge=(e,t,n)=>Re(`${e.name}:get`,()=>e.value[t],{...n}),Ke=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))r[n]=t(i);return Object.values(r)};return Re(`${e.name}:map`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.value);break;case`replace`:r[e.key]=t(e.value);break;case`remove`:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},qe=(e,t,n)=>{let r={},i=()=>{r={};for(let n of Object.keys(e.value)){let e=t(n);r[n]=e}return Object.values(r)};return Re(`${e.name}:keys`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.key);break;case`remove`:delete r[e.key];break;case`replace`:e.key in r||(r[e.key]=t(e.key));break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Je=(e,t)=>Re(`${e.name}:values`,()=>Object.values(e.value),{...t}),Ye=(e,t,n)=>{let r=new Set,i=new Set,a=()=>{r.clear(),i.clear();let n=!1;for(let[a,o]of Object.entries(e.value))n?i.add(a):t(o)&&(r.add(a),n=!0);return n},o=()=>{for(let n of i){i.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return r.add(n),!0}return!1};return Re(`${e.name}:some`,(n,s)=>{if(Pe(n))return a();let c=e.getDiffSince(s);if(c===we)return a();let l=He(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:r.size===0?t(e.value)&&r.add(e.key):i.add(e.key);break;case`remove`:i.delete(e.key),r.delete(e.key),r.size===0&&o();break;case`replace`:r.has(e.key)||r.size===0?(i.delete(e.key),t(e.value)?r.add(e.key):(r.delete(e.key),o())):i.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return r.size>0},{...n})},Xe=50,Ze=class e{key;mapValue;name;atom;asRecord;asList;keys;#e=new Map;#t=e.#a();#n=e.#a();#r=e.#a();#i=e.#a();static#a(){return new de({maxSize:Xe})}constructor(e){this.key=e.key,this.mapValue=e.mapValue,this.name=`ReplicacheTable(${this.key.name})`,this.atom=Me(this.name,{},{historyLength:1}),this.asRecord=this.atom,this.asList=Je(this.atom),this.keys=qe(this.atom,e=>this.key.decodeWithoutPrefix(e))}#o(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}#s(e){return typeof e==`string`?e:Array.isArray(e)?`${e[0]}/${e[1]}`:(console.error(`${this.name}.get: invalid key`,e),``)}get(e){let t=this.#s(e);return this.#o(this.#e,t,()=>Ge(this.atom,t))}find(e,t){return this.#o(this.#t,e,()=>We(this.atom,t))}filter(e,t){return this.#o(this.#n,e,()=>Ue(this.atom,t))}map(e,t){return this.#o(this.#r,e,()=>Ke(this.atom,t))}some(e,t){return this.#o(this.#i,e,()=>Ye(this.atom,t))}pushDiffList(e){Ve({diffList:e,source:this.atom,mapKey:e=>this.key.trimPrefix(e),mapValue:(e,t)=>this.mapValue(e,this.key.decode(t))})}clear(){let e=this.atom.__unsafe__getWithoutCapture(),t=Object.keys(e);if(t.length===0)return;let n=t.map(e=>({op:`remove`,key:e}));this.atom.set({},n)}},Qe=`store`,$e=S(`meta`)(),et=()=>{let e={meta:new Ze({key:$e,mapValue:e=>e}),person:new Ze({key:w.person,mapValue:(e,t)=>({id:t,name:e.name})}),surface:new Ze({key:w.surface,mapValue:(e,t)=>({id:t,key:e.key,name:e.name,description:e.description})}),sprite:new Ze({key:w.sprite,mapValue:(e,t)=>({id:t,name:e.name,surfaceId:e.surfaceId,ownedByPersonId:e.ownedByPersonId})}),spriteBuild:new Ze({key:w.spriteBuild,mapValue:(e,t)=>({id:t,spriteId:e.spriteId,parentSpriteBuildId:e.parentSpriteBuildId,createdByPersonId:e.createdByPersonId,prompt:e.prompt,status:e.status,cancelRequestedAt:e.cancelRequestedAt,artifactUrl:e.artifactUrl,sourceUrl:null,startedAt:e.startedAt,stoppedAt:e.stoppedAt,error:e.error,reasoningSummary:e.reasoningSummary,publishedAt:e.publishedAt})}),spriteBuildEvent:new Ze({key:w.spriteBuildEvent,mapValue:(e,t)=>({id:t,spriteBuildId:e.spriteBuildId,actionedAt:e.actionedAt,type:e.type,detail:e.detail})})},t={[w.person.name]:e.person,[w.surface.name]:e.surface,[w.spriteBuildEvent.name]:e.spriteBuildEvent,[w.spriteBuild.name]:e.spriteBuild,[w.sprite.name]:e.sprite},n=new Set,r,i=!1,a=t=>{let n=$e.encode(Qe);t===`LOADING`?e.meta.pushDiffList([{op:`add`,key:n,newValue:{state:t}}]):e.meta.pushDiffList([{op:`change`,key:n,newValue:{state:t},oldValue:{}}])},o=()=>{e.meta.clear(),e.person.clear(),e.surface.clear(),e.sprite.clear(),e.spriteBuild.clear(),e.spriteBuildEvent.clear()},s=()=>{for(let e of n)e()},c=e=>{if(i)return;r?.(),o(),a(`LOADING`);let n=!1;r=e.experimentalWatch(e=>{let r=ue(e,e=>e.key.match(/^(\w+)\//)?.[1]??``);for(let[e,n]of Object.entries(r))t[e]?.pushDiffList(n);n||(n=!0,a(`READY`)),s()},{initialValuesInFirstDiff:!0})},l=e=>(n.add(e),()=>{n.delete(e)}),u=async()=>{i=!0,r?.(),r=void 0,o(),n.clear()};return{...e,bind:c,subscribe:l,destroy:u}},tt=y(((e,t)=>{var n=self.crypto;function r(e){let t=new Uint8Array(e);return n.getRandomValues(t),t}t.exports={randomBytes:r}})),nt=y(((e,t)=>{var{randomBytes:n}=tt(),r=16;t.exports=new class{compare(e,t){let n=e.findIndex((e,n)=>e!==t[n]);return~n&&Math.sign(e[n]-t[n])}generateOneFilled(){return new Uint8Array(r).fill(255)}generateRandomFilled(){return n(r)}generateZeroFilled(){return new Uint8Array(r).fill(0)}}})),rt=y(((e,t)=>{var n=class extends Error{get name(){return this.constructor.name}};t.exports={Id128Error:n,ClockSequenceOverflow:class extends n{},InvalidBytes:class extends n{},InvalidEncoding:class extends n{},InvalidEpoch:class extends n{},UnsupportedVersion:class extends n{}}})),it=y(((e,t)=>{var{InvalidEpoch:n}=rt(),r=0,i=2**48;t.exports=new class{fromEpoch(e,t){return new Date(t+e)}toEpoch(e,t=null){let a=(t===null?Date.now():Number.isInteger(t)?t:t instanceof Date?t.getTime():(()=>{throw new n(`Failed to coerce time [${t}] to epoch`)})())-e;if(a<r||a>=i)throw new n(`Epoch must be between ${new Date(r+e).toISOString()} and ${new Date(i-1+e).toISOString()}`);return a}}})),at=y(((e,t)=>{var n=nt(),r=Symbol(`bytes`);t.exports={BaseId:class{constructor(e){this[r]=e}clone(){return new this.constructor(this.bytes.slice())}get bytes(){return this[r]}get[Symbol.toStringTag](){return this.constructor.name}compare(e){return n.compare(this.bytes,e.bytes)}equal(e){return this.compare(e)===0}}}})),ot=y(((e,t)=>{var n=nt(),r=it(),{BaseId:i}=at(),a=0,o=2**32,s=255;function c(e,t){let n=e%o,r=(e-n)/o,i=-1;t[++i]=r>>>8&s,t[++i]=r>>>0&s,t[++i]=n>>>24&s,t[++i]=n>>>16&s,t[++i]=n>>>8&s,t[++i]=n>>>0&s}t.exports={Ulid:class extends i{static generate({time:e}={}){e=r.toEpoch(a,e);let t=n.generateRandomFilled();return c(e,t),new this(t)}static MIN(){return new this(n.generateZeroFilled())}static MAX(){return new this(n.generateOneFilled())}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*o+(n>>>0);return r.fromEpoch(a,i)}},setTime:c}})),st=y(((e,t)=>{var{Ulid:n,setTime:r}=ot(),i=nt(),a=it(),{ClockSequenceOverflow:o}=rt(),s=0,c=6,l=8,u=0,d,f;function p(e){for(let t=7;t>5;--t)if(e[t]===255)e[t]=0;else{++e[t];return}throw new o(`Exhausted clock sequence`)}function m(e){e[c]&=127}function h(e){for(let t=s;t<l;++t)e[t]=d.bytes[t]}var g=class extends n{static reset(){f=-1,d=this.MIN()}static generate({time:e}={}){e=a.toEpoch(u,e);let t=i.generateRandomFilled();return e<=f?(h(t),p(t)):(r(e,t),m(t),f=e),d=new this(t)}};g.reset(),t.exports={UlidMonotonic:g}})),ct=y(((e,t)=>{var{BaseId:n}=at(),r=nt(),i=8,a=6;function o(e,t){t[i]&=255>>>e+1,t[i]|=(7<<3-e&7)<<5}function s(e,t){t[a]&=15,t[a]|=e<<4}t.exports={Uuid:class extends n{static MIN(){let e=r.generateZeroFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}static MAX(){let e=r.generateOneFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}get variant(){let e=this.bytes[i]>>>5;return e===7?3:(e&6)==6?2:+((e&4)==4)}get version(){return this.bytes[a]>>>4}},setVersion:s,setVariant:o}})),lt=y(((e,t)=>{var{randomBytes:n}=tt(),r=Symbol(`mac-address`);t.exports=new class{constructor(){this.reset()}get mac_address(){let e=this[r];return e||(e=this[r]=n(6),e[0]|=1),e}reset(){this[r]=null}}})),ut=y(((e,t)=>{var n=nt(),r=it(),i=lt(),{Uuid:a,setVariant:o,setVersion:s}=ct(),c=2,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**20,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function x(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=n*p+_,i=(e-n)/m,a=-1;t[++a]=r>>>24&h,t[++a]=r>>>16&h,t[++a]=r>>>8&h,t[++a]=r>>>0&h,t[++a]=i>>>8&h,t[++a]=i>>>0&h,t[++a]=i>>>24&h,t[++a]=i>>>16&h}var te=class extends a{static get VARIANT(){return 1}static get VERSION(){return 1}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return x(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[3])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<12|this.bytes[++e]<<4|this.bytes[++e]>>>4;++e;let n=(0|this.bytes[++e]<<8|this.bytes[++e]<<0|(this.bytes[++e]&15)<<24|this.bytes[++e]<<16)*m+t;return r.fromEpoch(f,n)}};te.reset(),t.exports={Uuid1:te}})),dt=y(((e,t)=>{var n=nt(),{Uuid:r,setVariant:i,setVersion:a}=ct();t.exports={Uuid4:class extends r{static get VARIANT(){return 1}static get VERSION(){return 4}static generate(){let e=n.generateRandomFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),ft=y(((e,t)=>{var n=nt(),r=it(),i=lt(),{Uuid:a,setVariant:o,setVersion:s}=ct(),c=6,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**32,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function x(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=(e-n)/m,i=-1;t[++i]=r>>>8&h,t[++i]=r>>>0&h,t[++i]=n>>>24&h,t[++i]=n>>>16&h,t[++i]=n>>>8&h,t[++i]=n>>>0&h,t[++i]=_>>>8&h,t[++i]=_>>>0&h}var te=class extends a{static get VARIANT(){return 1}static get VERSION(){return 6}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return x(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[7])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*m+(n>>>0);return r.fromEpoch(f,i)}};te.reset(),t.exports={Uuid6:te}})),pt=y(((e,t)=>{var n=nt(),{Uuid:r,setVariant:i,setVersion:a}=ct();t.exports={UuidNil:class extends r{static get VARIANT(){return 0}static get VERSION(){return 0}static generate(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}static MAX(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),mt=y(((e,t)=>{var{InvalidEncoding:n,InvalidBytes:r}=rt(),i=Symbol(`valid_encoding_pattern`);t.exports={BaseCoder:class{constructor({valid_encoding_pattern:e}={}){this[i]=e}decode(e){if(this.isValidEncoding(e))return this.decodeTrusted(e);throw new n(`Encoding [${e}] does not satisfy ${this[i]}`)}decodeTrusted(e){return ByteArray.generateRandomFilled()}encode(e){if(this.isValidBytes(e))return this.encodeTrusted(e);throw new r(`Requires a 16-byte Uint8Array`)}encodeTrusted(e){return``}isValidBytes(e){return e instanceof Uint8Array&&e.length===16}isValidEncoding(e){return(typeof e==`string`||e instanceof String)&&this[i].test(e)}}}})),ht=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,i=31,a=Array.from(r).reduce((e,t,n)=>(e[t]=e[t.toLowerCase()]=n,e),{I:r.indexOf(`1`),i:r.indexOf(`1`),L:r.indexOf(`1`),l:r.indexOf(`1`),O:r.indexOf(`0`),o:r.indexOf(`0`),U:r.indexOf(`V`),u:r.indexOf(`V`)}),o=Array.from(r);function s(e){return a[e]}function c(e){return o[e&i]}t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-7][^\W_]{25}$/})}decodeTrusted(e){let t=new Uint8Array(16),n=[];for(let t=0,r=e.length;t<r;++t)n.push(s(e[t]));return t[0]=n[0]<<5|n[1],t[1]=n[2]<<3|n[3]>>2,t[2]=n[3]<<6|n[4]<<1|n[5]>>4,t[3]=n[5]<<4|n[6]>>1,t[4]=n[6]<<7|n[7]<<2|n[8]>>3,t[5]=n[8]<<5|n[9],t[6]=n[10]<<3|n[11]>>2,t[7]=n[11]<<6|n[12]<<1|n[13]>>4,t[8]=n[13]<<4|n[14]>>1,t[9]=n[14]<<7|n[15]<<2|n[16]>>3,t[10]=n[16]<<5|n[17],t[11]=n[18]<<3|n[19]>>2,t[12]=n[19]<<6|n[20]<<1|n[21]>>4,t[13]=n[21]<<4|n[22]>>1,t[14]=n[22]<<7|n[23]<<2|n[24]>>3,t[15]=n[24]<<5|n[25],t}encodeTrusted(e){let t=[e[0]>>5,e[0],e[1]>>3,e[1]<<2|e[2]>>6,e[2]>>1,e[2]<<4|e[3]>>4,e[3]<<1|e[4]>>7,e[4]>>2,e[4]<<3|e[5]>>5,e[5],e[6]>>3,e[6]<<2|e[7]>>6,e[7]>>1,e[7]<<4|e[8]>>4,e[8]<<1|e[9]>>7,e[9]>>2,e[9]<<3|e[10]>>5,e[10],e[11]>>3,e[11]<<2|e[12]>>6,e[12]>>1,e[12]<<4|e[13]>>4,e[13]<<1|e[14]>>7,e[14]>>2,e[14]<<3|e[15]>>5,e[15]],n=``;for(let e=0,r=t.length;e<r;++e)n+=c(t[e]);return n}}})),gt=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{32}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r}return t}encodeTrusted(e){let t=``;for(let n=0,r=e.length;n<r;++n)t+=i[e[n]];return t}}})),_t=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{4}(?:-?[0-9A-Fa-f]{4}){7}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];o!==`-`&&(r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r)}return t}encodeTrusted(e){let t=-1;return``+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]}}})),vt=y(((e,t)=>{var n=Symbol(`id`),r=Symbol(`canonical_coder`),i=Symbol(`raw_coder`);t.exports={IdFactory:class{constructor({id:e,canonical_coder:t,raw_coder:a}={}){this[n]=class extends e{static get name(){return e.name}static get[Symbol.species](){return e}get[Symbol.toStringTag](){return`${e.name} ${this.toRaw()}`}toCanonical(){return t.encodeTrusted(this.bytes)}toRaw(){return a.encodeTrusted(this.bytes)}},this[r]=t,this[i]=a}get name(){return this[n].name}get type(){return this[n][Symbol.species]}construct(e){return new this[n](e)}generate(){return this[n].generate(...arguments)}MIN(){return this[n].MIN(...arguments)}MAX(){return this[n].MAX(...arguments)}fromCanonical(e){return this.construct(this[r].decode(e))}fromCanonicalTrusted(e){return this.construct(this[r].decodeTrusted(e))}fromRaw(e){return this.construct(this[i].decode(e))}fromRawTrusted(e){return this.construct(this[i].decodeTrusted(e))}toCanonical(e){return this[r].encode(e.bytes)}toRaw(e){return this[i].encode(e.bytes)}compare(e,t){return console.warn(`Deprecated: use generic idCompare instead.`),e.compare(t)}equal(e,t){return console.warn(`Deprecated: use generic idEqual instead.`),e.equal(t)}isCanonical(e){return this[r].isValidEncoding(e)}isRaw(e){return this[i].isValidEncoding(e)}}}})),yt=y(((e,t)=>{var{IdFactory:n}=vt(),{UnsupportedVersion:r}=rt(),i=Symbol(`id_by_version`);function a(e,{version:t}={}){return e[i][t]||(()=>{throw new r(`No support for version [${t}]`)})()}t.exports={VersionedIdFactory:class extends n{constructor({abstract_id:e,versioned_ids:t,canonical_coder:r,raw_coder:a}){super({id:e,canonical_coder:r,raw_coder:a}),this[i]=t.reduce((e,t)=>Object.assign(e,{[t.MIN().version]:new n({id:t,canonical_coder:r,raw_coder:a})}),Object.create(null))}get versioned_ids(){return Object.values(this[i])}construct(e){let t=super.construct(e),n=t.version;try{return a(this,{version:n}).construct(e)}catch(e){if(e instanceof r)return t;throw e}}generate(){return a(this,...arguments).generate(...arguments)}MIN(){return a(this,...arguments).MIN()}MAX(){return a(this,...arguments).MAX()}}}})),bt=x(y(((e,t)=>{var{Ulid:n}=ot(),{UlidMonotonic:r}=st(),{Uuid:i}=ct(),{Uuid1:a}=ut(),{Uuid4:o}=dt(),{Uuid6:s}=ft(),{UuidNil:c}=pt(),l=ht(),u=gt(),d=_t(),{IdFactory:f}=vt(),{VersionedIdFactory:p}=yt(),m={idCompare:function(e,t){return e.compare(t)},idEqual:function(e,t){return e.equal(t)},Exception:rt(),Ulid:new f({id:n,canonical_coder:l,raw_coder:u}),UlidMonotonic:new f({id:r,canonical_coder:l,raw_coder:u}),Uuid:new p({abstract_id:i,versioned_ids:[a,o,s,c],canonical_coder:d,raw_coder:u})};m.Uuid.versioned_ids.reduce((e,t)=>Object.assign(e,{[t.name]:t}),m),t.exports=m}))(),1),xt=e=>bt.default.UlidMonotonic.generate({time:e}).toCanonical(),St=async(e,t)=>e.query(async e=>{for await(let[n,r]of e.scan({prefix:w.surface.prefix()}).entries())if(r.key===t)return{id:w.surface.decode(n),...r}}),Ct=async e=>{let{replicache:n,key:r,name:i,description:a,toolList:o,projectId:s,signal:c}=e;return c?.aborted?Error(`Register surface aborted`):t(async()=>{let e=xt();return await n.mutate.surface_upsert_v1({surfaceId:e,projectPublicId:s,key:r,name:i,description:a,toolList:o.map(e=>e.toJSON()),context:{actionedAt:Date.now()}}),await n.push({now:!0}),await n.pull({now:!0}),await St(n,r)||Error(`Surface "${r}" missing from Replicache`)})},wt=class extends Error{name=`RoughClientDestroyedError`;constructor(e=`The Rough client has been destroyed`){super(e)}},Tt=class extends Error{name=`RoughReplicacheIdentityConflictError`;replicacheName;constructor(e){super(`Another Rough client is already using the local database "${e.replicacheName}". Share the existing client through your framework ownership boundary, or await its destroy() before creating a replacement.`),this.replicacheName=e.replicacheName}},Et=class extends Error{name=`RoughSurfaceContractConflictError`;surfaceKey;constructor(e){super(`Surface "${e.surfaceKey}" is already active on this client with a different contract. Close the operations using the old definition before activating the new one.`),this.surfaceKey=e.surfaceKey}},Dt=class extends Error{name=`RoughClientDestroyError`;errors;constructor(e){super(`Rough client destruction finished with ${e.errors.length} error(s): ${e.errors.map(e=>e.message).join(`; `)}`),this.errors=e.errors}},Ot=class extends Error{name=`RoughInvalidClientError`;constructor(e=`Expected a RoughClient created by createRoughClient()`){super(e)}},kt=e=>e instanceof Error?e:Error(String(e)),At=e=>e.reason instanceof Error?e.reason:new wt,jt=e=>new Promise((t,n)=>{if(e.aborted){n(At(e));return}e.addEventListener(`abort`,()=>n(At(e)),{once:!0})}),Mt=e=>new Promise(t=>{if(e.aborted){t();return}e.addEventListener(`abort`,()=>t(),{once:!0})}),Nt=Symbol(`rough.surface.definition`),Pt=(e,t)=>{if(typeof e!=`string`||e.trim()===``)throw TypeError(`defineRoughSurface: "${t}" must be a non-empty string`);return e},Ft=e=>{let t=Pt(e.key,`key`),n=Pt(e.name,`name`),r=Pt(e.description,`description`);if(!Array.isArray(e.tools))throw TypeError(`defineRoughSurface: "tools" must be an array`);for(let t of e.tools)if(typeof t?.toJSON!=`function`)throw TypeError(`defineRoughSurface: every entry in "tools" must be a Query, Mutation or Subscription`);let i={key:t,name:n,description:r,tools:Object.freeze([...e.tools])};return Object.defineProperty(i,Nt,{value:!0,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(i)},It=e=>typeof e==`object`&&!!e&&Nt in e&&e[Nt]===!0,Lt=e=>{if(!It(e))throw TypeError(`Expected a surface created by defineRoughSurface(). Object literals are not accepted because the definition must be validated and frozen.`);return e},Rt=e=>JSON.stringify({key:e.key,name:e.name,description:e.description,tools:e.tools.map(e=>e.toJSON())}),zt=e=>{let{getRuntime:t}=e,n=new Map,r=!1,i=(e,n)=>(async()=>{let r=t();r.assertUsable();let i=await Promise.race([r.getReplicache(),jt(n)]);r.assertUsable();let a=await Ct({replicache:i,projectId:r.projectId,key:e.key,name:e.name,description:e.description,toolList:e.tools,signal:n});if(a instanceof Error)throw a;return{id:a.id}})(),a=(e,t)=>{let r=new AbortController,a={registrationFingerprint:t,activeOperationCount:0,controller:r,resolution:i(e,r.signal)};return a.resolution.catch(()=>{n.get(e.key)===a&&n.delete(e.key)}),a};return{acquire:e=>{let i=Lt(e.surface);if(t().assertUsable(),r)throw new wt;let o=Rt(i),s=n.get(i.key);if(s&&s.registrationFingerprint!==o){if(s.activeOperationCount>0)throw new Et({surfaceKey:i.key});s.controller.abort(Error(`Surface contract replaced`)),n.delete(i.key),s=void 0}s||(s=a(i,o),n.set(i.key,s));let c=s;c.activeOperationCount+=1;let l=!1;return{surfaceKey:i.key,ready:c.resolution,release:()=>{l||(l=!0,c.activeOperationCount=Math.max(c.activeOperationCount-1,0))}}},destroy:async()=>{r=!0;let e=[...n.values()];n.clear();for(let t of e)t.controller.abort(new wt);await Promise.allSettled(e.map(e=>e.resolution))},getActiveOperationCount:e=>n.get(e)?.activeOperationCount??0}},Bt=()=>{let e=new Set;return{register:t=>(e.add(t),()=>{e.delete(t)}),closeAll:async()=>{let t=[...e];e.clear();let n=(await Promise.allSettled(t.map(async e=>{try{await e.close()}catch(t){let n=kt(t);throw n.message=`${e.label}: ${n.message}`,n}}))).flatMap(e=>e.status===`rejected`?[kt(e.reason)]:[]);if(n.length>0)throw new Dt({errors:n})},size:()=>e.size}},Vt=class{#e;constructor(e){this.#e=e}log(e,t,...n){for(let r of this.#e)r.log(e,t,...n)}async flush(){await Promise.all(this.#e.map(e=>e.flush?.()))}},Ht=class{debug=void 0;info=void 0;warn=void 0;error=void 0;flush;#e;#t;constructor(e,t=`info`,n){switch(this.#e=e,this.#t=n,t){case`debug`:this.debug=this.#n;case`info`:this.info=this.#r;case`warn`:this.warn=this.#i;case`error`:this.error=this.#a}this.flush=this.#o}#n(...e){this.#e.log(`debug`,this.#t,...e)}#r(...e){this.#e.log(`info`,this.#t,...e)}#i(...e){this.#e.log(`warn`,this.#t,...e)}#a(...e){this.#e.log(`error`,this.#t,...e)}#o(){return this.#e.flush?.()??Promise.resolve()}},Ut={log(e,t,...n){console[e](...Gt(t),...n.map(Kt))}},Wt=class e extends Ht{#e;#t;#n;constructor(e=`info`,t,n=Ut){super(n,e,t),this.#t=e,this.#e=n,this.#n=t}withContext(t,n){let r={...this.#n,[t]:n};return new e(this.#t,r,this.#e)}};function Gt(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=r===void 0?n:`${n}=${r}`;t.push(e)}return t}function Kt(e){switch(typeof e){case`string`:case`number`:case`boolean`:case`undefined`:case`symbol`:case`bigint`:return e;case`object`:if(e===null)return null}return JSON.stringify(e,qt)}function qt(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack,...`cause`in t?{cause:t.cause}:null}:t}function O(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Jt=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=O();return this._lockP=t,await e,n}withLock(e){return Xt(this.lock(),e)}},Yt=class{_lock=new Jt;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=O();return this._readP.push(e),t})}withRead(e){return Xt(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=O();return this._writeP=e,this._readP=[],t})}withWrite(e){return Xt(this.write(),e)}};async function Xt(e,t){let n=await e;try{return await t()}finally{n()}}var Zt=b({ValitaError:()=>sn,array:()=>nr,bigint:()=>qn,boolean:()=>Zn,err:()=>un,lazy:()=>ar,literal:()=>$n,never:()=>Ln,null:()=>Un,number:()=>Gn,object:()=>er,ok:()=>ln,record:()=>tr,string:()=>Yn,tuple:()=>rr,undefined:()=>Vn,union:()=>ir,unknown:()=>zn});function Qt(e,t){return e?{ok:!1,code:`join`,left:e,right:t}:t}function $t(e,t){return{ok:!1,code:`prepend`,key:e,tree:t}}function en(e,t){let n=e.code;switch(n){case`invalid_type`:return{code:n,path:t,expected:e.expected};case`invalid_literal`:return{code:n,path:t,expected:e.expected};case`missing_value`:return{code:n,path:t};case`invalid_length`:return{code:n,path:t,minLength:e.minLength,maxLength:e.maxLength};case`unrecognized_keys`:return{code:n,path:t,keys:e.keys};case`invalid_union`:return{code:n,path:t,tree:e.tree};case`custom_error`:return{code:n,path:t,error:e.error}}}function tn(e,t=[],n=[]){for(;;)if(e.code===`join`)tn(e.left,t.slice(),n),e=e.right;else if(e.code===`prepend`)t.push(e.key),e=e.tree;else return e.code===`custom_error`&&typeof e.error==`object`&&e.error.path!==void 0&&t.push(...e.error.path),n.push(en(e,t)),n}function nn(e,t){return e.length===0?`nothing`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} ${t} ${e[e.length-1]}`}function rn(e){return typeof e==`bigint`?`${e}n`:JSON.stringify(e)}function an(e){let t=0;for(;;)if(e.code===`join`)t+=an(e.left),e=e.right;else if(e.code===`prepend`)e=e.tree;else return t+1}function on(e){let t=``,n=0;for(;;)if(e.code===`join`)n+=an(e.right),e=e.left;else if(e.code===`prepend`)t+=`.${e.key}`,e=e.tree;else break;let r=`validation failed`;if(e.code===`invalid_type`)r=`expected ${nn(e.expected,`or`)}`;else if(e.code===`invalid_literal`)r=`expected ${nn(e.expected.map(rn),`or`)}`;else if(e.code===`missing_value`)r=`missing value`;else if(e.code===`unrecognized_keys`){let t=e.keys;r=`unrecognized ${t.length===1?`key`:`keys`} ${nn(t.map(rn),`and`)}`}else if(e.code===`invalid_length`){let t=e.minLength,n=e.maxLength;r=`expected an array with `,r+=t>0?n===t?`${t}`:n===void 0?`at least ${t}`:`between ${t} and ${n}`:`at most ${n??`∞`}`,r+=` item(s)`}else if(e.code===`custom_error`){let n=e.error;typeof n==`string`?r=n:n!==void 0&&(n.message!==void 0&&(r=n.message),n.path!==void 0&&(t+=`.`+n.path.join(`.`)))}let i=`${e.code} at .${t.slice(1)} (${r})`;return n===1?i+=` (+ 1 other issue)`:n>1&&(i+=` (+ ${n} other issues)`),i}var sn=class extends Error{constructor(e){super(on(e)),this.issueTree=e,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this._issues=void 0}get issues(){return this._issues===void 0&&(this._issues=tn(this.issueTree)),this._issues}},cn=class{constructor(e){this.issueTree=e,this.ok=!1,this._issues=void 0,this._message=void 0}get issues(){return this._issues===void 0&&(this._issues=tn(this.issueTree)),this._issues}get message(){return this._message===void 0&&(this._message=on(this.issueTree)),this._message}throw(){throw new sn(this.issueTree)}};function ln(e){return{ok:!0,value:e}}function un(e){return new cn({ok:!1,code:`custom_error`,error:e})}function dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fn=1,pn=2,mn=4,hn=class{optional(e){let t=new _n(this);return e?new Pn(t,t=>t===void 0?{ok:!0,value:e()}:void 0):t}default(e){let t=ln(e);return new Pn(this.optional(),e=>e===void 0?t:void 0)}assert(e,t){let n={ok:!1,code:`custom_error`,error:t};return new Pn(this,(t,r)=>e(t,r)?void 0:n)}map(e){return new Pn(this,(t,n)=>({ok:!0,value:e(t,n)}))}chain(e){return new Pn(this,(t,n)=>{let r=e(t,n);return r.ok?r:r.issueTree})}},k=class extends hn{nullable(){return new gn(this)}toTerminals(e){e(this)}try(e,t){let n=fn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=pn);let r=this.func(e,n);return r===void 0?{ok:!0,value:e}:r.ok?{ok:!0,value:r.value}:new cn(r)}parse(e,t){let n=fn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=pn);let r=this.func(e,n);if(r===void 0)return e;if(r.ok)return r.value;throw new sn(r)}},gn=class extends k{constructor(e){super(),this.type=e,this.name=`nullable`}func(e,t){return e===null?void 0:this.type.func(e,t)}toTerminals(e){e(Hn),this.type.toTerminals(e)}nullable(){return this}},_n=class extends hn{constructor(e){super(),this.type=e,this.name=`optional`}func(e,t){return e===void 0||t&mn?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(Bn),this.type.toTerminals(e)}optional(e){return e?new Pn(this,t=>t===void 0?{ok:!0,value:e()}:void 0):this}};function vn(e,t){if(typeof e!=`number`){let n=t>>5;for(let t=e.length;t<=n;t++)e.push(0);return e[n]|=1<<t%32,e}return t<32?e|1<<t:vn([e,0],t)}function yn(e,t){return typeof e==`number`?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}var bn=class e extends k{constructor(e,t,n){super(),this.shape=e,this.restType=t,this.checks=n,this.name=`object`,this._invalidType={ok:!1,code:`invalid_type`,expected:[`object`]}}check(t,n){let r={ok:!1,code:`custom_error`,error:n};return new e(this.shape,this.restType,[...this.checks??[],{func:t,issue:r}])}func(e,t){if(!dn(e))return this._invalidType;let n=this._func;return n===void 0&&(n=xn(this.shape,this.restType,this.checks),this._func=n),n(e,t)}rest(t){return new e(this.shape,t)}extend(t){return new e(Object.assign(Object.assign({},this.shape),t),this.restType)}pick(...t){let n={};return t.forEach(e=>{n[e]=this.shape[e]}),new e(n,void 0)}omit(...t){let n=Object.assign({},this.shape);return t.forEach(e=>{delete n[e]}),new e(n,this.restType)}partial(){let t={};Object.keys(this.shape).forEach(e=>{t[e]=this.shape[e].optional()});let n=this.restType?.optional();return new e(t,n)}};function xn(e,t,n){let r=[],i=[];for(let t in e){let n=!1;e[t].toTerminals(e=>{n||=e.name===`optional`}),n?i.push(t):r.push(t)}let a=[...r,...i],o=a.length;if(o===0&&t?.name===`unknown`)return function(e,t){if(n!==void 0){for(let t=0;t<n.length;t++)if(!n[t].func(e))return n[t].issue}};let s=a.map(t=>e[t]),c=r.length,l=Object.create(null);a.forEach((e,t)=>{l[e]=~t});let u=r.map(e=>$t(e,{ok:!1,code:`missing_value`}));function d(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}return function(e,r){let i=!1,f=e,p,m,h=0,g=0;if(r&fn||r&pn||t!==void 0)for(let n in e){let c=e[n],u=~l[n],_;if(u>=0)g++,h=vn(h,u),_=s[u].func(c,r);else if(t!==void 0)_=t.func(c,r);else{if(r&fn)m===void 0?m=[n]:m.push(n);else if(r&pn&&p===void 0&&!i){f={},i=!0;for(let t=0;t<o;t++)if(yn(h,t)){let n=a[t];d(f,n,e[n])}}continue}if(_===void 0)i&&p===void 0&&d(f,n,c);else if(!_.ok)p=Qt(p,$t(n,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t!==u&&yn(h,t)){let n=a[t];d(f,n,e[n])}}else for(let t in e)d(f,t,e[t])}d(f,n,_.value)}}if(g<o)for(let n=0;n<o;n++){if(yn(h,n))continue;let l=a[n],m=e[l],g=r&-5;if(m===void 0&&!(l in e)){if(n<c){p=Qt(p,u[n]);continue}g|=mn}let _=s[n].func(m,g);if(_===void 0)i&&p===void 0&&!(g&mn)&&d(f,l,m);else if(!_.ok)p=Qt(p,$t(l,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t<n||yn(h,t)){let n=a[t];d(f,n,e[n])}}else{for(let t in e)d(f,t,e[t]);for(let t=0;t<n;t++)if(!yn(h,t)){let n=a[t];d(f,n,e[n])}}}d(f,l,_.value)}}if(m!==void 0&&(p=Qt(p,{ok:!1,code:`unrecognized_keys`,keys:m})),p===void 0&&n!==void 0){for(let e=0;e<n.length;e++)if(!n[e].func(f))return n[e].issue}return p===void 0&&i?{ok:!0,value:f}:p}}var Sn=class e extends k{constructor(e,t,n){super(),this.prefix=e,this.rest=t,this.suffix=n,this.name=`array`,this.restType=t??Ln(),this.minLength=this.prefix.length+this.suffix.length,this.maxLength=t?void 0:this.minLength,this.invalidType={ok:!1,code:`invalid_type`,expected:[`array`]},this.invalidLength={ok:!1,code:`invalid_length`,minLength:this.minLength,maxLength:this.maxLength}}func(e,t){if(!Array.isArray(e))return this.invalidType;let n=e.length,r=this.minLength,i=this.maxLength??1/0;if(n<r||n>i)return this.invalidLength;let a=this.prefix.length,o=e.length-this.suffix.length,s,c=e;for(let n=0;n<e.length;n++){let r=(n<a?this.prefix[n]:n>=o?this.suffix[n-o]:this.restType).func(e[n],t);r!==void 0&&(r.ok?(c===e&&(c=e.slice()),c[n]=r.value):s=Qt(s,$t(n,r)))}return s||(e===c?void 0:{ok:!0,value:c})}concat(t){if(this.rest){if(t.rest)throw TypeError(`can not concatenate two variadic types`);return new e(this.prefix,this.rest,[...this.suffix,...t.prefix,...t.suffix])}return t.rest?new e([...this.prefix,...this.suffix,...t.prefix],t.rest,t.suffix):new e([...this.prefix,...this.suffix,...t.prefix,...t.suffix],t.rest,t.suffix)}};function Cn(e){let t=typeof e;return t===`object`?e===null?`null`:Array.isArray(e)?`array`:t:t}function wn(e){return Array.from(new Set(e))}function Tn(e){let t=new Map;e.forEach(e=>{for(let n in e)t.set(n,(t.get(n)??0)+1)});let n=[];return t.forEach((t,r)=>{t===e.length&&n.push(r)}),n}function En(e){let t=new Map,n=new Map,r=new Map,i=[],a=[],o=[];e.forEach(({root:e,terminal:s})=>{if(t.set(e,t.get(e)??t.size),s.name!==`never`){if(s.name===`optional`)a.push(e);else if(s.name===`unknown`)i.push(e);else if(s.name===`literal`){let t=n.get(s.value)??[];t.push(e),n.set(s.value,t),o.push(Cn(s.value))}else{let t=r.get(s.name)??[];t.push(e),r.set(s.name,t),o.push(s.name)}}}),n.forEach((e,t)=>{let i=r.get(Cn(t));i&&(i.push(...e),n.delete(t))});let s=(e,n)=>(t.get(e)??0)-(t.get(n)??0);return r.forEach((e,t)=>r.set(t,wn(e.concat(i).sort(s)))),n.forEach((e,t)=>n.set(t,wn(e.concat(i)).sort(s))),{types:r,literals:n,unknowns:wn(i).sort(s),optionals:wn(a).sort(s),expectedTypes:wn(o)}}function Dn(e,t){let n=[];for(let{root:r,terminal:i}of e)i.shape[t].toTerminals(e=>n.push({root:r,terminal:e}));let{types:r,literals:i,optionals:a,unknowns:o,expectedTypes:s}=En(n);if(o.length>0||a.length>1)return;for(let e of i.values())if(e.length>1)return;for(let e of r.values())if(e.length>1)return;let c=$t(t,{ok:!1,code:`missing_value`}),l=$t(t,r.size===0?{ok:!1,code:`invalid_literal`,expected:Array.from(i.keys())}:{ok:!1,code:`invalid_type`,expected:s}),u=i.size>0?new Map:void 0;for(let[e,t]of i)u.set(e,t[0]);let d=r.size>0?{}:void 0;for(let[e,t]of r)d[e]=t[0];return function(e,n){let r=e,i=r[t];if(i===void 0&&!(t in r))return a.length>0?a[0].func(r,n):c;let o=d?.[Cn(i)]??u?.get(i);return o?o.func(r,n):l}}function On(e){if(e.some(({terminal:e})=>e.name===`unknown`))return;let t=e.filter(e=>e.terminal.name===`object`);if(t.length<2)return;let n=t.map(({terminal:e})=>e.shape);for(let e of Tn(n)){let n=Dn(t,e);if(n)return n}}function kn(e){let{expectedTypes:t,literals:n,types:r,unknowns:i,optionals:a}=En(e),o=r.size===0&&i.length===0?{ok:!1,code:`invalid_literal`,expected:Array.from(n.keys())}:{ok:!1,code:`invalid_type`,expected:t},s=n.size>0?n:void 0,c=r.size>0?{}:void 0;for(let[e,t]of r)c[e]=t;return function(e,t){let n=t&mn?a:c?.[Cn(e)]??s?.get(e)??i,r=0,l=o;for(let i=0;i<n.length;i++){let a=n[i].func(e,t);if(a===void 0||a.ok)return a;l=r>0?Qt(l,a):a,r++}return r>1?{ok:!1,code:`invalid_union`,tree:l}:l}}var An=class extends k{constructor(e){super(),this.options=e,this.name=`union`}toTerminals(e){this.options.forEach(t=>{t.toTerminals(e)})}func(e,t){let n=this._func;if(n===void 0){let e=[];this.options.forEach(t=>{t.toTerminals(n=>{e.push({root:t,terminal:n})})});let t=kn(e),r=On(e);n=r?function(e,n){return dn(e)?r(e,n):t(e,n)}:t,this._func=n}return n(e,t)}},jn=Object.freeze({mode:`strict`}),Mn=Object.freeze({mode:`strip`}),Nn=Object.freeze({mode:`passthrough`}),Pn=class e extends k{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name=`transform`,this.undef=ln(void 0),this.transformChain=void 0,this.transformRoot=void 0}func(t,n){let r=this.transformChain;if(!r){r=[];let t=this;for(;t instanceof e;)r.push(t.transform),t=t.transformed;r.reverse(),this.transformChain=r,this.transformRoot=t}let i=this.transformRoot.func(t,n);if(i!==void 0&&!i.ok)return i;let a;i===void 0?n&mn?(a=void 0,i=this.undef):a=t:a=i.value;let o=n&fn?jn:n&pn?Mn:Nn;for(let e=0;e<r.length;e++){let t=r[e](a,o);if(t!==void 0){if(!t.ok)return t;a=t.value,i=t}}return i}toTerminals(e){this.transformed.toTerminals(e)}},Fn=class extends k{constructor(e){super(),this.definer=e,this.name=`lazy`,this.recursing=!1}func(e,t){return this.type||=this.definer(),this.type.func(e,t)}toTerminals(e){if(!this.recursing)try{this.recursing=!0,this.type||=this.definer(),this.type.toTerminals(e)}finally{this.recursing=!1}}},In=new class extends k{constructor(){super(...arguments),this.name=`never`,this.issue={ok:!1,code:`invalid_type`,expected:[]}}func(e,t){return this.issue}};function Ln(){return In}var Rn=new class extends k{constructor(){super(...arguments),this.name=`unknown`}func(e,t){}};function zn(){return Rn}var Bn=new class extends k{constructor(){super(...arguments),this.name=`undefined`,this.issue={ok:!1,code:`invalid_type`,expected:[`undefined`]}}func(e,t){return e===void 0?void 0:this.issue}};function Vn(){return Bn}var Hn=new class extends k{constructor(){super(...arguments),this.name=`null`,this.issue={ok:!1,code:`invalid_type`,expected:[`null`]}}func(e,t){return e===null?void 0:this.issue}};function Un(){return Hn}var Wn=new class extends k{constructor(){super(...arguments),this.name=`number`,this.issue={ok:!1,code:`invalid_type`,expected:[`number`]}}func(e,t){return typeof e==`number`?void 0:this.issue}};function Gn(){return Wn}var Kn=new class extends k{constructor(){super(...arguments),this.name=`bigint`,this.issue={ok:!1,code:`invalid_type`,expected:[`bigint`]}}func(e,t){return typeof e==`bigint`?void 0:this.issue}};function qn(){return Kn}var Jn=new class extends k{constructor(){super(...arguments),this.name=`string`,this.issue={ok:!1,code:`invalid_type`,expected:[`string`]}}func(e,t){return typeof e==`string`?void 0:this.issue}};function Yn(){return Jn}var Xn=new class extends k{constructor(){super(...arguments),this.name=`boolean`,this.issue={ok:!1,code:`invalid_type`,expected:[`boolean`]}}func(e,t){return typeof e==`boolean`?void 0:this.issue}};function Zn(){return Xn}var Qn=class extends k{constructor(e){super(),this.value=e,this.name=`literal`,this.issue={ok:!1,code:`invalid_literal`,expected:[e]}}func(e,t){return e===this.value?void 0:this.issue}};function $n(e){return new Qn(e)}function er(e){return new bn(e,void 0)}function tr(e){return new bn({},e??zn())}function nr(e){return new Sn([],e??zn(),[])}function rr(e){return new Sn(e,void 0,[])}function ir(...e){return new An(e)}function ar(e){return new Fn(e)}var or=Object.defineProperty,sr=Object.getOwnPropertyDescriptor,cr=Object.getOwnPropertyNames,lr=Object.prototype.hasOwnProperty,ur=(e,t)=>{for(var n in t)or(e,n,{get:t[n],enumerable:!0})},dr=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of cr(t))!lr.call(e,i)&&i!==n&&or(e,i,{get:()=>t[i],enumerable:!(r=sr(t,i))||r.enumerable});return e},fr=(e,t,n)=>(dr(e,t,`default`),n&&dr(n,t,`default`)),pr=class extends Error{name=`AbortError`};function A(e,t=`Assertion failed`){if(!e)throw Error(t)}function j(e){hr(e,`string`)}function M(e){hr(e,`number`)}function mr(e){hr(e,`boolean`)}function hr(e,t){typeof e!==t&&vr(e,t)}function N(e){e===null&&vr(e,`object`),hr(e,`object`)}function gr(e){Array.isArray(e)||vr(e,`array`)}function _r(e,t){let n=`Invalid type: `;return n+=e==null?e:`${typeof e} \`${e}\``,n+`, expected ${t}`}function vr(e,t){throw Error(_r(e,t))}function yr(e){if(e===null)throw Error(`Expected non-null value`)}function br(e,t=`Expected non undefined value`){if(e===void 0)throw Error(t)}function xr(e){throw Error(`Unreachable`)}function Sr(){return typeof document<`u`?document:void 0}function Cr(e,t,n){return e?new wr(e,t,n):new Dr}var wr=class{#e;#t;#n=0;visibilityState;#r=new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.visibilityState=e.visibilityState,this.#e.addEventListener(`visibilitychange`,this.#i,{signal:n})}#i=()=>{this.#e.visibilityState===`visible`?(clearTimeout(this.#n),this.#a(`visible`)):this.#n=setTimeout(()=>{this.#a(`hidden`)},this.#t)};#a(e){if(e!==this.visibilityState){this.visibilityState=e;for(let t of this.#r){let{resolve:n,state:r}=t;r===e&&(n(),this.#r.delete(t))}}}waitForVisible(){return this.#o(`visible`)}waitForHidden(){return this.#o(`hidden`)}#o(e){if(this.visibilityState===e)return Promise.resolve();let{promise:t,resolve:n}=O();return this.#r.add({resolve:n,state:e}),t}},Tr=Promise.resolve(),Er=new Promise(()=>{}),Dr=class{visibilityState=`visible`;waitForVisible(){return Tr}waitForHidden(){return Er}},Or=class{rep;invokeSend;maxConnections=1;constructor(e,t){this.rep=e,this.invokeSend=t}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},kr=class extends Or{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},Ar=class extends Or{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},jr=Promise.resolve();new Promise(()=>{});function Mr(e,t){return e===0?jr:new Promise((n,r)=>{let i;t&&(i=()=>{clearTimeout(a),r(new pr(`Aborted`))},t.addEventListener(`abort`,i,{once:!0}));let a=setTimeout(()=>{n(),t?.removeEventListener(`abort`,i)},e)})}var Nr=30,Pr=6e4,Fr=class{#e=O();#t=O();#n=O();#r;#i=!1;#a=0;#o;#s;constructor(e,t,n){this.#o=e,this.#r=t,this.#s=n,this.run()}close(){this.#i=!0,this.#a>0&&this.#n.resolve({error:Lr()})}async send(e){if(this.#i)return{error:Lr()};this.#a++,this.#o.debug?.(`send`,e),e?this.#t.resolve():await this.#s?.waitForVisible(),this.#e.resolve();let t=await this.#n.promise;return this.#a--,t}async run(){let e=[],t=O(),n,r=0,i=this.#r,{debug:a}=this.#o,o=0;a?.(`Starting connection loop`);let s=e=>Promise.race([this.#t.promise,Mr(e)]);for(;!this.#i;){a?.(Br(e)?`Last request failed. Trying again`:`Waiting for a send`);let c=[this.#e.promise],l=i.watchdogTimer;if(l!==null&&c.push(Mr(l)),await Promise.race(c),this.#i||(a?.(`Waiting for debounce`),await s(i.debounceDelay),this.#i))break;if(a?.(`debounced`),this.#e=O(),r>=i.maxConnections){if(a?.(`Too many request in flight. Waiting until one finishes...`),await this.#u(),this.#i)break;a?.(`...finished`)}r>0||Br(e)?(o=Rr(o,i,e),a?.(Br(e)?`Last connection errored. Sleeping for`:`More than one outstanding connection (`+r+`). Sleeping for`,o,`ms`)):o=0;let u=Math.min(i.maxDelayMs,Math.max(i.minDelayMs,o));if(n!==void 0){let e=Date.now()-n;if(u>e&&(await Promise.race([s(u-e),t.promise]),this.#i))break}r++,(async()=>{let o=Date.now(),s,c;try{n=o,a?.(`Sending request`),this.#t=O(),s=await i.invokeSend(),a?.(`Send returned`,s)}catch(e){a?.(`Send failed`,e),c=e,s=!1}if(this.#i){a?.(`Closed after invokeSend`);return}a?.(`Request done`,{duration:Date.now()-o,ok:s}),e.push({duration:Date.now()-o,ok:s}),Vr(e)&&(t.resolve(),t=O()),r--,this.#l();let l=this.#n;this.#n=O(),c?l.resolve({error:c}):l.resolve(void 0),s||this.#e.resolve()})()}}#c=void 0;#l(){if(this.#c){let e=this.#c;this.#c=void 0,e()}}#u(){let{promise:e,resolve:t}=O();return this.#c=t,e}},Ir=9;function Lr(){return Error(`Closed`)}function Rr(e,t,n){let{length:r}=n;if(r===0)return e;let{ok:i}=n[n.length-1],{maxConnections:a,minDelayMs:o}=t;if(!i)return e===0?o:e*2;if(r>1){let e=n[n.length-2];for(;n.length>Ir;)n.shift();if(i&&!e.ok)return o}return zr(n.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}function zr(e){e.sort();let{length:t}=e,n=t>>1;return t%2==1?e[n]:(e[n-1]+e[n])/2}function Br(e){return e.length>0&&!e[e.length-1].ok}function Vr(e){return e.length>1&&!e[e.length-2].ok&&e[e.length-1].ok}var Hr=process.env.NODE_ENV===`production`,Ur=Object.prototype.hasOwnProperty,Wr=Object.hasOwn||((e,t)=>Ur.call(e,t));function Gr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;switch(typeof e){case`boolean`:case`number`:case`string`:return!1}if(e=e,Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Gr(e[n],t[n]))return!1;return!0}if(e===null||t===null||Array.isArray(t))return!1;e=e,t=t;let n=0;for(let r in e)if(Wr(e,r)){if(!Gr(e[r],t[r]))return!1;n++}let r=0;for(let e in t)Wr(t,e)&&r++;return n===r}function Kr(e){if(!Hr){switch(typeof e){case`boolean`:case`number`:case`string`:return;case`object`:return e===null?void 0:Array.isArray(e)?Yr(e):Jr(e)}vr(e,`JSON value`)}}function qr(e){N(e),Jr(e)}function Jr(e){for(let t in e)if(Wr(e,t)){let n=e[t];n!==void 0&&Kr(n)}}function Yr(e){for(let t of e)Kr(t)}function Xr(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:return e===null?!0:Array.isArray(e)?$r(e,t):Qr(e,t)}return!1}function Zr(e,t){return typeof e!=`object`||!e?!1:Qr(e,t)}function Qr(e,t){for(let n in e)if(Wr(e,n)){t.push(n);let r=e[n];if(r!==void 0&&!Xr(r,t))return!1;t.pop()}return!0}function $r(e,t){for(let n=0;n<e.length;n++){if(t.push(n),!Xr(e[n],t))return!1;t.pop()}return!0}function ei(e,t){return e===t?0:e<t?-1:1}function ti(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;let n=ni(e),r=ni(t);return typeof n==`string`||typeof r==`string`?ei(String(n),String(r)):n-r}function ni(e){return typeof e==`string`||typeof e==`number`?e:e.order}function ri(e){if(e!==null&&typeof e!=`string`&&typeof e!=`number`&&(qr(e),typeof e.order!=`string`&&typeof e.order!=`number`))throw Error(`Invalid cookie`)}function*ii(...e){for(let t of e)yield*t}var ai=Promise.resolve(!0),oi=Promise.resolve(!1);Promise.resolve(void 0);var si=Promise.resolve(),ci=1,li=4,ui=5,di=8;function fi(e){switch(typeof e){case`string`:return ci+li+e.length;case`number`:return pi(e)?e<=-(2**30)||e>=2**30-1?ci+ui:ci+li:ci+di;case`boolean`:return ci;case`object`:if(e===null)return ci;if(Array.isArray(e)){let t=2*ci+li;for(let n of e)t+=fi(n);return t}{let t=e,n=2*ci+li;for(let e in t)if(Wr(t,e)){let r=t[e];r!==void 0&&(n+=fi(e)+fi(r))}return n}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function pi(e){return e===(e|0)}var mi=2*ci+li+ci+li;function hi(e,t){return mi+fi(e)+fi(t)}var gi=new WeakSet;function _i(e){return Hr||vi(e,[]),e}function vi(e,t){switch(typeof e){case`undefined`:throw TypeError(`Unexpected value undefined`);case`boolean`:case`number`:case`string`:return;case`object`:if(e===null||gi.has(e))return;gi.add(e),t.includes(e)&&vr(e,`Cyclic JSON object`),t.push(e),Object.freeze(e),Array.isArray(e)?yi(e,t):bi(e,t),t.pop();return;default:vr(e,`JSON value`)}}function yi(e,t){for(let n of e)vi(n,t)}function bi(e,t){for(let n in e)if(Wr(e,n)){let r=e[n];r!==void 0&&vi(r,t)}}function xi(e){if(!Hr&&!Si(e,[]))throw Error(`Expected frozen object`)}function Si(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:if(e===null||gi.has(e))return!0;if(!Object.isFrozen(e))return!1;if(t.includes(e)&&vr(e,`Cyclic JSON object`),t.push(e),Array.isArray(e)){for(let n of e)if(!Si(n,t))return t.pop(),!1}else for(let n in e)if(Wr(e,n)){let r=e[n];if(r!==void 0&&!Si(r,t))return t.pop(),!1}return gi.add(e),t.pop(),!0;default:vr(e,`JSON value`)}}function Ci(e){if(e!==void 0)return _i(e)}function wi(e){if(Array.isArray(e)){e.sort();for(let t=1;t<e.length;t++)A(e[t-1]!==e[t],`Refs must not have duplicates`);return e}let t=[...e];return t.sort(),t}var Ti=class{hash;data;meta;constructor(e,t,n){A(!n.includes(e),`Chunk cannot reference itself`),xi(t),this.hash=e,this.data=t,this.meta=n}};function Ei(e){if(!Array.isArray(e))throw Error(`Refs must be an array`);if(e.length>0){j(e[0]);for(let t=1;t<e.length;t++)j(e[t])}}function Di(e,t,n){return new Ti(n(),e,t)}function Oi(){throw Error(`unexpected call to compute chunk hash`)}function ki(){let e=Math.floor(Math.random()*4294967295),t=Math.floor(Math.random()*4294967295);return BigInt(e)<<32n|BigInt(t)}var P={};ur(P,{assert:()=>Ii,is:()=>Fi,parse:()=>Pi,readonly:()=>Ri,readonlyArray:()=>Bi,readonlyObject:()=>zi,readonlyRecord:()=>Vi,test:()=>Li}),fr(P,Zt);function Ai(e){switch(typeof e){case`string`:case`number`:case`boolean`:return JSON.stringify(e);case`undefined`:return`undefined`;case`bigint`:return e.toString()+`n`;default:return e===null?`null`:Array.isArray(e)?`array`:typeof e}}function ji(e,t){if(!t?.length)return Ai(e);let n=e;for(let e of t)n=n[e];return Ai(n)}function Mi(e,t,n=e=>String(e)){if(t.length===1)return n(t[0]);let r=`${n(t[t.length-2])} ${e} ${n(t[t.length-1])}`;return t.length===2?r:`${t.slice(0,-2).map(n).join(`, `)}, ${r}`}function Ni(e,t){let n=e.issues[0],{path:r}=n,i=r?.length?` at ${r.join(`.`)}`:``;switch(n.code){case`invalid_type`:return`Expected ${Mi(`or`,n.expected)}${i}. Got ${ji(t,r)}`;case`missing_value`:{let e=r&&r.length>1?` at ${r.slice(0,-1).join(`.`)}`:``;return n.path?.length?`Missing property ${n.path.at(-1)}${e}`:`TODO Unknown missing property${e}`}case`invalid_literal`:return`Expected literal value ${Mi(`or`,n.expected,Ai)}${i} Got ${ji(t,r)}`;case`invalid_length`:return`Expected array with length ${n.minLength===n.maxLength?n.minLength:`between ${n.minLength} and ${n.maxLength}`}${i}. Got array with length ${t.length}`;case`unrecognized_keys`:return n.keys.length===1?`Unexpected property ${n.keys[0]}${i}`:`Unexpected properties ${Mi(`and`,n.keys)}${i}`;case`invalid_union`:return`Invalid union value${i}`;case`custom_error`:{let{error:e}=n;return`${e?typeof e==`string`?e:e.message??`unknown`:`unknown`}${i}. Got ${ji(t,r)}`}}}function Pi(e,t,n){let r=Li(e,t,n);if(!r.ok)throw TypeError(r.error);return r.value}function Fi(e,t,n){return Li(e,t,n).ok}function Ii(e,t,n){Pi(e,t,n)}function Li(e,t,n){let r=t.try(e,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:Ni(r,e)}}function Ri(e){return e}function zi(e){return er(e)}function Bi(e){return nr(e)}function Vi(e){return tr(e)}var Hi=22,Ui=/^[0-9a-v-]+$/,F=`0`.repeat(Hi),Wi=Ki();function Gi(e,t){return e.toString(32).slice(-t).padStart(t,`0`)}function Ki(){let e=``,t=0;return()=>{e||=Gi(ki(),12);let n=Gi(t++,10);return e+n}}function qi(e){return typeof e==`string`&&Ui.test(e)}function Ji(e){Ii(e,Yi)}var Yi=P.string().assert(qi,`Invalid hash`);function Xi(e,t,n){return new Zi(e,t,n).compute()}var Zi=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e,t,n){let r=[],i=[];for(let t of e)t.old!==t.new&&(t.old&&i.push(t.old),t.new&&r.push(t.new));this.#e=r,this.#t=i,this.#n=t,this.#r=n,this.#a=new Map,this.#o=new Map,this.#s=n.areRefsCounted!==void 0,this.#i=this.#s?new Set:null}async compute(){for(let e of this.#e)await this.#c(e,1);if(await Promise.all(Array.from(this.#n.values(),e=>this.#u(e))),this.#s){A(this.#r.areRefsCounted),A(this.#i);let e;do{e=!1;for(let t of this.#n.values())if(!this.#r.areRefsCounted(t)&&!this.#i.has(t)&&this.#a.get(t)!==0){await this.#l(t,1),e=!0;break}}while(e)}for(let e of this.#t)await this.#c(e,-1);if(!Hr)for(let[e,t]of this.#a)A(t>=0,`ref count update must be non-negative. ${e}:${t}`);return this.#a}async#c(e,t){await this.#u(e),this.#d(e,t)&&await this.#l(e,t)}async#l(e,t){if(e===F)return;let n=await this.#r.getRefs(e);if(Hr||A(n||this.#s&&!this.#n.has(e),`refs must be defined`),n!==void 0){this.#i?.add(e);let r=n.map(e=>this.#c(e,t));await Promise.all(r)}}#u(e){let t=this.#o.get(e);return t===void 0&&(t=(async()=>{let t=await this.#r.getRefCount(e)||0;return this.#a.set(e,t),t})(),this.#o.set(e,t)),t}#d(e,t){let n=this.#a.get(e);return M(n),this.#a.set(e,n+t),n===0&&t===1||n===1&&t===-1}},Qi=class extends Error{name=`ChunkNotFoundError`;hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function $i(e,t){let n=await e.getChunk(t);if(n)return n;throw new Qi(t)}async function ea(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),n}var ta=class{#e=new Yt;#t=new Map;#n;#r;#i;t=new Map;n;h=new Map;m=new Map;constructor(e,t,n,r,i=fi){this.n=new ia(t,i,this.h,this.m),this.#n=e,this.#r=n,this.#i=r}async read(){let e=await this.#e.read();return new na(this.#t,this.t,this.n,this.#n,e,this.#i)}async write(){let e=await this.#e.write();return new ra(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#i)}close(){return si}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},na=class{a;t;n;f;#e=void 0;#t;#n=!1;assertValidHash;constructor(e,t,n,r,i,a){this.a=e,this.t=t,this.n=n,this.f=r,this.#t=i,this.assertValidHash=a}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let t=this.t.get(e);if(t!==void 0)return t;let n=this.n.get(e);return n===void 0&&(n=await(await this.y()).getChunk(e),n!==void 0&&this.n.put(n)),n}mustGetChunk(e){return $i(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#n||=(this.#t(),this.#e?.then(e=>e.release()).catch(e=>{}),!0)}get closed(){return this.#n}y(){return this.#e||=this.f.read(),this.#e}},ra=class extends na{#e;#t;#n;i=new Map;o=new Map;s=new Map;#r=new Set;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,o,c),this.#e=i,this.#t=a,this.#n=s}createChunk=(e,t)=>{let n=Di(e,t,this.#n);return this.#r.add(n.hash),n};putChunk(e,t){let{hash:n,meta:r}=e;if(this.assertValidHash(n),r.length>0)for(let e of r)this.assertValidHash(e);return this.#r.has(n)||this.isMemOnlyChunkHash(n)?this.o.set(n,e):this.s.set(n,{chunk:e,size:t??-1}),si}async setHead(e,t){await this.#i(e,t)}async removeHead(e){await this.#i(e,void 0)}async#i(e,t){let n=await this.getHead(e),r=this.i.get(e);r===void 0?this.i.set(e,{new:t,old:n}):r.new=t}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let t=this.o.get(e);if(t!==void 0)return t;let n=this.t.get(e);if(n!==void 0)return n;let r=this.s.get(e);if(r!==void 0)return r.chunk;let i=this.n.get(e);return i===void 0&&(i=await(await this.y()).getChunk(e),i!==void 0&&this.s.set(i.hash,{chunk:i,size:-1})),i}getHead(e){let t=this.i.get(e);return t?Promise.resolve(t.new):super.getHead(e)}async commit(){let e=new Set(ii(this.o.keys(),this.s.keys())),t=await Xi(this.i.values(),e,this);for(let[e,n]of t)if(this.isMemOnlyChunkHash(e)){if(n===0)this.#e.delete(e),this.t.delete(e),this.#t.delete(e);else{this.#e.set(e,n);let t=this.o.get(e);t&&(this.#t.set(e,t.meta),this.t.set(e,t))}t.delete(e)}this.n.updateForCommit(this.s,t);for(let[e,t]of this.i)t.new?this.a.set(e,t.new):this.a.delete(e);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#e.get(e)}getRefs(e){let t=this.o.get(e);if(t)return t.meta;let n=this.t.get(e);if(n)return n.meta;let r=this.s.get(e);return r===void 0?this.#t.get(e):r.chunk.meta}areRefsCounted(e){return this.#t.has(e)}chunksPersisted(e){let t=[];for(let n of e){let e=this.t.get(n);e&&(this.t.delete(n),t.push(e))}this.n.persisted(t)}},ia=class{#e;#t;#n;#r;#i=0;#a=!1;#o=[];cacheEntries=new Map;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}get(e){let t=this.cacheEntries.get(e);return t&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,t)),t?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:t}=e,n=this.cacheEntries.get(t);if(n){this.cacheEntries.delete(t),this.cacheEntries.set(t,n);return}let r=this.#n.get(t);if(!(r===void 0||r<1)&&this.#c(e)){if(!this.#r.has(t)){for(let t of e.meta)this.#n.set(t,(this.#n.get(t)||0)+1);this.#r.set(t,e.meta)}this.#s()}}#s(){if(!this.#a)for(let e of this.cacheEntries.values()){if(this.#i<=this.#e)break;this.#l(e)}}#c(e,t){let n=t??this.#t(e);return n>this.#e?!1:(this.#i+=n,this.cacheEntries.set(e.hash,{chunk:e,size:n}),!0)}#l(e){let{hash:t}=e.chunk;this.#i-=e.size,this.cacheEntries.delete(t)}#u(e){this.#n.delete(e),this.#r.delete(e);let t=this.cacheEntries.get(e);t&&(this.#i-=t.size,this.cacheEntries.delete(e))}updateForCommit(e,t){for(let[n,r]of t)if(r===0)this.#a?(this.#n.set(n,0),this.#o.push(n)):this.#u(n);else{this.#n.set(n,r);let t=e.get(n);if(t){let{chunk:e,size:r}=t,i=this.cacheEntries.get(n);i?(this.cacheEntries.delete(n),this.cacheEntries.set(n,i)):(this.#c(e,r===-1?void 0:r),this.#r.set(n,e.meta))}}this.#s()}persisted(e){for(let t of e)this.#c(t);this.#s()}async withSuspendedEvictsAndDeletes(e){this.#a=!0;try{return await e()}finally{this.#a=!1;for(let e of this.#o)this.#n.get(e)===0&&this.#u(e);this.#s()}}};function aa(e){return`c/${e}/d`}function oa(e){return`c/${e}/m`}function sa(e){return`c/${e}/r`}function ca(e){return`h/${e}`}var la=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){return new ua(await this.#e.read(),this.#n)}async write(){return new da(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},ua=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(aa(e))}async getChunk(e){let t=await this.e.get(aa(e));if(t===void 0)return;let n=await this.e.get(oa(e)),r;return n===void 0?r=[]:(Ei(n),r=n),new Ti(e,t,r)}mustGetChunk(e){return $i(this,e)}async getHead(e){let t=await this.e.get(ca(e));if(t!==void 0)return Ji(t),t}release(){this.e.release()}get closed(){return this.e.closed}},da=class extends ua{#e;#t=new Set;#n=new Map;constructor(e,t,n){super(e,n),this.#e=t}createChunk=(e,t)=>Di(e,t,this.#e);get kvWrite(){return this.e}async putChunk(e){let{hash:t,data:n,meta:r}=e;this.assertValidHash(t);let i=aa(t),a=this.e.put(i,n),o;if(r.length>0){for(let e of r)this.assertValidHash(e);o=this.e.put(oa(t),r)}this.#t.add(t),await a,await o}setHead(e,t){return this.#r(e,t)}removeHead(e){return this.#r(e,void 0)}async#r(e,t){let n=await this.getHead(e),r=ca(e),i;i=t===void 0?this.e.del(r):this.e.put(r,t);let a=this.#n.get(e);a===void 0?this.#n.set(e,{new:t,old:n}):a.new=t,await i}async commit(){let e=await Xi(this.#n.values(),this.#t,this);await this.#i(e),await this.e.commit()}async getRefCount(e){let t=await this.e.get(sa(e));if(t!==void 0){if(M(t),t<0||t>65535||t!==(t|0))throw Error(`Invalid ref count ${t}. We expect the value to be a Uint16`);return t}}async getRefs(e){let t=await this.e.get(oa(e));return t===void 0?[]:(Ei(t),t)}async#i(e){let t=[];for(let[n,r]of e)if(r===0)t.push(this.#a(n));else{let e=sa(n);t.push(this.e.put(e,r))}await Promise.all(t)}async#a(e){await Promise.all([this.e.del(aa(e)),this.e.del(oa(e)),this.e.del(sa(e))]),this.#t.delete(e)}release(){this.e.release()}},I=`main`;function fa(e){return Fa(e.meta)}function pa(e){return Pa(e.meta)}function ma(e){return pa(e)||fa(e)}function ha(e){return Va(e.meta)}function ga(e){return Ha(e.meta)}function _a(e){return ha(e)||ga(e)}var va=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,t){return ya(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function ya(e,t,n){switch(n.type){case 1:return n.lastMutationID;case 3:return n.lastMutationID;case 5:return n.lastMutationIDs[e]??0;case 2:return n.mutationID;case 4:{if(n.clientID===e)return n.mutationID;let{basisHash:r}=n;return ya(e,t,(await L(r,t)).meta)}default:xr(n)}}async function ba(e,t){return(await ka(e,t)).filter(e=>ma(e))}async function xa(e,t){return(await ka(e,t)).filter(e=>pa(e))}async function Sa(e,t,n){let r=[],i=new Map(Object.entries(t));for(;!_a(e)&&i.size>0;){if(pa(e)){let{meta:t}=e,n=i.get(t.clientID);n!==void 0&&(t.mutationID<=n?i.delete(t.clientID):r.push(e))}let{basisHash:t}=e.meta;if(t===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await L(t,n)}return r}async function Ca(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),Ta(n,t)}async function wa(e,t){return(await Ta(e,t)).chunk.hash}async function Ta(e,t){return Ea(await L(e,t),t)}async function Ea(e,t){for(;!_a(e);){let{meta:n}=e;if(Pa(n))e=await L(n.baseSnapshotHash,t);else{let{basisHash:r}=n;if(r===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await L(r,t)}}return e}function Da(e,t){let n=e.meta;return Va(n)?[n.lastMutationIDs[t]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function Oa(e,t){return ti(e.meta.cookieJSON,t.meta.cookieJSON)}async function ka(e,t){let n=await L(e,t),r=[];for(;!_a(n);){let{meta:e}=n,{basisHash:i}=e;if(i===null)throw Error(`Commit ${n.chunk.hash} has no basis`);r.push(n),n=await L(i,t)}return r.push(n),r}async function L(e,t){return no(await t.mustGetChunk(e))}async function Aa(e,t){return L(await ea(e,t),t)}function ja(e){M(e.lastMutationID)}function Ma(e){if(M(e.mutationID),j(e.mutatorName),!e.mutatorName)throw Error(`Missing mutator name`);Kr(e.mutatorArgsJSON),e.originalHash!==null&&Ji(e.originalHash),M(e.timestamp)}function Na(e){j(e.clientID),Ma(e)}function Pa(e){return e.type===4}function Fa(e){return e.type===2}function Ia(e){e.basisHash!==null&&Ji(e.basisHash),Kr(e.cookieJSON)}function La(e){Ia(e),M(e.lastMutationID)}function Ra(e){Ia(e),za(e.lastMutationIDs)}function za(e){N(e);for(let t of Object.values(e))M(t)}function Ba(e){Ra(e.meta)}function Va(e){return e.type===5}function Ha(e){return e.type===3}function Ua(e){switch(N(e),xi(e),e.basisHash!==null&&j(e.basisHash),M(e.type),e.type){case 1:ja(e);break;case 2:Ma(e);break;case 4:Na(e);break;case 3:La(e);break;case 5:Ra(e);break;default:throw Error(`Invalid enum value ${e.type}`)}}function Wa(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&e.keyPrefix===t.keyPrefix}function Ga(e){N(e),xi(e),j(e.name),j(e.keyPrefix),j(e.jsonPointer),e.allowEmpty!==void 0&&mr(e.allowEmpty)}function Ka(e,t){return{name:e,keyPrefix:t.prefix??``,jsonPointer:t.jsonPointer,allowEmpty:t.allowEmpty??!1}}function qa(e){N(e),xi(e),Ga(e.definition),j(e.valueHash)}function Ja(e){gr(e),xi(e);for(let t of e)qa(t)}function Ya(e,t,n,r,i,a,o,s,c){return ro(e,ao({type:2,basisHash:t,mutationID:n,mutatorName:r,mutatorArgsJSON:i,originalHash:a,timestamp:c},o,s))}function Xa(e,t,n,r,i,a,o,s,c,l,u){return ro(e,ao({type:4,basisHash:t,baseSnapshotHash:n,mutationID:r,mutatorName:i,mutatorArgsJSON:a,originalHash:o,timestamp:l,clientID:u},s,c))}function Za(e,t,n,r,i,a){return ro(e,$a(t,n,r,i,a))}function Qa(e,t,n,r,i,a){return ro(e,eo(t,n,r,i,a))}function $a(e,t,n,r,i){return ao({type:3,basisHash:e,lastMutationID:t,cookieJSON:n},r,i)}function eo(e,t,n,r,i){return ao({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:n},r,i)}function to(e,t,n,r,i){return ro(e,ao({type:1,basisHash:t,lastMutationID:n},r,i))}function no(e){return so(e),new va(e)}function ro(e,t){return new va(e(t,io(t)))}function io(e){let t=new Set;t.add(e.valueHash);let{meta:n}=e;switch(n.type){case 1:n.basisHash&&t.add(n.basisHash);break;case 2:case 4:n.basisHash&&t.add(n.basisHash);break;case 3:case 5:break;default:xr(n)}for(let n of e.indexes)t.add(n.valueHash);return wi(t)}function ao(e,t,n){return _i({meta:e,valueHash:t,indexes:n})}function oo(e){Hr||(N(e),xi(e),Ua(e.meta),j(e.valueHash),Ja(e.indexes))}function so(e){let{data:t}=e;oo(t);let n=new Set;for(let e of t.indexes){let{name:t}=e.definition;if(n.has(t))throw Error(`Duplicate index ${t}`);n.add(t)}}function co(e,t){let n=e.length,r=t.length,i=Math.min(n,r);for(let n=0;n<i;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i)return r<128&&i<128?r-i:lo(po,ho(r,po),mo,ho(i,mo));n+=uo(r)}return n-r}function lo(e,t,n,r){let i=Math.min(t,r);for(let t=0;t<i;t++){let r=e[t],i=n[t];if(r!==i)return r-i}return t-r}function uo(e){return e>65535?2:1}var fo=()=>Array.from({length:4},()=>0),po=fo(),mo=fo();function ho(e,t){if(e<128)return t[0]=e,1;let n,r;if(e<=2047)n=1,r=192;else if(e<=65535)n=2,r=224;else if(e<=1114111)n=3,r=240;else throw Error(`Invalid code point`);t[0]=(e>>6*n)+r;let i=1;for(;n>0;n--){let r=e>>6*(n-1);t[i++]=128|r&63}return i}function go(e,t){return co(e,t)>0}function _o(e,t){return co(e,t)<0}function vo(e,t){return co(e,t)<=0}function yo(e,t){let n=0;for(;n<e;){let r=n+(e-n>>1),i=t(r);if(i===0)return r;i>0?n=r+1:e=r}return n}function bo(e){if(e!==(e|0)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}var xo=0,So=1;function Co(e,t,n){return _i([e,n>=7?t:t.map(e=>e.slice(0,2))])}async function wo(e,t,n,r){let i=await n.getNode(t);if(r!==n.rootHash)return wo(e,n.rootHash,n,n.rootHash);if(Io(i))return i;let{entries:a}=i,o=To(e,a);o===a.length&&o--;let s=a[o];return wo(e,s[1],n,r)}function To(e,t){return yo(t.length,n=>co(e,t[n][0]))}function Eo(e,t,n){return e!==t.length&&t[e][0]===n}function Do(e,t,n){if(Hr&&t>=7)return e;gr(e),xi(e),A(e.length>=2);let[r,i]=e;M(r),gr(i);let a=r>0?j:Kr;if(t>=7){for(let e of i)Oo(e,a);return e}return[r,i.map(e=>ko(e,a,n))]}function Oo(e,t){gr(e),A(e.length>=3),j(e[0]),t(e[1]),M(e[2])}function ko(e,t,n){gr(e),A(e.length>=2),j(e[0]),t(e[1]);let r=n(e[0],e[1]);return[e[0],e[1],r]}var Ao=class{entries;hash;isMutable;#e=-1;constructor(e,t,n){this.entries=e,this.hash=t,this.isMutable=n}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(this.#e!==-1)return this.#e;let t=e.chunkHeaderSize;for(let e of this.entries)t+=e[2];return this.#e=t}c(e){this.#e=-1,e.updateNode(this)}};function jo(e,t){return Co(e.level,e.entries,t)}var Mo=class extends Ao{level=0;set(e,t,n,r){let i,a=To(e,this.entries);return i=+!!Eo(a,this.entries,e),Promise.resolve(this.#e(r,a,i,[e,t,n]))}#e(e,t,n,...r){if(this.isMutable)return this.entries.splice(t,n,...r),this.c(e),this;let i=No(this.entries,t,n,...r);return e.newDataNodeImpl(i)}del(e,t){let n=To(e,this.entries);return Eo(n,this.entries,e)?Promise.resolve(this.#e(t,n,1)):Promise.resolve(this)}async*keys(e){for(let e of this.entries)yield e[0]}async*entriesIter(e){for(let e of this.entries)yield e}};function No(e,t,n,...r){let i=e.slice(0,t);for(let e=0;e<r.length;e++)i.push(r[e]);for(let r=t+n;r<e.length;r++)i.push(e[r]);return i}var Po=class e extends Ao{level;constructor(e,t,n,r){super(e,t,r),this.level=n}async set(e,t,n,r){let i=To(e,this.entries);i===this.entries.length&&i--;let a=this.entries[i][1],o=await(await r.getNode(a)).set(e,t,n,r),s=o.getChildNodeSize(r);if(s>r.maxSize||s<r.minSize)return this.#e(r,i,o);let c=Bo(o,r.getEntrySize);return this.#t(r,i,c)}async#e(e,t,n){let r=this.level-1,i=this.entries,a,o,s;if(t>0){let r=i[t-1][1];a=ii((await e.getNode(r)).entries,n.entries),o=t-1,s=2}else if(t<i.length-1){let r=i[t+1][1],c=await e.getNode(r);a=ii(n.entries,c.entries),o=t,s=2}else a=n.entries,o=t,s=1;let c=Lo(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),l=[];for(let t of c){let n=Bo(e.newNodeImpl(t,r),e.getEntrySize);l.push(n)}if(this.isMutable)return this.entries.splice(o,s,...l),this.c(e),this;let u=No(i,o,s,...l);return e.newInternalNodeImpl(u,this.level)}#t(e,t,n){if(this.isMutable)return this.entries.splice(t,1,n),this.c(e),this;let r=No(this.entries,t,1,n);return e.newInternalNodeImpl(r,this.level)}async del(e,t){let n=To(e,this.entries);if(n===this.entries.length)return this;let r=this.entries[n][1],i=await t.getNode(r),a=i.hash,o=await i.del(e,t);if(o.hash===a)return this;if(o.entries.length===0){let e=No(this.entries,n,1);return t.newInternalNodeImpl(e,this.level)}if(n===0&&this.entries.length===1)return o;if(o.getChildNodeSize(t)>t.minSize){let e=Bo(o,t.getEntrySize);return this.#t(t,n,e)}return this.#e(t,n,o)}async*keys(e){for(let t of this.entries)yield*(await e.getNode(t[1])).keys(e)}async*entriesIter(e){for(let t of this.entries)yield*(await e.getNode(t[1])).entriesIter(e)}getChildren(e,t,n){let r=[];for(let i=e;i<t&&i<this.entries.length;i++)r.push(n.getNode(this.entries[i][1]));return Promise.all(r)}async getCompositeChildren(t,n,r){let{level:i}=this;if(n===0)return new e([],Wi(),i-1,!0);let a=await this.getChildren(t,t+n,r);if(i>1){let t=[];for(let e of a)t.push(...e.entries);return new e(t,Wi(),i-1,!0)}A(i===1);let o=[];for(let e of a)o.push(...e.entries);return new Mo(o,Wi(),!0)}};function Fo(e,t,n,r){return n===0?new Mo(e,t,r):new Po(e,t,n,r)}function Io(e){return e.level===0}function Lo(e,t,n,r){let i=[],a=[],o=0,s=[];for(let c of e){let e=t(c);e>=r?(s.length>0&&(i.push(s),a.push(o)),i.push([c]),a.push(e),o=0,s=[]):o+e>=n?(s.push(c),i.push(s),a.push(o+e),o=0,s=[]):(o+=e,s.push(c))}return o>0&&(a.length>0&&o+a[a.length-1]<=r?i[i.length-1].push(...s):i.push(s)),i}var Ro=Co(0,[],7),zo=new Mo([],F,!1);function Bo(e,t){let n=e.maxKey(),r=e.hash;return[n,r,t(n,r)]}var Vo=-1,Ho=0,Uo=1,Wo=2,Go=3,Ko=0,qo=1;function*Jo(e,t){let n=0,r=0,i;function a(e,t){e[Go]===Vo&&(e[Go]=t)}function o(){return[n,0,0,Vo]}for(;n<e.length&&r<t.length;)e[n][Ko]===t[r][Ko]?(Gr(e[n][qo],t[r][qo])?i&&=(a(i,0),yield i,void 0):(i||=o(),i[Wo]++,i[Uo]++,a(i,r)),n++,r++):e[n][Ko]<t[r][Ko]?(i||=o(),i[Uo]++,n++):(i||=o(),i[Wo]++,a(i,r),r++);r<t.length&&(i||=o(),i[Wo]+=t.length-r,a(i,r)),n<e.length&&(i||=o(),i[Uo]+=e.length-n),i&&(a(i,0),yield i)}var Yo=11,Xo=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,n=F,r=hi,i=Yo){this.l=e,this.u=t,this.rootHash=n,this.getEntrySize=r,this.chunkHeaderSize=i}async getNode(e){if(e===F)return zo;let t=this.p.get(e);if(t)return t;let n=Do((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),r=Fo(n[So],e,n[xo],!1);return this.p.set(e,r),r}async get(e){let t=await wo(e,this.rootHash,this,this.rootHash),n=To(e,t.entries);if(Eo(n,t.entries,e))return t.entries[n][1]}async has(e){let t=await wo(e,this.rootHash,this,this.rootHash);return Eo(To(e,t.entries),t.entries,e)}async isEmpty(){let{rootHash:e}=this,t=await this.getNode(this.rootHash);return this.rootHash===e?t.entries.length===0:this.isEmpty()}scan(e){return $o(this.rootHash,()=>this.rootHash,this.rootHash,e,async e=>{let t=await this.getNode(e);return t?[t.level,t.isMutable?t.entries.slice():t.entries]:Do((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize)})}async*keys(){yield*(await this.getNode(this.rootHash)).keys(this)}async*entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async*diff(e){let[t,n]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*Zo(n,t,e,this)}};async function*Zo(e,t,n,r){if(e.level>t.level){yield*Zo(await e.getCompositeChildren(0,e.entries.length,n),t,n,r);return}if(t.level>e.level){yield*Zo(e,await t.getCompositeChildren(0,t.entries.length,r),n,r);return}if(Io(e)&&Io(t)){yield*Qo(e.entries,t.entries);return}let i=Jo(e.entries,t.entries);for(let a of i){let[i,o]=await Promise.all([e.getCompositeChildren(a[Ho],a[Uo],n),t.getCompositeChildren(a[Go],a[Wo],r)]);yield*Zo(i,o,n,r)}}function*Qo(e,t){let n=e.length,r=t.length,i=0,a=0;for(;i<n&&a<r;){let n=e[i][0],r=t[a][0];n===r?(Gr(e[i][1],t[a][1])||(yield{op:`change`,key:n,oldValue:e[i][1],newValue:t[a][1]}),i++,a++):n<r?(yield{op:`del`,key:n,oldValue:e[i][1]},i++):(yield{op:`add`,key:r,newValue:t[a][1]},a++)}for(;i<n;i++)yield{op:`del`,key:e[i][0],oldValue:e[i][1]};for(;a<r;a++)yield{op:`add`,key:t[a][0],newValue:t[a][1]}}async function*$o(e,t,n,r,i){if(n===F)return;let a=await i(n),o=a[So],s=0;if(r&&(s=To(r,o)),a[xo]>0)for(;s<o.length;s++)yield*$o(e,t,o[s][1],r,i),r=``;else for(;s<o.length;s++){let n=t();if(e!==n){yield*$o(n,t,n,o[s][0],i);return}yield o[s]}}async function es(e,t){let n=[],r=t===`add`?e=>({op:`add`,key:e[0],newValue:e[1]}):e=>({op:`del`,key:e[0],oldValue:e[1]});for await(let t of e.entries())n.push(r(t));return n}var ts=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},ns=class extends ts{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function rs(e,t,n,r,i,a,o){try{for(let e of is(r,i,a,o))switch(n){case 0:await t.put(e,i);break;case 1:await t.del(e);break}}catch(t){e.info?.(`Not indexing value`,i,`:`,t)}}function is(e,t,n,r){let i=us(t,n);if(i===void 0){if(r)return[];throw Error(`No value at path: ${n}`)}let a=Array.isArray(i)?i:[i],o=[];for(let t of a)if(typeof t==`string`)o.push(ss([t,e]));else throw Error(`Unsupported target type`);return o}var as=`\0`,os=`\0`;function ss(e){let t=e[0],n=e[1];if(t.includes(`\0`))throw Error(`Secondary key cannot contain null byte`);return as+t+os+n}function cs(e,t){let n=ss([e,t||``]);return t===void 0?n.slice(0,n.length-1):n}function ls(e){if(e[0]!==as)throw Error(`Invalid version`);let t=as.length,n=os.length,r=e.indexOf(os,t);if(r===-1)throw Error(`Invalid formatting`);return[e.slice(t,r),e.slice(r+n)]}function us(e,t){function n(e){if(!(e.startsWith(`+`)||e.startsWith(`0`)&&e.length!==1))return parseInt(e,10)}if(t===``)return e;if(!t.startsWith(`/`))throw Error(`Invalid JSON pointer: ${t}`);let r=t.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){let t;if(Array.isArray(i)){let r=n(e);if(r===void 0)return;t=i[r]}else{if(i===null)return;typeof i==`object`&&(i=i,t=i[e])}if(t===void 0)return;i=t}return i}var ds=class{#e;map;indexes;constructor(e,t,n){this.#e=e,this.map=t,this.indexes=n}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let t=this.indexes.get(e);if(t===void 0)throw Error(`Unknown index name: ${e}`);return t.map}get closed(){return this.#e.closed}close(){this.#e.release()}};function fs(e,t){return ps(I,e,t)}async function ps(e,t,n){return ms(await Aa(e,t),t,n)}function ms(e,t,n){let r=hs(e,t,n);return new ds(t,new Xo(t,n,e.valueHash),r)}function hs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ts(i,new Xo(t,n,i.valueHash)));return r}async function gs(e){let t=[];for await(let n of e)t.push(n);return t}function _s(e){return e.indexName!==void 0}function vs(e){return typeof e==`string`?[e]:e}function ys(e){if(!e)return{};let t,n,r,i;return e.start&&({key:t,exclusive:n}=e.start,e.indexName?typeof t==`string`?i=t:(i=t[0],r=t[1]):r=t),{prefix:e.prefix,startSecondaryKey:i,startKey:r,startExclusive:n,limit:e.limit,indexName:e.indexName}}var bs=class extends Error{constructor(){super(`Transaction is closed`)}};function xs(e){if(e.closed)throw new bs}function Ss(e){return e.closed?Promise.reject(new bs):void 0}var Cs=class{#e;#t;#n;#r;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}[Symbol.asyncIterator](){return this.values()}values(){return new ws(this.#i(e=>e[1]))}keys(){return new ws(this.#i(e=>e[0]))}entries(){return new ws(this.#i(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#i(e){return Ts(e,this.#e,this.#t,this.#n,this.#r)}},ws=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return gs(this.#e)}};async function*Ts(e,t,n,r,i){xs(r);let{limit:a=1/0}=n,{prefix:o=``}=n,s=n.start?.exclusive,c=_s(n);for await(let r of t){let t=r[0];if(!(c?t[0]:t).startsWith(o))return;if(s){if(s=!0,c){if(Es(t,n.start.key))continue}else if(Ds(t,n.start.key))continue}if(yield e(r),--a===0){c||i(t);return}}}function Es(e,t){let[n,r]=vs(t),[i,a]=vs(e);return i===n?r===void 0||a===r:!1}function Ds(e,t){return e===t}function Os(e){let{prefix:t,start:n}=e,r=``;if(t!==void 0&&(r=cs(t,void 0)),!n)return r;let{key:i}=n,[a,o]=vs(i),s=cs(a,o);return go(s,r)?s:r}var ks=0,As=class{clientID;dbtx;d;location;environment;constructor(e,t,n,r=`openReadTransaction`){this.clientID=e,this.dbtx=t,this.d=n.withContext(r).withContext(`txid`,ks++),this.environment=`client`,this.location=`client`}get(e){return Ss(this.dbtx)||this.dbtx.get(e)}async has(e){return xs(this.dbtx),this.dbtx.has(e)}async isEmpty(){return xs(this.dbtx),this.dbtx.isEmpty()}scan(e){return Ms(e,this.dbtx,js)}};function js(e){}function Ms(e,t,n){return Ls(Fs(t,e),e??{},t,n)}var Ns=class{#e=new Set;#t=[];#n;constructor(e){this.#n=e}get environment(){return this.#n.location}get location(){return this.#n.location}get clientID(){return this.#n.clientID}isEmpty(){return this.#t.push({options:{}}),this.#n.isEmpty()}get(e){return this.#e.add(e),this.#n.get(e)}has(e){return this.#e.add(e),this.#n.has(e)}scan(e){let t={options:ys(e),inclusiveLimitKey:void 0};return this.#t.push(t),Ms(e,this.#n.dbtx,e=>{t.inclusiveLimitKey=e})}get keys(){return this.#e}get scans(){return this.#t}},Ps=class extends As{reason;mutationID;constructor(e,t,n,r,i,a=`openWriteTransaction`){super(e,r,i,a),this.mutationID=t,this.reason=n}put(e,t){return this.set(e,t)}async set(e,t){xs(this.dbtx),await this.dbtx.put(this.d,e,_i(t))}del(e){return Ss(this.dbtx)??this.dbtx.del(this.d,e)}};function Fs(e,t){return t&&_s(t)?Rs(e,t):e.map.scan(Is(t))}function Is(e){if(!e)return``;let{prefix:t=``,start:n}=e;return n&&go(n.key,t)?n.key:t}function Ls(e,t,n,r){return new Cs(e,t,n,r)}async function*Rs(e,t){let n=e.getMapForIndex(t.indexName);for await(let e of n.scan(Os(t)))yield[ls(e[0]),e[1]]}function zs(e,t){return gs(t.diff(e))}var Bs=class extends Xo{#e=new Jt;#t=new Map;minSize;maxSize;constructor(e,t,n=F,r=8192,i=16384,a=hi,o){super(e,t,n,a,o),this.minSize=r,this.maxSize=i}#n(e){A(e.isMutable),this.#t.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){A(e.isMutable),this.#t.delete(e.hash),e.hash=Wi(),this.#n(e)}newInternalNodeImpl(e,t){let n=new Po(e,Wi(),t,!0);return this.#n(n),n}newDataNodeImpl(e){let t=new Mo(e,Wi(),!0);return this.#n(t),t}newNodeImpl(e,t){let n=Fo(e,Wi(),t,!0);return this.#n(n),n}put(e,t){return this.#e.withLock(async()=>{let n=await this.getNode(this.rootHash),r=this.getEntrySize(e,t),i=await n.set(e,t,r,this);if(i.getChildNodeSize(this)>this.maxSize){let e=this.chunkHeaderSize,t=Lo(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:n}=i,r=t.map(e=>Bo(this.newNodeImpl(e,n),this.getEntrySize)),a=this.newInternalNodeImpl(r,n+1);this.rootHash=a.hash;return}this.rootHash=i.hash})}del(e){return this.#e.withLock(async()=>{let t=await(await this.getNode(this.rootHash)).del(e,this),n=this.rootHash!==t.hash;return n&&(this.rootHash=t.level>0&&t.entries.length===1?t.entries[0][1]:t.hash),n})}clear(){return this.#e.withLock(()=>{this.#t.clear(),this.rootHash=F})}flush(){return this.#e.withLock(async()=>{let e=this.l;if(this.rootHash===F){let t=e.createChunk(Ro,[]);return await e.putChunk(t),t.hash}let t=[],n=Vs(this.rootHash,t,e.createChunk,this.#t,this.u);return await Promise.all(t.map(t=>e.putChunk(t))),this.#t.clear(),this.rootHash=n,n})}};function Vs(e,t,n,r,i){let a=r.get(e);if(a===void 0)return e;if(Io(a)){let e=n(jo(a,i),[]);return t.push(e),e.hash}let o=[],{entries:s}=a;for(let e=0;e<s.length;e++){let a=s[e],c=a[1],l=Vs(c,t,n,r,i);l!==c&&(s[e]=[a[0],l,a[2]]),o.push(l)}let c=n(jo(a,i),wi(o));return t.push(c),c.hash}function Hs(e){let t;return()=>(t===void 0&&(t=e()),t)}var Us=class extends Map{set(e,t){return t.length===0?this:super.set(e,t)}};async function Ws(e,t,n,r,i){let a=new Us;if(!r.shouldComputeDiffs())return a;let o=await zs(new Xo(n,i,e.valueHash),new Xo(n,i,t.valueHash));return a.set(``,o),await Gs(e,t,n,a,r,i),a}async function Gs(e,t,n,r,i,a){let o=hs(e,n,a),s=hs(t,n,a);for(let[e,t]of o){if(!i.shouldComputeDiffsForIndex(e))continue;let n=s.get(e);if(n!==void 0){A(n!==t);let i=await zs(t.map,n.map);s.delete(e),r.set(e,i)}else{let n=await es(t.map,`del`);r.set(e,n)}}for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let n=await es(t.map,`add`);r.set(e,n)}}var Ks=class extends ds{#e;#t;#n;#r;#i;constructor(e,t,n,r,i,a,o){super(e,t,i),this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o,A(n===void 0?r.basisHash===F:r.basisHash===n.chunk.hash)}async put(e,t,n){if(this.#n.type===1)throw Error(`Not allowed`);let r=Hs(()=>this.map.get(t));await Xs(e,this.indexes,t,r,n),await this.map.put(t,n)}getMutationID(){return ya(this.#r,this.#e,this.#n)}async del(e,t){if(this.#n.type===1)throw Error(`Not allowed`);let n=Hs(()=>this.map.get(t));return n!==void 0&&await Xs(e,this.indexes,t,n,void 0),this.map.del(t)}async clear(){if(this.#n.type===1)throw Error(`Not allowed`);await this.map.clear();let e=[];for(let t of this.indexes.values())e.push(t.clear());await Promise.all(e)}async putCommit(){let e=await this.map.flush(),t=[];for(let e of this.indexes.values()){let n=await e.flush(),r={definition:e.meta.definition,valueHash:n};t.push(r)}let n,r=this.#n;switch(r.type){case 2:{let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Ya(this.#e.createChunk,i,a,o,s,c,e,t,l);break}case 4:{A(this.#i>=5);let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Xa(this.#e.createChunk,i,await wa(i,this.#e),a,o,s,c,e,t,l,this.#r);break}case 3:{A(this.#i<=4);let{basisHash:i,lastMutationID:a,cookieJSON:o}=r;n=Za(this.#e.createChunk,i,a,o,e,t);break}case 5:{A(this.#i>5);let{basisHash:i,lastMutationIDs:a,cookieJSON:o}=r;n=Qa(this.#e.createChunk,i,a,o,e,t);break}case 1:{let{basisHash:i,lastMutationID:a}=r;if(this.#t!==void 0){if(await this.#t.getMutationID(this.#r,this.#e)!==a)throw Error(`Index change must not change mutationID`);if(this.#t.valueHash!==e)throw Error(`Index change must not change valueHash`)}n=to(this.#e.createChunk,i,a,e,t);break}}return await this.#e.putChunk(n.chunk),n}async commit(e){let t=(await this.putCommit()).chunk.hash;return await this.#e.setHead(e,t),await this.#e.commit(),t}async commitWithDiffs(e,t){let n=this.putCommit(),r=await this.#a(t),i=(await n).chunk.hash;return await this.#e.setHead(e,i),await this.#e.commit(),r}async#a(e){let t=new Us;if(!e.shouldComputeDiffs())return t;let n=[];this.#t&&(n=await zs(new Xo(this.#e,this.#i,this.#t.valueHash),this.map)),t.set(``,n);let r;r=this.#t?hs(this.#t,this.#e,this.#i):new Map;for(let[n,i]of this.indexes){if(!e.shouldComputeDiffsForIndex(n))continue;let a=r.get(n);A(i!==a);let o=await(a?zs(a.map,i.map):es(i.map,`add`));t.set(n,o)}for(let[n,i]of r)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await es(i.map,`del`);t.set(n,e)}return t}close(){this.#e.release()}};async function qs(e,t,n,r,i,a,o,s){let c=await L(e,i),l=new Bs(i,s,c.valueHash),u=await c.getNextMutationID(o,i),d=Zs(c,i,s);return new Ks(i,l,c,s>=5?{type:4,basisHash:e,baseSnapshotHash:await wa(e,i),mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a,clientID:o}:{type:2,basisHash:e,mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a},d,o,s)}async function Js(e,t,n,r,i,a,o){A(o<=4);let s=await L(e,r);return new Ks(r,new Bs(r,o,s.valueHash),s,{basisHash:e,type:3,lastMutationID:t,cookieJSON:n},i,a,o)}async function Ys(e,t,n,r,i,a){let o=await L(e,r);return new Ks(r,new Bs(r,a,o.valueHash),o,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:n},Zs(o,r,a),i,a)}async function Xs(e,t,n,r,i){let a=[];for(let o of t.values()){let{keyPrefix:t}=o.meta.definition;if(!t||n.startsWith(t)){let t=await r();t!==void 0&&a.push(rs(e,o.map,1,n,t,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1)),i!==void 0&&a.push(rs(e,o.map,0,n,i,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function Zs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ns(i,new Bs(t,n,i.valueHash)));return r}async function Qs(e,t,n,r,i,a,o){let s=new Bs(t,o);for await(let t of n.scan(r)){let n=t[0];if(!n.startsWith(r))break;await rs(e,s,0,n,t[1],i,a)}return s}async function $s(e,t,n,r,i,a,o){let s=e.meta,c=s.mutatorName;Pa(s)&&A(s.clientID===a,`mutationClientID must match clientID of LocalMeta`);let l=r[c];l||i.error?.(`Cannot rebase unknown mutator ${c}`);let u=l||(async()=>{}),d=s.mutatorArgsJSON,f=await(await L(n,t)).getNextMutationID(a,t);if(f!==s.mutationID)throw Error(`Inconsistent mutation ID: original: ${s.mutationID}, next: ${f} - mutationClientID: ${a} mutatorName: ${c}`);o>=5&&Na(s);let p=await qs(n,c,d,e.chunk.hash,t,s.timestamp,a,o);return await u(new Ps(a,await p.getMutationID(),`rebase`,p,i),d),p}async function ec(e,t,n,r,i,a,o){return(await $s(e,t,n,r,i,a,o)).putCommit()}async function tc(e,t,n,r,i,a,o,s){return(await $s(e,t,n,i,a,o,s)).commit(r)}function nc(e,t){return typeof e==`object`&&!!e&&e.error===t}function rc(e){return typeof e.error==`string`}function ic(e){return nc(e,`ClientStateNotFound`)}function ac(e){if(!nc(e,`VersionNotSupported`))return!1;let{versionType:t}=e;switch(t){case void 0:case`pull`:case`push`:case`schema`:return!0}return!1}function oc(e){A(ac(e))}async function sc(e,t,n,r){let i={headers:{"Content-type":`application/json`,Authorization:t,"X-Replicache-RequestID":n},body:JSON.stringify(r),method:`POST`},a=new Request(e,i),o=await fetch(a),s=o.status;return s===200?[o,{httpStatusCode:s,errorMessage:``}]:[void 0,{httpStatusCode:s,errorMessage:await o.text()}]}function cc(e){N(e),M(e.httpStatusCode),j(e.errorMessage)}function lc(e){gr(e);for(let t of e)uc(t)}function uc(e){switch(N(e),e.op){case`put`:j(e.key),Kr(e.value);break;case`update`:if(j(e.key),e.merge!==void 0&&qr(e.merge),e.constrain!==void 0){gr(e.constrain);for(let t of e.constrain)j(t)}break;case`del`:j(e.key);break;case`clear`:break;default:throw Error(`unknown patch op \`${e.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}function dc(e){async function t(t,n){let[r,i]=await sc(e.pullURL,e.auth,n,t);return r?{response:await r.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return fc.add(t),t}var fc=new WeakSet;function pc(e){return fc.has(e)}function mc(e){if(N(e),ic(e)||ac(e))return;let t=e;t.cookie!==void 0&&Kr(t.cookie),M(t.lastMutationID),lc(t.patch)}function hc(e){if(N(e),ic(e)||ac(e))return;let t=e;t.cookie!==void 0&&ri(t.cookie),gc(t.lastMutationIDChanges),lc(t.patch)}function gc(e){N(e);for(let[t,n]of Object.entries(e))j(t),M(n)}function _c(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&hc(e.response)}function vc(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&mc(e.response)}function yc(e){async function t(t,n){let[r,i]=await sc(e.pushURL,e.auth,n,t);if(!r)return{httpRequestInfo:i};let a={httpRequestInfo:i},o;try{o=await r.json()}catch{return a}return(ic(o)||ac(o))&&(a.response=o),a}return bc.add(t),t}var bc=new WeakSet;function xc(e){return bc.has(e)}function Sc(e=`info`,t=[Ut],n){return new Wt(e,n,t.length===1?t[0]:new Vt(t))}var Cc=Vi(zi({prefix:P.string().optional(),jsonPointer:P.string(),allowEmpty:P.boolean().optional()}));function wc(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&(e.prefix??``)===(t.prefix??``)}function Tc(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let[n,r]of Object.entries(e)){let e=t[n];if(!e||!wc(r,e))return!1}return!0}var Ec=zi({headHash:Yi,mutatorNames:Bi(P.string()),indexes:Cc,mutationIDs:Vi(P.number()),lastServerAckdMutationIDs:P.record(P.number()),disabled:P.boolean()}),Dc=`client-groups`;function Oc(e){Ii(e,Ec)}function kc(e){N(e);let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&(Oc(r),t.set(n,r));return t}function Ac(e,t){let n={};for(let[r,i]of e.entries())t.assertValidHash(i.headHash),n[r]={...i,mutatorNames:[...i.mutatorNames.values()]};return _i(n)}async function jc(e,t){return kc((await t.getChunk(e))?.data)}async function Mc(e){let t=await e.getHead(Dc);return t?jc(t,e):new Map}async function Nc(e,t){let n=await Mc(t);for(let[t,r]of e)Fc(r,n.get(t));return Ic(e,t)}async function Pc(e,t,n){let r=await Mc(n);Fc(t,r.get(e));let i=new Map(r);return i.set(e,t),Ic(i,n)}function Fc(e,t){let n=new Set(e.mutatorNames);A(n.size===e.mutatorNames.length,`A client group's mutatorNames must be a set.`),t!==void 0&&(A(Tc(t.indexes,e.indexes),`A client group's index definitions must never change.`),A(Lc(n,t.mutatorNames),`A client group's mutatorNames must never change.`))}async function Ic(e,t){let n=Ac(e,t),r=new Set;for(let t of e.values())r.add(t.headHash);let i=t.createChunk(n,wi(r));return await t.putChunk(i),await t.setHead(Dc,i.hash),e}function Lc(e,t){if(t.length!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function Rc(e,t){return(await Mc(t)).get(e)}function zc(e){for(let[t,n]of Object.entries(e.mutationIDs)){let r=e.lastServerAckdMutationIDs[t];if(r===void 0&&n!==0||r<n)return!0}return!1}async function Bc(e,t){let n=await Rc(e,t);n&&await Pc(e,{...n,disabled:!0},t)}var Vc=P.string(),Hc=P.string();function R(e,t){return Wc(e.read(),t)}function Uc(e,t){return Wc(e.write(),t)}function z(e,t){return Wc(e.write(),async e=>{let n=await t(e);return await e.commit(),n})}async function Wc(e,t){let n=await e;try{return await t(n)}finally{n.release()}}function Gc(){let e=ki(),t=ki();return(e<<64n|t).toString(32).slice(-18).padStart(18,`0`)}var Kc=zi({heartbeatTimestampMs:P.number(),headHash:Yi,mutationID:P.number(),lastServerAckdMutationID:P.number()}),qc=zi({heartbeatTimestampMs:P.number(),headHash:Yi,tempRefreshHash:Yi.nullable(),clientGroupID:Vc}),Jc=zi({heartbeatTimestampMs:P.number(),refreshHashes:Bi(Yi),persistHash:Yi.nullable(),clientGroupID:Vc});function Yc(e){return e.refreshHashes!==void 0}function Xc(e){return e.clientGroupID!==void 0}var Zc=`clients`,Qc=P.union(Kc,qc,Jc);function $c(e){Ii(e,Qc)}function el(e){Ii(e,Kc)}function tl(e){Ii(e,Jc)}function nl(e){N(e);let t=new Map;for(let n in e)if(Wr(e,n)){let r=e[n];r!==void 0&&($c(r),t.set(n,r))}return t}function rl(e,t){for(let n of e.values())Yc(n)?(n.refreshHashes.forEach(t.assertValidHash),n.persistHash&&t.assertValidHash(n.persistHash)):(t.assertValidHash(n.headHash),Xc(n)&&n.tempRefreshHash&&t.assertValidHash(n.tempRefreshHash));return _i(Object.fromEntries(e))}async function il(e){return al(await e.getHead(Zc),e)}async function al(e,t){return e?nl((await t.getChunk(e))?.data):new Map}var ol=class extends Error{name=`ClientStateNotFoundError`;id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function sl(e,t){if(!await cl(e,t))throw new ol(e)}async function cl(e,t){return!!await ll(e,t)}async function ll(e,t){return(await il(t)).get(e)}async function ul(e,t){let n=await ll(e,t);if(!n)throw new ol(e);return n}function dl(e,t,n,r,i,a,o){return Uc(n,async n=>{async function s(t,a,o,s){let l=eo(t,{},a,o,s),u=n.createChunk(l,io(l)),d=Gc(),f={heartbeatTimestampMs:Date.now(),refreshHashes:[u.hash],persistHash:null,clientGroupID:d},p=new Map(c).set(e,f),m={headHash:u.hash,mutatorNames:r,indexes:i,mutationIDs:{},lastServerAckdMutationIDs:{},disabled:!1};return await Promise.all([n.putChunk(u),xl(p,n),Pc(d,m,n)]),await n.commit(),[f,u.hash,p,!0]}let c=await il(n),l=await gl(n,r,i);if(l.type===hl){let{clientGroupID:t,headHash:r}=l,i={clientGroupID:t,refreshHashes:[r],heartbeatTimestampMs:Date.now(),persistHash:null},a=new Map(c).set(e,i);return await xl(a,n),await n.commit(),[i,r,a,!1]}if(!o||l.type===pl){let e=n.createChunk(Ro,[]);await n.putChunk(e);let t=[];for(let[n,r]of Object.entries(i)){let i=Ka(n,r);t.push({definition:i,valueHash:e.hash})}return s(null,null,e.hash,t)}A(l.type===ml);let{snapshot:u}=l,d=[],{valueHash:f,indexes:p}=u,m=new Xo(n,a,f);for(let[e,r]of Object.entries(i)){let{prefix:i=``,jsonPointer:o,allowEmpty:s=!1}=r,c={name:e,keyPrefix:i,jsonPointer:o,allowEmpty:s},l=fl(p,c);if(l)d.push({definition:c,valueHash:l.valueHash});else{let e=await Qs(t,n,m,i,o,s,a);d.push({definition:c,valueHash:await e.flush()})}}return s(u.meta.basisHash,u.meta.cookieJSON,u.valueHash,d)})}function fl(e,t){return e.find(e=>Wa(e.definition,t))}var pl=0,ml=1,hl=2;async function gl(e,t,n){let r,i,a=new Set(t),o=await Mc(e);for(let[t,s]of o){if(!s.disabled&&Lc(a,s.mutatorNames)&&Tc(n,s.indexes))return{type:hl,clientGroupID:t,headHash:s.headHash};let o=await Ta(s.headHash,e);Ba(o);let{cookieJSON:c}=o.meta;(r===void 0||ti(c,r)>0)&&(r=c,i=o)}return i?{type:ml,snapshot:i}:{type:pl}}function _l(e){let t=new Set;for(let n of e.values())if(Yc(n)){for(let e of n.refreshHashes)t.add(e);n.persistHash&&t.add(n.persistHash)}else t.add(n.headHash),Xc(n)&&n.tempRefreshHash&&t.add(n.tempRefreshHash);return wi(t)}async function vl(e,t){let n=await yl(e,t);if(n)return Rc(n,t)}async function yl(e,t){let n=await ll(e,t);if(!(!n||!Xc(n)))return n.clientGroupID}async function bl(e,t,n){let r=await il(n);return xl(new Map(r).set(e,t),n)}async function xl(e,t){let n=rl(e,t),r=t.createChunk(n,_l(e));return await t.putChunk(r),await t.setHead(Zc,r.hash),r.hash}var Sl=typeof navigator<`u`?navigator:void 0,Cl=Symbol(),wl=class{r=new Map;#e;constructor(e){this.#e=e}has(e){switch(this.r.get(e)){case void 0:return this.#e.has(e);case Cl:return oi;default:return ai}}async get(e){let t=this.r.get(e);switch(t){case Cl:return;case void 0:return Ci(await this.#e.get(e));default:return t}}put(e,t){return this.r.set(e,_i(t)),si}del(e){return this.r.set(e,Cl),si}release(){this.#e.release()}get closed(){return this.#e.closed}},Tl={durability:`relaxed`},El=`chunks`,Dl=class{#e;#t=!1;#n=!1;constructor(e){this.#e=Nl(e)}read(){return this.#r(jl)}write(){return this.#r(Al)}async close(){this.#n||(await this.#e).close(),this.#t=!0}get closed(){return this.#t}async#r(e){let t=async e=>{let{promise:t,resolve:n,reject:r}=O(),i=indexedDB.open(e);i.onupgradeneeded=()=>{let t=i.transaction;yr(t),t.abort(),this.#n=!0,r(new Pl(`Replicache IndexedDB not found: ${e}`))},i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error);let a=await t;return a.onversionchange=()=>a.close(),a},n=await this.#e;try{return e(n)}catch(r){if(!this.#t&&r instanceof DOMException){if(r.name===`InvalidStateError`)return this.#e=t(n.name),e(await this.#e);if(r.name===`NotFoundError`)throw this.#n=!0,indexedDB.deleteDatabase(n.name),new Pl(`Replicache IndexedDB ${n.name} missing object store. Deleting db.`)}throw r}}},Ol=class{#e;#t=!1;constructor(e){this.#e=e}has(e){return new Promise((t,n)=>{let r=Ml(this.#e).count(e);r.onsuccess=()=>t(r.result>0),r.onerror=()=>n(r.error)})}get(e){return new Promise((t,n)=>{let r=Ml(this.#e).get(e);r.onsuccess=()=>t(Ci(r.result)),r.onerror=()=>n(r.error)})}release(){this.#t=!0}get closed(){return this.#t}},kl=class extends wl{#e;#t=!1;constructor(e){super(new Ol(e)),this.#e=e}commit(){return this.r.size===0?si:new Promise((e,t)=>{let n=this.#e,r=Ml(n);for(let[e,t]of this.r)t===Cl?r.delete(e):r.put(t,e);n.oncomplete=()=>e(),n.onerror=()=>t(n.error)})}release(){this.#t=!0}get closed(){return this.#t}};function Al(e){return new kl(e.transaction(El,`readwrite`,Tl))}function jl(e){return new Ol(e.transaction(El,`readonly`))}function Ml(e){return e.objectStore(El)}function Nl(e){return new Promise((t,n)=>{let r=indexedDB.open(e);r.onupgradeneeded=()=>{r.result.createObjectStore(El)},r.onsuccess=()=>{let e=r.result;e.onversionchange=()=>e.close(),t(e)},r.onerror=()=>n(r.error)})}var Pl=class extends Error{name=`IDBNotFoundError`},Fl=class{#e;#t;#n=!1;constructor(e,t){this.#e=e,this.#t=t}release(){this.#t(),this.#n=!0}get closed(){return this.#n}has(e){return Promise.resolve(this.#e.has(e))}get(e){return Promise.resolve(this.#e.get(e))}},Il=class extends wl{#e;constructor(e,t){super(new Fl(e,t)),this.#e=e}commit(){return this.r.forEach((e,t)=>{e===Cl?this.#e.delete(t):this.#e.set(t,e)}),this.r.clear(),this.release(),si}},Ll=new Map;function Rl(e){return Ll.delete(e),si}var zl=class{#e;#t;#n=!1;constructor(e){let t=Ll.get(e),n,r;t?{lock:n,map:r}=t:(n=new Yt,r=new Map,Ll.set(e,{lock:n,map:r})),this.#t=n,this.#e=r}async read(){let e=await this.#t.read();return new Fl(this.#e,e)}async write(){let e=await this.#t.write();return new Il(this.#e,e)}close(){return this.#n=!0,si}get closed(){return this.#n}},Bl=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=new Dl(t)}read(){return this.#r(e=>e.read())}write(){return this.#r(e=>e.write())}async#r(e){try{return await e(this.#n)}catch(t){if(Vl(t))return this.#n instanceof Dl&&(this.#e.info?.(`Switching to MemStore because of Firefox private browsing error`),this.#n=new zl(this.#t)),e(this.#n);throw t}}close(){return this.#n.close()}get closed(){return this.#n.closed}};function Vl(e){return Hl()&&e instanceof DOMException&&e.name===`InvalidStateError`&&e.message===`A mutation operation was attempted on a database that did not allow mutations.`}function Hl(){return Sl?.userAgent.includes(`Firefox`)??!1}function Ul(e,t){return Hl()?new Bl(e,t):new Dl(t)}function Wl(e){if(!Hl())return Gl(e);try{return Gl(e)}catch(t){if(Vl(t))return Rl(e)}return si}function Gl(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}var Kl=e=>new yf(e),ql=401;function Jl(e,t){return Yl(e,t,7)}function Yl(e,t,n){let r=`rep:${e}:${n}`;return t?`${r}:${t}`:r}var Xl=class{#e;constructor(e){this.#e=Kl(e)}get pullURL(){return this.#e.pullURL}set pullURL(e){this.#e.pullURL=e}get pushURL(){return this.#e.pushURL}set pushURL(e){this.#e.pushURL=e}get auth(){return this.#e.auth}set auth(e){this.#e.auth=e}get name(){return this.#e.name}get idbName(){return Jl(this.name,this.schemaVersion)}get schemaVersion(){return this.#e.schemaVersion}get mutate(){return this.#e.mutate}get pullInterval(){return this.#e.pullInterval}set pullInterval(e){this.#e.pullInterval=e}get pushDelay(){return this.#e.pushDelay}set pushDelay(e){this.#e.pushDelay=e}get puller(){return this.#e.puller}set puller(e){this.#e.puller=e}get pusher(){return this.#e.pusher}set pusher(e){this.#e.pusher=e}get requestOptions(){return this.#e.requestOptions}get onSync(){return this.#e.onSync}set onSync(e){this.#e.onSync=e}get onClientStateNotFound(){return this.#e.onClientStateNotFound}set onClientStateNotFound(e){this.#e.onClientStateNotFound=e}get onUpdateNeeded(){return this.#e.onUpdateNeeded}set onUpdateNeeded(e){this.#e.onUpdateNeeded=e}get getAuth(){return this.#e.getAuth}set getAuth(e){this.#e.getAuth=e}get profileID(){return this.#e.profileID}get clientID(){return this.#e.clientID}get clientGroupID(){return this.#e.clientGroupID}get onOnlineChange(){return this.#e.onOnlineChange}set onOnlineChange(e){this.#e.onOnlineChange=e}get online(){return this.#e.online}get closed(){return this.#e.closed}close(){return this.#e.close()}push({now:e=!1}={}){return this.#e.push({now:e})}pull({now:e=!1}={}){return this.#e.pull({now:e})}poke(e){return this.#e.poke(e)}subscribe(e,t){return this.#e.subscribe(e,t)}experimentalWatch(e,t){return this.#e.experimentalWatch(e,t)}query(e){return this.#e.query(e)}experimentalPendingMutations(){return this.#e.experimentalPendingMutations()}},Zl=class extends Error{};function Ql(e){return new zl(e)}function $l(e,t){switch(t){case`idb`:case void 0:return{create:t=>Ul(e,t),drop:Wl};case`mem`:return{create:Ql,drop:e=>Rl(e)};default:return t}}function eu(e){return e instanceof Error?e:Error(String(e))}async function tu(e,t,n){for(let r of n)switch(r.op){case`put`:await t.put(e,r.key,_i(r.value));break;case`update`:{let n=await t.get(r.key),i=[],a=e=>{for(let[t,n]of Object.entries(e))(!r.constrain||r.constrain.length===0||r.constrain.indexOf(t)>-1)&&i.push([t,n])};n!==void 0&&(N(n),a(n)),r.merge&&a(r.merge),await t.put(e,r.key,_i(Object.fromEntries(i)));break}case`del`:await t.del(e,r.key);break;case`clear`:await t.clear();break}}var nu=class extends Error{name=`PullError`;causedBy;constructor(e){super(`Failed to pull`),this.causedBy=e}},ru=`sync`,iu=0,au=1;function ou(e){return e.pullVersion===au}async function su(e,t,n,r,i,a,o,s,c=!0){let[l,u]=await R(a,async e=>{let n=await e.getHead(I);if(!n)throw Error(`Internal no main head found`);let r=await Ta(n,e),i=r.meta.cookieJSON;return[await r.getMutationID(t,e),i]}),{response:d,httpRequestInfo:f}=await lu(s,r,{profileID:e,clientID:t,cookie:u,lastMutationID:l,pullVersion:iu,schemaVersion:n},i);if(!d)return{httpRequestInfo:f,syncHead:F};if(!c||rc(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await uu(s,a,u,d,t,o);if(p.type===2)throw Error(`Overlapping sync`);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:F}}async function cu(e,t,n,r,i,a,o,s,c,l=!0){let u=await R(o,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta;return Ra(n),n.cookieJSON}),{response:d,httpRequestInfo:f}=await lu(c,i,{profileID:e,clientGroupID:n,cookie:u,pullVersion:au,schemaVersion:r},a);if(!d)return{httpRequestInfo:f,syncHead:F};if(!l||rc(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await fu(c,o,u,d,t,s);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:F}}async function lu(e,t,n,r){e.debug?.(`Starting pull...`);let i=Date.now(),a;try{a=await t(n,r),e.debug?.(`...Pull ${a.response?`complete`:`failed`} in `,Date.now()-i,`ms`)}catch(e){throw new nu(eu(e))}try{return ou(n)?_c(a):vc(a),a}catch(e){throw new Zl(`Invalid puller result`,eu(e))}}function uu(e,t,n,r,i,a){return Uc(t,async t=>{A(a<=4);let o=t,s=await o.getHead(I);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),[l,u]=Da(c,i);if(!Gr(n,u))return{type:2};if(r.lastMutationID<l)throw Error(du(`lastMutationID`,String(r.lastMutationID),String(l)));let d=_i(r.cookie??null);if(Gr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),r.lastMutationID!==l&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationID did change`),{type:1};let f=await ka(s,o),p;for(let e of f)if(await e.getMutationID(i,o)<=r.lastMutationID){p=e;break}if(!p)throw Error(`Internal invalid chain`);let m=await Js(c.chunk.hash,r.lastMutationID,d,t,Zs(p,t,a),i,a);await tu(e,m,r.patch);let h=new Xo(o,a,p.valueHash);for await(let t of m.map.diff(h))await Xs(e,m.indexes,t.key,()=>Promise.resolve(t.oldValue),t.newValue);return{type:0,syncHead:await m.commit(ru)}})}function du(e,t,n){return`Received ${e} ${t} is < than last snapshot ${e} ${n}; ignoring client view`}function fu(e,t,n,r,i,a){return Uc(t,async t=>{let o=t,s=await o.getHead(I);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),l=c.meta;Ra(l);let u=l.cookieJSON;if(!Gr(n,u))return e.debug?.(`handlePullResponse: cookie mismatch, response is not applicable`),{type:2};for(let[e,t]of Object.entries(r.lastMutationIDChanges)){let n=l.lastMutationIDs[e];if(n!==void 0&&t<n)throw Error(du(`${e} lastMutationID`,String(t),String(n)))}let d=_i(r.cookie);if(ti(d,u)<0)throw Error(du(`cookie`,JSON.stringify(d),JSON.stringify(u)));if(Gr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),Object.keys(r.lastMutationIDChanges).length>0&&(console.log(r.lastMutationIDChanges),e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationIDChanges is not empty`)),{type:1};let f=await Ys(c.chunk.hash,{...l.lastMutationIDs,...r.lastMutationIDChanges},d,t,i,a);return await tu(e,f,r.patch),{type:0,syncHead:await f.commit(ru)}})}function pu(e,t,n,r,i,a){return Uc(e,async e=>{let o=e,s=await o.getHead(ru);if(s===void 0)throw Error(`Missing sync head`);if(s!==n)throw t.error?.(`maybeEndPull, Wrong sync head. Expecting:`,n,`got:`,s),Error(`Wrong sync head`);let c=await Ta(s,o),l=await o.getHead(I);if(l===void 0)throw Error(`Missing main head`);let u=await Ta(l,o),{meta:d}=c,f=d.basisHash;if(c===null)throw Error(`Sync snapshot with no basis`);if(f!==u.chunk.hash)throw Error(`Overlapping syncs`);let p=await L(s,o),m=[],h=await ba(l,o);for(let e of h){let t=r;pa(e)&&(t=e.meta.clientID),await e.getMutationID(t,o)>await p.getMutationID(t,o)&&m.push(e)}m.reverse();let g=new Us;if(m.length>0)return{syncHead:s,replayMutations:m,diffs:g};let _=await L(l,o);if(i.shouldComputeDiffs()){let e=await zs(new Xo(o,a,_.valueHash),new Xo(o,a,p.valueHash));g.set(``,e),await Gs(_,p,o,g,i,a)}if(await Promise.all([e.setHead(I,s),e.removeHead(ru)]),await e.commit(),t.debug){let[e,n]=Da(u,r),[i,a]=Da(c,r);t.debug(`Successfully pulled new snapshot with lastMutationID:`,i,`(prev:`,e,`), cookie: `,a,`(prev:`,n,`), sync head hash:`,s,`, main head hash:`,l,`, valueHash:`,p.valueHash,`(prev:`,u.valueHash)}return{syncHead:s,replayMutations:[],diffs:g}})}var mu=[],hu=P.unknown().chain(e=>{if(Hr)return ln(e);let t=Xr(e,mu)?ln(e):un({message:`Not a JSON value`,path:mu.slice()});return mu.length=0,t});P.unknown().chain(e=>{if(Hr)return ln(e);let t=Zr(e,mu)?ln(e):un({message:`Not a JSON object`,path:mu.slice()});return mu.length=0,t});function gu(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&_u(e.response)}function _u(e){ic(e)||oc(e)}var vu=class extends Error{name=`PushError`;causedBy;constructor(e){super(`Failed to push`),this.causedBy=e}},yu=0,bu=1,xu=zi({id:P.number(),name:P.string(),args:hu,timestamp:P.number()}),Su=zi({id:P.number(),name:P.string(),args:hu,timestamp:P.number(),clientID:Hc});P.object({pushVersion:P.literal(0),schemaVersion:P.string(),profileID:P.string(),clientID:Hc,mutations:P.array(xu)}),P.object({pushVersion:P.literal(1),schemaVersion:P.string(),profileID:P.string(),clientGroupID:Vc,mutations:P.array(Su)});function Cu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp}}function wu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp,clientID:e.clientID}}async function Tu(e,t,n,r,i,a,o,s,c){let l=await R(t,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head`);return ba(t,e)});if(l.length===0)return;l.reverse();let u;if(c===bu){let e=[];for(let t of l)if(pa(t))e.push(wu(t.meta));else throw Error(`Internal non local pending commit`);A(i),u={profileID:r,clientGroupID:i,mutations:e,pushVersion:bu,schemaVersion:s}}else{A(c===yu);let e=[];for(let t of l)if(fa(t))e.push(Cu(t.meta));else throw Error(`Internal non local pending commit`);u={profileID:r,clientID:a,mutations:e,pushVersion:yu,schemaVersion:s}}n.debug?.(`Starting push...`);let d=Date.now(),f=await Eu(o,u,e);return n.debug?.(`...Push complete in `,Date.now()-d,`ms`),f}async function Eu(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new vu(eu(e))}try{return gu(r),r}catch(e){throw new Zl(`Invalid pusher result`,eu(e))}}var Du=10*2**20,Ou=class{#e=!1;#t;constructor(e){this.#t=e}async recoverMutations(e,t,n,r,i,a){let{lc:o,enableMutationRecovery:s,isPushDisabled:c,delegate:l}=this.#t;if(!s||this.#e||!l.online||l.closed||c())return!1;let u=`Recovering mutations.`;o.debug?.(`Start:`,u);try{this.#e=!0,await t,await Mu(r,this.#t,n,e);for(let e of Object.values(await i.getDatabases())){if(l.closed)return o.debug?.(`Exiting early due to close:`,u),!0;if(e.replicacheName===l.name&&e.name!==l.idbName)switch(e.replicacheFormatVersion){case 4:case 5:case 6:case 7:await ju(e,this.#t,void 0,a)}}}catch(e){ku(e,o,u,l)}finally{o.debug?.(`End:`,u),this.#e=!1}return!0}};function ku(e,t,n,r){r.closed?t.debug?.(`Mutation recovery error likely due to close during:
|
|
1
|
+
import{z as e}from"zod";import{errorBoundary as t,errorListBoundary as n}from"@stayradiated/error-boundary";import{z as r}from"zod/mini";import{getContext as i,mount as a,onDestroy as o,onMount as s,tick as c,unmount as l}from"svelte";import"svelte/internal/disclose-version";import"svelte/internal/flags/async";import*as u from"svelte/internal/client";import{SvelteMap as d,SvelteSet as f}from"svelte/reactivity";import{newMessagePortRpcSession as p}from"capnweb";import"@andypf/json-viewer";var m=Object.create,h=Object.defineProperty,g=Object.getOwnPropertyDescriptor,_=Object.getOwnPropertyNames,v=Object.getPrototypeOf,y=Object.prototype.hasOwnProperty,b=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),x=(e,t)=>{let n={};for(var r in e)h(n,r,{get:e[r],enumerable:!0});return t||h(n,Symbol.toStringTag,{value:`Module`}),n},S=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=_(t),a=0,o=i.length,s;a<o;a++)s=i[a],!y.call(e,s)&&s!==n&&h(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=g(t,s))||r.enumerable});return e},C=(e,t,n)=>(n=e==null?{}:m(v(e)),S(t||!e||!e.__esModule||!y.call(e,`default`)?h(n,`default`,{value:e,enumerable:!0}):n,e)),ee=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,t=>e.call(t)];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup(),i=await e.subscribe(r,t);return async()=>{i(),r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),w=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,async t=>e.outputSample];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup();return r(e.outputSample),async()=>{r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),te=e=>({type:e.type,id:e.id,name:e.name,description:e.description,inputSchema:e.inputSchema.toJSONSchema(),outputSchema:e.outputSchema.toJSONSchema(),outputSample:e.outputSample}),ne=class t{type=`mutation`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return te(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},re=class t{type=`query`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return te(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},ie=class t{type=`subscription`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return te(this)}async subscribe(t,n){let r=this.inputSchema.safeParse(n);if(!r.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(r.error)}`);return await this.implementation(n=>{let r=this.outputSchema.safeParse(n);if(!r.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(r.error)}`);t(r.data)},r.data)}},T=e=>{let t=new URL(e.path,e.baseUrl);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,String(r));return t.toString()},ae=async e=>{let{replicache:n,projectId:r,signal:i}=e;return i?.aborted?Error(`Ping project aborted`):t(async()=>{await n.mutate.project_ping_v1({projectPublicId:r,context:{actionedAt:Date.now()}}),await n.push({now:!0})})},E=`/`,D=e=>{let t=`${e}${E}`,n=t.length;return()=>({name:e,value:t=>({name:e,idA:t,idB:void 0}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:e=>`${t}${e}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n)},decodeWithoutPrefix:e=>e})},O=e=>{let t=`${e}${E}`,n=t.length;return()=>({name:e,value:(t,n)=>({name:e,idA:t,idB:n}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}${E}`;case 2:return`${t}${e[0]}${E}${e[1]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:(e,n)=>`${t}${e}${E}${n}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n).split(E)},decodeWithoutPrefix:e=>e.split(E)})},k={internal:D(`__internal`)(),apiToken:D(`apiToken`)(),asset:D(`asset`)(),backlogTask:D(`backlogTask`)(),block:D(`block`)(),comment:D(`comment`)(),commentThread:D(`commentThread`)(),content:D(`content`)(),document:D(`document`)(),draftContent:D(`draftContent`)(),event:D(`event`)(),filter:D(`filter`)(),filterRule:D(`filterRule`)(),fizzyAccount:D(`fizzyAccount`)(),fizzyBoard:D(`fizzyBoard`)(),fizzyIntegration:D(`fizzyIntegration`)(),invitation:D(`invitation`)(),inviteLink:D(`inviteLink`)(),label:D(`label`)(),llmModel:D(`llmModel`)(),llmModelDefault:D(`llmModelDefault`)(),llmProvider:D(`llmProvider`)(),note:D(`note`)(),notification:D(`notification`)(),person:D(`person`)(),project:D(`project`)(),projectAccount:D(`projectAccount`)(),reaction:D(`reaction`)(),reference:D(`reference`)(),sequence:D(`sequence`)(),signingKey:D(`signingKey`)(),sprite:D(`sprite`)(),spriteBuild:D(`spriteBuild`)(),spriteBuildEvent:D(`spriteBuildEvent`)(),surface:D(`surface`)(),task:D(`task`)(),vcsBranch:D(`vcsBranch`)(),vcsCommit:D(`vcsCommit`)(),vcsIntegration:D(`vcsIntegration`)(),vcsRepo:D(`vcsRepo`)(),vcsUser:D(`vcsUser`)(),watch:D(`watch`)(),workspace:D(`workspace`)(),blockUser:O(`blockUser`)(),documentUser:O(`documentUser`)(),sequenceDocument:O(`sequenceDocument`)(),signingKeyProject:O(`signingKeyProject`)(),vcsCommitDocument:O(`vcsCommitDocument`)(),noteLabel:O(`noteLabel`)(),spriteProjectAccount:O(`spriteProjectAccount`)(),taskLabel:O(`taskLabel`)(),relatedDocumentNote:O(`relatedDocumentNote`)(),relatedDocumentPair:O(`relatedDocumentPair`)(),relatedNotePair:O(`relatedNotePair`)(),relatedSpritePair:O(`relatedSpritePair`)(),stackTask:O(`stackTask`)(),workspaceUser:D(`workspaceUser`)()},oe=(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e]?.push(r):Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:[r],writable:!0})}return n},A=class{#e=0;#t=new Map;#n=new Map;#r;#i;#a;constructor(e){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge==`number`&&e.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#r=e.maxSize,this.#i=e.maxAge??1/0,this.#a=e.onEviction,Object.defineProperty(this,Symbol.for(`nodejs.util.inspect.custom`),{value:()=>this.toString()})}get __oldCache(){return this.#n}#o(e){if(typeof this.#a==`function`)for(let[t,n]of e)this.#a(t,n.value)}#s(e,t){return typeof t.expiry==`number`&&t.expiry<=Date.now()&&(this.#a?.(e,t.value),this.delete(e))}#c(e,t){if(!this.#s(e,t))return t.value}#l(e,t){if(t)return t.expiry?this.#c(e,t):t.value}#u(e,t){return this.#l(e,t.get(e))}#d(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#r&&(this.#e=0,this.#o(this.#n),this.#n=this.#t,this.#t=new Map)}#f(e,t){this.#n.delete(e),this.#d(e,t)}*#p(){for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t]);for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t])}get(e){if(this.#t.has(e))return this.#l(e,this.#t.get(e));if(this.#n.has(e)){let t=this.#n.get(e);if(t&&!this.#s(e,t))return this.#f(e,t),t.value}}set(e,t,{maxAge:n=this.#i}={}){let r={value:t,expiry:typeof n==`number`&&n!==1/0?Date.now()+n:void 0};return this.#t.has(e)?this.#t.set(e,r):this.#d(e,r),this}has(e){if(this.#t.has(e)){let t=this.#t.get(e);return t?!this.#s(e,t):!1}if(this.#n.has(e)){let t=this.#n.get(e);return t?!this.#s(e,t):!1}return!1}peek(e){if(this.#t.has(e))return this.#u(e,this.#t);if(this.#n.has(e))return this.#u(e,this.#n)}expiresIn(e){let t=this.#t.get(e)??this.#n.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#n.delete(e)||t}clear(){this.#t.clear(),this.#n.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw TypeError("`maxSize` must be a number greater than 0");let t=[...this.#p()],n=t.length-e;n<0?(this.#t=new Map(t),this.#n=new Map,this.#e=t.length):(n>0&&this.#o(t.slice(0,n)),this.#n=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#r=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#p()],r=Math.trunc(Math.min(t,Math.max(n.length-1,0)));r<=0||(this.#o(n.slice(0,r)),this.#n=new Map(n.slice(r)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t.value]);for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t.value])}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;this.#s(r,i)||(yield[r,i.value])}e=[...this.#n];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;!this.#t.has(r)&&!this.#s(r,i)&&(yield[r,i.value])}}*entriesAscending(){for(let[e,t]of this.#p())yield[e,t.value]}get size(){if(!this.#e)return this.#n.size;let e=0;for(let t of this.#n.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#r)}get maxSize(){return this.#r}get maxAge(){return this.#i}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,r]of this.entriesAscending())e.call(t,r,n,this)}get[Symbol.toStringTag](){return`QuickLRU`}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}},se=class{arraySize=0;array=Array(8);set=null;get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw Error(`no set or array`)}add(e){if(this.array)return this.array.indexOf(e)===-1?this.arraySize<8?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0):!1;if(this.set)return!this.set.has(e)&&(this.set.add(e),!0);throw Error(`no set or array`)}remove(e){if(this.array){let t=this.array.indexOf(e);return t!==-1&&(this.array[t]=void 0,this.arraySize--,t!==this.arraySize&&(this.array[t]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw Error(`no set or array`)}visit(e){if(this.array){for(let t=0;t<this.arraySize;t++){let n=this.array[t];n!==void 0&&e(n)}return}if(this.set){this.set.forEach(e);return}throw Error(`no set or array`)}};function ce(e){return e&&typeof e==`object`&&`parents`in e}function le(e){for(let t=0,n=e.parents.length;t<n;t++)if(e.parents[t].__unsafe__getWithoutCapture(),e.parents[t].lastChangedEpoch!==e.parentEpochs[t])return!0;return!1}var j=(e,t)=>{if(e.children.remove(t)&&e.children.isEmpty&&ce(e))for(let t=0,n=e.parents.length;t<n;t++)j(e.parents[t],e)},ue=(e,t)=>{if(e.children.add(t)&&ce(e))for(let t=0,n=e.parents.length;t<n;t++)ue(e.parents[t],e)};function de(e,t){return e===t||Object.is(e,t)||!!(e&&t&&typeof e.equals==`function`&&e.equals(t))}var fe=Object.freeze([]),pe=Symbol.for(`__signia__`),me=globalThis;me[pe]?console.error(`Multiple versions of signia detected. This will cause unexpected behavior. Please add "resolutions" (yarn/pnpm) or "overrides" (npm) in your package.json to ensure only one version of signia is loaded.`):me[pe]=!0;var he=class{constructor(e,t){this.below=e,this.child=t}offset=0;numNewParents=0;maybeRemoved},M=null;function ge(e){M=new he(M,e)}function _e(){let e=M;if(M=e.below,e.numNewParents>0||e.offset!==e.child.parents.length){for(let t=e.offset;t<e.child.parents.length;t++){let n=e.child.parents[t];e.child.parents.indexOf(n)>=e.offset&&j(n,e.child)}if(e.child.parents.length=e.offset,e.child.parentEpochs.length=e.offset,M?.maybeRemoved)for(let t=0;t<M.maybeRemoved.length;t++){let n=M.maybeRemoved[t];e.child.parents.indexOf(n)===-1&&j(n,e.child)}}}function ve(e){if(M){let t=M.child.parents.indexOf(e);if(t<0&&(M.numNewParents++,M.child.isActivelyListening&&ue(e,M.child)),t<0||t>=M.offset){if(t!==M.offset&&t>0){let e=M.child.parents[M.offset];M.maybeRemoved?M.maybeRemoved.indexOf(e)===-1&&M.maybeRemoved.push(e):M.maybeRemoved=[e]}M.child.parents[M.offset]=e,M.child.parentEpochs[M.offset]=e.lastChangedEpoch,M.offset++}}}var ye=Symbol(`RESET_VALUE`),be=class{constructor(e){this.capacity=e,this.buffer=Array(e)}index=0;buffer;pushEntry(e,t,n){if(n!==void 0){if(n===ye){this.clear();return}this.buffer[this.index]=[e,t,n],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){let{index:t,capacity:n,buffer:r}=this;for(let i=0;i<n;i++){let a=(t-1+n-i)%n,o=r[a];if(!o)return ye;let[s,c]=o;if(i===0&&e>=c)return[];if(s<=e&&e<c){let e=i+1,t=Array(e);for(let i=0;i<e;i++)t[i]=r[(a+i)%n][2];return t}}return ye}},xe=0,Se=!1;function Ce(){xe++}function we(e){if(Se)throw Error(`cannot change atoms during reaction cycle`);try{Se=!0;let t=new Set,n=e=>{e.lastTraversedEpoch!==xe&&(e.lastTraversedEpoch=xe,`maybeScheduleEffect`in e?t.add(e):e.children.visit(n))};for(let t of e)t.children.visit(n);for(let e of t)e.maybeScheduleEffect()}finally{Se=!1}}function Te(e,t){Ee?Ee.initialAtomValues.has(e)||Ee.initialAtomValues.set(e,t):we([e])}var Ee=null,De=class{constructor(e,t,n){this.name=e,this.current=t,this.isEqual=n?.isEqual??null,n&&(n.historyLength&&(this.historyBuffer=new be(n.historyLength)),this.computeDiff=n.computeDiff)}isEqual;computeDiff;lastChangedEpoch=xe;children=new se;historyBuffer;__unsafe__getWithoutCapture(){return this.current}get value(){return ve(this),this.current}set(e,t){if(this.isEqual?.(this.current,e)??de(this.current,e))return this.current;Ce(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,xe,t??this.computeDiff?.(this.current,e,this.lastChangedEpoch,xe)??ye),this.lastChangedEpoch=xe;let n=this.current;return this.current=e,Te(this,n),e}update(e){return this.set(e(this.current))}getDiffSince(e){return ve(this),e>=this.lastChangedEpoch?fe:this.historyBuffer?.getChangesSince(e)??ye}};function Oe(e,t,n){return new De(e,t,n)}var ke=Symbol(`UNINITIALIZED`),Ae=e=>e===ke,je=class{constructor(e,t){this.value=e,this.diff=t}},Me=class{constructor(e,t,n){this.name=e,this.derive=t,n?.historyLength&&(this.historyBuffer=new be(n.historyLength)),this.computeDiff=n?.computeDiff,this.isEqual=n?.isEqual??de}lastChangedEpoch=-1;lastTraversedEpoch=-1;lastCheckedEpoch=-1;parents=[];parentEpochs=[];children=new se;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=ke;computeDiff;isEqual;__unsafe__getWithoutCapture(){let e=this.lastChangedEpoch===-1;if(!e&&(this.lastCheckedEpoch===xe||!le(this)))return this.lastCheckedEpoch=xe,this.state;try{ge(this);let t=this.derive(this.state,this.lastCheckedEpoch),n=t instanceof je?t.value:t;if(this.state===ke||!this.isEqual(n,this.state)){if(this.historyBuffer&&!e){let e=t instanceof je?t.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,xe,e??this.computeDiff?.(this.state,n,this.lastCheckedEpoch,xe)??ye)}this.lastChangedEpoch=xe,this.state=n}return this.lastCheckedEpoch=xe,this.state}finally{_e()}}get value(){let e=this.__unsafe__getWithoutCapture();return ve(this),e}getDiffSince(e){return this.value,e>=this.lastChangedEpoch?fe:this.historyBuffer?.getChangesSince(e)??ye}};function Ne(e={},t,n,r){let i=r.get,a=Symbol.for(`__signia__computed__`+n);return r.get=function(){let t=this[a];return t||(t=new Me(n,i.bind(this),e),Object.defineProperty(this,a,{enumerable:!1,configurable:!1,writable:!1,value:t})),t.value},r}function Pe(){if(arguments.length===1){let e=arguments[0];return(t,n,r)=>Ne(e,t,n,r)}return typeof arguments[0]==`string`?new Me(arguments[0],arguments[1],arguments[2]):Ne(void 0,arguments[0],arguments[1],arguments[2])}var Fe=class{constructor(e,t,n){this.name=e,this.runEffect=t,this._scheduleEffect=n?.scheduleEffect}_isActivelyListening=!1;get isActivelyListening(){return this._isActivelyListening}lastTraversedEpoch=-1;lastReactedEpoch=-1;_scheduleCount=0;get scheduleCount(){return this._scheduleCount}parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==xe){if(this.parents.length&&!le(this)){this.lastReactedEpoch=xe;return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}maybeExecute=()=>{this._isActivelyListening&&this.execute()};attach(){this._isActivelyListening=!0;for(let e=0,t=this.parents.length;e<t;e++)ue(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)j(this.parents[e],this)}execute(){try{ge(this);let e=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=xe,e}finally{_e()}}};function Ie(e,t,n){let r=new Fe(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}var Le=e=>{let{diffList:t,source:n,mapKey:r,mapValue:i}=e;if(t.length===0)return;let a={...n.__unsafe__getWithoutCapture()},o=[];for(let e of t)switch(e.op){case`add`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`add`,key:t,value:n});break}case`change`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`replace`,key:t,value:n});break}case`del`:{let t=r(e.key);delete a[t],o.push({op:`remove`,key:t});break}default:throw Error(`Unhandled diff op: ${JSON.stringify(e)}`)}n.set(a,o)},Re=e=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];for(let e=i.length-1;e>=0;e--){let r=i[e];t.has(r.key)||(t.add(r.key),n.push(r))}}return n.reverse(),n},ze=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))t(i)&&(r[n]=i);return Object.values(r)};return Pe(`${e.name}:filter`,(n,a)=>{if(Ae(n))return i();let o=e.getDiffSince(a);if(o===ye)return i();let s=Re(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:t(e.value)&&(r[e.key]=e.value);break;case`remove`:delete r[e.key];break;case`replace`:t(e.value)?r[e.key]=e.value:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Be=(e,t,n)=>{let r=new Set,i,a=()=>{r.clear(),i=void 0;let n=!1,a;for(let[o,s]of Object.entries(e.value))n?r.add(o):t(s)&&(n=!0,a=s,i=o);return a},o=()=>{for(let n of r){r.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return i=n,a}i=void 0};return Pe(`${e.name}:find`,(n,s)=>{if(Ae(n))return a();let c=e.getDiffSince(s);if(c===ye)return a();let l=Re(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:i===void 0?t(e.value)&&(i=e.key):r.add(e.key);break;case`remove`:e.key===i?o():r.delete(e.key);break;case`replace`:e.key===i||i===void 0?t(e.value)?i=e.key:o():r.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return i===void 0?void 0:e.value[i]},{...n})},Ve=(e,t,n)=>Pe(`${e.name}:get`,()=>e.value[t],{...n}),He=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))r[n]=t(i);return Object.values(r)};return Pe(`${e.name}:map`,(n,a)=>{if(Ae(n))return i();let o=e.getDiffSince(a);if(o===ye)return i();let s=Re(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.value);break;case`replace`:r[e.key]=t(e.value);break;case`remove`:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Ue=(e,t,n)=>{let r={},i=()=>{r={};for(let n of Object.keys(e.value)){let e=t(n);r[n]=e}return Object.values(r)};return Pe(`${e.name}:keys`,(n,a)=>{if(Ae(n))return i();let o=e.getDiffSince(a);if(o===ye)return i();let s=Re(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.key);break;case`remove`:delete r[e.key];break;case`replace`:e.key in r||(r[e.key]=t(e.key));break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},We=(e,t)=>Pe(`${e.name}:values`,()=>Object.values(e.value),{...t}),Ge=(e,t,n)=>{let r=new Set,i=new Set,a=()=>{r.clear(),i.clear();let n=!1;for(let[a,o]of Object.entries(e.value))n?i.add(a):t(o)&&(r.add(a),n=!0);return n},o=()=>{for(let n of i){i.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return r.add(n),!0}return!1};return Pe(`${e.name}:some`,(n,s)=>{if(Ae(n))return a();let c=e.getDiffSince(s);if(c===ye)return a();let l=Re(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:r.size===0?t(e.value)&&r.add(e.key):i.add(e.key);break;case`remove`:i.delete(e.key),r.delete(e.key),r.size===0&&o();break;case`replace`:r.has(e.key)||r.size===0?(i.delete(e.key),t(e.value)?r.add(e.key):(r.delete(e.key),o())):i.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return r.size>0},{...n})},Ke=50,qe=class e{key;mapValue;name;atom;asRecord;asList;keys;#e=new Map;#t=e.#a();#n=e.#a();#r=e.#a();#i=e.#a();static#a(){return new A({maxSize:Ke})}constructor(e){this.key=e.key,this.mapValue=e.mapValue,this.name=`ReplicacheTable(${this.key.name})`,this.atom=Oe(this.name,{},{historyLength:1}),this.asRecord=this.atom,this.asList=We(this.atom),this.keys=Ue(this.atom,e=>this.key.decodeWithoutPrefix(e))}#o(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}#s(e){return typeof e==`string`?e:Array.isArray(e)?`${e[0]}/${e[1]}`:(console.error(`${this.name}.get: invalid key`,e),``)}get(e){let t=this.#s(e);return this.#o(this.#e,t,()=>Ve(this.atom,t))}find(e,t){return this.#o(this.#t,e,()=>Be(this.atom,t))}filter(e,t){return this.#o(this.#n,e,()=>ze(this.atom,t))}map(e,t){return this.#o(this.#r,e,()=>He(this.atom,t))}some(e,t){return this.#o(this.#i,e,()=>Ge(this.atom,t))}pushDiffList(e){Le({diffList:e,source:this.atom,mapKey:e=>this.key.trimPrefix(e),mapValue:(e,t)=>this.mapValue(e,this.key.decode(t))})}clear(){let e=this.atom.__unsafe__getWithoutCapture(),t=Object.keys(e);if(t.length===0)return;let n=t.map(e=>({op:`remove`,key:e}));this.atom.set({},n)}},Je=`store`,Ye=D(`meta`)(),Xe=()=>{let e={meta:new qe({key:Ye,mapValue:e=>e}),person:new qe({key:k.person,mapValue:(e,t)=>({id:t,name:e.name})}),surface:new qe({key:k.surface,mapValue:(e,t)=>({id:t,key:e.key,name:e.name,description:e.description})}),sprite:new qe({key:k.sprite,mapValue:(e,t)=>({id:t,name:e.name,surfaceId:e.surfaceId,ownedByPersonId:e.ownedByPersonId})}),spriteBuild:new qe({key:k.spriteBuild,mapValue:(e,t)=>({id:t,spriteId:e.spriteId,parentSpriteBuildId:e.parentSpriteBuildId,createdByPersonId:e.createdByPersonId,prompt:e.prompt,status:e.status,cancelRequestedAt:e.cancelRequestedAt,artifactUrl:e.artifactUrl,sourceUrl:null,startedAt:e.startedAt,stoppedAt:e.stoppedAt,error:e.error,reasoningSummary:e.reasoningSummary,publishedAt:e.publishedAt})}),spriteBuildEvent:new qe({key:k.spriteBuildEvent,mapValue:(e,t)=>({id:t,spriteBuildId:e.spriteBuildId,actionedAt:e.actionedAt,type:e.type,detail:e.detail})})},t={[k.person.name]:e.person,[k.surface.name]:e.surface,[k.spriteBuildEvent.name]:e.spriteBuildEvent,[k.spriteBuild.name]:e.spriteBuild,[k.sprite.name]:e.sprite},n=new Set,r,i=!1,a=t=>{let n=Ye.encode(Je);t===`LOADING`?e.meta.pushDiffList([{op:`add`,key:n,newValue:{state:t}}]):e.meta.pushDiffList([{op:`change`,key:n,newValue:{state:t},oldValue:{}}])},o=()=>{e.meta.clear(),e.person.clear(),e.surface.clear(),e.sprite.clear(),e.spriteBuild.clear(),e.spriteBuildEvent.clear()},s=()=>{for(let e of n)e()},c=e=>{if(i)return;r?.(),o(),a(`LOADING`);let n=!1;r=e.experimentalWatch(e=>{let r=oe(e,e=>e.key.match(/^(\w+)\//)?.[1]??``);for(let[e,n]of Object.entries(r))t[e]?.pushDiffList(n);n||(n=!0,a(`READY`)),s()},{initialValuesInFirstDiff:!0})},l=e=>(n.add(e),()=>{n.delete(e)}),u=async()=>{i=!0,r?.(),r=void 0,o(),n.clear()};return{...e,bind:c,subscribe:l,destroy:u}},Ze=b(((e,t)=>{var n=self.crypto;function r(e){let t=new Uint8Array(e);return n.getRandomValues(t),t}t.exports={randomBytes:r}})),Qe=b(((e,t)=>{var{randomBytes:n}=Ze(),r=16;t.exports=new class{compare(e,t){let n=e.findIndex((e,n)=>e!==t[n]);return~n&&Math.sign(e[n]-t[n])}generateOneFilled(){return new Uint8Array(r).fill(255)}generateRandomFilled(){return n(r)}generateZeroFilled(){return new Uint8Array(r).fill(0)}}})),$e=b(((e,t)=>{var n=class extends Error{get name(){return this.constructor.name}};t.exports={Id128Error:n,ClockSequenceOverflow:class extends n{},InvalidBytes:class extends n{},InvalidEncoding:class extends n{},InvalidEpoch:class extends n{},UnsupportedVersion:class extends n{}}})),et=b(((e,t)=>{var{InvalidEpoch:n}=$e(),r=0,i=2**48;t.exports=new class{fromEpoch(e,t){return new Date(t+e)}toEpoch(e,t=null){let a=(t===null?Date.now():Number.isInteger(t)?t:t instanceof Date?t.getTime():(()=>{throw new n(`Failed to coerce time [${t}] to epoch`)})())-e;if(a<r||a>=i)throw new n(`Epoch must be between ${new Date(r+e).toISOString()} and ${new Date(i-1+e).toISOString()}`);return a}}})),tt=b(((e,t)=>{var n=Qe(),r=Symbol(`bytes`);t.exports={BaseId:class{constructor(e){this[r]=e}clone(){return new this.constructor(this.bytes.slice())}get bytes(){return this[r]}get[Symbol.toStringTag](){return this.constructor.name}compare(e){return n.compare(this.bytes,e.bytes)}equal(e){return this.compare(e)===0}}}})),nt=b(((e,t)=>{var n=Qe(),r=et(),{BaseId:i}=tt(),a=0,o=2**32,s=255;function c(e,t){let n=e%o,r=(e-n)/o,i=-1;t[++i]=r>>>8&s,t[++i]=r>>>0&s,t[++i]=n>>>24&s,t[++i]=n>>>16&s,t[++i]=n>>>8&s,t[++i]=n>>>0&s}t.exports={Ulid:class extends i{static generate({time:e}={}){e=r.toEpoch(a,e);let t=n.generateRandomFilled();return c(e,t),new this(t)}static MIN(){return new this(n.generateZeroFilled())}static MAX(){return new this(n.generateOneFilled())}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*o+(n>>>0);return r.fromEpoch(a,i)}},setTime:c}})),rt=b(((e,t)=>{var{Ulid:n,setTime:r}=nt(),i=Qe(),a=et(),{ClockSequenceOverflow:o}=$e(),s=0,c=6,l=8,u=0,d,f;function p(e){for(let t=7;t>5;--t)if(e[t]===255)e[t]=0;else{++e[t];return}throw new o(`Exhausted clock sequence`)}function m(e){e[c]&=127}function h(e){for(let t=s;t<l;++t)e[t]=d.bytes[t]}var g=class extends n{static reset(){f=-1,d=this.MIN()}static generate({time:e}={}){e=a.toEpoch(u,e);let t=i.generateRandomFilled();return e<=f?(h(t),p(t)):(r(e,t),m(t),f=e),d=new this(t)}};g.reset(),t.exports={UlidMonotonic:g}})),it=b(((e,t)=>{var{BaseId:n}=tt(),r=Qe(),i=8,a=6;function o(e,t){t[i]&=255>>>e+1,t[i]|=(7<<3-e&7)<<5}function s(e,t){t[a]&=15,t[a]|=e<<4}t.exports={Uuid:class extends n{static MIN(){let e=r.generateZeroFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}static MAX(){let e=r.generateOneFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}get variant(){let e=this.bytes[i]>>>5;return e===7?3:(e&6)==6?2:+((e&4)==4)}get version(){return this.bytes[a]>>>4}},setVersion:s,setVariant:o}})),at=b(((e,t)=>{var{randomBytes:n}=Ze(),r=Symbol(`mac-address`);t.exports=new class{constructor(){this.reset()}get mac_address(){let e=this[r];return e||(e=this[r]=n(6),e[0]|=1),e}reset(){this[r]=null}}})),ot=b(((e,t)=>{var n=Qe(),r=et(),i=at(),{Uuid:a,setVariant:o,setVersion:s}=it(),c=2,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**20,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function x(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function S(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=n*p+_,i=(e-n)/m,a=-1;t[++a]=r>>>24&h,t[++a]=r>>>16&h,t[++a]=r>>>8&h,t[++a]=r>>>0&h,t[++a]=i>>>8&h,t[++a]=i>>>0&h,t[++a]=i>>>24&h,t[++a]=i>>>16&h}var C=class extends a{static get VARIANT(){return 1}static get VERSION(){return 1}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return S(t,a),b(t,a),x(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[3])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<12|this.bytes[++e]<<4|this.bytes[++e]>>>4;++e;let n=(0|this.bytes[++e]<<8|this.bytes[++e]<<0|(this.bytes[++e]&15)<<24|this.bytes[++e]<<16)*m+t;return r.fromEpoch(f,n)}};C.reset(),t.exports={Uuid1:C}})),st=b(((e,t)=>{var n=Qe(),{Uuid:r,setVariant:i,setVersion:a}=it();t.exports={Uuid4:class extends r{static get VARIANT(){return 1}static get VERSION(){return 4}static generate(){let e=n.generateRandomFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),ct=b(((e,t)=>{var n=Qe(),r=et(),i=at(),{Uuid:a,setVariant:o,setVersion:s}=it(),c=6,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**32,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function x(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function S(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=(e-n)/m,i=-1;t[++i]=r>>>8&h,t[++i]=r>>>0&h,t[++i]=n>>>24&h,t[++i]=n>>>16&h,t[++i]=n>>>8&h,t[++i]=n>>>0&h,t[++i]=_>>>8&h,t[++i]=_>>>0&h}var C=class extends a{static get VARIANT(){return 1}static get VERSION(){return 6}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return S(t,a),b(t,a),x(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[7])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*m+(n>>>0);return r.fromEpoch(f,i)}};C.reset(),t.exports={Uuid6:C}})),lt=b(((e,t)=>{var n=Qe(),{Uuid:r,setVariant:i,setVersion:a}=it();t.exports={UuidNil:class extends r{static get VARIANT(){return 0}static get VERSION(){return 0}static generate(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}static MAX(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),ut=b(((e,t)=>{var{InvalidEncoding:n,InvalidBytes:r}=$e(),i=Symbol(`valid_encoding_pattern`);t.exports={BaseCoder:class{constructor({valid_encoding_pattern:e}={}){this[i]=e}decode(e){if(this.isValidEncoding(e))return this.decodeTrusted(e);throw new n(`Encoding [${e}] does not satisfy ${this[i]}`)}decodeTrusted(e){return ByteArray.generateRandomFilled()}encode(e){if(this.isValidBytes(e))return this.encodeTrusted(e);throw new r(`Requires a 16-byte Uint8Array`)}encodeTrusted(e){return``}isValidBytes(e){return e instanceof Uint8Array&&e.length===16}isValidEncoding(e){return(typeof e==`string`||e instanceof String)&&this[i].test(e)}}}})),dt=b(((e,t)=>{var{BaseCoder:n}=ut(),r=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,i=31,a=Array.from(r).reduce((e,t,n)=>(e[t]=e[t.toLowerCase()]=n,e),{I:r.indexOf(`1`),i:r.indexOf(`1`),L:r.indexOf(`1`),l:r.indexOf(`1`),O:r.indexOf(`0`),o:r.indexOf(`0`),U:r.indexOf(`V`),u:r.indexOf(`V`)}),o=Array.from(r);function s(e){return a[e]}function c(e){return o[e&i]}t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-7][^\W_]{25}$/})}decodeTrusted(e){let t=new Uint8Array(16),n=[];for(let t=0,r=e.length;t<r;++t)n.push(s(e[t]));return t[0]=n[0]<<5|n[1],t[1]=n[2]<<3|n[3]>>2,t[2]=n[3]<<6|n[4]<<1|n[5]>>4,t[3]=n[5]<<4|n[6]>>1,t[4]=n[6]<<7|n[7]<<2|n[8]>>3,t[5]=n[8]<<5|n[9],t[6]=n[10]<<3|n[11]>>2,t[7]=n[11]<<6|n[12]<<1|n[13]>>4,t[8]=n[13]<<4|n[14]>>1,t[9]=n[14]<<7|n[15]<<2|n[16]>>3,t[10]=n[16]<<5|n[17],t[11]=n[18]<<3|n[19]>>2,t[12]=n[19]<<6|n[20]<<1|n[21]>>4,t[13]=n[21]<<4|n[22]>>1,t[14]=n[22]<<7|n[23]<<2|n[24]>>3,t[15]=n[24]<<5|n[25],t}encodeTrusted(e){let t=[e[0]>>5,e[0],e[1]>>3,e[1]<<2|e[2]>>6,e[2]>>1,e[2]<<4|e[3]>>4,e[3]<<1|e[4]>>7,e[4]>>2,e[4]<<3|e[5]>>5,e[5],e[6]>>3,e[6]<<2|e[7]>>6,e[7]>>1,e[7]<<4|e[8]>>4,e[8]<<1|e[9]>>7,e[9]>>2,e[9]<<3|e[10]>>5,e[10],e[11]>>3,e[11]<<2|e[12]>>6,e[12]>>1,e[12]<<4|e[13]>>4,e[13]<<1|e[14]>>7,e[14]>>2,e[14]<<3|e[15]>>5,e[15]],n=``;for(let e=0,r=t.length;e<r;++e)n+=c(t[e]);return n}}})),ft=b(((e,t)=>{var{BaseCoder:n}=ut(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{32}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r}return t}encodeTrusted(e){let t=``;for(let n=0,r=e.length;n<r;++n)t+=i[e[n]];return t}}})),pt=b(((e,t)=>{var{BaseCoder:n}=ut(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{4}(?:-?[0-9A-Fa-f]{4}){7}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];o!==`-`&&(r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r)}return t}encodeTrusted(e){let t=-1;return``+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]}}})),mt=b(((e,t)=>{var n=Symbol(`id`),r=Symbol(`canonical_coder`),i=Symbol(`raw_coder`);t.exports={IdFactory:class{constructor({id:e,canonical_coder:t,raw_coder:a}={}){this[n]=class extends e{static get name(){return e.name}static get[Symbol.species](){return e}get[Symbol.toStringTag](){return`${e.name} ${this.toRaw()}`}toCanonical(){return t.encodeTrusted(this.bytes)}toRaw(){return a.encodeTrusted(this.bytes)}},this[r]=t,this[i]=a}get name(){return this[n].name}get type(){return this[n][Symbol.species]}construct(e){return new this[n](e)}generate(){return this[n].generate(...arguments)}MIN(){return this[n].MIN(...arguments)}MAX(){return this[n].MAX(...arguments)}fromCanonical(e){return this.construct(this[r].decode(e))}fromCanonicalTrusted(e){return this.construct(this[r].decodeTrusted(e))}fromRaw(e){return this.construct(this[i].decode(e))}fromRawTrusted(e){return this.construct(this[i].decodeTrusted(e))}toCanonical(e){return this[r].encode(e.bytes)}toRaw(e){return this[i].encode(e.bytes)}compare(e,t){return console.warn(`Deprecated: use generic idCompare instead.`),e.compare(t)}equal(e,t){return console.warn(`Deprecated: use generic idEqual instead.`),e.equal(t)}isCanonical(e){return this[r].isValidEncoding(e)}isRaw(e){return this[i].isValidEncoding(e)}}}})),ht=b(((e,t)=>{var{IdFactory:n}=mt(),{UnsupportedVersion:r}=$e(),i=Symbol(`id_by_version`);function a(e,{version:t}={}){return e[i][t]||(()=>{throw new r(`No support for version [${t}]`)})()}t.exports={VersionedIdFactory:class extends n{constructor({abstract_id:e,versioned_ids:t,canonical_coder:r,raw_coder:a}){super({id:e,canonical_coder:r,raw_coder:a}),this[i]=t.reduce((e,t)=>Object.assign(e,{[t.MIN().version]:new n({id:t,canonical_coder:r,raw_coder:a})}),Object.create(null))}get versioned_ids(){return Object.values(this[i])}construct(e){let t=super.construct(e),n=t.version;try{return a(this,{version:n}).construct(e)}catch(e){if(e instanceof r)return t;throw e}}generate(){return a(this,...arguments).generate(...arguments)}MIN(){return a(this,...arguments).MIN()}MAX(){return a(this,...arguments).MAX()}}}})),gt=C(b(((e,t)=>{var{Ulid:n}=nt(),{UlidMonotonic:r}=rt(),{Uuid:i}=it(),{Uuid1:a}=ot(),{Uuid4:o}=st(),{Uuid6:s}=ct(),{UuidNil:c}=lt(),l=dt(),u=ft(),d=pt(),{IdFactory:f}=mt(),{VersionedIdFactory:p}=ht(),m={idCompare:function(e,t){return e.compare(t)},idEqual:function(e,t){return e.equal(t)},Exception:$e(),Ulid:new f({id:n,canonical_coder:l,raw_coder:u}),UlidMonotonic:new f({id:r,canonical_coder:l,raw_coder:u}),Uuid:new p({abstract_id:i,versioned_ids:[a,o,s,c],canonical_coder:d,raw_coder:u})};m.Uuid.versioned_ids.reduce((e,t)=>Object.assign(e,{[t.name]:t}),m),t.exports=m}))(),1),_t=e=>gt.default.UlidMonotonic.generate({time:e}).toCanonical(),vt=async(e,t)=>e.query(async e=>{for await(let[n,r]of e.scan({prefix:k.surface.prefix()}).entries())if(r.key===t)return{id:k.surface.decode(n),...r}}),yt=async e=>{let{replicache:n,key:r,name:i,description:a,toolList:o,projectId:s,signal:c}=e;return c?.aborted?Error(`Register surface aborted`):t(async()=>{let e=_t();return await n.mutate.surface_upsert_v1({surfaceId:e,projectPublicId:s,key:r,name:i,description:a,toolList:o.map(e=>e.toJSON()),context:{actionedAt:Date.now()}}),await n.push({now:!0}),await n.pull({now:!0}),await vt(n,r)||Error(`Surface "${r}" missing from Replicache`)})},bt=class extends Error{name=`RoughClientDestroyedError`;constructor(e=`The Rough client has been destroyed`){super(e)}},xt=class extends Error{name=`RoughReplicacheIdentityConflictError`;replicacheName;constructor(e){super(`Another Rough client is already using the local database "${e.replicacheName}". Share the existing client through your framework ownership boundary, or await its destroy() before creating a replacement.`),this.replicacheName=e.replicacheName}},St=class extends Error{name=`RoughSurfaceContractConflictError`;surfaceKey;constructor(e){super(`Surface "${e.surfaceKey}" is already active on this client with a different contract. Close the operations using the old definition before activating the new one.`),this.surfaceKey=e.surfaceKey}},Ct=class extends Error{name=`RoughClientDestroyError`;errors;constructor(e){super(`Rough client destruction finished with ${e.errors.length} error(s): ${e.errors.map(e=>e.message).join(`; `)}`),this.errors=e.errors}},wt=class extends Error{name=`RoughInvalidClientError`;constructor(e=`Expected a RoughClient created by createRoughClient()`){super(e)}},Tt=e=>e instanceof Error?e:Error(String(e)),Et=e=>e.reason instanceof Error?e.reason:new bt,Dt=e=>new Promise((t,n)=>{if(e.aborted){n(Et(e));return}e.addEventListener(`abort`,()=>n(Et(e)),{once:!0})}),Ot=e=>new Promise(t=>{if(e.aborted){t();return}e.addEventListener(`abort`,()=>t(),{once:!0})}),kt=Symbol(`rough.surface.definition`),At=(e,t)=>{if(typeof e!=`string`||e.trim()===``)throw TypeError(`defineRoughSurface: "${t}" must be a non-empty string`);return e},jt=e=>{let t=At(e.key,`key`),n=At(e.name,`name`),r=At(e.description,`description`);if(!Array.isArray(e.tools))throw TypeError(`defineRoughSurface: "tools" must be an array`);for(let t of e.tools)if(typeof t?.toJSON!=`function`)throw TypeError(`defineRoughSurface: every entry in "tools" must be a Query, Mutation or Subscription`);let i={key:t,name:n,description:r,tools:Object.freeze([...e.tools])};return Object.defineProperty(i,kt,{value:!0,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(i)},Mt=e=>typeof e==`object`&&!!e&&kt in e&&e[kt]===!0,Nt=e=>{if(!Mt(e))throw TypeError(`Expected a surface created by defineRoughSurface(). Object literals are not accepted because the definition must be validated and frozen.`);return e},Pt=e=>JSON.stringify({key:e.key,name:e.name,description:e.description,tools:e.tools.map(e=>e.toJSON())}),Ft=e=>{let{getRuntime:t}=e,n=new Map,r=!1,i=(e,n)=>(async()=>{let r=t();r.assertUsable();let i=await Promise.race([r.getReplicache(),Dt(n)]);r.assertUsable();let a=await yt({replicache:i,projectId:r.projectId,key:e.key,name:e.name,description:e.description,toolList:e.tools,signal:n});if(a instanceof Error)throw a;return{id:a.id}})(),a=(e,t)=>{let r=new AbortController,a={registrationFingerprint:t,activeOperationCount:0,controller:r,resolution:i(e,r.signal)};return a.resolution.catch(()=>{n.get(e.key)===a&&n.delete(e.key)}),a};return{acquire:e=>{let i=Nt(e.surface);if(t().assertUsable(),r)throw new bt;let o=Pt(i),s=n.get(i.key);if(s&&s.registrationFingerprint!==o){if(s.activeOperationCount>0)throw new St({surfaceKey:i.key});s.controller.abort(Error(`Surface contract replaced`)),n.delete(i.key),s=void 0}s||(s=a(i,o),n.set(i.key,s));let c=s;c.activeOperationCount+=1;let l=!1;return{surfaceKey:i.key,ready:c.resolution,release:()=>{l||(l=!0,c.activeOperationCount=Math.max(c.activeOperationCount-1,0))}}},destroy:async()=>{r=!0;let e=[...n.values()];n.clear();for(let t of e)t.controller.abort(new bt);await Promise.allSettled(e.map(e=>e.resolution))},getActiveOperationCount:e=>n.get(e)?.activeOperationCount??0}},It=()=>{let e=new Set;return{register:t=>(e.add(t),()=>{e.delete(t)}),closeAll:async()=>{let t=[...e];e.clear();let n=(await Promise.allSettled(t.map(async e=>{try{await e.close()}catch(t){let n=Tt(t);throw n.message=`${e.label}: ${n.message}`,n}}))).flatMap(e=>e.status===`rejected`?[Tt(e.reason)]:[]);if(n.length>0)throw new Ct({errors:n})},size:()=>e.size}},Lt=class{#e;constructor(e){this.#e=e}log(e,t,...n){for(let r of this.#e)r.log(e,t,...n)}async flush(){await Promise.all(this.#e.map(e=>e.flush?.()))}},Rt=class{debug=void 0;info=void 0;warn=void 0;error=void 0;flush;#e;#t;constructor(e,t=`info`,n){switch(this.#e=e,this.#t=n,t){case`debug`:this.debug=this.#n;case`info`:this.info=this.#r;case`warn`:this.warn=this.#i;case`error`:this.error=this.#a}this.flush=this.#o}#n(...e){this.#e.log(`debug`,this.#t,...e)}#r(...e){this.#e.log(`info`,this.#t,...e)}#i(...e){this.#e.log(`warn`,this.#t,...e)}#a(...e){this.#e.log(`error`,this.#t,...e)}#o(){return this.#e.flush?.()??Promise.resolve()}},zt={log(e,t,...n){console[e](...Vt(t),...n.map(Ht))}},Bt=class e extends Rt{#e;#t;#n;constructor(e=`info`,t,n=zt){super(n,e,t),this.#t=e,this.#e=n,this.#n=t}withContext(t,n){let r={...this.#n,[t]:n};return new e(this.#t,r,this.#e)}};function Vt(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=r===void 0?n:`${n}=${r}`;t.push(e)}return t}function Ht(e){switch(typeof e){case`string`:case`number`:case`boolean`:case`undefined`:case`symbol`:case`bigint`:return e;case`object`:if(e===null)return null}return JSON.stringify(e,Ut)}function Ut(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack,...`cause`in t?{cause:t.cause}:null}:t}function Wt(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Gt=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=Wt();return this._lockP=t,await e,n}withLock(e){return qt(this.lock(),e)}},Kt=class{_lock=new Gt;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=Wt();return this._readP.push(e),t})}withRead(e){return qt(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=Wt();return this._writeP=e,this._readP=[],t})}withWrite(e){return qt(this.write(),e)}};async function qt(e,t){let n=await e;try{return await t()}finally{n()}}var Jt=x({ValitaError:()=>rn,array:()=>er,bigint:()=>Gn,boolean:()=>Yn,err:()=>sn,lazy:()=>rr,literal:()=>Zn,never:()=>Fn,null:()=>Vn,number:()=>Un,object:()=>Qn,ok:()=>on,record:()=>$n,string:()=>qn,tuple:()=>tr,undefined:()=>zn,union:()=>nr,unknown:()=>Ln});function Yt(e,t){return e?{ok:!1,code:`join`,left:e,right:t}:t}function Xt(e,t){return{ok:!1,code:`prepend`,key:e,tree:t}}function Zt(e,t){let n=e.code;switch(n){case`invalid_type`:return{code:n,path:t,expected:e.expected};case`invalid_literal`:return{code:n,path:t,expected:e.expected};case`missing_value`:return{code:n,path:t};case`invalid_length`:return{code:n,path:t,minLength:e.minLength,maxLength:e.maxLength};case`unrecognized_keys`:return{code:n,path:t,keys:e.keys};case`invalid_union`:return{code:n,path:t,tree:e.tree};case`custom_error`:return{code:n,path:t,error:e.error}}}function Qt(e,t=[],n=[]){for(;;)if(e.code===`join`)Qt(e.left,t.slice(),n),e=e.right;else if(e.code===`prepend`)t.push(e.key),e=e.tree;else return e.code===`custom_error`&&typeof e.error==`object`&&e.error.path!==void 0&&t.push(...e.error.path),n.push(Zt(e,t)),n}function $t(e,t){return e.length===0?`nothing`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} ${t} ${e[e.length-1]}`}function en(e){return typeof e==`bigint`?`${e}n`:JSON.stringify(e)}function tn(e){let t=0;for(;;)if(e.code===`join`)t+=tn(e.left),e=e.right;else if(e.code===`prepend`)e=e.tree;else return t+1}function nn(e){let t=``,n=0;for(;;)if(e.code===`join`)n+=tn(e.right),e=e.left;else if(e.code===`prepend`)t+=`.${e.key}`,e=e.tree;else break;let r=`validation failed`;if(e.code===`invalid_type`)r=`expected ${$t(e.expected,`or`)}`;else if(e.code===`invalid_literal`)r=`expected ${$t(e.expected.map(en),`or`)}`;else if(e.code===`missing_value`)r=`missing value`;else if(e.code===`unrecognized_keys`){let t=e.keys;r=`unrecognized ${t.length===1?`key`:`keys`} ${$t(t.map(en),`and`)}`}else if(e.code===`invalid_length`){let t=e.minLength,n=e.maxLength;r=`expected an array with `,r+=t>0?n===t?`${t}`:n===void 0?`at least ${t}`:`between ${t} and ${n}`:`at most ${n??`∞`}`,r+=` item(s)`}else if(e.code===`custom_error`){let n=e.error;typeof n==`string`?r=n:n!==void 0&&(n.message!==void 0&&(r=n.message),n.path!==void 0&&(t+=`.`+n.path.join(`.`)))}let i=`${e.code} at .${t.slice(1)} (${r})`;return n===1?i+=` (+ 1 other issue)`:n>1&&(i+=` (+ ${n} other issues)`),i}var rn=class extends Error{constructor(e){super(nn(e)),this.issueTree=e,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this._issues=void 0}get issues(){return this._issues===void 0&&(this._issues=Qt(this.issueTree)),this._issues}},an=class{constructor(e){this.issueTree=e,this.ok=!1,this._issues=void 0,this._message=void 0}get issues(){return this._issues===void 0&&(this._issues=Qt(this.issueTree)),this._issues}get message(){return this._message===void 0&&(this._message=nn(this.issueTree)),this._message}throw(){throw new rn(this.issueTree)}};function on(e){return{ok:!0,value:e}}function sn(e){return new an({ok:!1,code:`custom_error`,error:e})}function cn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ln=1,un=2,dn=4,fn=class{optional(e){let t=new hn(this);return e?new Mn(t,t=>t===void 0?{ok:!0,value:e()}:void 0):t}default(e){let t=on(e);return new Mn(this.optional(),e=>e===void 0?t:void 0)}assert(e,t){let n={ok:!1,code:`custom_error`,error:t};return new Mn(this,(t,r)=>e(t,r)?void 0:n)}map(e){return new Mn(this,(t,n)=>({ok:!0,value:e(t,n)}))}chain(e){return new Mn(this,(t,n)=>{let r=e(t,n);return r.ok?r:r.issueTree})}},pn=class extends fn{nullable(){return new mn(this)}toTerminals(e){e(this)}try(e,t){let n=ln;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=un);let r=this.func(e,n);return r===void 0?{ok:!0,value:e}:r.ok?{ok:!0,value:r.value}:new an(r)}parse(e,t){let n=ln;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=un);let r=this.func(e,n);if(r===void 0)return e;if(r.ok)return r.value;throw new rn(r)}},mn=class extends pn{constructor(e){super(),this.type=e,this.name=`nullable`}func(e,t){return e===null?void 0:this.type.func(e,t)}toTerminals(e){e(Bn),this.type.toTerminals(e)}nullable(){return this}},hn=class extends fn{constructor(e){super(),this.type=e,this.name=`optional`}func(e,t){return e===void 0||t&dn?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(Rn),this.type.toTerminals(e)}optional(e){return e?new Mn(this,t=>t===void 0?{ok:!0,value:e()}:void 0):this}};function gn(e,t){if(typeof e!=`number`){let n=t>>5;for(let t=e.length;t<=n;t++)e.push(0);return e[n]|=1<<t%32,e}return t<32?e|1<<t:gn([e,0],t)}function _n(e,t){return typeof e==`number`?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}var vn=class e extends pn{constructor(e,t,n){super(),this.shape=e,this.restType=t,this.checks=n,this.name=`object`,this._invalidType={ok:!1,code:`invalid_type`,expected:[`object`]}}check(t,n){let r={ok:!1,code:`custom_error`,error:n};return new e(this.shape,this.restType,[...this.checks??[],{func:t,issue:r}])}func(e,t){if(!cn(e))return this._invalidType;let n=this._func;return n===void 0&&(n=yn(this.shape,this.restType,this.checks),this._func=n),n(e,t)}rest(t){return new e(this.shape,t)}extend(t){return new e(Object.assign(Object.assign({},this.shape),t),this.restType)}pick(...t){let n={};return t.forEach(e=>{n[e]=this.shape[e]}),new e(n,void 0)}omit(...t){let n=Object.assign({},this.shape);return t.forEach(e=>{delete n[e]}),new e(n,this.restType)}partial(){let t={};Object.keys(this.shape).forEach(e=>{t[e]=this.shape[e].optional()});let n=this.restType?.optional();return new e(t,n)}};function yn(e,t,n){let r=[],i=[];for(let t in e){let n=!1;e[t].toTerminals(e=>{n||=e.name===`optional`}),n?i.push(t):r.push(t)}let a=[...r,...i],o=a.length;if(o===0&&t?.name===`unknown`)return function(e,t){if(n!==void 0){for(let t=0;t<n.length;t++)if(!n[t].func(e))return n[t].issue}};let s=a.map(t=>e[t]),c=r.length,l=Object.create(null);a.forEach((e,t)=>{l[e]=~t});let u=r.map(e=>Xt(e,{ok:!1,code:`missing_value`}));function d(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}return function(e,r){let i=!1,f=e,p,m,h=0,g=0;if(r&ln||r&un||t!==void 0)for(let n in e){let c=e[n],u=~l[n],_;if(u>=0)g++,h=gn(h,u),_=s[u].func(c,r);else if(t!==void 0)_=t.func(c,r);else{if(r&ln)m===void 0?m=[n]:m.push(n);else if(r&un&&p===void 0&&!i){f={},i=!0;for(let t=0;t<o;t++)if(_n(h,t)){let n=a[t];d(f,n,e[n])}}continue}if(_===void 0)i&&p===void 0&&d(f,n,c);else if(!_.ok)p=Yt(p,Xt(n,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t!==u&&_n(h,t)){let n=a[t];d(f,n,e[n])}}else for(let t in e)d(f,t,e[t])}d(f,n,_.value)}}if(g<o)for(let n=0;n<o;n++){if(_n(h,n))continue;let l=a[n],m=e[l],g=r&-5;if(m===void 0&&!(l in e)){if(n<c){p=Yt(p,u[n]);continue}g|=dn}let _=s[n].func(m,g);if(_===void 0)i&&p===void 0&&!(g&dn)&&d(f,l,m);else if(!_.ok)p=Yt(p,Xt(l,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t<n||_n(h,t)){let n=a[t];d(f,n,e[n])}}else{for(let t in e)d(f,t,e[t]);for(let t=0;t<n;t++)if(!_n(h,t)){let n=a[t];d(f,n,e[n])}}}d(f,l,_.value)}}if(m!==void 0&&(p=Yt(p,{ok:!1,code:`unrecognized_keys`,keys:m})),p===void 0&&n!==void 0){for(let e=0;e<n.length;e++)if(!n[e].func(f))return n[e].issue}return p===void 0&&i?{ok:!0,value:f}:p}}var bn=class e extends pn{constructor(e,t,n){super(),this.prefix=e,this.rest=t,this.suffix=n,this.name=`array`,this.restType=t??Fn(),this.minLength=this.prefix.length+this.suffix.length,this.maxLength=t?void 0:this.minLength,this.invalidType={ok:!1,code:`invalid_type`,expected:[`array`]},this.invalidLength={ok:!1,code:`invalid_length`,minLength:this.minLength,maxLength:this.maxLength}}func(e,t){if(!Array.isArray(e))return this.invalidType;let n=e.length,r=this.minLength,i=this.maxLength??1/0;if(n<r||n>i)return this.invalidLength;let a=this.prefix.length,o=e.length-this.suffix.length,s,c=e;for(let n=0;n<e.length;n++){let r=(n<a?this.prefix[n]:n>=o?this.suffix[n-o]:this.restType).func(e[n],t);r!==void 0&&(r.ok?(c===e&&(c=e.slice()),c[n]=r.value):s=Yt(s,Xt(n,r)))}return s||(e===c?void 0:{ok:!0,value:c})}concat(t){if(this.rest){if(t.rest)throw TypeError(`can not concatenate two variadic types`);return new e(this.prefix,this.rest,[...this.suffix,...t.prefix,...t.suffix])}return t.rest?new e([...this.prefix,...this.suffix,...t.prefix],t.rest,t.suffix):new e([...this.prefix,...this.suffix,...t.prefix,...t.suffix],t.rest,t.suffix)}};function xn(e){let t=typeof e;return t===`object`?e===null?`null`:Array.isArray(e)?`array`:t:t}function Sn(e){return Array.from(new Set(e))}function Cn(e){let t=new Map;e.forEach(e=>{for(let n in e)t.set(n,(t.get(n)??0)+1)});let n=[];return t.forEach((t,r)=>{t===e.length&&n.push(r)}),n}function wn(e){let t=new Map,n=new Map,r=new Map,i=[],a=[],o=[];e.forEach(({root:e,terminal:s})=>{if(t.set(e,t.get(e)??t.size),s.name!==`never`){if(s.name===`optional`)a.push(e);else if(s.name===`unknown`)i.push(e);else if(s.name===`literal`){let t=n.get(s.value)??[];t.push(e),n.set(s.value,t),o.push(xn(s.value))}else{let t=r.get(s.name)??[];t.push(e),r.set(s.name,t),o.push(s.name)}}}),n.forEach((e,t)=>{let i=r.get(xn(t));i&&(i.push(...e),n.delete(t))});let s=(e,n)=>(t.get(e)??0)-(t.get(n)??0);return r.forEach((e,t)=>r.set(t,Sn(e.concat(i).sort(s)))),n.forEach((e,t)=>n.set(t,Sn(e.concat(i)).sort(s))),{types:r,literals:n,unknowns:Sn(i).sort(s),optionals:Sn(a).sort(s),expectedTypes:Sn(o)}}function Tn(e,t){let n=[];for(let{root:r,terminal:i}of e)i.shape[t].toTerminals(e=>n.push({root:r,terminal:e}));let{types:r,literals:i,optionals:a,unknowns:o,expectedTypes:s}=wn(n);if(o.length>0||a.length>1)return;for(let e of i.values())if(e.length>1)return;for(let e of r.values())if(e.length>1)return;let c=Xt(t,{ok:!1,code:`missing_value`}),l=Xt(t,r.size===0?{ok:!1,code:`invalid_literal`,expected:Array.from(i.keys())}:{ok:!1,code:`invalid_type`,expected:s}),u=i.size>0?new Map:void 0;for(let[e,t]of i)u.set(e,t[0]);let d=r.size>0?{}:void 0;for(let[e,t]of r)d[e]=t[0];return function(e,n){let r=e,i=r[t];if(i===void 0&&!(t in r))return a.length>0?a[0].func(r,n):c;let o=d?.[xn(i)]??u?.get(i);return o?o.func(r,n):l}}function En(e){if(e.some(({terminal:e})=>e.name===`unknown`))return;let t=e.filter(e=>e.terminal.name===`object`);if(t.length<2)return;let n=t.map(({terminal:e})=>e.shape);for(let e of Cn(n)){let n=Tn(t,e);if(n)return n}}function Dn(e){let{expectedTypes:t,literals:n,types:r,unknowns:i,optionals:a}=wn(e),o=r.size===0&&i.length===0?{ok:!1,code:`invalid_literal`,expected:Array.from(n.keys())}:{ok:!1,code:`invalid_type`,expected:t},s=n.size>0?n:void 0,c=r.size>0?{}:void 0;for(let[e,t]of r)c[e]=t;return function(e,t){let n=t&dn?a:c?.[xn(e)]??s?.get(e)??i,r=0,l=o;for(let i=0;i<n.length;i++){let a=n[i].func(e,t);if(a===void 0||a.ok)return a;l=r>0?Yt(l,a):a,r++}return r>1?{ok:!1,code:`invalid_union`,tree:l}:l}}var On=class extends pn{constructor(e){super(),this.options=e,this.name=`union`}toTerminals(e){this.options.forEach(t=>{t.toTerminals(e)})}func(e,t){let n=this._func;if(n===void 0){let e=[];this.options.forEach(t=>{t.toTerminals(n=>{e.push({root:t,terminal:n})})});let t=Dn(e),r=En(e);n=r?function(e,n){return cn(e)?r(e,n):t(e,n)}:t,this._func=n}return n(e,t)}},kn=Object.freeze({mode:`strict`}),An=Object.freeze({mode:`strip`}),jn=Object.freeze({mode:`passthrough`}),Mn=class e extends pn{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name=`transform`,this.undef=on(void 0),this.transformChain=void 0,this.transformRoot=void 0}func(t,n){let r=this.transformChain;if(!r){r=[];let t=this;for(;t instanceof e;)r.push(t.transform),t=t.transformed;r.reverse(),this.transformChain=r,this.transformRoot=t}let i=this.transformRoot.func(t,n);if(i!==void 0&&!i.ok)return i;let a;i===void 0?n&dn?(a=void 0,i=this.undef):a=t:a=i.value;let o=n&ln?kn:n&un?An:jn;for(let e=0;e<r.length;e++){let t=r[e](a,o);if(t!==void 0){if(!t.ok)return t;a=t.value,i=t}}return i}toTerminals(e){this.transformed.toTerminals(e)}},Nn=class extends pn{constructor(e){super(),this.definer=e,this.name=`lazy`,this.recursing=!1}func(e,t){return this.type||=this.definer(),this.type.func(e,t)}toTerminals(e){if(!this.recursing)try{this.recursing=!0,this.type||=this.definer(),this.type.toTerminals(e)}finally{this.recursing=!1}}},Pn=new class extends pn{constructor(){super(...arguments),this.name=`never`,this.issue={ok:!1,code:`invalid_type`,expected:[]}}func(e,t){return this.issue}};function Fn(){return Pn}var In=new class extends pn{constructor(){super(...arguments),this.name=`unknown`}func(e,t){}};function Ln(){return In}var Rn=new class extends pn{constructor(){super(...arguments),this.name=`undefined`,this.issue={ok:!1,code:`invalid_type`,expected:[`undefined`]}}func(e,t){return e===void 0?void 0:this.issue}};function zn(){return Rn}var Bn=new class extends pn{constructor(){super(...arguments),this.name=`null`,this.issue={ok:!1,code:`invalid_type`,expected:[`null`]}}func(e,t){return e===null?void 0:this.issue}};function Vn(){return Bn}var Hn=new class extends pn{constructor(){super(...arguments),this.name=`number`,this.issue={ok:!1,code:`invalid_type`,expected:[`number`]}}func(e,t){return typeof e==`number`?void 0:this.issue}};function Un(){return Hn}var Wn=new class extends pn{constructor(){super(...arguments),this.name=`bigint`,this.issue={ok:!1,code:`invalid_type`,expected:[`bigint`]}}func(e,t){return typeof e==`bigint`?void 0:this.issue}};function Gn(){return Wn}var Kn=new class extends pn{constructor(){super(...arguments),this.name=`string`,this.issue={ok:!1,code:`invalid_type`,expected:[`string`]}}func(e,t){return typeof e==`string`?void 0:this.issue}};function qn(){return Kn}var Jn=new class extends pn{constructor(){super(...arguments),this.name=`boolean`,this.issue={ok:!1,code:`invalid_type`,expected:[`boolean`]}}func(e,t){return typeof e==`boolean`?void 0:this.issue}};function Yn(){return Jn}var Xn=class extends pn{constructor(e){super(),this.value=e,this.name=`literal`,this.issue={ok:!1,code:`invalid_literal`,expected:[e]}}func(e,t){return e===this.value?void 0:this.issue}};function Zn(e){return new Xn(e)}function Qn(e){return new vn(e,void 0)}function $n(e){return new vn({},e??Ln())}function er(e){return new bn([],e??Ln(),[])}function tr(e){return new bn(e,void 0,[])}function nr(...e){return new On(e)}function rr(e){return new Nn(e)}var ir=Object.defineProperty,ar=Object.getOwnPropertyDescriptor,or=Object.getOwnPropertyNames,sr=Object.prototype.hasOwnProperty,cr=(e,t)=>{for(var n in t)ir(e,n,{get:t[n],enumerable:!0})},lr=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of or(t))!sr.call(e,i)&&i!==n&&ir(e,i,{get:()=>t[i],enumerable:!(r=ar(t,i))||r.enumerable});return e},ur=(e,t,n)=>(lr(e,t,`default`),n&&lr(n,t,`default`)),dr=class extends Error{name=`AbortError`};function N(e,t=`Assertion failed`){if(!e)throw Error(t)}function P(e){mr(e,`string`)}function fr(e){mr(e,`number`)}function pr(e){mr(e,`boolean`)}function mr(e,t){typeof e!==t&&_r(e,t)}function F(e){e===null&&_r(e,`object`),mr(e,`object`)}function hr(e){Array.isArray(e)||_r(e,`array`)}function gr(e,t){let n=`Invalid type: `;return n+=e==null?e:`${typeof e} \`${e}\``,n+`, expected ${t}`}function _r(e,t){throw Error(gr(e,t))}function vr(e){if(e===null)throw Error(`Expected non-null value`)}function yr(e,t=`Expected non undefined value`){if(e===void 0)throw Error(t)}function br(e){throw Error(`Unreachable`)}function xr(){return typeof document<`u`?document:void 0}function Sr(e,t,n){return e?new Cr(e,t,n):new Er}var Cr=class{#e;#t;#n=0;visibilityState;#r=new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.visibilityState=e.visibilityState,this.#e.addEventListener(`visibilitychange`,this.#i,{signal:n})}#i=()=>{this.#e.visibilityState===`visible`?(clearTimeout(this.#n),this.#a(`visible`)):this.#n=setTimeout(()=>{this.#a(`hidden`)},this.#t)};#a(e){if(e!==this.visibilityState){this.visibilityState=e;for(let t of this.#r){let{resolve:n,state:r}=t;r===e&&(n(),this.#r.delete(t))}}}waitForVisible(){return this.#o(`visible`)}waitForHidden(){return this.#o(`hidden`)}#o(e){if(this.visibilityState===e)return Promise.resolve();let{promise:t,resolve:n}=Wt();return this.#r.add({resolve:n,state:e}),t}},wr=Promise.resolve(),Tr=new Promise(()=>{}),Er=class{visibilityState=`visible`;waitForVisible(){return wr}waitForHidden(){return Tr}},Dr=class{rep;invokeSend;maxConnections=1;constructor(e,t){this.rep=e,this.invokeSend=t}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},Or=class extends Dr{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},kr=class extends Dr{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},Ar=Promise.resolve();new Promise(()=>{});function jr(e,t){return e===0?Ar:new Promise((n,r)=>{let i;t&&(i=()=>{clearTimeout(a),r(new dr(`Aborted`))},t.addEventListener(`abort`,i,{once:!0}));let a=setTimeout(()=>{n(),t?.removeEventListener(`abort`,i)},e)})}var Mr=30,Nr=6e4,Pr=class{#e=Wt();#t=Wt();#n=Wt();#r;#i=!1;#a=0;#o;#s;constructor(e,t,n){this.#o=e,this.#r=t,this.#s=n,this.run()}close(){this.#i=!0,this.#a>0&&this.#n.resolve({error:Ir()})}async send(e){if(this.#i)return{error:Ir()};this.#a++,this.#o.debug?.(`send`,e),e?this.#t.resolve():await this.#s?.waitForVisible(),this.#e.resolve();let t=await this.#n.promise;return this.#a--,t}async run(){let e=[],t=Wt(),n,r=0,i=this.#r,{debug:a}=this.#o,o=0;a?.(`Starting connection loop`);let s=e=>Promise.race([this.#t.promise,jr(e)]);for(;!this.#i;){a?.(zr(e)?`Last request failed. Trying again`:`Waiting for a send`);let c=[this.#e.promise],l=i.watchdogTimer;if(l!==null&&c.push(jr(l)),await Promise.race(c),this.#i||(a?.(`Waiting for debounce`),await s(i.debounceDelay),this.#i))break;if(a?.(`debounced`),this.#e=Wt(),r>=i.maxConnections){if(a?.(`Too many request in flight. Waiting until one finishes...`),await this.#u(),this.#i)break;a?.(`...finished`)}r>0||zr(e)?(o=Lr(o,i,e),a?.(zr(e)?`Last connection errored. Sleeping for`:`More than one outstanding connection (`+r+`). Sleeping for`,o,`ms`)):o=0;let u=Math.min(i.maxDelayMs,Math.max(i.minDelayMs,o));if(n!==void 0){let e=Date.now()-n;if(u>e&&(await Promise.race([s(u-e),t.promise]),this.#i))break}r++,(async()=>{let o=Date.now(),s,c;try{n=o,a?.(`Sending request`),this.#t=Wt(),s=await i.invokeSend(),a?.(`Send returned`,s)}catch(e){a?.(`Send failed`,e),c=e,s=!1}if(this.#i){a?.(`Closed after invokeSend`);return}a?.(`Request done`,{duration:Date.now()-o,ok:s}),e.push({duration:Date.now()-o,ok:s}),Br(e)&&(t.resolve(),t=Wt()),r--,this.#l();let l=this.#n;this.#n=Wt(),c?l.resolve({error:c}):l.resolve(void 0),s||this.#e.resolve()})()}}#c=void 0;#l(){if(this.#c){let e=this.#c;this.#c=void 0,e()}}#u(){let{promise:e,resolve:t}=Wt();return this.#c=t,e}},Fr=9;function Ir(){return Error(`Closed`)}function Lr(e,t,n){let{length:r}=n;if(r===0)return e;let{ok:i}=n[n.length-1],{maxConnections:a,minDelayMs:o}=t;if(!i)return e===0?o:e*2;if(r>1){let e=n[n.length-2];for(;n.length>Fr;)n.shift();if(i&&!e.ok)return o}return Rr(n.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}function Rr(e){e.sort();let{length:t}=e,n=t>>1;return t%2==1?e[n]:(e[n-1]+e[n])/2}function zr(e){return e.length>0&&!e[e.length-1].ok}function Br(e){return e.length>1&&!e[e.length-2].ok&&e[e.length-1].ok}var Vr=process.env.NODE_ENV===`production`,Hr=Object.prototype.hasOwnProperty,Ur=Object.hasOwn||((e,t)=>Hr.call(e,t));function Wr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;switch(typeof e){case`boolean`:case`number`:case`string`:return!1}if(e=e,Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Wr(e[n],t[n]))return!1;return!0}if(e===null||t===null||Array.isArray(t))return!1;e=e,t=t;let n=0;for(let r in e)if(Ur(e,r)){if(!Wr(e[r],t[r]))return!1;n++}let r=0;for(let e in t)Ur(t,e)&&r++;return n===r}function Gr(e){if(!Vr){switch(typeof e){case`boolean`:case`number`:case`string`:return;case`object`:return e===null?void 0:Array.isArray(e)?Jr(e):qr(e)}_r(e,`JSON value`)}}function Kr(e){F(e),qr(e)}function qr(e){for(let t in e)if(Ur(e,t)){let n=e[t];n!==void 0&&Gr(n)}}function Jr(e){for(let t of e)Gr(t)}function Yr(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:return e===null?!0:Array.isArray(e)?Qr(e,t):Zr(e,t)}return!1}function Xr(e,t){return typeof e!=`object`||!e?!1:Zr(e,t)}function Zr(e,t){for(let n in e)if(Ur(e,n)){t.push(n);let r=e[n];if(r!==void 0&&!Yr(r,t))return!1;t.pop()}return!0}function Qr(e,t){for(let n=0;n<e.length;n++){if(t.push(n),!Yr(e[n],t))return!1;t.pop()}return!0}function $r(e,t){return e===t?0:e<t?-1:1}function ei(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;let n=ti(e),r=ti(t);return typeof n==`string`||typeof r==`string`?$r(String(n),String(r)):n-r}function ti(e){return typeof e==`string`||typeof e==`number`?e:e.order}function ni(e){if(e!==null&&typeof e!=`string`&&typeof e!=`number`&&(Kr(e),typeof e.order!=`string`&&typeof e.order!=`number`))throw Error(`Invalid cookie`)}function*ri(...e){for(let t of e)yield*t}var ii=Promise.resolve(!0),ai=Promise.resolve(!1);Promise.resolve(void 0);var oi=Promise.resolve(),si=1,ci=4,li=5,ui=8;function di(e){switch(typeof e){case`string`:return si+ci+e.length;case`number`:return fi(e)?e<=-(2**30)||e>=2**30-1?si+li:si+ci:si+ui;case`boolean`:return si;case`object`:if(e===null)return si;if(Array.isArray(e)){let t=2*si+ci;for(let n of e)t+=di(n);return t}{let t=e,n=2*si+ci;for(let e in t)if(Ur(t,e)){let r=t[e];r!==void 0&&(n+=di(e)+di(r))}return n}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function fi(e){return e===(e|0)}var pi=2*si+ci+si+ci;function mi(e,t){return pi+di(e)+di(t)}var hi=new WeakSet;function gi(e){return Vr||_i(e,[]),e}function _i(e,t){switch(typeof e){case`undefined`:throw TypeError(`Unexpected value undefined`);case`boolean`:case`number`:case`string`:return;case`object`:if(e===null||hi.has(e))return;hi.add(e),t.includes(e)&&_r(e,`Cyclic JSON object`),t.push(e),Object.freeze(e),Array.isArray(e)?vi(e,t):yi(e,t),t.pop();return;default:_r(e,`JSON value`)}}function vi(e,t){for(let n of e)_i(n,t)}function yi(e,t){for(let n in e)if(Ur(e,n)){let r=e[n];r!==void 0&&_i(r,t)}}function bi(e){if(!Vr&&!xi(e,[]))throw Error(`Expected frozen object`)}function xi(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:if(e===null||hi.has(e))return!0;if(!Object.isFrozen(e))return!1;if(t.includes(e)&&_r(e,`Cyclic JSON object`),t.push(e),Array.isArray(e)){for(let n of e)if(!xi(n,t))return t.pop(),!1}else for(let n in e)if(Ur(e,n)){let r=e[n];if(r!==void 0&&!xi(r,t))return t.pop(),!1}return hi.add(e),t.pop(),!0;default:_r(e,`JSON value`)}}function Si(e){if(e!==void 0)return gi(e)}function Ci(e){if(Array.isArray(e)){e.sort();for(let t=1;t<e.length;t++)N(e[t-1]!==e[t],`Refs must not have duplicates`);return e}let t=[...e];return t.sort(),t}var wi=class{hash;data;meta;constructor(e,t,n){N(!n.includes(e),`Chunk cannot reference itself`),bi(t),this.hash=e,this.data=t,this.meta=n}};function Ti(e){if(!Array.isArray(e))throw Error(`Refs must be an array`);if(e.length>0){P(e[0]);for(let t=1;t<e.length;t++)P(e[t])}}function Ei(e,t,n){return new wi(n(),e,t)}function Di(){throw Error(`unexpected call to compute chunk hash`)}function Oi(){let e=Math.floor(Math.random()*4294967295),t=Math.floor(Math.random()*4294967295);return BigInt(e)<<32n|BigInt(t)}var I={};cr(I,{assert:()=>Fi,is:()=>Pi,parse:()=>Ni,readonly:()=>Li,readonlyArray:()=>zi,readonlyObject:()=>Ri,readonlyRecord:()=>Bi,test:()=>Ii}),ur(I,Jt);function ki(e){switch(typeof e){case`string`:case`number`:case`boolean`:return JSON.stringify(e);case`undefined`:return`undefined`;case`bigint`:return e.toString()+`n`;default:return e===null?`null`:Array.isArray(e)?`array`:typeof e}}function Ai(e,t){if(!t?.length)return ki(e);let n=e;for(let e of t)n=n[e];return ki(n)}function ji(e,t,n=e=>String(e)){if(t.length===1)return n(t[0]);let r=`${n(t[t.length-2])} ${e} ${n(t[t.length-1])}`;return t.length===2?r:`${t.slice(0,-2).map(n).join(`, `)}, ${r}`}function Mi(e,t){let n=e.issues[0],{path:r}=n,i=r?.length?` at ${r.join(`.`)}`:``;switch(n.code){case`invalid_type`:return`Expected ${ji(`or`,n.expected)}${i}. Got ${Ai(t,r)}`;case`missing_value`:{let e=r&&r.length>1?` at ${r.slice(0,-1).join(`.`)}`:``;return n.path?.length?`Missing property ${n.path.at(-1)}${e}`:`TODO Unknown missing property${e}`}case`invalid_literal`:return`Expected literal value ${ji(`or`,n.expected,ki)}${i} Got ${Ai(t,r)}`;case`invalid_length`:return`Expected array with length ${n.minLength===n.maxLength?n.minLength:`between ${n.minLength} and ${n.maxLength}`}${i}. Got array with length ${t.length}`;case`unrecognized_keys`:return n.keys.length===1?`Unexpected property ${n.keys[0]}${i}`:`Unexpected properties ${ji(`and`,n.keys)}${i}`;case`invalid_union`:return`Invalid union value${i}`;case`custom_error`:{let{error:e}=n;return`${e?typeof e==`string`?e:e.message??`unknown`:`unknown`}${i}. Got ${Ai(t,r)}`}}}function Ni(e,t,n){let r=Ii(e,t,n);if(!r.ok)throw TypeError(r.error);return r.value}function Pi(e,t,n){return Ii(e,t,n).ok}function Fi(e,t,n){Ni(e,t,n)}function Ii(e,t,n){let r=t.try(e,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:Mi(r,e)}}function Li(e){return e}function Ri(e){return Qn(e)}function zi(e){return er(e)}function Bi(e){return $n(e)}var Vi=22,Hi=/^[0-9a-v-]+$/,Ui=`0`.repeat(Vi),Wi=Ki();function Gi(e,t){return e.toString(32).slice(-t).padStart(t,`0`)}function Ki(){let e=``,t=0;return()=>{e||=Gi(Oi(),12);let n=Gi(t++,10);return e+n}}function qi(e){return typeof e==`string`&&Hi.test(e)}function Ji(e){Fi(e,Yi)}var Yi=I.string().assert(qi,`Invalid hash`);function Xi(e,t,n){return new Zi(e,t,n).compute()}var Zi=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e,t,n){let r=[],i=[];for(let t of e)t.old!==t.new&&(t.old&&i.push(t.old),t.new&&r.push(t.new));this.#e=r,this.#t=i,this.#n=t,this.#r=n,this.#a=new Map,this.#o=new Map,this.#s=n.areRefsCounted!==void 0,this.#i=this.#s?new Set:null}async compute(){for(let e of this.#e)await this.#c(e,1);if(await Promise.all(Array.from(this.#n.values(),e=>this.#u(e))),this.#s){N(this.#r.areRefsCounted),N(this.#i);let e;do{e=!1;for(let t of this.#n.values())if(!this.#r.areRefsCounted(t)&&!this.#i.has(t)&&this.#a.get(t)!==0){await this.#l(t,1),e=!0;break}}while(e)}for(let e of this.#t)await this.#c(e,-1);if(!Vr)for(let[e,t]of this.#a)N(t>=0,`ref count update must be non-negative. ${e}:${t}`);return this.#a}async#c(e,t){await this.#u(e),this.#d(e,t)&&await this.#l(e,t)}async#l(e,t){if(e===Ui)return;let n=await this.#r.getRefs(e);if(Vr||N(n||this.#s&&!this.#n.has(e),`refs must be defined`),n!==void 0){this.#i?.add(e);let r=n.map(e=>this.#c(e,t));await Promise.all(r)}}#u(e){let t=this.#o.get(e);return t===void 0&&(t=(async()=>{let t=await this.#r.getRefCount(e)||0;return this.#a.set(e,t),t})(),this.#o.set(e,t)),t}#d(e,t){let n=this.#a.get(e);return fr(n),this.#a.set(e,n+t),n===0&&t===1||n===1&&t===-1}},Qi=class extends Error{name=`ChunkNotFoundError`;hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function $i(e,t){let n=await e.getChunk(t);if(n)return n;throw new Qi(t)}async function ea(e,t){let n=await t.getHead(e);return N(n,`Missing head ${e}`),n}var ta=class{#e=new Kt;#t=new Map;#n;#r;#i;t=new Map;n;h=new Map;m=new Map;constructor(e,t,n,r,i=di){this.n=new ia(t,i,this.h,this.m),this.#n=e,this.#r=n,this.#i=r}async read(){let e=await this.#e.read();return new na(this.#t,this.t,this.n,this.#n,e,this.#i)}async write(){let e=await this.#e.write();return new ra(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#i)}close(){return oi}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},na=class{a;t;n;f;#e=void 0;#t;#n=!1;assertValidHash;constructor(e,t,n,r,i,a){this.a=e,this.t=t,this.n=n,this.f=r,this.#t=i,this.assertValidHash=a}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let t=this.t.get(e);if(t!==void 0)return t;let n=this.n.get(e);return n===void 0&&(n=await(await this.y()).getChunk(e),n!==void 0&&this.n.put(n)),n}mustGetChunk(e){return $i(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#n||=(this.#t(),this.#e?.then(e=>e.release()).catch(e=>{}),!0)}get closed(){return this.#n}y(){return this.#e||=this.f.read(),this.#e}},ra=class extends na{#e;#t;#n;i=new Map;o=new Map;s=new Map;#r=new Set;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,o,c),this.#e=i,this.#t=a,this.#n=s}createChunk=(e,t)=>{let n=Ei(e,t,this.#n);return this.#r.add(n.hash),n};putChunk(e,t){let{hash:n,meta:r}=e;if(this.assertValidHash(n),r.length>0)for(let e of r)this.assertValidHash(e);return this.#r.has(n)||this.isMemOnlyChunkHash(n)?this.o.set(n,e):this.s.set(n,{chunk:e,size:t??-1}),oi}async setHead(e,t){await this.#i(e,t)}async removeHead(e){await this.#i(e,void 0)}async#i(e,t){let n=await this.getHead(e),r=this.i.get(e);r===void 0?this.i.set(e,{new:t,old:n}):r.new=t}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let t=this.o.get(e);if(t!==void 0)return t;let n=this.t.get(e);if(n!==void 0)return n;let r=this.s.get(e);if(r!==void 0)return r.chunk;let i=this.n.get(e);return i===void 0&&(i=await(await this.y()).getChunk(e),i!==void 0&&this.s.set(i.hash,{chunk:i,size:-1})),i}getHead(e){let t=this.i.get(e);return t?Promise.resolve(t.new):super.getHead(e)}async commit(){let e=new Set(ri(this.o.keys(),this.s.keys())),t=await Xi(this.i.values(),e,this);for(let[e,n]of t)if(this.isMemOnlyChunkHash(e)){if(n===0)this.#e.delete(e),this.t.delete(e),this.#t.delete(e);else{this.#e.set(e,n);let t=this.o.get(e);t&&(this.#t.set(e,t.meta),this.t.set(e,t))}t.delete(e)}this.n.updateForCommit(this.s,t);for(let[e,t]of this.i)t.new?this.a.set(e,t.new):this.a.delete(e);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#e.get(e)}getRefs(e){let t=this.o.get(e);if(t)return t.meta;let n=this.t.get(e);if(n)return n.meta;let r=this.s.get(e);return r===void 0?this.#t.get(e):r.chunk.meta}areRefsCounted(e){return this.#t.has(e)}chunksPersisted(e){let t=[];for(let n of e){let e=this.t.get(n);e&&(this.t.delete(n),t.push(e))}this.n.persisted(t)}},ia=class{#e;#t;#n;#r;#i=0;#a=!1;#o=[];cacheEntries=new Map;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}get(e){let t=this.cacheEntries.get(e);return t&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,t)),t?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:t}=e,n=this.cacheEntries.get(t);if(n){this.cacheEntries.delete(t),this.cacheEntries.set(t,n);return}let r=this.#n.get(t);if(!(r===void 0||r<1)&&this.#c(e)){if(!this.#r.has(t)){for(let t of e.meta)this.#n.set(t,(this.#n.get(t)||0)+1);this.#r.set(t,e.meta)}this.#s()}}#s(){if(!this.#a)for(let e of this.cacheEntries.values()){if(this.#i<=this.#e)break;this.#l(e)}}#c(e,t){let n=t??this.#t(e);return n>this.#e?!1:(this.#i+=n,this.cacheEntries.set(e.hash,{chunk:e,size:n}),!0)}#l(e){let{hash:t}=e.chunk;this.#i-=e.size,this.cacheEntries.delete(t)}#u(e){this.#n.delete(e),this.#r.delete(e);let t=this.cacheEntries.get(e);t&&(this.#i-=t.size,this.cacheEntries.delete(e))}updateForCommit(e,t){for(let[n,r]of t)if(r===0)this.#a?(this.#n.set(n,0),this.#o.push(n)):this.#u(n);else{this.#n.set(n,r);let t=e.get(n);if(t){let{chunk:e,size:r}=t,i=this.cacheEntries.get(n);i?(this.cacheEntries.delete(n),this.cacheEntries.set(n,i)):(this.#c(e,r===-1?void 0:r),this.#r.set(n,e.meta))}}this.#s()}persisted(e){for(let t of e)this.#c(t);this.#s()}async withSuspendedEvictsAndDeletes(e){this.#a=!0;try{return await e()}finally{this.#a=!1;for(let e of this.#o)this.#n.get(e)===0&&this.#u(e);this.#s()}}};function aa(e){return`c/${e}/d`}function oa(e){return`c/${e}/m`}function sa(e){return`c/${e}/r`}function ca(e){return`h/${e}`}var la=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){return new ua(await this.#e.read(),this.#n)}async write(){return new da(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},ua=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(aa(e))}async getChunk(e){let t=await this.e.get(aa(e));if(t===void 0)return;let n=await this.e.get(oa(e)),r;return n===void 0?r=[]:(Ti(n),r=n),new wi(e,t,r)}mustGetChunk(e){return $i(this,e)}async getHead(e){let t=await this.e.get(ca(e));if(t!==void 0)return Ji(t),t}release(){this.e.release()}get closed(){return this.e.closed}},da=class extends ua{#e;#t=new Set;#n=new Map;constructor(e,t,n){super(e,n),this.#e=t}createChunk=(e,t)=>Ei(e,t,this.#e);get kvWrite(){return this.e}async putChunk(e){let{hash:t,data:n,meta:r}=e;this.assertValidHash(t);let i=aa(t),a=this.e.put(i,n),o;if(r.length>0){for(let e of r)this.assertValidHash(e);o=this.e.put(oa(t),r)}this.#t.add(t),await a,await o}setHead(e,t){return this.#r(e,t)}removeHead(e){return this.#r(e,void 0)}async#r(e,t){let n=await this.getHead(e),r=ca(e),i;i=t===void 0?this.e.del(r):this.e.put(r,t);let a=this.#n.get(e);a===void 0?this.#n.set(e,{new:t,old:n}):a.new=t,await i}async commit(){let e=await Xi(this.#n.values(),this.#t,this);await this.#i(e),await this.e.commit()}async getRefCount(e){let t=await this.e.get(sa(e));if(t!==void 0){if(fr(t),t<0||t>65535||t!==(t|0))throw Error(`Invalid ref count ${t}. We expect the value to be a Uint16`);return t}}async getRefs(e){let t=await this.e.get(oa(e));return t===void 0?[]:(Ti(t),t)}async#i(e){let t=[];for(let[n,r]of e)if(r===0)t.push(this.#a(n));else{let e=sa(n);t.push(this.e.put(e,r))}await Promise.all(t)}async#a(e){await Promise.all([this.e.del(aa(e)),this.e.del(oa(e)),this.e.del(sa(e))]),this.#t.delete(e)}release(){this.e.release()}},L=`main`;function fa(e){return Ia(e.meta)}function pa(e){return Fa(e.meta)}function ma(e){return pa(e)||fa(e)}function ha(e){return Ha(e.meta)}function ga(e){return Ua(e.meta)}function _a(e){return ha(e)||ga(e)}var va=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,t){return ya(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function ya(e,t,n){switch(n.type){case 1:return n.lastMutationID;case 3:return n.lastMutationID;case 5:return n.lastMutationIDs[e]??0;case 2:return n.mutationID;case 4:{if(n.clientID===e)return n.mutationID;let{basisHash:r}=n;return ya(e,t,(await Aa(r,t)).meta)}default:br(n)}}async function ba(e,t){return(await ka(e,t)).filter(e=>ma(e))}async function xa(e,t){return(await ka(e,t)).filter(e=>pa(e))}async function Sa(e,t,n){let r=[],i=new Map(Object.entries(t));for(;!_a(e)&&i.size>0;){if(pa(e)){let{meta:t}=e,n=i.get(t.clientID);n!==void 0&&(t.mutationID<=n?i.delete(t.clientID):r.push(e))}let{basisHash:t}=e.meta;if(t===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await Aa(t,n)}return r}async function Ca(e,t){let n=await t.getHead(e);return N(n,`Missing head ${e}`),Ta(n,t)}async function wa(e,t){return(await Ta(e,t)).chunk.hash}async function Ta(e,t){return Ea(await Aa(e,t),t)}async function Ea(e,t){for(;!_a(e);){let{meta:n}=e;if(Fa(n))e=await Aa(n.baseSnapshotHash,t);else{let{basisHash:r}=n;if(r===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await Aa(r,t)}}return e}function Da(e,t){let n=e.meta;return Ha(n)?[n.lastMutationIDs[t]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function Oa(e,t){return ei(e.meta.cookieJSON,t.meta.cookieJSON)}async function ka(e,t){let n=await Aa(e,t),r=[];for(;!_a(n);){let{meta:e}=n,{basisHash:i}=e;if(i===null)throw Error(`Commit ${n.chunk.hash} has no basis`);r.push(n),n=await Aa(i,t)}return r.push(n),r}async function Aa(e,t){return ro(await t.mustGetChunk(e))}async function ja(e,t){return Aa(await ea(e,t),t)}function Ma(e){fr(e.lastMutationID)}function Na(e){if(fr(e.mutationID),P(e.mutatorName),!e.mutatorName)throw Error(`Missing mutator name`);Gr(e.mutatorArgsJSON),e.originalHash!==null&&Ji(e.originalHash),fr(e.timestamp)}function Pa(e){P(e.clientID),Na(e)}function Fa(e){return e.type===4}function Ia(e){return e.type===2}function La(e){e.basisHash!==null&&Ji(e.basisHash),Gr(e.cookieJSON)}function Ra(e){La(e),fr(e.lastMutationID)}function za(e){La(e),Ba(e.lastMutationIDs)}function Ba(e){F(e);for(let t of Object.values(e))fr(t)}function Va(e){za(e.meta)}function Ha(e){return e.type===5}function Ua(e){return e.type===3}function Wa(e){switch(F(e),bi(e),e.basisHash!==null&&P(e.basisHash),fr(e.type),e.type){case 1:Ma(e);break;case 2:Na(e);break;case 4:Pa(e);break;case 3:Ra(e);break;case 5:za(e);break;default:throw Error(`Invalid enum value ${e.type}`)}}function Ga(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&e.keyPrefix===t.keyPrefix}function Ka(e){F(e),bi(e),P(e.name),P(e.keyPrefix),P(e.jsonPointer),e.allowEmpty!==void 0&&pr(e.allowEmpty)}function qa(e,t){return{name:e,keyPrefix:t.prefix??``,jsonPointer:t.jsonPointer,allowEmpty:t.allowEmpty??!1}}function Ja(e){F(e),bi(e),Ka(e.definition),P(e.valueHash)}function Ya(e){hr(e),bi(e);for(let t of e)Ja(t)}function Xa(e,t,n,r,i,a,o,s,c){return io(e,oo({type:2,basisHash:t,mutationID:n,mutatorName:r,mutatorArgsJSON:i,originalHash:a,timestamp:c},o,s))}function Za(e,t,n,r,i,a,o,s,c,l,u){return io(e,oo({type:4,basisHash:t,baseSnapshotHash:n,mutationID:r,mutatorName:i,mutatorArgsJSON:a,originalHash:o,timestamp:l,clientID:u},s,c))}function Qa(e,t,n,r,i,a){return io(e,eo(t,n,r,i,a))}function $a(e,t,n,r,i,a){return io(e,to(t,n,r,i,a))}function eo(e,t,n,r,i){return oo({type:3,basisHash:e,lastMutationID:t,cookieJSON:n},r,i)}function to(e,t,n,r,i){return oo({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:n},r,i)}function no(e,t,n,r,i){return io(e,oo({type:1,basisHash:t,lastMutationID:n},r,i))}function ro(e){return co(e),new va(e)}function io(e,t){return new va(e(t,ao(t)))}function ao(e){let t=new Set;t.add(e.valueHash);let{meta:n}=e;switch(n.type){case 1:n.basisHash&&t.add(n.basisHash);break;case 2:case 4:n.basisHash&&t.add(n.basisHash);break;case 3:case 5:break;default:br(n)}for(let n of e.indexes)t.add(n.valueHash);return Ci(t)}function oo(e,t,n){return gi({meta:e,valueHash:t,indexes:n})}function so(e){Vr||(F(e),bi(e),Wa(e.meta),P(e.valueHash),Ya(e.indexes))}function co(e){let{data:t}=e;so(t);let n=new Set;for(let e of t.indexes){let{name:t}=e.definition;if(n.has(t))throw Error(`Duplicate index ${t}`);n.add(t)}}function lo(e,t){let n=e.length,r=t.length,i=Math.min(n,r);for(let n=0;n<i;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i)return r<128&&i<128?r-i:uo(mo,go(r,mo),ho,go(i,ho));n+=fo(r)}return n-r}function uo(e,t,n,r){let i=Math.min(t,r);for(let t=0;t<i;t++){let r=e[t],i=n[t];if(r!==i)return r-i}return t-r}function fo(e){return e>65535?2:1}var po=()=>Array.from({length:4},()=>0),mo=po(),ho=po();function go(e,t){if(e<128)return t[0]=e,1;let n,r;if(e<=2047)n=1,r=192;else if(e<=65535)n=2,r=224;else if(e<=1114111)n=3,r=240;else throw Error(`Invalid code point`);t[0]=(e>>6*n)+r;let i=1;for(;n>0;n--){let r=e>>6*(n-1);t[i++]=128|r&63}return i}function _o(e,t){return lo(e,t)>0}function vo(e,t){return lo(e,t)<0}function yo(e,t){return lo(e,t)<=0}function bo(e,t){let n=0;for(;n<e;){let r=n+(e-n>>1),i=t(r);if(i===0)return r;i>0?n=r+1:e=r}return n}function xo(e){if(e!==(e|0)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}var So=0,Co=1;function wo(e,t,n){return gi([e,n>=7?t:t.map(e=>e.slice(0,2))])}async function To(e,t,n,r){let i=await n.getNode(t);if(r!==n.rootHash)return To(e,n.rootHash,n,n.rootHash);if(Lo(i))return i;let{entries:a}=i,o=Eo(e,a);o===a.length&&o--;let s=a[o];return To(e,s[1],n,r)}function Eo(e,t){return bo(t.length,n=>lo(e,t[n][0]))}function Do(e,t,n){return e!==t.length&&t[e][0]===n}function Oo(e,t,n){if(Vr&&t>=7)return e;hr(e),bi(e),N(e.length>=2);let[r,i]=e;fr(r),hr(i);let a=r>0?P:Gr;if(t>=7){for(let e of i)ko(e,a);return e}return[r,i.map(e=>Ao(e,a,n))]}function ko(e,t){hr(e),N(e.length>=3),P(e[0]),t(e[1]),fr(e[2])}function Ao(e,t,n){hr(e),N(e.length>=2),P(e[0]),t(e[1]);let r=n(e[0],e[1]);return[e[0],e[1],r]}var jo=class{entries;hash;isMutable;#e=-1;constructor(e,t,n){this.entries=e,this.hash=t,this.isMutable=n}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(this.#e!==-1)return this.#e;let t=e.chunkHeaderSize;for(let e of this.entries)t+=e[2];return this.#e=t}c(e){this.#e=-1,e.updateNode(this)}};function Mo(e,t){return wo(e.level,e.entries,t)}var No=class extends jo{level=0;set(e,t,n,r){let i,a=Eo(e,this.entries);return i=+!!Do(a,this.entries,e),Promise.resolve(this.#e(r,a,i,[e,t,n]))}#e(e,t,n,...r){if(this.isMutable)return this.entries.splice(t,n,...r),this.c(e),this;let i=Po(this.entries,t,n,...r);return e.newDataNodeImpl(i)}del(e,t){let n=Eo(e,this.entries);return Do(n,this.entries,e)?Promise.resolve(this.#e(t,n,1)):Promise.resolve(this)}async*keys(e){for(let e of this.entries)yield e[0]}async*entriesIter(e){for(let e of this.entries)yield e}};function Po(e,t,n,...r){let i=e.slice(0,t);for(let e=0;e<r.length;e++)i.push(r[e]);for(let r=t+n;r<e.length;r++)i.push(e[r]);return i}var Fo=class e extends jo{level;constructor(e,t,n,r){super(e,t,r),this.level=n}async set(e,t,n,r){let i=Eo(e,this.entries);i===this.entries.length&&i--;let a=this.entries[i][1],o=await(await r.getNode(a)).set(e,t,n,r),s=o.getChildNodeSize(r);if(s>r.maxSize||s<r.minSize)return this.#e(r,i,o);let c=Vo(o,r.getEntrySize);return this.#t(r,i,c)}async#e(e,t,n){let r=this.level-1,i=this.entries,a,o,s;if(t>0){let r=i[t-1][1];a=ri((await e.getNode(r)).entries,n.entries),o=t-1,s=2}else if(t<i.length-1){let r=i[t+1][1],c=await e.getNode(r);a=ri(n.entries,c.entries),o=t,s=2}else a=n.entries,o=t,s=1;let c=Ro(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),l=[];for(let t of c){let n=Vo(e.newNodeImpl(t,r),e.getEntrySize);l.push(n)}if(this.isMutable)return this.entries.splice(o,s,...l),this.c(e),this;let u=Po(i,o,s,...l);return e.newInternalNodeImpl(u,this.level)}#t(e,t,n){if(this.isMutable)return this.entries.splice(t,1,n),this.c(e),this;let r=Po(this.entries,t,1,n);return e.newInternalNodeImpl(r,this.level)}async del(e,t){let n=Eo(e,this.entries);if(n===this.entries.length)return this;let r=this.entries[n][1],i=await t.getNode(r),a=i.hash,o=await i.del(e,t);if(o.hash===a)return this;if(o.entries.length===0){let e=Po(this.entries,n,1);return t.newInternalNodeImpl(e,this.level)}if(n===0&&this.entries.length===1)return o;if(o.getChildNodeSize(t)>t.minSize){let e=Vo(o,t.getEntrySize);return this.#t(t,n,e)}return this.#e(t,n,o)}async*keys(e){for(let t of this.entries)yield*(await e.getNode(t[1])).keys(e)}async*entriesIter(e){for(let t of this.entries)yield*(await e.getNode(t[1])).entriesIter(e)}getChildren(e,t,n){let r=[];for(let i=e;i<t&&i<this.entries.length;i++)r.push(n.getNode(this.entries[i][1]));return Promise.all(r)}async getCompositeChildren(t,n,r){let{level:i}=this;if(n===0)return new e([],Wi(),i-1,!0);let a=await this.getChildren(t,t+n,r);if(i>1){let t=[];for(let e of a)t.push(...e.entries);return new e(t,Wi(),i-1,!0)}N(i===1);let o=[];for(let e of a)o.push(...e.entries);return new No(o,Wi(),!0)}};function Io(e,t,n,r){return n===0?new No(e,t,r):new Fo(e,t,n,r)}function Lo(e){return e.level===0}function Ro(e,t,n,r){let i=[],a=[],o=0,s=[];for(let c of e){let e=t(c);e>=r?(s.length>0&&(i.push(s),a.push(o)),i.push([c]),a.push(e),o=0,s=[]):o+e>=n?(s.push(c),i.push(s),a.push(o+e),o=0,s=[]):(o+=e,s.push(c))}return o>0&&(a.length>0&&o+a[a.length-1]<=r?i[i.length-1].push(...s):i.push(s)),i}var zo=wo(0,[],7),Bo=new No([],Ui,!1);function Vo(e,t){let n=e.maxKey(),r=e.hash;return[n,r,t(n,r)]}var Ho=-1,Uo=0,Wo=1,Go=2,Ko=3,qo=0,Jo=1;function*Yo(e,t){let n=0,r=0,i;function a(e,t){e[Ko]===Ho&&(e[Ko]=t)}function o(){return[n,0,0,Ho]}for(;n<e.length&&r<t.length;)e[n][qo]===t[r][qo]?(Wr(e[n][Jo],t[r][Jo])?i&&=(a(i,0),yield i,void 0):(i||=o(),i[Go]++,i[Wo]++,a(i,r)),n++,r++):e[n][qo]<t[r][qo]?(i||=o(),i[Wo]++,n++):(i||=o(),i[Go]++,a(i,r),r++);r<t.length&&(i||=o(),i[Go]+=t.length-r,a(i,r)),n<e.length&&(i||=o(),i[Wo]+=e.length-n),i&&(a(i,0),yield i)}var Xo=11,Zo=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,n=Ui,r=mi,i=Xo){this.l=e,this.u=t,this.rootHash=n,this.getEntrySize=r,this.chunkHeaderSize=i}async getNode(e){if(e===Ui)return Bo;let t=this.p.get(e);if(t)return t;let n=Oo((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),r=Io(n[Co],e,n[So],!1);return this.p.set(e,r),r}async get(e){let t=await To(e,this.rootHash,this,this.rootHash),n=Eo(e,t.entries);if(Do(n,t.entries,e))return t.entries[n][1]}async has(e){let t=await To(e,this.rootHash,this,this.rootHash);return Do(Eo(e,t.entries),t.entries,e)}async isEmpty(){let{rootHash:e}=this,t=await this.getNode(this.rootHash);return this.rootHash===e?t.entries.length===0:this.isEmpty()}scan(e){return es(this.rootHash,()=>this.rootHash,this.rootHash,e,async e=>{let t=await this.getNode(e);return t?[t.level,t.isMutable?t.entries.slice():t.entries]:Oo((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize)})}async*keys(){yield*(await this.getNode(this.rootHash)).keys(this)}async*entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async*diff(e){let[t,n]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*Qo(n,t,e,this)}};async function*Qo(e,t,n,r){if(e.level>t.level){yield*Qo(await e.getCompositeChildren(0,e.entries.length,n),t,n,r);return}if(t.level>e.level){yield*Qo(e,await t.getCompositeChildren(0,t.entries.length,r),n,r);return}if(Lo(e)&&Lo(t)){yield*$o(e.entries,t.entries);return}let i=Yo(e.entries,t.entries);for(let a of i){let[i,o]=await Promise.all([e.getCompositeChildren(a[Uo],a[Wo],n),t.getCompositeChildren(a[Ko],a[Go],r)]);yield*Qo(i,o,n,r)}}function*$o(e,t){let n=e.length,r=t.length,i=0,a=0;for(;i<n&&a<r;){let n=e[i][0],r=t[a][0];n===r?(Wr(e[i][1],t[a][1])||(yield{op:`change`,key:n,oldValue:e[i][1],newValue:t[a][1]}),i++,a++):n<r?(yield{op:`del`,key:n,oldValue:e[i][1]},i++):(yield{op:`add`,key:r,newValue:t[a][1]},a++)}for(;i<n;i++)yield{op:`del`,key:e[i][0],oldValue:e[i][1]};for(;a<r;a++)yield{op:`add`,key:t[a][0],newValue:t[a][1]}}async function*es(e,t,n,r,i){if(n===Ui)return;let a=await i(n),o=a[Co],s=0;if(r&&(s=Eo(r,o)),a[So]>0)for(;s<o.length;s++)yield*es(e,t,o[s][1],r,i),r=``;else for(;s<o.length;s++){let n=t();if(e!==n){yield*es(n,t,n,o[s][0],i);return}yield o[s]}}async function ts(e,t){let n=[],r=t===`add`?e=>({op:`add`,key:e[0],newValue:e[1]}):e=>({op:`del`,key:e[0],oldValue:e[1]});for await(let t of e.entries())n.push(r(t));return n}var ns=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},rs=class extends ns{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function is(e,t,n,r,i,a,o){try{for(let e of as(r,i,a,o))switch(n){case 0:await t.put(e,i);break;case 1:await t.del(e)}}catch(t){e.info?.(`Not indexing value`,i,`:`,t)}}function as(e,t,n,r){let i=ds(t,n);if(i===void 0){if(r)return[];throw Error(`No value at path: ${n}`)}let a=Array.isArray(i)?i:[i],o=[];for(let t of a)if(typeof t==`string`)o.push(cs([t,e]));else throw Error(`Unsupported target type`);return o}var os=`\0`,ss=`\0`;function cs(e){let t=e[0],n=e[1];if(t.includes(`\0`))throw Error(`Secondary key cannot contain null byte`);return os+t+ss+n}function ls(e,t){let n=cs([e,t||``]);return t===void 0?n.slice(0,n.length-1):n}function us(e){if(e[0]!==os)throw Error(`Invalid version`);let t=os.length,n=ss.length,r=e.indexOf(ss,t);if(r===-1)throw Error(`Invalid formatting`);return[e.slice(t,r),e.slice(r+n)]}function ds(e,t){function n(e){if(!(e.startsWith(`+`)||e.startsWith(`0`)&&e.length!==1))return parseInt(e,10)}if(t===``)return e;if(!t.startsWith(`/`))throw Error(`Invalid JSON pointer: ${t}`);let r=t.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){let t;if(Array.isArray(i)){let r=n(e);if(r===void 0)return;t=i[r]}else{if(i===null)return;typeof i==`object`&&(i=i,t=i[e])}if(t===void 0)return;i=t}return i}var fs=class{#e;map;indexes;constructor(e,t,n){this.#e=e,this.map=t,this.indexes=n}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let t=this.indexes.get(e);if(t===void 0)throw Error(`Unknown index name: ${e}`);return t.map}get closed(){return this.#e.closed}close(){this.#e.release()}};function ps(e,t){return ms(L,e,t)}async function ms(e,t,n){return hs(await ja(e,t),t,n)}function hs(e,t,n){let r=gs(e,t,n);return new fs(t,new Zo(t,n,e.valueHash),r)}function gs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ns(i,new Zo(t,n,i.valueHash)));return r}async function _s(e){let t=[];for await(let n of e)t.push(n);return t}function vs(e){return e.indexName!==void 0}function ys(e){return typeof e==`string`?[e]:e}function bs(e){if(!e)return{};let t,n,r,i;return e.start&&({key:t,exclusive:n}=e.start,e.indexName?typeof t==`string`?i=t:(i=t[0],r=t[1]):r=t),{prefix:e.prefix,startSecondaryKey:i,startKey:r,startExclusive:n,limit:e.limit,indexName:e.indexName}}var xs=class extends Error{constructor(){super(`Transaction is closed`)}};function Ss(e){if(e.closed)throw new xs}function Cs(e){return e.closed?Promise.reject(new xs):void 0}var ws=class{#e;#t;#n;#r;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}[Symbol.asyncIterator](){return this.values()}values(){return new Ts(this.#i(e=>e[1]))}keys(){return new Ts(this.#i(e=>e[0]))}entries(){return new Ts(this.#i(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#i(e){return Es(e,this.#e,this.#t,this.#n,this.#r)}},Ts=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return _s(this.#e)}};async function*Es(e,t,n,r,i){Ss(r);let{limit:a=1/0}=n,{prefix:o=``}=n,s=n.start?.exclusive,c=vs(n);for await(let r of t){let t=r[0];if(!(c?t[0]:t).startsWith(o))return;if(s){if(s=!0,c){if(Ds(t,n.start.key))continue}else if(Os(t,n.start.key))continue}if(yield e(r),--a===0){c||i(t);return}}}function Ds(e,t){let[n,r]=ys(t),[i,a]=ys(e);return i===n?r===void 0||a===r:!1}function Os(e,t){return e===t}function ks(e){let{prefix:t,start:n}=e,r=``;if(t!==void 0&&(r=ls(t,void 0)),!n)return r;let{key:i}=n,[a,o]=ys(i),s=ls(a,o);return _o(s,r)?s:r}var As=0,js=class{clientID;dbtx;d;location;environment;constructor(e,t,n,r=`openReadTransaction`){this.clientID=e,this.dbtx=t,this.d=n.withContext(r).withContext(`txid`,As++),this.environment=`client`,this.location=`client`}get(e){return Cs(this.dbtx)||this.dbtx.get(e)}async has(e){return Ss(this.dbtx),this.dbtx.has(e)}async isEmpty(){return Ss(this.dbtx),this.dbtx.isEmpty()}scan(e){return Ns(e,this.dbtx,Ms)}};function Ms(e){}function Ns(e,t,n){return Rs(Is(t,e),e??{},t,n)}var Ps=class{#e=new Set;#t=[];#n;constructor(e){this.#n=e}get environment(){return this.#n.location}get location(){return this.#n.location}get clientID(){return this.#n.clientID}isEmpty(){return this.#t.push({options:{}}),this.#n.isEmpty()}get(e){return this.#e.add(e),this.#n.get(e)}has(e){return this.#e.add(e),this.#n.has(e)}scan(e){let t={options:bs(e),inclusiveLimitKey:void 0};return this.#t.push(t),Ns(e,this.#n.dbtx,e=>{t.inclusiveLimitKey=e})}get keys(){return this.#e}get scans(){return this.#t}},Fs=class extends js{reason;mutationID;constructor(e,t,n,r,i,a=`openWriteTransaction`){super(e,r,i,a),this.mutationID=t,this.reason=n}put(e,t){return this.set(e,t)}async set(e,t){Ss(this.dbtx),await this.dbtx.put(this.d,e,gi(t))}del(e){return Cs(this.dbtx)??this.dbtx.del(this.d,e)}};function Is(e,t){return t&&vs(t)?zs(e,t):e.map.scan(Ls(t))}function Ls(e){if(!e)return``;let{prefix:t=``,start:n}=e;return n&&_o(n.key,t)?n.key:t}function Rs(e,t,n,r){return new ws(e,t,n,r)}async function*zs(e,t){let n=e.getMapForIndex(t.indexName);for await(let e of n.scan(ks(t)))yield[us(e[0]),e[1]]}function Bs(e,t){return _s(t.diff(e))}var Vs=class extends Zo{#e=new Gt;#t=new Map;minSize;maxSize;constructor(e,t,n=Ui,r=8192,i=16384,a=mi,o){super(e,t,n,a,o),this.minSize=r,this.maxSize=i}#n(e){N(e.isMutable),this.#t.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){N(e.isMutable),this.#t.delete(e.hash),e.hash=Wi(),this.#n(e)}newInternalNodeImpl(e,t){let n=new Fo(e,Wi(),t,!0);return this.#n(n),n}newDataNodeImpl(e){let t=new No(e,Wi(),!0);return this.#n(t),t}newNodeImpl(e,t){let n=Io(e,Wi(),t,!0);return this.#n(n),n}put(e,t){return this.#e.withLock(async()=>{let n=await this.getNode(this.rootHash),r=this.getEntrySize(e,t),i=await n.set(e,t,r,this);if(i.getChildNodeSize(this)>this.maxSize){let e=this.chunkHeaderSize,t=Ro(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:n}=i,r=t.map(e=>Vo(this.newNodeImpl(e,n),this.getEntrySize)),a=this.newInternalNodeImpl(r,n+1);this.rootHash=a.hash;return}this.rootHash=i.hash})}del(e){return this.#e.withLock(async()=>{let t=await(await this.getNode(this.rootHash)).del(e,this),n=this.rootHash!==t.hash;return n&&(this.rootHash=t.level>0&&t.entries.length===1?t.entries[0][1]:t.hash),n})}clear(){return this.#e.withLock(()=>{this.#t.clear(),this.rootHash=Ui})}flush(){return this.#e.withLock(async()=>{let e=this.l;if(this.rootHash===Ui){let t=e.createChunk(zo,[]);return await e.putChunk(t),t.hash}let t=[],n=Hs(this.rootHash,t,e.createChunk,this.#t,this.u);return await Promise.all(t.map(t=>e.putChunk(t))),this.#t.clear(),this.rootHash=n,n})}};function Hs(e,t,n,r,i){let a=r.get(e);if(a===void 0)return e;if(Lo(a)){let e=n(Mo(a,i),[]);return t.push(e),e.hash}let o=[],{entries:s}=a;for(let e=0;e<s.length;e++){let a=s[e],c=a[1],l=Hs(c,t,n,r,i);l!==c&&(s[e]=[a[0],l,a[2]]),o.push(l)}let c=n(Mo(a,i),Ci(o));return t.push(c),c.hash}function Us(e){let t;return()=>(t===void 0&&(t=e()),t)}var Ws=class extends Map{set(e,t){return t.length===0?this:super.set(e,t)}};async function Gs(e,t,n,r,i){let a=new Ws;if(!r.shouldComputeDiffs())return a;let o=await Bs(new Zo(n,i,e.valueHash),new Zo(n,i,t.valueHash));return a.set(``,o),await Ks(e,t,n,a,r,i),a}async function Ks(e,t,n,r,i,a){let o=gs(e,n,a),s=gs(t,n,a);for(let[e,t]of o){if(!i.shouldComputeDiffsForIndex(e))continue;let n=s.get(e);if(n!==void 0){N(n!==t);let i=await Bs(t.map,n.map);s.delete(e),r.set(e,i)}else{let n=await ts(t.map,`del`);r.set(e,n)}}for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let n=await ts(t.map,`add`);r.set(e,n)}}var qs=class extends fs{#e;#t;#n;#r;#i;constructor(e,t,n,r,i,a,o){super(e,t,i),this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o,N(n===void 0?r.basisHash===Ui:r.basisHash===n.chunk.hash)}async put(e,t,n){if(this.#n.type===1)throw Error(`Not allowed`);let r=Us(()=>this.map.get(t));await Zs(e,this.indexes,t,r,n),await this.map.put(t,n)}getMutationID(){return ya(this.#r,this.#e,this.#n)}async del(e,t){if(this.#n.type===1)throw Error(`Not allowed`);let n=Us(()=>this.map.get(t));return n!==void 0&&await Zs(e,this.indexes,t,n,void 0),this.map.del(t)}async clear(){if(this.#n.type===1)throw Error(`Not allowed`);await this.map.clear();let e=[];for(let t of this.indexes.values())e.push(t.clear());await Promise.all(e)}async putCommit(){let e=await this.map.flush(),t=[];for(let e of this.indexes.values()){let n=await e.flush(),r={definition:e.meta.definition,valueHash:n};t.push(r)}let n,r=this.#n;switch(r.type){case 2:{let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Xa(this.#e.createChunk,i,a,o,s,c,e,t,l);break}case 4:{N(this.#i>=5);let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Za(this.#e.createChunk,i,await wa(i,this.#e),a,o,s,c,e,t,l,this.#r);break}case 3:{N(this.#i<=4);let{basisHash:i,lastMutationID:a,cookieJSON:o}=r;n=Qa(this.#e.createChunk,i,a,o,e,t);break}case 5:{N(this.#i>5);let{basisHash:i,lastMutationIDs:a,cookieJSON:o}=r;n=$a(this.#e.createChunk,i,a,o,e,t);break}case 1:{let{basisHash:i,lastMutationID:a}=r;if(this.#t!==void 0){if(await this.#t.getMutationID(this.#r,this.#e)!==a)throw Error(`Index change must not change mutationID`);if(this.#t.valueHash!==e)throw Error(`Index change must not change valueHash`)}n=no(this.#e.createChunk,i,a,e,t);break}}return await this.#e.putChunk(n.chunk),n}async commit(e){let t=(await this.putCommit()).chunk.hash;return await this.#e.setHead(e,t),await this.#e.commit(),t}async commitWithDiffs(e,t){let n=this.putCommit(),r=await this.#a(t),i=(await n).chunk.hash;return await this.#e.setHead(e,i),await this.#e.commit(),r}async#a(e){let t=new Ws;if(!e.shouldComputeDiffs())return t;let n=[];this.#t&&(n=await Bs(new Zo(this.#e,this.#i,this.#t.valueHash),this.map)),t.set(``,n);let r;r=this.#t?gs(this.#t,this.#e,this.#i):new Map;for(let[n,i]of this.indexes){if(!e.shouldComputeDiffsForIndex(n))continue;let a=r.get(n);N(i!==a);let o=await(a?Bs(a.map,i.map):ts(i.map,`add`));t.set(n,o)}for(let[n,i]of r)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await ts(i.map,`del`);t.set(n,e)}return t}close(){this.#e.release()}};async function Js(e,t,n,r,i,a,o,s){let c=await Aa(e,i),l=new Vs(i,s,c.valueHash),u=await c.getNextMutationID(o,i),d=Qs(c,i,s);return new qs(i,l,c,s>=5?{type:4,basisHash:e,baseSnapshotHash:await wa(e,i),mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a,clientID:o}:{type:2,basisHash:e,mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a},d,o,s)}async function Ys(e,t,n,r,i,a,o){N(o<=4);let s=await Aa(e,r);return new qs(r,new Vs(r,o,s.valueHash),s,{basisHash:e,type:3,lastMutationID:t,cookieJSON:n},i,a,o)}async function Xs(e,t,n,r,i,a){let o=await Aa(e,r);return new qs(r,new Vs(r,a,o.valueHash),o,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:n},Qs(o,r,a),i,a)}async function Zs(e,t,n,r,i){let a=[];for(let o of t.values()){let{keyPrefix:t}=o.meta.definition;if(!t||n.startsWith(t)){let t=await r();t!==void 0&&a.push(is(e,o.map,1,n,t,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1)),i!==void 0&&a.push(is(e,o.map,0,n,i,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function Qs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new rs(i,new Vs(t,n,i.valueHash)));return r}async function $s(e,t,n,r,i,a,o){let s=new Vs(t,o);for await(let t of n.scan(r)){let n=t[0];if(!n.startsWith(r))break;await is(e,s,0,n,t[1],i,a)}return s}async function ec(e,t,n,r,i,a,o){let s=e.meta,c=s.mutatorName;Fa(s)&&N(s.clientID===a,`mutationClientID must match clientID of LocalMeta`);let l=r[c];l||i.error?.(`Cannot rebase unknown mutator ${c}`);let u=l||(async()=>{}),d=s.mutatorArgsJSON,f=await(await Aa(n,t)).getNextMutationID(a,t);if(f!==s.mutationID)throw Error(`Inconsistent mutation ID: original: ${s.mutationID}, next: ${f} - mutationClientID: ${a} mutatorName: ${c}`);o>=5&&Pa(s);let p=await Js(n,c,d,e.chunk.hash,t,s.timestamp,a,o);return await u(new Fs(a,await p.getMutationID(),`rebase`,p,i),d),p}async function tc(e,t,n,r,i,a,o){return(await ec(e,t,n,r,i,a,o)).putCommit()}async function nc(e,t,n,r,i,a,o,s){return(await ec(e,t,n,i,a,o,s)).commit(r)}function rc(e,t){return typeof e==`object`&&!!e&&e.error===t}function ic(e){return typeof e.error==`string`}function ac(e){return rc(e,`ClientStateNotFound`)}function oc(e){if(!rc(e,`VersionNotSupported`))return!1;let{versionType:t}=e;switch(t){case void 0:case`pull`:case`push`:case`schema`:return!0}return!1}function sc(e){N(oc(e))}async function cc(e,t,n,r){let i={headers:{"Content-type":`application/json`,Authorization:t,"X-Replicache-RequestID":n},body:JSON.stringify(r),method:`POST`},a=new Request(e,i),o=await fetch(a),s=o.status;return s===200?[o,{httpStatusCode:s,errorMessage:``}]:[void 0,{httpStatusCode:s,errorMessage:await o.text()}]}function lc(e){F(e),fr(e.httpStatusCode),P(e.errorMessage)}function uc(e){hr(e);for(let t of e)dc(t)}function dc(e){switch(F(e),e.op){case`put`:P(e.key),Gr(e.value);break;case`update`:if(P(e.key),e.merge!==void 0&&Kr(e.merge),e.constrain!==void 0){hr(e.constrain);for(let t of e.constrain)P(t)}break;case`del`:P(e.key);break;case`clear`:break;default:throw Error(`unknown patch op \`${e.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}function fc(e){async function t(t,n){let[r,i]=await cc(e.pullURL,e.auth,n,t);return r?{response:await r.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return pc.add(t),t}var pc=new WeakSet;function mc(e){return pc.has(e)}function hc(e){if(F(e),ac(e)||oc(e))return;let t=e;t.cookie!==void 0&&Gr(t.cookie),fr(t.lastMutationID),uc(t.patch)}function gc(e){if(F(e),ac(e)||oc(e))return;let t=e;t.cookie!==void 0&&ni(t.cookie),_c(t.lastMutationIDChanges),uc(t.patch)}function _c(e){F(e);for(let[t,n]of Object.entries(e))P(t),fr(n)}function vc(e){F(e),lc(e.httpRequestInfo),e.response!==void 0&&gc(e.response)}function yc(e){F(e),lc(e.httpRequestInfo),e.response!==void 0&&hc(e.response)}function bc(e){async function t(t,n){let[r,i]=await cc(e.pushURL,e.auth,n,t);if(!r)return{httpRequestInfo:i};let a={httpRequestInfo:i},o;try{o=await r.json()}catch{return a}return(ac(o)||oc(o))&&(a.response=o),a}return xc.add(t),t}var xc=new WeakSet;function Sc(e){return xc.has(e)}function Cc(e=`info`,t=[zt],n){return new Bt(e,n,t.length===1?t[0]:new Lt(t))}var wc=Bi(Ri({prefix:I.string().optional(),jsonPointer:I.string(),allowEmpty:I.boolean().optional()}));function Tc(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&(e.prefix??``)===(t.prefix??``)}function Ec(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let[n,r]of Object.entries(e)){let e=t[n];if(!e||!Tc(r,e))return!1}return!0}var Dc=Ri({headHash:Yi,mutatorNames:zi(I.string()),indexes:wc,mutationIDs:Bi(I.number()),lastServerAckdMutationIDs:I.record(I.number()),disabled:I.boolean()}),Oc=`client-groups`;function kc(e){Fi(e,Dc)}function Ac(e){F(e);let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&(kc(r),t.set(n,r));return t}function jc(e,t){let n={};for(let[r,i]of e.entries())t.assertValidHash(i.headHash),n[r]={...i,mutatorNames:[...i.mutatorNames.values()]};return gi(n)}async function Mc(e,t){return Ac((await t.getChunk(e))?.data)}async function Nc(e){let t=await e.getHead(Oc);return t?Mc(t,e):new Map}async function Pc(e,t){let n=await Nc(t);for(let[t,r]of e)Ic(r,n.get(t));return Lc(e,t)}async function Fc(e,t,n){let r=await Nc(n);Ic(t,r.get(e));let i=new Map(r);return i.set(e,t),Lc(i,n)}function Ic(e,t){let n=new Set(e.mutatorNames);N(n.size===e.mutatorNames.length,`A client group's mutatorNames must be a set.`),t!==void 0&&(N(Ec(t.indexes,e.indexes),`A client group's index definitions must never change.`),N(Rc(n,t.mutatorNames),`A client group's mutatorNames must never change.`))}async function Lc(e,t){let n=jc(e,t),r=new Set;for(let t of e.values())r.add(t.headHash);let i=t.createChunk(n,Ci(r));return await t.putChunk(i),await t.setHead(Oc,i.hash),e}function Rc(e,t){if(t.length!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function zc(e,t){return(await Nc(t)).get(e)}function Bc(e){for(let[t,n]of Object.entries(e.mutationIDs)){let r=e.lastServerAckdMutationIDs[t];if(r===void 0&&n!==0||r<n)return!0}return!1}async function Vc(e,t){let n=await zc(e,t);n&&await Fc(e,{...n,disabled:!0},t)}var Hc=I.string(),Uc=I.string();function Wc(e,t){return Kc(e.read(),t)}function Gc(e,t){return Kc(e.write(),t)}function R(e,t){return Kc(e.write(),async e=>{let n=await t(e);return await e.commit(),n})}async function Kc(e,t){let n=await e;try{return await t(n)}finally{n.release()}}function qc(){let e=Oi(),t=Oi();return(e<<64n|t).toString(32).slice(-18).padStart(18,`0`)}var Jc=Ri({heartbeatTimestampMs:I.number(),headHash:Yi,mutationID:I.number(),lastServerAckdMutationID:I.number()}),Yc=Ri({heartbeatTimestampMs:I.number(),headHash:Yi,tempRefreshHash:Yi.nullable(),clientGroupID:Hc}),Xc=Ri({heartbeatTimestampMs:I.number(),refreshHashes:zi(Yi),persistHash:Yi.nullable(),clientGroupID:Hc});function Zc(e){return e.refreshHashes!==void 0}function Qc(e){return e.clientGroupID!==void 0}var $c=`clients`,el=I.union(Jc,Yc,Xc);function tl(e){Fi(e,el)}function nl(e){Fi(e,Jc)}function rl(e){Fi(e,Xc)}function il(e){F(e);let t=new Map;for(let n in e)if(Ur(e,n)){let r=e[n];r!==void 0&&(tl(r),t.set(n,r))}return t}function al(e,t){for(let n of e.values())Zc(n)?(n.refreshHashes.forEach(t.assertValidHash),n.persistHash&&t.assertValidHash(n.persistHash)):(t.assertValidHash(n.headHash),Qc(n)&&n.tempRefreshHash&&t.assertValidHash(n.tempRefreshHash));return gi(Object.fromEntries(e))}async function ol(e){return sl(await e.getHead($c),e)}async function sl(e,t){return e?il((await t.getChunk(e))?.data):new Map}var cl=class extends Error{name=`ClientStateNotFoundError`;id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function ll(e,t){if(!await ul(e,t))throw new cl(e)}async function ul(e,t){return!!await dl(e,t)}async function dl(e,t){return(await ol(t)).get(e)}async function fl(e,t){let n=await dl(e,t);if(!n)throw new cl(e);return n}function pl(e,t,n,r,i,a,o){return Gc(n,async n=>{async function s(t,a,o,s){let l=to(t,{},a,o,s),u=n.createChunk(l,ao(l)),d=qc(),f={heartbeatTimestampMs:Date.now(),refreshHashes:[u.hash],persistHash:null,clientGroupID:d},p=new Map(c).set(e,f),m={headHash:u.hash,mutatorNames:r,indexes:i,mutationIDs:{},lastServerAckdMutationIDs:{},disabled:!1};return await Promise.all([n.putChunk(u),Cl(p,n),Fc(d,m,n)]),await n.commit(),[f,u.hash,p,!0]}let c=await ol(n),l=await vl(n,r,i);if(l.type===_l){let{clientGroupID:t,headHash:r}=l,i={clientGroupID:t,refreshHashes:[r],heartbeatTimestampMs:Date.now(),persistHash:null},a=new Map(c).set(e,i);return await Cl(a,n),await n.commit(),[i,r,a,!1]}if(!o||l.type===hl){let e=n.createChunk(zo,[]);await n.putChunk(e);let t=[];for(let[n,r]of Object.entries(i)){let i=qa(n,r);t.push({definition:i,valueHash:e.hash})}return s(null,null,e.hash,t)}N(l.type===gl);let{snapshot:u}=l,d=[],{valueHash:f,indexes:p}=u,m=new Zo(n,a,f);for(let[e,r]of Object.entries(i)){let{prefix:i=``,jsonPointer:o,allowEmpty:s=!1}=r,c={name:e,keyPrefix:i,jsonPointer:o,allowEmpty:s},l=ml(p,c);if(l)d.push({definition:c,valueHash:l.valueHash});else{let e=await $s(t,n,m,i,o,s,a);d.push({definition:c,valueHash:await e.flush()})}}return s(u.meta.basisHash,u.meta.cookieJSON,u.valueHash,d)})}function ml(e,t){return e.find(e=>Ga(e.definition,t))}var hl=0,gl=1,_l=2;async function vl(e,t,n){let r,i,a=new Set(t),o=await Nc(e);for(let[t,s]of o){if(!s.disabled&&Rc(a,s.mutatorNames)&&Ec(n,s.indexes))return{type:_l,clientGroupID:t,headHash:s.headHash};let o=await Ta(s.headHash,e);Va(o);let{cookieJSON:c}=o.meta;(r===void 0||ei(c,r)>0)&&(r=c,i=o)}return i?{type:gl,snapshot:i}:{type:hl}}function yl(e){let t=new Set;for(let n of e.values())if(Zc(n)){for(let e of n.refreshHashes)t.add(e);n.persistHash&&t.add(n.persistHash)}else t.add(n.headHash),Qc(n)&&n.tempRefreshHash&&t.add(n.tempRefreshHash);return Ci(t)}async function bl(e,t){let n=await xl(e,t);if(n)return zc(n,t)}async function xl(e,t){let n=await dl(e,t);if(n&&Qc(n))return n.clientGroupID}async function Sl(e,t,n){let r=await ol(n);return Cl(new Map(r).set(e,t),n)}async function Cl(e,t){let n=al(e,t),r=t.createChunk(n,yl(e));return await t.putChunk(r),await t.setHead($c,r.hash),r.hash}var wl=typeof navigator<`u`?navigator:void 0,Tl=Symbol(),El=class{r=new Map;#e;constructor(e){this.#e=e}has(e){switch(this.r.get(e)){case void 0:return this.#e.has(e);case Tl:return ai;default:return ii}}async get(e){let t=this.r.get(e);switch(t){case Tl:return;case void 0:return Si(await this.#e.get(e));default:return t}}put(e,t){return this.r.set(e,gi(t)),oi}del(e){return this.r.set(e,Tl),oi}release(){this.#e.release()}get closed(){return this.#e.closed}},Dl={durability:`relaxed`},Ol=`chunks`,kl=class{#e;#t=!1;#n=!1;constructor(e){this.#e=Fl(e)}read(){return this.#r(Nl)}write(){return this.#r(Ml)}async close(){this.#n||(await this.#e).close(),this.#t=!0}get closed(){return this.#t}async#r(e){let t=async e=>{let{promise:t,resolve:n,reject:r}=Wt(),i=indexedDB.open(e);i.onupgradeneeded=()=>{let t=i.transaction;vr(t),t.abort(),this.#n=!0,r(new Il(`Replicache IndexedDB not found: ${e}`))},i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error);let a=await t;return a.onversionchange=()=>a.close(),a},n=await this.#e;try{return e(n)}catch(r){if(!this.#t&&r instanceof DOMException){if(r.name===`InvalidStateError`)return this.#e=t(n.name),e(await this.#e);if(r.name===`NotFoundError`)throw this.#n=!0,indexedDB.deleteDatabase(n.name),new Il(`Replicache IndexedDB ${n.name} missing object store. Deleting db.`)}throw r}}},Al=class{#e;#t=!1;constructor(e){this.#e=e}has(e){return new Promise((t,n)=>{let r=Pl(this.#e).count(e);r.onsuccess=()=>t(r.result>0),r.onerror=()=>n(r.error)})}get(e){return new Promise((t,n)=>{let r=Pl(this.#e).get(e);r.onsuccess=()=>t(Si(r.result)),r.onerror=()=>n(r.error)})}release(){this.#t=!0}get closed(){return this.#t}},jl=class extends El{#e;#t=!1;constructor(e){super(new Al(e)),this.#e=e}commit(){return this.r.size===0?oi:new Promise((e,t)=>{let n=this.#e,r=Pl(n);for(let[e,t]of this.r)t===Tl?r.delete(e):r.put(t,e);n.oncomplete=()=>e(),n.onerror=()=>t(n.error)})}release(){this.#t=!0}get closed(){return this.#t}};function Ml(e){return new jl(e.transaction(Ol,`readwrite`,Dl))}function Nl(e){return new Al(e.transaction(Ol,`readonly`))}function Pl(e){return e.objectStore(Ol)}function Fl(e){return new Promise((t,n)=>{let r=indexedDB.open(e);r.onupgradeneeded=()=>{r.result.createObjectStore(Ol)},r.onsuccess=()=>{let e=r.result;e.onversionchange=()=>e.close(),t(e)},r.onerror=()=>n(r.error)})}var Il=class extends Error{name=`IDBNotFoundError`},Ll=class{#e;#t;#n=!1;constructor(e,t){this.#e=e,this.#t=t}release(){this.#t(),this.#n=!0}get closed(){return this.#n}has(e){return Promise.resolve(this.#e.has(e))}get(e){return Promise.resolve(this.#e.get(e))}},Rl=class extends El{#e;constructor(e,t){super(new Ll(e,t)),this.#e=e}commit(){return this.r.forEach((e,t)=>{e===Tl?this.#e.delete(t):this.#e.set(t,e)}),this.r.clear(),this.release(),oi}},zl=new Map;function Bl(e){return zl.delete(e),oi}var Vl=class{#e;#t;#n=!1;constructor(e){let t=zl.get(e),n,r;t?{lock:n,map:r}=t:(n=new Kt,r=new Map,zl.set(e,{lock:n,map:r})),this.#t=n,this.#e=r}async read(){let e=await this.#t.read();return new Ll(this.#e,e)}async write(){let e=await this.#t.write();return new Rl(this.#e,e)}close(){return this.#n=!0,oi}get closed(){return this.#n}},Hl=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=new kl(t)}read(){return this.#r(e=>e.read())}write(){return this.#r(e=>e.write())}async#r(e){try{return await e(this.#n)}catch(t){if(Ul(t))return this.#n instanceof kl&&(this.#e.info?.(`Switching to MemStore because of Firefox private browsing error`),this.#n=new Vl(this.#t)),e(this.#n);throw t}}close(){return this.#n.close()}get closed(){return this.#n.closed}};function Ul(e){return Wl()&&e instanceof DOMException&&e.name===`InvalidStateError`&&e.message===`A mutation operation was attempted on a database that did not allow mutations.`}function Wl(){return wl?.userAgent.includes(`Firefox`)??!1}function Gl(e,t){return Wl()?new Hl(e,t):new kl(t)}function Kl(e){if(!Wl())return ql(e);try{return ql(e)}catch(t){if(Ul(t))return Bl(e)}return oi}function ql(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}var Jl=e=>new xf(e),Yl=401;function Xl(e,t){return Zl(e,t,7)}function Zl(e,t,n){let r=`rep:${e}:${n}`;return t?`${r}:${t}`:r}var Ql=class{#e;constructor(e){this.#e=Jl(e)}get pullURL(){return this.#e.pullURL}set pullURL(e){this.#e.pullURL=e}get pushURL(){return this.#e.pushURL}set pushURL(e){this.#e.pushURL=e}get auth(){return this.#e.auth}set auth(e){this.#e.auth=e}get name(){return this.#e.name}get idbName(){return Xl(this.name,this.schemaVersion)}get schemaVersion(){return this.#e.schemaVersion}get mutate(){return this.#e.mutate}get pullInterval(){return this.#e.pullInterval}set pullInterval(e){this.#e.pullInterval=e}get pushDelay(){return this.#e.pushDelay}set pushDelay(e){this.#e.pushDelay=e}get puller(){return this.#e.puller}set puller(e){this.#e.puller=e}get pusher(){return this.#e.pusher}set pusher(e){this.#e.pusher=e}get requestOptions(){return this.#e.requestOptions}get onSync(){return this.#e.onSync}set onSync(e){this.#e.onSync=e}get onClientStateNotFound(){return this.#e.onClientStateNotFound}set onClientStateNotFound(e){this.#e.onClientStateNotFound=e}get onUpdateNeeded(){return this.#e.onUpdateNeeded}set onUpdateNeeded(e){this.#e.onUpdateNeeded=e}get getAuth(){return this.#e.getAuth}set getAuth(e){this.#e.getAuth=e}get profileID(){return this.#e.profileID}get clientID(){return this.#e.clientID}get clientGroupID(){return this.#e.clientGroupID}get onOnlineChange(){return this.#e.onOnlineChange}set onOnlineChange(e){this.#e.onOnlineChange=e}get online(){return this.#e.online}get closed(){return this.#e.closed}close(){return this.#e.close()}push({now:e=!1}={}){return this.#e.push({now:e})}pull({now:e=!1}={}){return this.#e.pull({now:e})}poke(e){return this.#e.poke(e)}subscribe(e,t){return this.#e.subscribe(e,t)}experimentalWatch(e,t){return this.#e.experimentalWatch(e,t)}query(e){return this.#e.query(e)}experimentalPendingMutations(){return this.#e.experimentalPendingMutations()}},$l=class extends Error{};function eu(e){return new Vl(e)}function tu(e,t){switch(t){case`idb`:case void 0:return{create:t=>Gl(e,t),drop:Kl};case`mem`:return{create:eu,drop:e=>Bl(e)};default:return t}}function nu(e){return e instanceof Error?e:Error(String(e))}async function ru(e,t,n){for(let r of n)switch(r.op){case`put`:await t.put(e,r.key,gi(r.value));break;case`update`:{let n=await t.get(r.key),i=[],a=e=>{for(let[t,n]of Object.entries(e))(!r.constrain||r.constrain.length===0||r.constrain.indexOf(t)>-1)&&i.push([t,n])};n!==void 0&&(F(n),a(n)),r.merge&&a(r.merge),await t.put(e,r.key,gi(Object.fromEntries(i)));break}case`del`:await t.del(e,r.key);break;case`clear`:await t.clear()}}var iu=class extends Error{name=`PullError`;causedBy;constructor(e){super(`Failed to pull`),this.causedBy=e}},au=`sync`,ou=0,su=1;function cu(e){return e.pullVersion===su}async function lu(e,t,n,r,i,a,o,s,c=!0){let[l,u]=await Wc(a,async e=>{let n=await e.getHead(L);if(!n)throw Error(`Internal no main head found`);let r=await Ta(n,e),i=r.meta.cookieJSON;return[await r.getMutationID(t,e),i]}),{response:d,httpRequestInfo:f}=await du(s,r,{profileID:e,clientID:t,cookie:u,lastMutationID:l,pullVersion:ou,schemaVersion:n},i);if(!d)return{httpRequestInfo:f,syncHead:Ui};if(!c||ic(d))return{httpRequestInfo:f,pullResponse:d,syncHead:Ui};let p=await fu(s,a,u,d,t,o);if(p.type===2)throw Error(`Overlapping sync`);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:Ui}}async function uu(e,t,n,r,i,a,o,s,c,l=!0){let u=await Wc(o,async e=>{let t=await e.getHead(L);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta;return za(n),n.cookieJSON}),{response:d,httpRequestInfo:f}=await du(c,i,{profileID:e,clientGroupID:n,cookie:u,pullVersion:su,schemaVersion:r},a);if(!d)return{httpRequestInfo:f,syncHead:Ui};if(!l||ic(d))return{httpRequestInfo:f,pullResponse:d,syncHead:Ui};let p=await mu(c,o,u,d,t,s);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:Ui}}async function du(e,t,n,r){e.debug?.(`Starting pull...`);let i=Date.now(),a;try{a=await t(n,r),e.debug?.(`...Pull ${a.response?`complete`:`failed`} in `,Date.now()-i,`ms`)}catch(e){throw new iu(nu(e))}try{return cu(n)?vc(a):yc(a),a}catch(e){throw new $l(`Invalid puller result`,nu(e))}}function fu(e,t,n,r,i,a){return Gc(t,async t=>{N(a<=4);let o=t,s=await o.getHead(L);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),[l,u]=Da(c,i);if(!Wr(n,u))return{type:2};if(r.lastMutationID<l)throw Error(pu(`lastMutationID`,String(r.lastMutationID),String(l)));let d=gi(r.cookie??null);if(Wr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),r.lastMutationID!==l&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationID did change`),{type:1};let f=await ka(s,o),p;for(let e of f)if(await e.getMutationID(i,o)<=r.lastMutationID){p=e;break}if(!p)throw Error(`Internal invalid chain`);let m=await Ys(c.chunk.hash,r.lastMutationID,d,t,Qs(p,t,a),i,a);await ru(e,m,r.patch);let h=new Zo(o,a,p.valueHash);for await(let t of m.map.diff(h))await Zs(e,m.indexes,t.key,()=>Promise.resolve(t.oldValue),t.newValue);return{type:0,syncHead:await m.commit(au)}})}function pu(e,t,n){return`Received ${e} ${t} is < than last snapshot ${e} ${n}; ignoring client view`}function mu(e,t,n,r,i,a){return Gc(t,async t=>{let o=t,s=await o.getHead(L);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),l=c.meta;za(l);let u=l.cookieJSON;if(!Wr(n,u))return e.debug?.(`handlePullResponse: cookie mismatch, response is not applicable`),{type:2};for(let[e,t]of Object.entries(r.lastMutationIDChanges)){let n=l.lastMutationIDs[e];if(n!==void 0&&t<n)throw Error(pu(`${e} lastMutationID`,String(t),String(n)))}let d=gi(r.cookie);if(ei(d,u)<0)throw Error(pu(`cookie`,JSON.stringify(d),JSON.stringify(u)));if(Wr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),Object.keys(r.lastMutationIDChanges).length>0&&(console.log(r.lastMutationIDChanges),e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationIDChanges is not empty`)),{type:1};let f=await Xs(c.chunk.hash,{...l.lastMutationIDs,...r.lastMutationIDChanges},d,t,i,a);return await ru(e,f,r.patch),{type:0,syncHead:await f.commit(au)}})}function hu(e,t,n,r,i,a){return Gc(e,async e=>{let o=e,s=await o.getHead(au);if(s===void 0)throw Error(`Missing sync head`);if(s!==n)throw t.error?.(`maybeEndPull, Wrong sync head. Expecting:`,n,`got:`,s),Error(`Wrong sync head`);let c=await Ta(s,o),l=await o.getHead(L);if(l===void 0)throw Error(`Missing main head`);let u=await Ta(l,o),{meta:d}=c,f=d.basisHash;if(c===null)throw Error(`Sync snapshot with no basis`);if(f!==u.chunk.hash)throw Error(`Overlapping syncs`);let p=await Aa(s,o),m=[],h=await ba(l,o);for(let e of h){let t=r;pa(e)&&(t=e.meta.clientID),await e.getMutationID(t,o)>await p.getMutationID(t,o)&&m.push(e)}m.reverse();let g=new Ws;if(m.length>0)return{syncHead:s,replayMutations:m,diffs:g};let _=await Aa(l,o);if(i.shouldComputeDiffs()){let e=await Bs(new Zo(o,a,_.valueHash),new Zo(o,a,p.valueHash));g.set(``,e),await Ks(_,p,o,g,i,a)}if(await Promise.all([e.setHead(L,s),e.removeHead(au)]),await e.commit(),t.debug){let[e,n]=Da(u,r),[i,a]=Da(c,r);t.debug(`Successfully pulled new snapshot with lastMutationID:`,i,`(prev:`,e,`), cookie: `,a,`(prev:`,n,`), sync head hash:`,s,`, main head hash:`,l,`, valueHash:`,p.valueHash,`(prev:`,u.valueHash)}return{syncHead:s,replayMutations:[],diffs:g}})}var gu=[],_u=I.unknown().chain(e=>{if(Vr)return on(e);let t=Yr(e,gu)?on(e):sn({message:`Not a JSON value`,path:gu.slice()});return gu.length=0,t});I.unknown().chain(e=>{if(Vr)return on(e);let t=Xr(e,gu)?on(e):sn({message:`Not a JSON object`,path:gu.slice()});return gu.length=0,t});function vu(e){F(e),lc(e.httpRequestInfo),e.response!==void 0&&yu(e.response)}function yu(e){ac(e)||sc(e)}var bu=class extends Error{name=`PushError`;causedBy;constructor(e){super(`Failed to push`),this.causedBy=e}},xu=0,Su=1,Cu=Ri({id:I.number(),name:I.string(),args:_u,timestamp:I.number()}),wu=Ri({id:I.number(),name:I.string(),args:_u,timestamp:I.number(),clientID:Uc});I.object({pushVersion:I.literal(0),schemaVersion:I.string(),profileID:I.string(),clientID:Uc,mutations:I.array(Cu)}),I.object({pushVersion:I.literal(1),schemaVersion:I.string(),profileID:I.string(),clientGroupID:Hc,mutations:I.array(wu)});function Tu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp}}function Eu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp,clientID:e.clientID}}async function Du(e,t,n,r,i,a,o,s,c){let l=await Wc(t,async e=>{let t=await e.getHead(L);if(!t)throw Error(`Internal no main head`);return ba(t,e)});if(l.length===0)return;l.reverse();let u;if(c===Su){let e=[];for(let t of l)if(pa(t))e.push(Eu(t.meta));else throw Error(`Internal non local pending commit`);N(i),u={profileID:r,clientGroupID:i,mutations:e,pushVersion:Su,schemaVersion:s}}else{N(c===xu);let e=[];for(let t of l)if(fa(t))e.push(Tu(t.meta));else throw Error(`Internal non local pending commit`);u={profileID:r,clientID:a,mutations:e,pushVersion:xu,schemaVersion:s}}n.debug?.(`Starting push...`);let d=Date.now(),f=await Ou(o,u,e);return n.debug?.(`...Push complete in `,Date.now()-d,`ms`),f}async function Ou(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new bu(nu(e))}try{return vu(r),r}catch(e){throw new $l(`Invalid pusher result`,nu(e))}}var ku=10*2**20,Au=class{#e=!1;#t;constructor(e){this.#t=e}async recoverMutations(e,t,n,r,i,a){let{lc:o,enableMutationRecovery:s,isPushDisabled:c,delegate:l}=this.#t;if(!s||this.#e||!l.online||l.closed||c())return!1;let u=`Recovering mutations.`;o.debug?.(`Start:`,u);try{this.#e=!0,await t,await Pu(r,this.#t,n,e);for(let e of Object.values(await i.getDatabases())){if(l.closed)return o.debug?.(`Exiting early due to close:`,u),!0;if(e.replicacheName===l.name&&e.name!==l.idbName)switch(e.replicacheFormatVersion){case 4:case 5:case 6:case 7:await Nu(e,this.#t,void 0,a)}}}catch(e){ju(e,o,u,l)}finally{o.debug?.(`End:`,u),this.#e=!1}return!0}};function ju(e,t,n,r){r.closed?t.debug?.(`Mutation recovery error likely due to close during:
|
|
2
2
|
${n}
|
|
3
3
|
Error:
|
|
4
4
|
`,e):t.error?.(`Mutation recovery error during:
|
|
5
5
|
${n}
|
|
6
6
|
Error:
|
|
7
|
-
`,e)}async function Au(e,t,n,r,i,a){A(r.replicacheFormatVersion===4),el(e);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d}=i,f=o.clientID;if(f===t||e.lastServerAckdMutationID>=e.mutationID)return;let p=`Recovering mutations for ${t}.`;s.debug?.(`Start:`,p);let m=new ta(n,Du,Oi,Ji);try{if(await z(m,t=>t.setHead(I,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client ${t} because push is disabled.`);return}let{pusher:i}=o,p=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{br(m);let a=await Tu(e,m,n,await o.profileID,void 0,t,i,r.schemaVersion,yu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},p,s);return!!e&&e.httpRequestInfo.httpStatusCode===200},p)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,_;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{let i=await su(await o.profileID,t,r.schemaVersion,h,e,m,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s);return{pullResponse:_}=e,!!_&&e.httpRequestInfo.httpStatusCode===200},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return s.debug&&_&&(ic(_)?s.debug?.(`Client ${f} cannot recover mutations for client ${t}. The client no longer exists on the server.`):ac(_)?s.debug?.(`Version is not supported on the server. versionType: ${_.versionType}. Cannot recover mutations for client ${t}.`):s.debug?.(`Client ${f} recovered mutations for client ${t}. Details`,{mutationID:e.mutationID,lastServerAckdMutationID:e.lastServerAckdMutationID,lastMutationID:_.lastMutationID})),await z(n,async e=>{let n=await il(e),r=n.get(t);if(!r)return n;el(r);let i=async t=>(await xl(t,e),t);if(ic(_)||ac(_)){let e=new Map(n);return e.delete(t),i(e)}return A(_),r.lastServerAckdMutationID>=_.lastMutationID?n:i(new Map(n).set(t,{...r,lastServerAckdMutationID:_.lastMutationID}))})}catch(e){ku(e,s,p,o)}finally{await m.close(),s.debug?.(`End:`,p)}}async function ju(e,t,n,r){let i=new la(r(e.name),Wi,Ji);try{await Mu(e,t,i,n)}finally{await i.close()}}function Mu(e,t,n,r){return e.replicacheFormatVersion>=5?Pu(e,t,n):Nu(e,t,n,r)}async function Nu(e,t,n,r){let{delegate:i,lc:a}=t,o=`Recovering mutations from db ${e.name}.`;a.debug?.(`Start:`,o);try{let s=bo(e.replicacheFormatVersion),c=r||await R(n,e=>il(e)),l=new Set;for(;c;){let r;for(let[u,d]of c){if(i.closed){a.debug?.(`Exiting early due to close:`,o);return}if(!l.has(u)&&(l.add(u),r=await Au(d,u,n,e,t,s),r))break}c=r}}catch(e){ku(e,a,o,i)}a.debug?.(`End:`,o)}async function Pu(e,t,n){let{delegate:r,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.(`Start:`,a);try{let o=bo(e.replicacheFormatVersion),s=await R(n,e=>Mc(e)),c=new Set;for(;s;){let l;for(let[u,d]of s){if(r.closed){i.debug?.(`Exiting early due to close:`,a);return}if(!c.has(u)&&(c.add(u),l=await Lu(d,u,n,e,t,o),l))break}s=l}}catch(e){ku(e,i,a,r)}i.debug?.(`End:`,a)}function Fu(e){return ic(e)||ac(e)}async function Iu(e,t,n,r,i){ic(r)?e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group is unknown on the server. Marking it as disabled.`):ac(r)&&e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group's version is not supported on the server. versionType: ${r.versionType}. Marking it as disabled.`),await z(i,e=>Bc(n,e))}async function Lu(e,t,n,r,i,a){A(r.replicacheFormatVersion>=5);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d,clientGroupIDPromise:f}=i,p=await f;if(br(p),p===t)return;let m,h=!0;for(let[t,n]of Object.entries(e.mutationIDs))if(!e.lastServerAckdMutationIDs[t]||e.lastServerAckdMutationIDs[t]<n){m=t,h=!1;break}if(h)return;if(e.disabled){s.debug?.(`Not recovering mutations for client group ${t} because group is disabled.`);return}let g=`Recovering mutations for client group ${t}.`;s.debug?.(`Start:`,g);let _=new ta(n,Du,Oi,Ji);try{if(await z(_,t=>t.setHead(I,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client group ${t} because push is disabled.`);return}let{pusher:i}=o,f=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{A(m),A(_);let a=await Tu(e,_,n,await o.profileID,t,m,i,r.schemaVersion,bu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},f,s);if(!e)return!1;let a=e.response;return Fu(a)?(await Iu(s,p,t,a,n),!1):e.httpRequestInfo.httpStatusCode===200},f)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,v;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{A(m);let i=await cu(await o.profileID,m,t,r.schemaVersion,h,e,_,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s),{pullResponse:i}=e;return Fu(i)?(await Iu(s,p,t,i,n),!1):!i||e.httpRequestInfo.httpStatusCode!==200?!1:(v=i,!0)},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return A(v),s.debug?.(`Client group ${p} recovered mutations for client group ${t}. Details`,{mutationIDs:e.mutationIDs,lastServerAckdMutationIDs:e.lastServerAckdMutationIDs,lastMutationIDChanges:v.lastMutationIDChanges}),await z(n,async e=>{let n=await Mc(e),r=n.get(t);if(!r)return n;A(v);let i={},a=!1;for(let[e,t]of Object.entries(v.lastMutationIDChanges))(r.lastServerAckdMutationIDs[e]??0)<t&&(i[e]=t,a=!0);if(!a)return n;let o=new Map(n).set(t,{...r,lastServerAckdMutationIDs:{...r.lastServerAckdMutationIDs,...i}});return await Nc(o,e),o})}catch(e){ku(e,s,g,o)}finally{await _.close(),s.debug?.(`End:`,g)}}var Ru=class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}},zu=typeof BroadcastChannel>`u`?Ru:BroadcastChannel;function Bu(e){return`replicache-new-client-group:${e}`}function Vu(e){return`replicache-new-client-group-v1:${e}`}function Hu(e){return typeof e==`object`&&typeof e.clientGroupID==`string`&&typeof e.idbName==`string`}function Uu(e,t,n,r,i,a,o){if(n.aborted)return;let s=new zu(Vu(e));if(i){s.postMessage({clientGroupID:r,idbName:t});let n=new zu(Bu(e));n.postMessage([r]),n.close()}s.onmessage=async e=>{let{data:n}=e;if(Hu(n)){let{clientGroupID:e,idbName:i}=n;if(e!==r){if(i===t)await R(o,async t=>await Rc(e,t)!==void 0)&&a();else{a();return}}}},n.addEventListener(`abort`,()=>s.close(),{once:!0})}function Wu(e){return`replicache-on-persist:${e}`}function Gu(e){N(e),j(e.clientGroupID),j(e.clientID)}function Ku(e,t,n){if(t.aborted)return()=>{};let r=new zu(Wu(e));return r.onmessage=e=>{let{data:t}=e;Gu(t),n({clientGroupID:t.clientGroupID,clientID:t.clientID})},t.addEventListener(`abort`,()=>r.close(),{once:!0}),e=>{t.aborted||(r.postMessage(e),n(e))}}async function qu(e){return(await xa(await ea(I,e),e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}function Ju(e,t,n,r,i){Yu(e,t,n,r,i)}async function Yu(e,t,n,r,i){if(!i.aborted){for(r=r.withContext(`bgIntervalProcess`,e),r.debug?.(`Starting`);!i.aborted;){try{await Mr(n(),i)}catch(e){if(!(e instanceof pr))throw e}if(!i.aborted){r.debug?.(`Running`);try{await t()}catch(e){i.aborted?r.debug?.(`Error running most likely due to close.`,e):r.error?.(`Error running.`,e)}}}r.debug?.(`Stopping`)}}var Xu=864e5,Zu=3e5,Qu;function $u(e,t,n,r,i,a){Ju(`ClientGC`,()=>(Qu=ed(e,t,n),Qu),()=>r,i,a)}function ed(e,t,n){return z(t,async t=>{let r=Date.now(),i=await il(t),a=Array.from(i).filter(([t,i])=>t===e||r-i.heartbeatTimestampMs<=n);if(a.length===i.size)return i;let o=new Map(a);return await xl(o,t),o})}var td=3e5,nd;function rd(e,t,n){Ju(`ClientGroupGC`,()=>(nd=id(e),nd),()=>td,t,n)}function id(e){return z(e,async e=>{let t=await il(e),n=new Set;for(let e of t.values())tl(e),n.add(e.clientGroupID);let r=new Map;for(let[t,i]of await Mc(e))(n.has(t)||zc(i))&&r.set(t,i);return await Nc(r,e),r})}var ad=`replicache-dbs-v0`,od=``;function sd(){return od+ad}var cd=`dbs`,ld=`profileId`;function ud(e){N(e);for(let[t,n]of Object.entries(e))j(t),dd(n),A(t===n.name)}function dd(e){N(e),j(e.name),j(e.replicacheName),M(e.replicacheFormatVersion),j(e.schemaVersion),e.lastOpenedTimestampMS!==void 0&&M(e.lastOpenedTimestampMS)}var fd=class{#e;constructor(e){this.#e=e(sd())}putDatabase(e){return this.#t({...e,lastOpenedTimestampMS:Date.now()})}putDatabaseForTesting(e){return this.#t(e)}#t(e){return z(this.#e,async t=>{let n={...await pd(t),[e.name]:e};return await t.put(cd,n),n})}clearDatabases(){return z(this.#e,e=>e.del(cd))}deleteDatabases(e){return z(this.#e,async t=>{let n={...await pd(t)};for(let t of e)delete n[t];await t.put(cd,n)})}getDatabases(){return R(this.#e,pd)}close(){return this.#e.close()}getProfileID(){return z(this.#e,async e=>{let t=await e.get(ld);return t===void 0&&(t=`p${Gc()}`,await e.put(ld,t)),j(t),t})}};async function pd(e){let t=await e.get(cd);return t||=_i({}),ud(t),t}var md=432e5,hd=2592e6,gd=3e5;function _d(e,t,n,r,i,a,o,s){let c=!0;Ju(`CollectIDBDatabases`,async()=>{await vd(e,Date.now(),i,a,t)},()=>c?(c=!1,r):n,o,s)}async function vd(e,t,n,r,i,a=xd){let o=await e.getDatabases(),s=Object.values(o),{errors:c}=await bd(e,(await Promise.all(s.map(async e=>[e.name,await Sd(e,t,n,r,a)]))).filter(e=>e[1]).map(e=>e[0]),i);if(c.length)throw c[0]}async function yd(e,t,n){await n(e),await t.deleteDatabases([e])}async function bd(e,t,n){let r=await Promise.allSettled(t.map(async t=>(await yd(t,e,n),t))),i=[],a=[];for(let e of r)e.status===`fulfilled`?i.push(e.value):a.push(e.reason);return{dropped:i,errors:a}}function xd(e){return new la(new Dl(e),Wi,Ji)}async function Sd(e,t,n,r,i){if(e.replicacheFormatVersion>7)return!1;if(e.lastOpenedTimestampMS!==void 0){let a=e.replicacheFormatVersion>=5;return t-e.lastOpenedTimestampMS<(a?r:n)?!1:!a||(A(e.replicacheFormatVersion===5||e.replicacheFormatVersion===6||e.replicacheFormatVersion===7),!await wd(i(e.name)))}let a=i(e.name),o=await R(a,il);return await a.close(),Cd(o,t,n)}function Cd(e,t,n){for(let r of e.values())if(t-r.heartbeatTimestampMs<n)return!1;return!0}async function wd(e){let t=await R(e,Mc);for(let e of t.values())if(zc(e))return!0;return!1}var Td=6e4,Ed;function Dd(e,t,n,r,i,a){Ju(`Heartbeat`,async()=>{Ed=Od(e,t);try{return await Ed}catch(e){if(e instanceof ol){n();return}throw e}},()=>r,i,a)}function Od(e,t){return z(t,async t=>{let n=await il(t),r=n.get(e);if(!r)throw new ol(e);let i={...r,heartbeatTimestampMs:Date.now()},a=new Map(n).set(e,i);return await xl(a,t),a})}var kd=class{#e=new Set;#t;constructor(e){this.#t=e}async visit(e){if(this.#e.has(e))return;this.#e.add(e);let t=await this.#t.mustGetChunk(e);await this.visitChunk(t)}async visitChunk(e){await Promise.all(e.meta.map(e=>this.visit(e)))}},Ad=class extends kd{#e=new Map;#t;constructor(e){super(e),this.#t=e}get gatheredChunks(){return this.#e}visit(e){return this.#t.isMemOnlyChunkHash(e)?super.visit(e):si}visitChunk(e){return this.#e.set(e.hash,e),super.visitChunk(e)}};async function jd(e,t,n,r,i,a,o,s=()=>Promise.resolve()){if(a())return;let[c,l,u]=await R(r,async e=>{await sl(t,e);let n=await yl(t,e);A(n,`No main client group for clientID: ${t}`);let[,r]=await Md(e,n),i=await r.getMutationID(t,e),a=await Ea(r,e);return Ba(a),[i,a,n]});if(a())return;let[d,f,p]=await R(n,async e=>{let n=await Aa(I,e),r=await Sa(n,{[t]:c||0},e),i=await Ea(n,e);Ba(i);let a;if(Oa(i,l)>0){await s();let t=i.chunk.hash,n=new Ad(e);await n.visit(t),a=n.gatheredChunks}return[r,i,a]});if(a())return;let m=!1;await z(r,async n=>{let[r,a]=await Md(n,u),s=a.chunk.hash,c={...r.mutationIDs},{lastServerAckdMutationIDs:l}=r;if(p){let u=await ul(t,n);tl(u);let d=await Ea(a,n);if(Ba(d),Oa(f,d)>0){m=!0,await Promise.all(Array.from(p.values(),e=>n.putChunk(e))),await bl(t,{...u,persistHash:f.chunk.hash},n),s=f.chunk.hash;let a=await xa(r.headHash,n);l=f.meta.lastMutationIDs,c={...l},s=await Nd(a,s,n,i,c,e,o)}}s=await Nd(d,s,n,i,c,e,o);let h={...r,headHash:s,mutationIDs:c,lastServerAckdMutationIDs:l};await Pc(u,h,n)}),p&&m&&await z(n,e=>e.chunksPersisted([...p.keys()]))}async function Md(e,t){let n=await Rc(t,e);return A(n,`No client group for clientGroupID: ${t}`),[n,await L(n.headHash,e)]}async function Nd(e,t,n,r,i,a,o){for(let s=e.length-1;s>=0;s--){let c=e[s],{meta:l}=c,u=await L(t,n);await c.getMutationID(l.clientID,n)>await u.getMutationID(l.clientID,n)&&(i[l.clientID]=l.mutationID,t=(await ec(c,n,t,r,a,l.clientID,o)).chunk.hash)}return t}var Pd=class extends kd{#e=new Map;#t=0;#n;#r;#i;constructor(e,t,n,r=fi){super(e),this.#n=t,this.#r=n,this.#i=r}get gatheredChunks(){return this.#e}visit(e){return this.#t>=this.#r||this.#n.isCached(e)?si:super.visit(e)}visitChunk(e){if(this.#t<this.#r){let t=this.#i(e);this.#e.set(e.hash,{chunk:e,size:t}),this.#t+=t}return super.visitChunk(e)}},Fd=5*2**20,Id=300;async function Ld(e,t,n,r,i,a,o,s){if(o())return;let c=await R(t,e=>Ca(I,e));Ba(c);let l=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let l=await z(n,async e=>{let n=await vl(r,e);if(!n)throw new ol(r);let i=n.headHash,a=await(await L(i,e)).getMutationID(r,e),o=await ul(r,e);tl(o);let s=await Ta(i,e);if(Ba(s),Rd(c,s,i))return;let l=new Pd(e,t,Fd);await l.visit(i);let{gatheredChunks:u}=l,d=new Set(o.refreshHashes);return d.add(i),await bl(r,{...o,refreshHashes:[...d]},e),[i,s,a,u,o.refreshHashes]});if(o()||!l||(await Mr(Id),o()))return{type:`aborted`};let[u,d,f,p,m]=l;return z(t,async t=>{let n=await Aa(I,t),o=await Ea(n,t);if(Ba(o),Rd(o,d,u))return{type:`aborted`,refreshHashesForRevert:m};let c=await Sa(n,{[r]:f},t),l=[];for(let{chunk:e,size:n}of p.values())l.push(t.putChunk(e,n));await Promise.all(l);let h=u;for(let n=c.length-1;n>=0;n--)h=(await ec(c[n],t,h,i,e,c[n].meta.clientID,s)).chunk.hash;let g=await Ws(n,await L(h,t),t,a,s);return await t.setHead(I,h),{type:`complete`,diffs:g,newPerdagClientHeadHash:u}})});if(o())return;let u=e=>z(n,async t=>{await bl(r,{...await ul(r,t),refreshHashes:e},t)});if(l.type===`aborted`){l.refreshHashesForRevert&&await u(l.refreshHashesForRevert);return}return await u([l.newPerdagClientHeadHash]),l.diffs}function Rd(e,t,n){let r=Oa(e,t);return r>0||r===0&&n===t.chunk.hash}function zd(e){return new Promise(t=>{typeof requestIdleCallback==`function`?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var Bd=class{#e;#t;#n;#r;#i;#a=void 0;#o=void 0;#s=Promise.resolve();#c=Promise.resolve();constructor(e,t,n,r,i=zd){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,this.#r.addEventListener(`abort`,()=>{let e=new pr(`Aborted`);this.#o?.reject(e),this.#a?.reject(e),this.#o=void 0,this.#a=void 0},{once:!0})}schedule(){return this.#r.aborted?Promise.reject(new pr(`Aborted`)):this.#a?this.#a.promise:(this.#a=O(),this.#l(),this.#a.promise)}async#l(){try{await this.#s}catch{}if(await this.#c,this.#a&&(await this.#i(this.#t),this.#a)){this.#c=Vd(this.#n,this.#r),this.#o=this.#a,this.#a=void 0;try{this.#s=this.#e(),await this.#s,this.#o?.resolve()}catch(e){this.#o?.reject(e)}this.#o=void 0}}};async function Vd(e,t){try{await Mr(e,t)}catch(e){A(e instanceof pr)}}function Hd(e,t,n){let r=setInterval(e,t);n.addEventListener(`abort`,()=>{clearInterval(r)})}var Ud=new Set,Wd=Symbol(),Gd=class{#e;#t;#n=Wd;#r=Ud;#i=[];onError;onDone;#a;constructor(e,t,n,r,i=Gr){this.#e=e,this.#t=t,this.onError=n,this.onDone=r,this.#a=i}hasIndexSubscription(e){for(let t of this.#i)if(t.options.indexName===e)return!0;return!1}invoke(e,t,n){return this.#e(e)}matches(e){for(let[t,n]of e)if(Yd(this.#r,this.#i,t,n))return!0;return!1}updateDeps(e,t){this.#r=e,this.#i=t}onData(e){(this.#n===Wd||!this.#a(this.#n,e))&&(this.#n=e,this.#t(e))}},Kd=class{#e;#t;#n;#r;onError=void 0;onDone=void 0;constructor(e,t){this.#e=e,this.#t=t?.prefix??``,this.#n=t?.indexName,this.#r=t?.initialValuesInFirstDiff??!1}hasIndexSubscription(e){return this.#n===e}onData(e){e!==void 0&&this.#e(e)}invoke(e,t,n){let r=async(r,i,a,o)=>{let s;if(t===0){if(!this.#r)return;A(n===void 0);let t=[];for await(let n of e.scan({prefix:i,indexName:r}).entries())t.push({op:`add`,key:n[0],newValue:n[1]});s=t}else A(n),s=o(n.get(r??``)??[]);let c=[],{length:l}=s;for(let e=tf(s,i,a);e<l&&a(s[e]).startsWith(i);e++)c.push(s[e]);return t===0||c.length>0?c:void 0};return this.#n?r(this.#n,this.#t,e=>e.key[0],e=>qd(e,ls)):r(void 0,this.#t,e=>e.key,e=>qd(e,e=>e))}matches(e){let t=e.get(this.#n??``);return t!==void 0&&ef(t,this.#t,this.#n)}updateDeps(e,t){}};function qd(e,t){return e.map(e=>{let n=t(e.key);switch(e.op){case`add`:return{op:`add`,key:n,newValue:e.newValue};case`change`:return{op:`change`,key:n,oldValue:e.oldValue,newValue:e.newValue};case`del`:return{op:`del`,key:n,oldValue:e.oldValue}}})}var Jd=class{#e=new Set;#t=new Set;#n;#r;hasPendingSubscriptionRuns=!1;constructor(e,t){this.#n=e,this.#r=t}add(e){return this.#e.add(e),this.#a(e),()=>this.#e.delete(e)}clear(){for(let e of this.#e)e.onDone?.();this.#e.clear()}async fire(e){let t=$d(this.#e,e);await this.#i(t,1,e)}async#i(e,t,n){let r=[...e];if(r.length===0)return;let i=await this.#n(e=>Promise.allSettled(r.map(async r=>{let i=new Ns(e);try{return await r.invoke(i,t,n)}finally{r.updateDeps(i.keys,i.scans)}})));this.callCallbacks(r,i)}callCallbacks(e,t){for(let n=0;n<e.length;n++){let r=e[n],i=t[n];i.status===`fulfilled`?r.onData(i.value):r.onError?r.onError(i.reason):this.#r.error?.(`Error in subscription body:`,i.reason)}}async#a(e){if(this.#t.add(e),!this.hasPendingSubscriptionRuns){this.hasPendingSubscriptionRuns=!0,await Promise.resolve(),this.hasPendingSubscriptionRuns=!1;let e=[...this.#t];this.#t.clear(),await this.#i(e,0,void 0)}}shouldComputeDiffs(){return this.#e.size>0}shouldComputeDiffsForIndex(e){for(let t of this.#e)if(t.hasIndexSubscription(e))return!0;return!1}};function Yd(e,t,n,r){if(n===``){for(let t of r)if(e.has(t.key))return!0}for(let e of t)if(Xd(e,n,r))return!0;return!1}function Xd(e,t,n){for(let r of n)if(Zd(e,t,r.key))return!0;return!1}function Zd(e,t,n){let{indexName:r=``,limit:i,prefix:a,startKey:o,startExclusive:s,startSecondaryKey:c}=e.options;if(t!==r)return!1;if(!r)return i!==void 0&&i<=0?!1:!a&&!o||!(a&&(!n.startsWith(a)||Qd(e,n))||o&&(s&&vo(n,o)||_o(n,o)||Qd(e,n)));if(!a&&!o&&!c)return!0;let[l,u]=ls(n);return!(a&&!l.startsWith(a)||c&&(s&&vo(l,c)||_o(l,c))||o&&(s&&vo(u,o)||_o(u,o)))}function Qd(e,t){let{inclusiveLimitKey:n}=e;return e.options.limit!==void 0&&n!==void 0&&go(t,n)}function*$d(e,t){for(let n of e)n.matches(t)&&(yield n)}function ef(e,t,n){if(t===``)return!0;let r=n?e=>ls(e.key)[0]:e=>e.key,i=tf(e,t,r);return i<e.length&&r(e[i]).startsWith(t)}function tf(e,t,n){return yo(e.length,r=>co(t,n(e[r])))}function nf(e){if(e===null)throw TypeError(`array cannot be null`);for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e}var rf=``;function af(){if(rf===``){let e=new Uint8Array(4);nf(e),rf=Array.from(e,e=>e.toString(16)).join(``)}return rf}var of=new Map;function sf(e){let t=of.get(e);return t?(t++,of.set(e,t)):(of.set(e,0),t=0),`${e}-${af()}-${t}`}var cf=`15.3.0`,lf=8,uf=1e3,df=1e3,ff=500,pf=500,mf=100*2**20,hf=3e5,gf=()=>{},_f={type:`NewClientGroup`},vf=(e,t)=>new Jd(e,t),yf=class{pullURL;pushURL;auth;name;subscriptions;#e;isClientGroupDisabled=!1;#t;lastMutationID=0;get idbName(){return Jl(this.name,this.schemaVersion)}schemaVersion;get#n(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#r=!1;#i=!0;#a=Gc();#o;#s;#c;#l={};mutate;#u=0;#d=0;#f;#p;pullInterval;pushDelay;#m;puller;pusher;memdag;perdag;#h;#g;#_=new AbortController;#v=!1;#y;#b;#x;#S=new Bd(()=>this.persist(),uf,ff,this.#_.signal);#C;#w=new Bd(()=>this.refresh(),df,pf,this.#_.signal);get requestOptions(){return this.#m}onSync=null;onClientStateNotFound=Sf;onUpdateNeeded=Sf;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){Cf(e);let{name:n,logLevel:r=`info`,logSinks:i=[Ut],pullURL:a=``,auth:o,pushDelay:s=10,pushURL:c=``,schemaVersion:l=``,pullInterval:u=6e4,mutators:d={},requestOptions:f={},puller:p,pusher:m,indexes:h={},clientMaxAgeMs:g=Xu}=e,{enableMutationRecovery:_=!0,enableScheduledPersist:v=!0,enableScheduledRefresh:y=!0,enablePullAndPushInOpen:b=!0,makeSubscriptionsManager:ee=vf,enableClientGroupForking:x=!0}=t;this.auth=o??``,this.pullURL=a,this.pushURL=c,this.name=n,this.schemaVersion=l,this.pullInterval=u,this.pushDelay=s,this.puller=p??dc(this),this.pusher=m??yc(this),this.#y=v,this.#b=y,this.#x=b,this.#g=Sc(r,i,{name:n}),this.#g.debug?.(`Constructing Replicache`,{name:n,"replicache version":cf}),this.subscriptions=ee(this.#W,this.#g);let te=$l(this.#g,e.kvStore);this.#t=te;let ne=te.create(this.idbName);this.#h=new fd(te.create),this.perdag=new la(ne,Wi,Ji),this.memdag=new ta(this.perdag,mf,Wi,Ji);let re=O();this.#o=re.promise;let{minDelayMs:ie=Nr,maxDelayMs:ae=Pr}=f;this.#m={maxDelayMs:ae,minDelayMs:ie};let oe=Cr(Sr(),0,this.#_.signal);this.#f=new Fr(this.#g.withContext(`PULL`),new kr(this,()=>this.#O()),oe),this.#p=new Fr(this.#g.withContext(`PUSH`),new Ar(this,()=>this.#N())),this.mutate=this.#K(d);let se=O();this.#s=se.promise;let ce=O();this.#c=ce.promise,this.#e=new Ou({delegate:this,lc:this.#g,enableMutationRecovery:_,wrapInOnlineCheck:this.#A.bind(this),wrapInReauthRetries:this.#j.bind(this),isPullDisabled:this.#k.bind(this),isPushDisabled:this.#M.bind(this),clientGroupIDPromise:this.#c}),this.#C=Ku(this.name,this.#_.signal,e=>{this.#B(e)}),this.#T(h,x,g,se.resolve,ce.resolve,re.resolve)}async#T(e,t,n,r,i,a){let{clientID:o}=this;await bf.get(this.name),await this.#h.getProfileID().then(r),await this.#h.putDatabase(this.#n);let[s,c,l,u]=await dl(o,this.#g,this.perdag,Object.keys(this.#l),e,7,t);i(s.clientGroupID),await z(this.memdag,e=>e.setHead(I,c)),a(),this.#x&&(this.pull().catch(gf),this.push().catch(gf));let{signal:d}=this.#_;Dd(o,this.perdag,()=>{this.#I(o)},Td,this.#g,d),$u(o,this.perdag,n,Zu,this.#g,d),_d(this.#h,this.#t.drop,md,gd,hd,2*n,this.#g,d),rd(this.perdag,this.#g,d),Uu(this.name,this.idbName,d,s.clientGroupID,u,()=>{this.#R(_f)},this.perdag),Hd(()=>this.recoverMutations(),hf,d),this.recoverMutations(l),Sr()?.addEventListener(`visibilitychange`,this.#E)}#E=async()=>{this.#r||Sr()?.visibilityState===`visible`&&await this.#D()};async#D(){let{clientID:e}=this,t=await R(this.perdag,t=>cl(e,t));return t||this.#I(e),!t}get profileID(){return this.#s}get clientID(){return this.#a}get clientGroupID(){return this.#c}onOnlineChange=null;get online(){return this.#i}get closed(){return this.#r}async close(){this.#r=!0;let{promise:e,resolve:t}=O();bf.set(this.name,e),this.#_.abort(),Sr()?.removeEventListener(`visibilitychange`,this.#E),await this.#o;let n=[this.memdag.close(),this.perdag.close(),this.#h.close()];this.#f.close(),this.#p.close(),this.subscriptions.clear(),await Promise.all(n),bf.delete(this.name),t()}async maybeEndPull(e,t){for(;;){if(this.#r)return;await this.#o;let{clientID:n}=this,r=this.#g.withContext(`maybeEndPull`).withContext(`requestID`,t),{replayMutations:i,diffs:a}=await pu(this.memdag,r,e,n,this.subscriptions,7);if(!i||i.length===0){await this.subscriptions.fire(a),this.#z();return}for(let t of i){this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve();let{meta:i}=t;e=await Uc(this.memdag,a=>tc(t,a,e,ru,this.#l,r,Pa(i)?i.clientID:n,7))}}}#O(){return this.#k()?Promise.resolve(!0):this.#A(async()=>{try{this.#U(0,1);let{syncHead:e,requestID:t,ok:n}=await this.beginPull();if(!n)return!1;e!==F&&await this.maybeEndPull(e,t)}catch(e){throw await this.#J(e)}finally{this.#U(0,-1)}return!0},`Pull`)}#k(){return this.isClientGroupDisabled||this.pullURL===``&&pc(this.puller)}async#A(e,t){let n=!0;try{return await e()}catch(e){return e instanceof vu||e instanceof nu?(n=!1,this.#g.debug?.(`${t} threw:
|
|
7
|
+
`,e)}async function Mu(e,t,n,r,i,a){N(r.replicacheFormatVersion===4),nl(e);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d}=i,f=o.clientID;if(f===t||e.lastServerAckdMutationID>=e.mutationID)return;let p=`Recovering mutations for ${t}.`;s.debug?.(`Start:`,p);let m=new ta(n,ku,Di,Ji);try{if(await R(m,t=>t.setHead(L,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client ${t} because push is disabled.`);return}let{pusher:i}=o,p=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{yr(m);let a=await Du(e,m,n,await o.profileID,void 0,t,i,r.schemaVersion,xu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},p,s);return!!e&&e.httpRequestInfo.httpStatusCode===200},p)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,_;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{let i=await lu(await o.profileID,t,r.schemaVersion,h,e,m,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s);return{pullResponse:_}=e,!!_&&e.httpRequestInfo.httpStatusCode===200},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return s.debug&&_&&(ac(_)?s.debug?.(`Client ${f} cannot recover mutations for client ${t}. The client no longer exists on the server.`):oc(_)?s.debug?.(`Version is not supported on the server. versionType: ${_.versionType}. Cannot recover mutations for client ${t}.`):s.debug?.(`Client ${f} recovered mutations for client ${t}. Details`,{mutationID:e.mutationID,lastServerAckdMutationID:e.lastServerAckdMutationID,lastMutationID:_.lastMutationID})),await R(n,async e=>{let n=await ol(e),r=n.get(t);if(!r)return n;nl(r);let i=async t=>(await Cl(t,e),t);if(ac(_)||oc(_)){let e=new Map(n);return e.delete(t),i(e)}return N(_),r.lastServerAckdMutationID>=_.lastMutationID?n:i(new Map(n).set(t,{...r,lastServerAckdMutationID:_.lastMutationID}))})}catch(e){ju(e,s,p,o)}finally{await m.close(),s.debug?.(`End:`,p)}}async function Nu(e,t,n,r){let i=new la(r(e.name),Wi,Ji);try{await Pu(e,t,i,n)}finally{await i.close()}}function Pu(e,t,n,r){return e.replicacheFormatVersion>=5?Iu(e,t,n):Fu(e,t,n,r)}async function Fu(e,t,n,r){let{delegate:i,lc:a}=t,o=`Recovering mutations from db ${e.name}.`;a.debug?.(`Start:`,o);try{let s=xo(e.replicacheFormatVersion),c=r||await Wc(n,e=>ol(e)),l=new Set;for(;c;){let r;for(let[u,d]of c){if(i.closed){a.debug?.(`Exiting early due to close:`,o);return}if(!l.has(u)&&(l.add(u),r=await Mu(d,u,n,e,t,s),r))break}c=r}}catch(e){ju(e,a,o,i)}a.debug?.(`End:`,o)}async function Iu(e,t,n){let{delegate:r,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.(`Start:`,a);try{let o=xo(e.replicacheFormatVersion),s=await Wc(n,e=>Nc(e)),c=new Set;for(;s;){let l;for(let[u,d]of s){if(r.closed){i.debug?.(`Exiting early due to close:`,a);return}if(!c.has(u)&&(c.add(u),l=await zu(d,u,n,e,t,o),l))break}s=l}}catch(e){ju(e,i,a,r)}i.debug?.(`End:`,a)}function Lu(e){return ac(e)||oc(e)}async function Ru(e,t,n,r,i){ac(r)?e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group is unknown on the server. Marking it as disabled.`):oc(r)&&e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group's version is not supported on the server. versionType: ${r.versionType}. Marking it as disabled.`),await R(i,e=>Vc(n,e))}async function zu(e,t,n,r,i,a){N(r.replicacheFormatVersion>=5);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d,clientGroupIDPromise:f}=i,p=await f;if(yr(p),p===t)return;let m,h=!0;for(let[t,n]of Object.entries(e.mutationIDs))if(!e.lastServerAckdMutationIDs[t]||e.lastServerAckdMutationIDs[t]<n){m=t,h=!1;break}if(h)return;if(e.disabled){s.debug?.(`Not recovering mutations for client group ${t} because group is disabled.`);return}let g=`Recovering mutations for client group ${t}.`;s.debug?.(`Start:`,g);let _=new ta(n,ku,Di,Ji);try{if(await R(_,t=>t.setHead(L,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client group ${t} because push is disabled.`);return}let{pusher:i}=o,f=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{N(m),N(_);let a=await Du(e,_,n,await o.profileID,t,m,i,r.schemaVersion,Su);return{result:a,httpRequestInfo:a?.httpRequestInfo}},f,s);if(!e)return!1;let a=e.response;return Lu(a)?(await Ru(s,p,t,a,n),!1):e.httpRequestInfo.httpStatusCode===200},f)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,v;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{N(m);let i=await uu(await o.profileID,m,t,r.schemaVersion,h,e,_,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s),{pullResponse:i}=e;return Lu(i)?(await Ru(s,p,t,i,n),!1):!i||e.httpRequestInfo.httpStatusCode!==200?!1:(v=i,!0)},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return N(v),s.debug?.(`Client group ${p} recovered mutations for client group ${t}. Details`,{mutationIDs:e.mutationIDs,lastServerAckdMutationIDs:e.lastServerAckdMutationIDs,lastMutationIDChanges:v.lastMutationIDChanges}),await R(n,async e=>{let n=await Nc(e),r=n.get(t);if(!r)return n;N(v);let i={},a=!1;for(let[e,t]of Object.entries(v.lastMutationIDChanges))(r.lastServerAckdMutationIDs[e]??0)<t&&(i[e]=t,a=!0);if(!a)return n;let o=new Map(n).set(t,{...r,lastServerAckdMutationIDs:{...r.lastServerAckdMutationIDs,...i}});return await Pc(o,e),o})}catch(e){ju(e,s,g,o)}finally{await _.close(),s.debug?.(`End:`,g)}}var Bu=class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}},Vu=typeof BroadcastChannel>`u`?Bu:BroadcastChannel;function Hu(e){return`replicache-new-client-group:${e}`}function Uu(e){return`replicache-new-client-group-v1:${e}`}function Wu(e){return typeof e==`object`&&typeof e.clientGroupID==`string`&&typeof e.idbName==`string`}function Gu(e,t,n,r,i,a,o){if(n.aborted)return;let s=new Vu(Uu(e));if(i){s.postMessage({clientGroupID:r,idbName:t});let n=new Vu(Hu(e));n.postMessage([r]),n.close()}s.onmessage=async e=>{let{data:n}=e;if(Wu(n)){let{clientGroupID:e,idbName:i}=n;if(e!==r){if(i===t)await Wc(o,async t=>await zc(e,t)!==void 0)&&a();else{a();return}}}},n.addEventListener(`abort`,()=>s.close(),{once:!0})}function Ku(e){return`replicache-on-persist:${e}`}function qu(e){F(e),P(e.clientGroupID),P(e.clientID)}function Ju(e,t,n){if(t.aborted)return()=>{};let r=new Vu(Ku(e));return r.onmessage=e=>{let{data:t}=e;qu(t),n({clientGroupID:t.clientGroupID,clientID:t.clientID})},t.addEventListener(`abort`,()=>r.close(),{once:!0}),e=>{t.aborted||(r.postMessage(e),n(e))}}async function Yu(e){return(await xa(await ea(L,e),e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}function Xu(e,t,n,r,i){Zu(e,t,n,r,i)}async function Zu(e,t,n,r,i){if(!i.aborted){for(r=r.withContext(`bgIntervalProcess`,e),r.debug?.(`Starting`);!i.aborted;){try{await jr(n(),i)}catch(e){if(!(e instanceof dr))throw e}if(!i.aborted){r.debug?.(`Running`);try{await t()}catch(e){i.aborted?r.debug?.(`Error running most likely due to close.`,e):r.error?.(`Error running.`,e)}}}r.debug?.(`Stopping`)}}var Qu=864e5,$u=3e5,ed;function td(e,t,n,r,i,a){Xu(`ClientGC`,()=>(ed=nd(e,t,n),ed),()=>r,i,a)}function nd(e,t,n){return R(t,async t=>{let r=Date.now(),i=await ol(t),a=Array.from(i).filter(([t,i])=>t===e||r-i.heartbeatTimestampMs<=n);if(a.length===i.size)return i;let o=new Map(a);return await Cl(o,t),o})}var rd=3e5,id;function ad(e,t,n){Xu(`ClientGroupGC`,()=>(id=od(e),id),()=>rd,t,n)}function od(e){return R(e,async e=>{let t=await ol(e),n=new Set;for(let e of t.values())rl(e),n.add(e.clientGroupID);let r=new Map;for(let[t,i]of await Nc(e))(n.has(t)||Bc(i))&&r.set(t,i);return await Pc(r,e),r})}var sd=`replicache-dbs-v0`,cd=``;function ld(){return cd+sd}var ud=`dbs`,dd=`profileId`;function fd(e){F(e);for(let[t,n]of Object.entries(e))P(t),pd(n),N(t===n.name)}function pd(e){F(e),P(e.name),P(e.replicacheName),fr(e.replicacheFormatVersion),P(e.schemaVersion),e.lastOpenedTimestampMS!==void 0&&fr(e.lastOpenedTimestampMS)}var md=class{#e;constructor(e){this.#e=e(ld())}putDatabase(e){return this.#t({...e,lastOpenedTimestampMS:Date.now()})}putDatabaseForTesting(e){return this.#t(e)}#t(e){return R(this.#e,async t=>{let n={...await hd(t),[e.name]:e};return await t.put(ud,n),n})}clearDatabases(){return R(this.#e,e=>e.del(ud))}deleteDatabases(e){return R(this.#e,async t=>{let n={...await hd(t)};for(let t of e)delete n[t];await t.put(ud,n)})}getDatabases(){return Wc(this.#e,hd)}close(){return this.#e.close()}getProfileID(){return R(this.#e,async e=>{let t=await e.get(dd);return t===void 0&&(t=`p${qc()}`,await e.put(dd,t)),P(t),t})}};async function hd(e){let t=await e.get(ud);return t||=gi({}),fd(t),t}var gd=432e5,_d=2592e6,vd=3e5;function yd(e,t,n,r,i,a,o,s){let c=!0;Xu(`CollectIDBDatabases`,async()=>{await bd(e,Date.now(),i,a,t)},()=>c?(c=!1,r):n,o,s)}async function bd(e,t,n,r,i,a=Cd){let o=await e.getDatabases(),s=Object.values(o),{errors:c}=await Sd(e,(await Promise.all(s.map(async e=>[e.name,await wd(e,t,n,r,a)]))).filter(e=>e[1]).map(e=>e[0]),i);if(c.length)throw c[0]}async function xd(e,t,n){await n(e),await t.deleteDatabases([e])}async function Sd(e,t,n){let r=await Promise.allSettled(t.map(async t=>(await xd(t,e,n),t))),i=[],a=[];for(let e of r)e.status===`fulfilled`?i.push(e.value):a.push(e.reason);return{dropped:i,errors:a}}function Cd(e){return new la(new kl(e),Wi,Ji)}async function wd(e,t,n,r,i){if(e.replicacheFormatVersion>7)return!1;if(e.lastOpenedTimestampMS!==void 0){let a=e.replicacheFormatVersion>=5;return t-e.lastOpenedTimestampMS<(a?r:n)?!1:!a||(N(e.replicacheFormatVersion===5||e.replicacheFormatVersion===6||e.replicacheFormatVersion===7),!await Ed(i(e.name)))}let a=i(e.name),o=await Wc(a,ol);return await a.close(),Td(o,t,n)}function Td(e,t,n){for(let r of e.values())if(t-r.heartbeatTimestampMs<n)return!1;return!0}async function Ed(e){let t=await Wc(e,Nc);for(let e of t.values())if(Bc(e))return!0;return!1}var Dd=6e4,Od;function kd(e,t,n,r,i,a){Xu(`Heartbeat`,async()=>{Od=Ad(e,t);try{return await Od}catch(e){if(e instanceof cl){n();return}throw e}},()=>r,i,a)}function Ad(e,t){return R(t,async t=>{let n=await ol(t),r=n.get(e);if(!r)throw new cl(e);let i={...r,heartbeatTimestampMs:Date.now()},a=new Map(n).set(e,i);return await Cl(a,t),a})}var jd=class{#e=new Set;#t;constructor(e){this.#t=e}async visit(e){if(this.#e.has(e))return;this.#e.add(e);let t=await this.#t.mustGetChunk(e);await this.visitChunk(t)}async visitChunk(e){await Promise.all(e.meta.map(e=>this.visit(e)))}},Md=class extends jd{#e=new Map;#t;constructor(e){super(e),this.#t=e}get gatheredChunks(){return this.#e}visit(e){return this.#t.isMemOnlyChunkHash(e)?super.visit(e):oi}visitChunk(e){return this.#e.set(e.hash,e),super.visitChunk(e)}};async function Nd(e,t,n,r,i,a,o,s=()=>Promise.resolve()){if(a())return;let[c,l,u]=await Wc(r,async e=>{await ll(t,e);let n=await xl(t,e);N(n,`No main client group for clientID: ${t}`);let[,r]=await Pd(e,n),i=await r.getMutationID(t,e),a=await Ea(r,e);return Va(a),[i,a,n]});if(a())return;let[d,f,p]=await Wc(n,async e=>{let n=await ja(L,e),r=await Sa(n,{[t]:c||0},e),i=await Ea(n,e);Va(i);let a;if(Oa(i,l)>0){await s();let t=i.chunk.hash,n=new Md(e);await n.visit(t),a=n.gatheredChunks}return[r,i,a]});if(a())return;let m=!1;await R(r,async n=>{let[r,a]=await Pd(n,u),s=a.chunk.hash,c={...r.mutationIDs},{lastServerAckdMutationIDs:l}=r;if(p){let u=await fl(t,n);rl(u);let d=await Ea(a,n);if(Va(d),Oa(f,d)>0){m=!0,await Promise.all(Array.from(p.values(),e=>n.putChunk(e))),await Sl(t,{...u,persistHash:f.chunk.hash},n),s=f.chunk.hash;let a=await xa(r.headHash,n);l=f.meta.lastMutationIDs,c={...l},s=await Fd(a,s,n,i,c,e,o)}}s=await Fd(d,s,n,i,c,e,o);let h={...r,headHash:s,mutationIDs:c,lastServerAckdMutationIDs:l};await Fc(u,h,n)}),p&&m&&await R(n,e=>e.chunksPersisted([...p.keys()]))}async function Pd(e,t){let n=await zc(t,e);return N(n,`No client group for clientGroupID: ${t}`),[n,await Aa(n.headHash,e)]}async function Fd(e,t,n,r,i,a,o){for(let s=e.length-1;s>=0;s--){let c=e[s],{meta:l}=c,u=await Aa(t,n);await c.getMutationID(l.clientID,n)>await u.getMutationID(l.clientID,n)&&(i[l.clientID]=l.mutationID,t=(await tc(c,n,t,r,a,l.clientID,o)).chunk.hash)}return t}var Id=class extends jd{#e=new Map;#t=0;#n;#r;#i;constructor(e,t,n,r=di){super(e),this.#n=t,this.#r=n,this.#i=r}get gatheredChunks(){return this.#e}visit(e){return this.#t>=this.#r||this.#n.isCached(e)?oi:super.visit(e)}visitChunk(e){if(this.#t<this.#r){let t=this.#i(e);this.#e.set(e.hash,{chunk:e,size:t}),this.#t+=t}return super.visitChunk(e)}},Ld=5*2**20,Rd=300;async function zd(e,t,n,r,i,a,o,s){if(o())return;let c=await Wc(t,e=>Ca(L,e));Va(c);let l=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let l=await R(n,async e=>{let n=await bl(r,e);if(!n)throw new cl(r);let i=n.headHash,a=await(await Aa(i,e)).getMutationID(r,e),o=await fl(r,e);rl(o);let s=await Ta(i,e);if(Va(s),Bd(c,s,i))return;let l=new Id(e,t,Ld);await l.visit(i);let{gatheredChunks:u}=l,d=new Set(o.refreshHashes);return d.add(i),await Sl(r,{...o,refreshHashes:[...d]},e),[i,s,a,u,o.refreshHashes]});if(o()||!l||(await jr(Rd),o()))return{type:`aborted`};let[u,d,f,p,m]=l;return R(t,async t=>{let n=await ja(L,t),o=await Ea(n,t);if(Va(o),Bd(o,d,u))return{type:`aborted`,refreshHashesForRevert:m};let c=await Sa(n,{[r]:f},t),l=[];for(let{chunk:e,size:n}of p.values())l.push(t.putChunk(e,n));await Promise.all(l);let h=u;for(let n=c.length-1;n>=0;n--)h=(await tc(c[n],t,h,i,e,c[n].meta.clientID,s)).chunk.hash;let g=await Gs(n,await Aa(h,t),t,a,s);return await t.setHead(L,h),{type:`complete`,diffs:g,newPerdagClientHeadHash:u}})});if(o())return;let u=e=>R(n,async t=>{await Sl(r,{...await fl(r,t),refreshHashes:e},t)});if(l.type===`aborted`){l.refreshHashesForRevert&&await u(l.refreshHashesForRevert);return}return await u([l.newPerdagClientHeadHash]),l.diffs}function Bd(e,t,n){let r=Oa(e,t);return r>0||r===0&&n===t.chunk.hash}function Vd(e){return new Promise(t=>{typeof requestIdleCallback==`function`?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var Hd=class{#e;#t;#n;#r;#i;#a=void 0;#o=void 0;#s=Promise.resolve();#c=Promise.resolve();constructor(e,t,n,r,i=Vd){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,this.#r.addEventListener(`abort`,()=>{let e=new dr(`Aborted`);this.#o?.reject(e),this.#a?.reject(e),this.#o=void 0,this.#a=void 0},{once:!0})}schedule(){return this.#r.aborted?Promise.reject(new dr(`Aborted`)):this.#a?this.#a.promise:(this.#a=Wt(),this.#l(),this.#a.promise)}async#l(){try{await this.#s}catch{}if(await this.#c,this.#a&&(await this.#i(this.#t),this.#a)){this.#c=Ud(this.#n,this.#r),this.#o=this.#a,this.#a=void 0;try{this.#s=this.#e(),await this.#s,this.#o?.resolve()}catch(e){this.#o?.reject(e)}this.#o=void 0}}};async function Ud(e,t){try{await jr(e,t)}catch(e){N(e instanceof dr)}}function Wd(e,t,n){let r=setInterval(e,t);n.addEventListener(`abort`,()=>{clearInterval(r)})}var Gd=new Set,Kd=Symbol(),qd=class{#e;#t;#n=Kd;#r=Gd;#i=[];onError;onDone;#a;constructor(e,t,n,r,i=Wr){this.#e=e,this.#t=t,this.onError=n,this.onDone=r,this.#a=i}hasIndexSubscription(e){for(let t of this.#i)if(t.options.indexName===e)return!0;return!1}invoke(e,t,n){return this.#e(e)}matches(e){for(let[t,n]of e)if(Zd(this.#r,this.#i,t,n))return!0;return!1}updateDeps(e,t){this.#r=e,this.#i=t}onData(e){(this.#n===Kd||!this.#a(this.#n,e))&&(this.#n=e,this.#t(e))}},Jd=class{#e;#t;#n;#r;onError=void 0;onDone=void 0;constructor(e,t){this.#e=e,this.#t=t?.prefix??``,this.#n=t?.indexName,this.#r=t?.initialValuesInFirstDiff??!1}hasIndexSubscription(e){return this.#n===e}onData(e){e!==void 0&&this.#e(e)}invoke(e,t,n){let r=async(r,i,a,o)=>{let s;if(t===0){if(!this.#r)return;N(n===void 0);let t=[];for await(let n of e.scan({prefix:i,indexName:r}).entries())t.push({op:`add`,key:n[0],newValue:n[1]});s=t}else N(n),s=o(n.get(r??``)??[]);let c=[],{length:l}=s;for(let e=rf(s,i,a);e<l&&a(s[e]).startsWith(i);e++)c.push(s[e]);return t===0||c.length>0?c:void 0};return this.#n?r(this.#n,this.#t,e=>e.key[0],e=>Yd(e,us)):r(void 0,this.#t,e=>e.key,e=>Yd(e,e=>e))}matches(e){let t=e.get(this.#n??``);return t!==void 0&&nf(t,this.#t,this.#n)}updateDeps(e,t){}};function Yd(e,t){return e.map(e=>{let n=t(e.key);switch(e.op){case`add`:return{op:`add`,key:n,newValue:e.newValue};case`change`:return{op:`change`,key:n,oldValue:e.oldValue,newValue:e.newValue};case`del`:return{op:`del`,key:n,oldValue:e.oldValue}}})}var Xd=class{#e=new Set;#t=new Set;#n;#r;hasPendingSubscriptionRuns=!1;constructor(e,t){this.#n=e,this.#r=t}add(e){return this.#e.add(e),this.#a(e),()=>this.#e.delete(e)}clear(){for(let e of this.#e)e.onDone?.();this.#e.clear()}async fire(e){let t=tf(this.#e,e);await this.#i(t,1,e)}async#i(e,t,n){let r=[...e];if(r.length===0)return;let i=await this.#n(e=>Promise.allSettled(r.map(async r=>{let i=new Ps(e);try{return await r.invoke(i,t,n)}finally{r.updateDeps(i.keys,i.scans)}})));this.callCallbacks(r,i)}callCallbacks(e,t){for(let n=0;n<e.length;n++){let r=e[n],i=t[n];i.status===`fulfilled`?r.onData(i.value):r.onError?r.onError(i.reason):this.#r.error?.(`Error in subscription body:`,i.reason)}}async#a(e){if(this.#t.add(e),!this.hasPendingSubscriptionRuns){this.hasPendingSubscriptionRuns=!0,await Promise.resolve(),this.hasPendingSubscriptionRuns=!1;let e=[...this.#t];this.#t.clear(),await this.#i(e,0,void 0)}}shouldComputeDiffs(){return this.#e.size>0}shouldComputeDiffsForIndex(e){for(let t of this.#e)if(t.hasIndexSubscription(e))return!0;return!1}};function Zd(e,t,n,r){if(n===``){for(let t of r)if(e.has(t.key))return!0}for(let e of t)if(Qd(e,n,r))return!0;return!1}function Qd(e,t,n){for(let r of n)if($d(e,t,r.key))return!0;return!1}function $d(e,t,n){let{indexName:r=``,limit:i,prefix:a,startKey:o,startExclusive:s,startSecondaryKey:c}=e.options;if(t!==r)return!1;if(!r)return i!==void 0&&i<=0?!1:!a&&!o||!(a&&(!n.startsWith(a)||ef(e,n))||o&&(s&&yo(n,o)||vo(n,o)||ef(e,n)));if(!a&&!o&&!c)return!0;let[l,u]=us(n);return!(a&&!l.startsWith(a)||c&&(s&&yo(l,c)||vo(l,c))||o&&(s&&yo(u,o)||vo(u,o)))}function ef(e,t){let{inclusiveLimitKey:n}=e;return e.options.limit!==void 0&&n!==void 0&&_o(t,n)}function*tf(e,t){for(let n of e)n.matches(t)&&(yield n)}function nf(e,t,n){if(t===``)return!0;let r=n?e=>us(e.key)[0]:e=>e.key,i=rf(e,t,r);return i<e.length&&r(e[i]).startsWith(t)}function rf(e,t,n){return bo(e.length,r=>lo(t,n(e[r])))}function af(e){if(e===null)throw TypeError(`array cannot be null`);for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e}var of=``;function sf(){if(of===``){let e=new Uint8Array(4);af(e),of=Array.from(e,e=>e.toString(16)).join(``)}return of}var cf=new Map;function lf(e){let t=cf.get(e);return t?(t++,cf.set(e,t)):(cf.set(e,0),t=0),`${e}-${sf()}-${t}`}var uf=`15.3.0`,df=8,ff=1e3,pf=1e3,mf=500,hf=500,gf=100*2**20,_f=3e5,vf=()=>{},yf={type:`NewClientGroup`},bf=(e,t)=>new Xd(e,t),xf=class{pullURL;pushURL;auth;name;subscriptions;#e;isClientGroupDisabled=!1;#t;lastMutationID=0;get idbName(){return Xl(this.name,this.schemaVersion)}schemaVersion;get#n(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#r=!1;#i=!0;#a=qc();#o;#s;#c;#l={};mutate;#u=0;#d=0;#f;#p;pullInterval;pushDelay;#m;puller;pusher;memdag;perdag;#h;#g;#_=new AbortController;#v=!1;#y;#b;#x;#S=new Hd(()=>this.persist(),ff,mf,this.#_.signal);#C;#w=new Hd(()=>this.refresh(),pf,hf,this.#_.signal);get requestOptions(){return this.#m}onSync=null;onClientStateNotFound=wf;onUpdateNeeded=wf;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){Tf(e);let{name:n,logLevel:r=`info`,logSinks:i=[zt],pullURL:a=``,auth:o,pushDelay:s=10,pushURL:c=``,schemaVersion:l=``,pullInterval:u=6e4,mutators:d={},requestOptions:f={},puller:p,pusher:m,indexes:h={},clientMaxAgeMs:g=Qu}=e,{enableMutationRecovery:_=!0,enableScheduledPersist:v=!0,enableScheduledRefresh:y=!0,enablePullAndPushInOpen:b=!0,makeSubscriptionsManager:x=bf,enableClientGroupForking:S=!0}=t;this.auth=o??``,this.pullURL=a,this.pushURL=c,this.name=n,this.schemaVersion=l,this.pullInterval=u,this.pushDelay=s,this.puller=p??fc(this),this.pusher=m??bc(this),this.#y=v,this.#b=y,this.#x=b,this.#g=Cc(r,i,{name:n}),this.#g.debug?.(`Constructing Replicache`,{name:n,"replicache version":uf}),this.subscriptions=x(this.#W,this.#g);let C=tu(this.#g,e.kvStore);this.#t=C;let ee=C.create(this.idbName);this.#h=new md(C.create),this.perdag=new la(ee,Wi,Ji),this.memdag=new ta(this.perdag,gf,Wi,Ji);let w=Wt();this.#o=w.promise;let{minDelayMs:te=Mr,maxDelayMs:ne=Nr}=f;this.#m={maxDelayMs:ne,minDelayMs:te};let re=Sr(xr(),0,this.#_.signal);this.#f=new Pr(this.#g.withContext(`PULL`),new Or(this,()=>this.#O()),re),this.#p=new Pr(this.#g.withContext(`PUSH`),new kr(this,()=>this.#N())),this.mutate=this.#K(d);let ie=Wt();this.#s=ie.promise;let T=Wt();this.#c=T.promise,this.#e=new Au({delegate:this,lc:this.#g,enableMutationRecovery:_,wrapInOnlineCheck:this.#A.bind(this),wrapInReauthRetries:this.#j.bind(this),isPullDisabled:this.#k.bind(this),isPushDisabled:this.#M.bind(this),clientGroupIDPromise:this.#c}),this.#C=Ju(this.name,this.#_.signal,e=>{this.#B(e)}),this.#T(h,S,g,ie.resolve,T.resolve,w.resolve)}async#T(e,t,n,r,i,a){let{clientID:o}=this;await Sf.get(this.name),await this.#h.getProfileID().then(r),await this.#h.putDatabase(this.#n);let[s,c,l,u]=await pl(o,this.#g,this.perdag,Object.keys(this.#l),e,7,t);i(s.clientGroupID),await R(this.memdag,e=>e.setHead(L,c)),a(),this.#x&&(this.pull().catch(vf),this.push().catch(vf));let{signal:d}=this.#_;kd(o,this.perdag,()=>{this.#I(o)},Dd,this.#g,d),td(o,this.perdag,n,$u,this.#g,d),yd(this.#h,this.#t.drop,gd,vd,_d,2*n,this.#g,d),ad(this.perdag,this.#g,d),Gu(this.name,this.idbName,d,s.clientGroupID,u,()=>{this.#R(yf)},this.perdag),Wd(()=>this.recoverMutations(),_f,d),this.recoverMutations(l),xr()?.addEventListener(`visibilitychange`,this.#E)}#E=async()=>{this.#r||xr()?.visibilityState===`visible`&&await this.#D()};async#D(){let{clientID:e}=this,t=await Wc(this.perdag,t=>ul(e,t));return t||this.#I(e),!t}get profileID(){return this.#s}get clientID(){return this.#a}get clientGroupID(){return this.#c}onOnlineChange=null;get online(){return this.#i}get closed(){return this.#r}async close(){this.#r=!0;let{promise:e,resolve:t}=Wt();Sf.set(this.name,e),this.#_.abort(),xr()?.removeEventListener(`visibilitychange`,this.#E),await this.#o;let n=[this.memdag.close(),this.perdag.close(),this.#h.close()];this.#f.close(),this.#p.close(),this.subscriptions.clear(),await Promise.all(n),Sf.delete(this.name),t()}async maybeEndPull(e,t){for(;;){if(this.#r)return;await this.#o;let{clientID:n}=this,r=this.#g.withContext(`maybeEndPull`).withContext(`requestID`,t),{replayMutations:i,diffs:a}=await hu(this.memdag,r,e,n,this.subscriptions,7);if(!i||i.length===0){await this.subscriptions.fire(a),this.#z();return}for(let t of i){this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve();let{meta:i}=t;e=await Gc(this.memdag,a=>nc(t,a,e,au,this.#l,r,Fa(i)?i.clientID:n,7))}}}#O(){return this.#k()?Promise.resolve(!0):this.#A(async()=>{try{this.#U(0,1);let{syncHead:e,requestID:t,ok:n}=await this.beginPull();if(!n)return!1;e!==Ui&&await this.maybeEndPull(e,t)}catch(e){throw await this.#J(e)}finally{this.#U(0,-1)}return!0},`Pull`)}#k(){return this.isClientGroupDisabled||this.pullURL===``&&mc(this.puller)}async#A(e,t){let n=!0;try{return await e()}catch(e){return e instanceof bu||e instanceof iu?(n=!1,this.#g.debug?.(`${t} threw:
|
|
8
8
|
`,e,`
|
|
9
9
|
with cause:
|
|
10
|
-
`,e.causedBy)):e instanceof
|
|
11
|
-
`,e),!1}finally{this.#i!==n&&(this.#i=n,this.onOnlineChange?.(n),n&&this.recoverMutations())}}async#j(e,t,n,r=gf,i=gf){let{clientID:a}=this,o=0,s;n=n.withContext(t);do{let c=sf(a),l=n.withContext(`requestID`,c),{httpRequestInfo:u,result:d}=await e(c,l);if(s=d,!u)return{result:d,authFailure:!1};let{errorMessage:f,httpStatusCode:p}=u;if((f||p!==200)&&l.error?.(`Got a non 200 response doing ${t}: ${p}`+(f?`: ${f}`:``)),p!==ql)return{result:d,authFailure:!1};if(!this.getAuth)return{result:d,authFailure:!0};let m;try{await r(),m=await this.getAuth()}finally{await i()}if(m==null)return{result:d,authFailure:!0};this.auth=m,o++}while(o<lf);return n.info?.(`Tried to reauthenticate too many times`),{result:s,authFailure:!0}}#M(){return this.isClientGroupDisabled||this.pushURL===``&&xc(this.pusher)}async#N(){if(this.#M())return!0;await this.#o;let e=await this.#s,{clientID:t}=this,n=await this.#c;return this.#A(async()=>{let{result:r}=await this.#j(async(r,i)=>{try{this.#U(1,0);let a=await Tu(r,this.memdag,i,e,n,t,this.pusher,this.schemaVersion,bu);return{result:a,httpRequestInfo:a?.httpRequestInfo}}finally{this.#U(-1,0)}},`push`,this.#g);if(r===void 0)return!0;let{response:i,httpRequestInfo:a}=r;return ac(i)?this.#P(i):ic(i)&&await this.#L(),a.httpStatusCode===200},`Push`)}#P(e){let t={type:e.error};e.versionType&&(t.versionType=e.versionType),this.#R(t)}push({now:e=!1}={}){return xf(this.#p.send(e))}pull({now:e=!1}={}){return xf(this.#f.send(e))}async poke(e){await this.#o;let{clientID:t}=this,n=sf(t),r=this.#g.withContext(`handlePullResponse`).withContext(`requestID`,n),{pullResponse:i}=e;if(ac(i)){this.#P(i);return}if(ic(i)){await this.#L();return}let a=await fu(r,this.memdag,_i(e.baseCookie),i,t,7);switch(a.type){case 0:await this.maybeEndPull(a.syncHead,n);break;case 2:throw Error(`unexpected base cookie for poke: `+JSON.stringify(e))}}async beginPull(){await this.#o;let e=await this.profileID,{clientID:t}=this,n=await this.#c,{result:{beginPullResponse:r,requestID:i}}=await this.#j(async(r,i)=>{let a=await cu(e,t,n,this.schemaVersion,this.puller,r,this.memdag,7,i);return{result:{beginPullResponse:a,requestID:r},httpRequestInfo:a.httpRequestInfo}},`pull`,this.#g,()=>this.#U(0,-1),()=>this.#U(0,1)),{pullResponse:a}=r;ac(a)?this.#P(a):ic(r.pullResponse)&&await this.#L();let{syncHead:o,httpRequestInfo:s}=r;return{requestID:i,syncHead:o,ok:s.httpStatusCode===200}}async persist(){A(!this.#v),this.#v=!0;try{let{clientID:e}=this;if(await this.#o,this.#r)return;try{await jd(this.#g,e,this.memdag,this.perdag,this.#l,()=>this.closed,7)}catch(t){if(t instanceof ol)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception persisting during close`,t);else throw t}}finally{this.#v=!1}let{clientID:e}=this,t=await this.#c;A(t),this.#C({clientID:e,clientGroupID:t})}async refresh(){await this.#o;let{clientID:e}=this;if(this.#r)return;let t;try{t=await Ld(this.#g,this.memdag,this.perdag,e,this.#l,this.subscriptions,()=>this.closed,7)}catch(t){if(t instanceof ol)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception refreshing during close`,t);else throw t}t!==void 0&&await this.subscriptions.fire(t)}#F(){this.onClientStateNotFound?.()}#I(e){this.#g.error?.(`Client state not found on client, clientID: ${e}`),this.#F()}async#L(){let e=await this.#c;this.#g.error?.(`Client state not found on server, clientGroupID: ${e}`),await this.disableClientGroup(),this.#F()}async disableClientGroup(){let e=await this.#c;A(e),this.isClientGroupDisabled=!0,await z(this.perdag,t=>Bc(e,t))}#R(e){this.#g.debug?.(`Update needed, reason: ${e}`),this.onUpdateNeeded?.(e)}async#z(){this.#y&&await this.#H(`persist`,this.#S)}async#B(e){this.#g.debug?.(`Handling persist`,e);let t=await this.#c;e.clientGroupID===t&&this.#V()}async#V(){this.#b&&await this.#H(`refresh from storage`,this.#w)}async#H(e,t){try{await t.schedule()}catch(t){t instanceof pr?this.#g.debug?.(`Scheduled ${e} did not complete before close.`):this.#g.error?.(`Error during ${e}`,t)}}#U(e,t){this.#u+=e,this.#d+=t;let n=e+t,r=this.#u+this.#d;if(n===1&&r===1||r===0){let e=r>0;Promise.resolve().then(()=>this.onSync?.(e))}}subscribe(e,t){typeof t==`function`&&(t={onData:t});let{onData:n,onError:r,onDone:i,isEqual:a}=t;return this.subscriptions.add(new Gd(e,n,r,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new Kd(e,t))}query(e){return this.#W(e)}get cookie(){return this.#o.then(()=>R(this.memdag,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta.cookieJSON;return ri(n),n}))}#W=async e=>{await this.#o;let{clientID:t}=this;return R(this.memdag,async n=>{try{let r=await fs(n,7);return await e(new As(t,r,this.#g))}catch(e){throw await this.#J(e)}})};#G(e,t){return this.#l[e]=t,n=>this.#q(e,t,n,performance.now())}#K(e){let t=Object.create(null);for(let n in e)t[n]=this.#G(n,e[n]);return t}async#q(e,t,n,r){let i=_i(n??null);this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#o;let{clientID:a}=this;return Uc(this.memdag,async o=>{try{let s=await qs(await ea(I,o),e,i,null,o,r,a,7),c=await t(new Ps(a,await s.getMutationID(),`initial`,s,this.#g),n);xs(s);let l=await s.getMutationID(),u=await s.commitWithDiffs(I,this.subscriptions);return this.lastMutationID=l,this.#p.send(!1).catch(()=>{}),await this.subscriptions.fire(u),this.#z(),c}catch(e){throw await this.#J(e)}})}async#J(e){return e instanceof Qi&&await this.#D()?new ol(this.clientID):e}recoverMutations(e){return this.#e.recoverMutations(e,this.#o,this.perdag,this.#n,this.#h,this.#t.create)}experimentalPendingMutations(){return R(this.memdag,qu)}},bf=new Map;async function xf(e){let t=await e;if(t)throw t.error}function Sf(){typeof location<`u`&&location.reload()}function Cf(e){let{name:t,clientMaxAgeMs:n}=e;if(typeof t!=`string`||!t)throw TypeError(`name is required and must be non-empty`);if(n!==void 0){let e=Math.max(Zu,Td);if(typeof n!=`number`||n<=e)throw TypeError(`clientAgeMaxMs must be a number larger than ${e}ms`)}}var wf={PENDING:`PENDING`,IN_PROGRESS:`IN_PROGRESS`,READY:`READY`,ERROR:`ERROR`,CANCELED:`CANCELED`},Tf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,spriteBuildId:a,prompt:o,name:s,surfaceId:c}=t,l=w.sprite.encode(i);if(await n.get(l))return Error(`Sprite "${i}" already exists`);let u=w.spriteBuild.encode(a);if(await n.get(u))return Error(`SpriteBuild "${a}" already exists`);let d={name:s?.trim().length?s:``,surfaceId:c,ownedByPersonId:r};await n.set(l,d);let f={spriteId:i,parentSpriteBuildId:null,prompt:o,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(u,f)},Ef=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,name:a,surfaceId:o}=t,s=w.sprite.encode(i);if(await n.get(s))return Error(`Sprite "${i}" already exists`);let c={name:a?.trim().length?a:``,surfaceId:o,ownedByPersonId:r};await n.set(s,c)},Df=async()=>{},Of=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);o.status!==wf.PENDING&&o.status!==wf.IN_PROGRESS||o.cancelRequestedAt!==null||await n.set(a,{...o,cancelRequestedAt:r})},kf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=w.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o,prompt:s,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},Af=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=w.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o??null,prompt:s,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},jf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==wf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})},Mf={surface_upsert_v1:async(e,t)=>{let{tx:n}=e,{surfaceId:r,key:i,name:a,description:o}=t,s={key:i,name:a,description:o};for await(let[e,t]of n.scan({prefix:w.surface.prefix()}).entries())if(t.key===i){await n.set(e,s);return}await n.set(w.surface.encode(r),s)},project_ping_v1:Df,sprite_create_v2:Ef,spriteBuild_create_v2:Af,spriteBuild_cancel_v1:Of,spriteBuild_publish_v2:async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==wf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})}},Nf={sprite_create_v1:Tf,spriteBuild_create_v1:kf,spriteBuild_publish_v1:jf},Pf={...Mf,...Nf};async function Ff(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};if(i){if(i.aborted){y(i.reason);return}i.addEventListener(`abort`,g,{once:!0})}let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==If&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===If&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var If=Symbol(`skip`),Lf={concurrency:5,stopOnError:!1},Rf=async(e,r,i=Lf)=>{let{stopOnError:a}=i;return n(async()=>Ff(e,async e=>{let n=await t(async()=>r(e));if(a&&n instanceof Error)throw n;return n},i))},zf=async(e,t,n)=>{let r=await Rf(Object.entries(e),async([e,n])=>[e,await t(n,e)],n);return r instanceof Error?r:Object.fromEntries(r)},Bf=async(e,t)=>zf(t,async t=>{let n=t;return async(t,r)=>{let{context:i,...a}=r,o={...e,tx:t,actionedAt:i?.actionedAt??Date.now(),sessionPersonId:i?.sessionPersonId??e.sessionPersonId},s=await n(o,a);if(s instanceof Error)throw s;return s}}),Vf=`2026.08.20/1`,Hf=async e=>{let{name:t,pushURL:n,pullURL:r,auth:i,getAuth:a,pullInterval:o,sessionPersonId:s}=e;if(!t)return Error(`Replicache name is required`);let c=new Xl({schemaVersion:Vf,name:t,pushURL:n,pullURL:r,auth:i,pullInterval:o,mutators:await Bf({sessionPersonId:s},Pf)});return c.getAuth=a,c},Uf=class{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw Error(`Base must be a positive integer or zero`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw Error(`ExpMax must be undefined, a positive integer, or zero`);this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*2**this.i}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}},B={open:`open`,close:`close`,error:`error`,message:`message`,retry:`retry`,reconnect:`reconnect`},Wf=class{constructor(e,t,n){this._closedByUser=!1,this.handleOpenEvent=e=>this.handleEvent(B.open,e),this.handleErrorEvent=e=>this.handleEvent(B.error,e),this.handleCloseEvent=e=>this.handleEvent(B.close,e),this.handleMessageEvent=e=>this.handleEvent(B.message,e),this._urlProvider=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:n?.retry?.maxRetries,instantReconnect:n?.retry?.instantReconnect,backoff:n?.retry?.backoff},listeners:{open:[...n?.listeners?.open??[]],close:[...n?.listeners?.close??[]],error:[...n?.listeners?.error??[]],message:[...n?.listeners?.message??[]],retry:[...n?.listeners?.retry??[]],reconnect:[...n?.listeners?.reconnect??[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){let r=e=>e.listener!==t||e.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._url=typeof this._urlProvider==`function`?this._urlProvider():this._urlProvider,this._underlyingWebsocket=new WebSocket(this._url,this.protocols),this._underlyingWebsocket.addEventListener(B.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(B.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(B.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(B.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(B.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(B.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(B.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(B.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){let n=this._options.listeners[e],r=[];n.forEach(({listener:e,options:n})=>{e(this,t),(n===void 0||n.once===void 0||!n.once)&&r.push({listener:e,options:n})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case B.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case B.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){let e={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},t=new CustomEvent(B.reconnect,{detail:e});this.dispatchEvent(B.reconnect,t),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case B.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t)}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;let e=e=>{let t=new CustomEvent(B.retry,{detail:e});this.handleEvent(B.retry,t)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}},Gf=class{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{maxRetries:e})}),this}get maxRetries(){return this._options?.retry?.maxRetries}withInstantReconnect(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{instantReconnect:e})}),this}get instantReconnect(){return this._options?.retry?.instantReconnect}withBackoff(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{backoff:e})}),this}get backoff(){return this._options?.retry?.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){return this._options?.buffer}onOpen(e,t){return this.addListener(B.open,e,t),this}onClose(e,t){return this.addListener(B.close,e,t),this}onError(e,t){return this.addListener(B.error,e,t),this}onMessage(e,t){return this.addListener(B.message,e,t),this}onRetry(e,t){return this.addListener(B.retry,e,t),this}onReconnect(e,t){return this.addListener(B.reconnect,e,t),this}build(){return new Wf(this._url,this._protocols,this._options)}addListener(e,t,n){return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:this._options?.listeners?.open??[],close:this._options?.listeners?.close??[],error:this._options?.listeners?.error??[],message:this._options?.listeners?.message??[],retry:this._options?.listeners?.retry??[],reconnect:this._options?.listeners?.reconnect??[],[e]:[...this._options?.listeners?.[e]??[],{listener:t,options:n}]}}),this}},Kf=e.object({type:e.literal(`poke`)}).strict(),qf=e=>{console.warn(`[Rough poke] ${e}`)},Jf=e=>{let{getToken:t,onPoke:n,url:r}=e,i=!1,a=0;try{let e=new Gf(r).withBackoff(new Uf(1e3,7)).build(),o=()=>{let n=++a;t().then(t=>{i||n!==a||e.readyState!==1||e.send(JSON.stringify({type:`authenticate`,token:t}))}).catch(()=>{qf(`Failed to get a session token`)})},s=(e,t)=>{if(typeof t.data!=`string`){qf(`Received an invalid server message`);return}let r;try{r=JSON.parse(t.data)}catch{qf(`Received malformed server JSON`);return}if(!Kf.safeParse(r).success){qf(`Received an invalid server message`);return}Promise.resolve(n()).catch(()=>{qf(`Failed to pull after a server poke`)})},c=()=>{qf(`Connection failed`)},l=()=>{i||qf(`Connection closed; reconnecting`)};return e.addEventListener(B.open,o),e.addEventListener(B.message,s),e.addEventListener(B.error,c),e.addEventListener(B.close,l),{close:()=>{i||(i=!0,e.removeEventListener(B.open,o),e.removeEventListener(B.message,s),e.removeEventListener(B.error,c),e.removeEventListener(B.close,l),e.close())}}}catch{return qf(`Failed to create connection`),{close:()=>{}}}};function Yf(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}var Xf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Zf(e,t){return e>>>t|e<<32-t}function Qf(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=Zf(t,7)^Zf(t,18)^t>>>3,i=Zf(n,17)^Zf(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=Zf(a,6)^Zf(a,11)^Zf(a,25),s=a&g^~a&_,c=v+o+s+(Xf[e]??0)+(h[e]??0)>>>0,l=(Zf(t,2)^Zf(t,13)^Zf(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function $f(e){return`sha256:${Qf(e)}`}function ep(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(ep(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ep(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function tp(e){return ep(e,new WeakSet)}function np(e,t=$f){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function rp(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(rp),Object.freeze(e))}function V(e){let t=JSON.parse(tp(e));return rp(t),t}function ip(e){let t=V([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=tp(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:np(n)})}function ap(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function op(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function sp(e){if(!op(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function cp(e){return op(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function lp(e){return Object.keys(e).length>0?e:void 0}function up(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=up(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Array.isArray(r.items)?r.items[0]:r.items,a=t?up(t,t.required||[]):void 0;e[n]={...r,items:a?a.schema:r.items,...i?{type:[`array`,`null`]}:{}},o=i,s=a?.nullWidening?{items:a.nullWidening}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Array.isArray(n.items)?n.items[0]:n.items;if(e){let t=up(e,e.required||[]);n.items=t.schema,t.nullWidening&&(r.items=t.nullWidening)}}return{schema:n,nullWidening:lp(r)}}function dp(e){if(sp(e)){let t=ap(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(cp(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?ap(e):e}function fp(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!sp(e)&&!cp(e))return e;let r=dp(e);return!r||typeof r!=`object`||!n?r:up(r,r.required||[]).schema}var pp=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function mp(e,t){if(!cp(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new pp(n.issues)}var hp=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function gp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function _p(e){return gp(e)&&Object.keys(e).some(e=>hp.has(e))}function vp(e){return cp(e)||sp(e)||_p(e)}function yp(e){if(!gp(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>vp(e[t]))}function bp(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function xp(e){if(cp(e)){let t=sp(e)?bp(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(_p(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Sp(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Cp(e,t){let n=t===void 0?null:xp(t),r=null,i=null;if(e!==void 0){if(cp(e)||_p(e))r=xp(e),i=r;else if(yp(e))r=e.approve===void 0?null:xp(e.approve),i=e.reject===void 0?null:xp(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Sp({approved:!0,payload:r,inputSchema:n}),Sp({approved:!1,payload:i,inputSchema:null})]},o=tp(a),s=tp({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:np(o),approvalSchemaHash:np(s)}}function wp(e){return np(e===void 0?`undefined`:tp(xp(e).jsonSchema??{standardValidator:`unserialized`}))}var Tp=`tanstack:interruptBinding`,Ep=Tp;function Dp(e){return e&&typeof e==`object`?e:null}function Op(e,t){return typeof e[t]==`string`?e[t]:void 0}function kp(e){let t=e.v;return t===void 0||t===1}function Ap(e){let t=Dp(e.metadata),n=t?Dp(t[Ep]):null;if(!n||Op(n,`interruptId`)!==e.id||!kp(n))return;let r=Op(n,`kind`),i=Op(n,`interruptId`),a=Op(n,`responseSchemaHash`),o=Op(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Op(n,`definitionId`),t=Op(n,`key`),s=n.batchIndex,c=Op(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Op(n,`toolName`),c=Op(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=Op(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Op(n,`inputSchemaHash`),t=Op(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function jp(e){let t=Ap(e);if(!t)return;let n=Dp(e.metadata),r=n?Dp(n[Ep]):null;if(!r)return;let i=Op(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Mp=`tanstack:interruptPayload`;function Np(e,t){if(!sp(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:tp(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Pp(e){return np(Np(e,`Interrupt schema`).canonicalJson)}var Fp=`tanstack:interruptContinuation`;function Ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lp(e){return{[Fp]:e}}function Rp(e){let t=Ap(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Ip(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Mp]}:{}}}var zp=new Set([`text`,`image`,`audio`,`video`,`document`]);function Bp(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!zp.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function Vp(e){return Array.isArray(e)&&e.length>0&&e.every(Bp)}function Hp(e){return typeof e==`string`||Vp(e)?e:JSON.stringify(e)}function Up(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Wp(e){return Up(e)!==null}function Gp(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Kp(e){try{return JSON.stringify(e)??``}catch{return``}}function qp(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function Jp(e){return e===null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function Yp(e){let t=new Set;for(let n of e)if(`parts`in n)for(let e of n.parts)e.type===`tool-result`&&t.add(e.toolCallId);let n=[];for(let r of e){if(`parts`in r){n.push(...Xp(r));continue}let e=r.role;if(!(e===`tool`&&r.toolCallId&&t.has(r.toolCallId))&&e!==`reasoning`&&e!==`activity`){if(e===`developer`){n.push({role:`system`,content:r.content});continue}n.push(r)}}return n}function Xp(e){return e.role===`system`?[]:e.role===`assistant`?em(e):[Zp(e)]}function Zp(e){let t=[];for(let n of e.parts)Gp(n)&&t.push(n);return{id:e.id,role:e.role,content:qp(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function Qp(){return{contentParts:[],toolCalls:[]}}function $p(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function em(e){let t=[],n=Qp(),r=[],i=new Set;function a(){let i=qp(n.contentParts),a=i!==null,o=n.toolCalls.length>0,s=r.length>0;(a||o||s)&&(t.push({id:e.id,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...s&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r=[]),n=Qp()}for(let o of e.parts)switch(o.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(o);break;case`tool-call`:$p(o)&&n.toolCalls.push({id:o.id,type:`function`,function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case`tool-result`:a(),(o.state===`complete`||o.state===`error`)&&!i.has(o.toolCallId)&&(t.push({id:e.id,role:`tool`,content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(o.toolCallId));break;case`thinking`:o.content&&(n.toolCalls.some(Wp)&&a(),r.push({content:o.content,...o.signature&&{signature:o.signature}}));break;case`structured-output`:if(o.status===`complete`){let e=o.raw===``?o.data===void 0?``:Kp(o.data):o.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=o)}}a();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({id:e.id,role:`tool`,content:Hp(n.output),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let r=n.approval.approved;t.push({id:e.id,role:`tool`,content:JSON.stringify({approved:r,...r&&{pendingExecution:!0},message:r?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)}return t.length===0&&t.push({id:e.id,role:`assistant`,content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function tm(e,t){let n=[];if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)t.content&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});if(e.role===`assistant`&&e.structuredOutput)n.push(e.structuredOutput);else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:Jp(e.content),state:`complete`});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=Jp(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}return{id:t||am(),role:e.role===`tool`?`assistant`:e.role,parts:n,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function nm(e){if(`parts`in e)return{...e,id:e.id||am()};let t=e.id||am();switch(e.role){case`user`:return{id:t,role:`user`,parts:rm(e.content)};case`assistant`:return tm({role:`assistant`,content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case`tool`:return tm({role:`tool`,content:e.content,toolCallId:e.toolCallId},t);case`system`:case`developer`:return{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]};case`reasoning`:return{id:t,role:`assistant`,parts:e.content?[{type:`thinking`,content:e.content}]:[]};default:return{id:t,role:`assistant`,parts:[]}}}function rm(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function im(e,t){return`parts`in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...tm(e,t()),createdAt:e.createdAt??new Date}}function am(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function om(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}var sm=y((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),cm=y((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=sm();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(sm(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
|
|
12
|
-
\r `.includes(e[o]);)o++};return l()};e.parse=o}))(),lm=new class{parse(e){if(!(!e||e.trim()===``))try{return(0,cm.parse)(e)}catch{return}}};function um(e){return lm.parse(e)}var dm=class{shouldEmit(e,t){return!0}};function fm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function pm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function mm(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function hm(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function gm(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function _m(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function vm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=um(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function ym(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function bm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function xm(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var Sm=12;function Cm(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Tp];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var wm=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new dm,this.events=e.events||{},this.jsonParser=e.jsonParser||lm,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t){let n=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),r={id:t??am(),role:`user`,parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=gm(this.messages,e,t,n?`error`:void 0,n),a=Hp(t),o=n?`error`:`complete`;i=mm(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=_m(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Xp(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Wp(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}return null}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||am(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let e=this.pendingManualMessageId;if(this.pendingManualMessageId=null,e!==t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t)}this.messageStates.has(t)||(this.createMessageState(t,r),this.activeMessageIds.add(t)),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let e=this.messageStates.get(t);e?e.hasToolCallsSinceTextStart&&=(e.currentSegmentText!==e.lastEmittedText&&this.emitTextUpdateForMessage(t),e.currentSegmentText=``,e.lastEmittedText=``,!1):this.createMessageState(t,r);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e,n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=e.messages.map(nm);this.messages=this.reconcileSnapshotToolCalls(n,t),this.emitMessagesChange()}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.role===`assistant`&&t.parts.length===1?t.parts.find(e=>e.type===`tool-result`):void 0;if(!e){i.push(t);continue}let a=i.findLast(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!a){r.has(e.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${e.toolCallId}") will not be able to locate this call`),i.push(t);continue}let o=[...a.parts];if(!r.has(e.toolCallId)&&!o.some(t=>t.type===`tool-call`&&t.id===e.toolCallId)){let t=n.get(e.toolCallId);t?(o.push({...t}),r.add(t.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${e.toolCallId}") will not be able to locate this call`)}o.push(e),a.parts=o}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.structuredMessageIds.has(t)){let r=e.delta||``;if(r===``&&e.content!==void 0&&e.content!==``){let n=(this.messages.find(e=>e.id===t)?.parts.find(e=>e.type===`structured-output`)??{raw:``}).raw;r=e.content.startsWith(n)?e.content.slice(n.length):n.startsWith(e.content)?``:e.content}r!==``&&(this.messages=vm(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1);let i=n.currentSegmentText,a=i,o=e.delta||``;o===``?e.content!==void 0&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content):a=i+o;let s=a.slice(i.length);n.currentSegmentText=a,n.totalTextContent+=s;let c=e.delta||e.content||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName??e.toolName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:e.index??r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=pm(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=pm(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){if(e.input!==void 0&&!r.arguments)try{r.arguments=JSON.stringify(e.input)}catch{}let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r),e.input!==void 0&&(r.parsedArguments=e.input,this.messages=pm(this.messages,t,{id:r.id,name:r.name,arguments:r.arguments,state:`input-complete`,input:e.input,...r.metadata!==void 0&&{metadata:r.metadata}}),this.emitMessagesChange())}if(e.result){let n;if(Array.isArray(e.result))n=e.result;else try{n=JSON.parse(e.result)}catch{n=e.result}this.messages=gm(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=mm(this.messages,t,e.toolCallId,e.result,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n;try{n=JSON.parse(e.content)}catch{n=e.content}this.messages=gm(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=mm(this.messages,t,e.toolCallId,e.content,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){this.finishReason=e.finishReason??null,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(e){let t=Cm(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=hm(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=`runId`in e&&typeof e.runId==`string`?e.runId:void 0;t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||e.error?.message||`An error occurred`;!e.message&&!e.error?.message&&console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=bm(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(Yf(e))}handleStepStartedEvent(e){let t=e.stepId??am(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(e.signature){let r=n.currentThinkingStepId??e.stepId;if(!r)return;let i=n.thinkingSteps.get(r);i!==void 0&&(n.thinkingStepSignatures.set(r,e.signature),this.messages=xm(this.messages,t,r,i,e.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);let r=n.currentThinkingStepId??e.stepId??am();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,``),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);let i=n.thinkingSteps.get(r)??``,a=i;e.delta&&e.delta!==``?a=i+e.delta:e.content&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content),n.thinkingSteps.set(r,a),e.signature&&n.thinkingStepSignatures.set(r,e.signature),this.messages=xm(this.messages,t,r,a,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,r,a)}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=xm(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=ym(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=hm(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return e.content!==void 0&&(e.content.length<t.length||!e.content.startsWith(t)&&!t.startsWith(e.content))}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=pm(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=fm(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=Sm&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=bm(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&this.events.onStreamEnd?.(e)}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Tm(t))}};function Tm(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}function Em(e){let t=[];for(let n of e){let e=n.parts??[];if(n.role===`system`){t.push({...n,content:e.length>0?Dm(e):n.content??``});continue}if(n.role===`user`){t.push({...n,content:e.length>0?Om(e):n.content??``});continue}for(let r of e)r.type===`thinking`&&t.push({role:`reasoning`,id:Am(n.id,r),content:r.content});let r=Dm(e),i=km(e);t.push({...n,...r!==``&&{content:r},...i&&{toolCalls:i}});for(let n of e)n.type===`tool-result`&&t.push({role:`tool`,id:jm(n.toolCallId),toolCallId:n.toolCallId,content:typeof n.content==`string`?n.content:JSON.stringify(n.content),...n.error!==void 0&&{error:n.error}})}return t}function Dm(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Om(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Dm(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function km(e){let t=[];for(let n of e)n.type===`tool-call`&&t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments}});return t.length>0?t:void 0}function Am(e,t){return`${e}-reasoning-${t.id??Mm(t.content)}`}function jm(e){return`tool-${e}`}function Mm(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}var Nm=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Pm=e.object({type:e.enum([`query`,`mutation`,`subscription`]),id:e.string(),name:e.string(),description:e.string(),inputSchema:e.unknown(),outputSchema:e.unknown(),outputSample:e.unknown()}),Fm=om({name:`getCapabilities`,description:`Get the APIs available to the generated Rough feature`,inputSchema:e.object({}),outputSchema:e.array(Pm)}),Im=om({name:`getLogs`,description:`Get Rough feature logs`,inputSchema:e.object({spriteBuildId:e.string().min(1)}),outputSchema:e.array(e.object({id:e.string().min(1),spriteBuildId:e.string().min(1),actionedAt:e.number(),type:e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_USAGE`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`]),detail:e.unknown()}))}),Lm=om({name:`startBuild`,description:`Start a Rough feature build`,inputSchema:e.object({prompt:e.string().min(1)}),outputSchema:e.object({spriteBuildId:e.string().min(1)})}),Rm=e=>{let{content:t}=e;return t===null?``:typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content??``).join(`
|
|
13
|
-
`)},
|
|
10
|
+
`,e.causedBy)):e instanceof $l?this.#g.error?.(e):this.#g.info?.(`${t} threw:
|
|
11
|
+
`,e),!1}finally{this.#i!==n&&(this.#i=n,this.onOnlineChange?.(n),n&&this.recoverMutations())}}async#j(e,t,n,r=vf,i=vf){let{clientID:a}=this,o=0,s;n=n.withContext(t);do{let c=lf(a),l=n.withContext(`requestID`,c),{httpRequestInfo:u,result:d}=await e(c,l);if(s=d,!u)return{result:d,authFailure:!1};let{errorMessage:f,httpStatusCode:p}=u;if((f||p!==200)&&l.error?.(`Got a non 200 response doing ${t}: ${p}`+(f?`: ${f}`:``)),p!==Yl)return{result:d,authFailure:!1};if(!this.getAuth)return{result:d,authFailure:!0};let m;try{await r(),m=await this.getAuth()}finally{await i()}if(m==null)return{result:d,authFailure:!0};this.auth=m,o++}while(o<df);return n.info?.(`Tried to reauthenticate too many times`),{result:s,authFailure:!0}}#M(){return this.isClientGroupDisabled||this.pushURL===``&&Sc(this.pusher)}async#N(){if(this.#M())return!0;await this.#o;let e=await this.#s,{clientID:t}=this,n=await this.#c;return this.#A(async()=>{let{result:r}=await this.#j(async(r,i)=>{try{this.#U(1,0);let a=await Du(r,this.memdag,i,e,n,t,this.pusher,this.schemaVersion,Su);return{result:a,httpRequestInfo:a?.httpRequestInfo}}finally{this.#U(-1,0)}},`push`,this.#g);if(r===void 0)return!0;let{response:i,httpRequestInfo:a}=r;return oc(i)?this.#P(i):ac(i)&&await this.#L(),a.httpStatusCode===200},`Push`)}#P(e){let t={type:e.error};e.versionType&&(t.versionType=e.versionType),this.#R(t)}push({now:e=!1}={}){return Cf(this.#p.send(e))}pull({now:e=!1}={}){return Cf(this.#f.send(e))}async poke(e){await this.#o;let{clientID:t}=this,n=lf(t),r=this.#g.withContext(`handlePullResponse`).withContext(`requestID`,n),{pullResponse:i}=e;if(oc(i)){this.#P(i);return}if(ac(i)){await this.#L();return}let a=await mu(r,this.memdag,gi(e.baseCookie),i,t,7);switch(a.type){case 0:await this.maybeEndPull(a.syncHead,n);break;case 2:throw Error(`unexpected base cookie for poke: `+JSON.stringify(e))}}async beginPull(){await this.#o;let e=await this.profileID,{clientID:t}=this,n=await this.#c,{result:{beginPullResponse:r,requestID:i}}=await this.#j(async(r,i)=>{let a=await uu(e,t,n,this.schemaVersion,this.puller,r,this.memdag,7,i);return{result:{beginPullResponse:a,requestID:r},httpRequestInfo:a.httpRequestInfo}},`pull`,this.#g,()=>this.#U(0,-1),()=>this.#U(0,1)),{pullResponse:a}=r;oc(a)?this.#P(a):ac(r.pullResponse)&&await this.#L();let{syncHead:o,httpRequestInfo:s}=r;return{requestID:i,syncHead:o,ok:s.httpStatusCode===200}}async persist(){N(!this.#v),this.#v=!0;try{let{clientID:e}=this;if(await this.#o,this.#r)return;try{await Nd(this.#g,e,this.memdag,this.perdag,this.#l,()=>this.closed,7)}catch(t){if(t instanceof cl)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception persisting during close`,t);else throw t}}finally{this.#v=!1}let{clientID:e}=this,t=await this.#c;N(t),this.#C({clientID:e,clientGroupID:t})}async refresh(){await this.#o;let{clientID:e}=this;if(this.#r)return;let t;try{t=await zd(this.#g,this.memdag,this.perdag,e,this.#l,this.subscriptions,()=>this.closed,7)}catch(t){if(t instanceof cl)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception refreshing during close`,t);else throw t}t!==void 0&&await this.subscriptions.fire(t)}#F(){this.onClientStateNotFound?.()}#I(e){this.#g.error?.(`Client state not found on client, clientID: ${e}`),this.#F()}async#L(){let e=await this.#c;this.#g.error?.(`Client state not found on server, clientGroupID: ${e}`),await this.disableClientGroup(),this.#F()}async disableClientGroup(){let e=await this.#c;N(e),this.isClientGroupDisabled=!0,await R(this.perdag,t=>Vc(e,t))}#R(e){this.#g.debug?.(`Update needed, reason: ${e}`),this.onUpdateNeeded?.(e)}async#z(){this.#y&&await this.#H(`persist`,this.#S)}async#B(e){this.#g.debug?.(`Handling persist`,e);let t=await this.#c;e.clientGroupID===t&&this.#V()}async#V(){this.#b&&await this.#H(`refresh from storage`,this.#w)}async#H(e,t){try{await t.schedule()}catch(t){t instanceof dr?this.#g.debug?.(`Scheduled ${e} did not complete before close.`):this.#g.error?.(`Error during ${e}`,t)}}#U(e,t){this.#u+=e,this.#d+=t;let n=e+t,r=this.#u+this.#d;if(n===1&&r===1||r===0){let e=r>0;Promise.resolve().then(()=>this.onSync?.(e))}}subscribe(e,t){typeof t==`function`&&(t={onData:t});let{onData:n,onError:r,onDone:i,isEqual:a}=t;return this.subscriptions.add(new qd(e,n,r,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new Jd(e,t))}query(e){return this.#W(e)}get cookie(){return this.#o.then(()=>Wc(this.memdag,async e=>{let t=await e.getHead(L);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta.cookieJSON;return ni(n),n}))}#W=async e=>{await this.#o;let{clientID:t}=this;return Wc(this.memdag,async n=>{try{let r=await ps(n,7);return await e(new js(t,r,this.#g))}catch(e){throw await this.#J(e)}})};#G(e,t){return this.#l[e]=t,n=>this.#q(e,t,n,performance.now())}#K(e){let t=Object.create(null);for(let n in e)t[n]=this.#G(n,e[n]);return t}async#q(e,t,n,r){let i=gi(n??null);this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#o;let{clientID:a}=this;return Gc(this.memdag,async o=>{try{let s=await Js(await ea(L,o),e,i,null,o,r,a,7),c=await t(new Fs(a,await s.getMutationID(),`initial`,s,this.#g),n);Ss(s);let l=await s.getMutationID(),u=await s.commitWithDiffs(L,this.subscriptions);return this.lastMutationID=l,this.#p.send(!1).catch(()=>{}),await this.subscriptions.fire(u),this.#z(),c}catch(e){throw await this.#J(e)}})}async#J(e){return e instanceof Qi&&await this.#D()?new cl(this.clientID):e}recoverMutations(e){return this.#e.recoverMutations(e,this.#o,this.perdag,this.#n,this.#h,this.#t.create)}experimentalPendingMutations(){return Wc(this.memdag,Yu)}},Sf=new Map;async function Cf(e){let t=await e;if(t)throw t.error}function wf(){typeof location<`u`&&location.reload()}function Tf(e){let{name:t,clientMaxAgeMs:n}=e;if(typeof t!=`string`||!t)throw TypeError(`name is required and must be non-empty`);if(n!==void 0){let e=Math.max($u,Dd);if(typeof n!=`number`||n<=e)throw TypeError(`clientAgeMaxMs must be a number larger than ${e}ms`)}}var Ef={IMAGE:`IMAGE`,VIDEO:`VIDEO`,AUDIO:`AUDIO`,OTHER:`OTHER`},Df={PENDING:`PENDING`,IN_PROGRESS:`IN_PROGRESS`,READY:`READY`,ERROR:`ERROR`,CANCELED:`CANCELED`},Of=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,spriteBuildId:a,prompt:o,name:s,surfaceId:c}=t,l=k.sprite.encode(i);if(await n.get(l))return Error(`Sprite "${i}" already exists`);let u=k.spriteBuild.encode(a);if(await n.get(u))return Error(`SpriteBuild "${a}" already exists`);let d={name:s?.trim().length?s:``,surfaceId:c,ownedByPersonId:r};await n.set(l,d);let f={spriteId:i,parentSpriteBuildId:null,prompt:o,status:Df.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(u,f)},kf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,name:a,surfaceId:o}=t,s=k.sprite.encode(i);if(await n.get(s))return Error(`Sprite "${i}" already exists`);let c={name:a?.trim().length?a:``,surfaceId:o,ownedByPersonId:r};await n.set(s,c)},Af=async()=>{},jf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=k.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);o.status!==Df.PENDING&&o.status!==Df.IN_PROGRESS||o.cancelRequestedAt!==null||await n.set(a,{...o,cancelRequestedAt:r})},Mf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=k.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o,prompt:s,status:Df.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},Nf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=k.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o??null,prompt:s,status:Df.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},Pf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=k.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==Df.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})},Ff={surface_upsert_v1:async(e,t)=>{let{tx:n}=e,{surfaceId:r,key:i,name:a,description:o}=t,s={key:i,name:a,description:o};for await(let[e,t]of n.scan({prefix:k.surface.prefix()}).entries())if(t.key===i){await n.set(e,s);return}await n.set(k.surface.encode(r),s)},project_ping_v1:Af,sprite_create_v2:kf,spriteBuild_create_v2:Nf,spriteBuild_cancel_v1:jf,spriteBuild_publish_v2:async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=k.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==Df.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})}},If={sprite_create_v1:Of,spriteBuild_create_v1:Mf,spriteBuild_publish_v1:Pf},Lf={...Ff,...If};async function Rf(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};if(i){if(i.aborted){y(i.reason);return}i.addEventListener(`abort`,g,{once:!0})}let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==zf&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===zf&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var zf=Symbol(`skip`),Bf={concurrency:5,stopOnError:!1},Vf=async(e,r,i=Bf)=>{let{stopOnError:a}=i;return n(async()=>Rf(e,async e=>{let n=await t(async()=>r(e));if(a&&n instanceof Error)throw n;return n},i))},Hf=async(e,t,n)=>{let r=await Vf(Object.entries(e),async([e,n])=>[e,await t(n,e)],n);return r instanceof Error?r:Object.fromEntries(r)},Uf=async(e,t)=>Hf(t,async t=>{let n=t;return async(t,r)=>{let{context:i,...a}=r,o={...e,tx:t,actionedAt:i?.actionedAt??Date.now(),sessionPersonId:i?.sessionPersonId??e.sessionPersonId},s=await n(o,a);if(s instanceof Error)throw s;return s}}),Wf=`2026.08.20/1`,Gf=async e=>{let{name:t,pushURL:n,pullURL:r,auth:i,getAuth:a,pullInterval:o,sessionPersonId:s}=e;if(!t)return Error(`Replicache name is required`);let c=new Ql({schemaVersion:Wf,name:t,pushURL:n,pullURL:r,auth:i,pullInterval:o,mutators:await Uf({sessionPersonId:s},Lf)});return c.getAuth=a,c},Kf=class{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw Error(`Base must be a positive integer or zero`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw Error(`ExpMax must be undefined, a positive integer, or zero`);this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*2**this.i}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}},z={open:`open`,close:`close`,error:`error`,message:`message`,retry:`retry`,reconnect:`reconnect`},qf=class{constructor(e,t,n){this._closedByUser=!1,this.handleOpenEvent=e=>this.handleEvent(z.open,e),this.handleErrorEvent=e=>this.handleEvent(z.error,e),this.handleCloseEvent=e=>this.handleEvent(z.close,e),this.handleMessageEvent=e=>this.handleEvent(z.message,e),this._urlProvider=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:n?.retry?.maxRetries,instantReconnect:n?.retry?.instantReconnect,backoff:n?.retry?.backoff},listeners:{open:[...n?.listeners?.open??[]],close:[...n?.listeners?.close??[]],error:[...n?.listeners?.error??[]],message:[...n?.listeners?.message??[]],retry:[...n?.listeners?.retry??[]],reconnect:[...n?.listeners?.reconnect??[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){let r=e=>e.listener!==t||e.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._url=typeof this._urlProvider==`function`?this._urlProvider():this._urlProvider,this._underlyingWebsocket=new WebSocket(this._url,this.protocols),this._underlyingWebsocket.addEventListener(z.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(z.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(z.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(z.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(z.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(z.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(z.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(z.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){let n=this._options.listeners[e],r=[];n.forEach(({listener:e,options:n})=>{e(this,t),(n===void 0||n.once===void 0||!n.once)&&r.push({listener:e,options:n})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case z.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case z.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){let e={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},t=new CustomEvent(z.reconnect,{detail:e});this.dispatchEvent(z.reconnect,t),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case z.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t)}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;let e=e=>{let t=new CustomEvent(z.retry,{detail:e});this.handleEvent(z.retry,t)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}},Jf=class{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{maxRetries:e})}),this}get maxRetries(){return this._options?.retry?.maxRetries}withInstantReconnect(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{instantReconnect:e})}),this}get instantReconnect(){return this._options?.retry?.instantReconnect}withBackoff(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{backoff:e})}),this}get backoff(){return this._options?.retry?.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){return this._options?.buffer}onOpen(e,t){return this.addListener(z.open,e,t),this}onClose(e,t){return this.addListener(z.close,e,t),this}onError(e,t){return this.addListener(z.error,e,t),this}onMessage(e,t){return this.addListener(z.message,e,t),this}onRetry(e,t){return this.addListener(z.retry,e,t),this}onReconnect(e,t){return this.addListener(z.reconnect,e,t),this}build(){return new qf(this._url,this._protocols,this._options)}addListener(e,t,n){return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:this._options?.listeners?.open??[],close:this._options?.listeners?.close??[],error:this._options?.listeners?.error??[],message:this._options?.listeners?.message??[],retry:this._options?.listeners?.retry??[],reconnect:this._options?.listeners?.reconnect??[],[e]:[...this._options?.listeners?.[e]??[],{listener:t,options:n}]}}),this}},Yf=e.object({type:e.literal(`poke`)}).strict(),Xf=e=>{console.warn(`[Rough poke] ${e}`)},Zf=e=>{let{getToken:t,onPoke:n,url:r}=e,i=!1,a=0;try{let e=new Jf(r).withBackoff(new Kf(1e3,7)).build(),o=()=>{let n=++a;t().then(t=>{i||n!==a||e.readyState!==1||e.send(JSON.stringify({type:`authenticate`,token:t}))}).catch(()=>{Xf(`Failed to get a session token`)})},s=(e,t)=>{if(typeof t.data!=`string`){Xf(`Received an invalid server message`);return}let r;try{r=JSON.parse(t.data)}catch{Xf(`Received malformed server JSON`);return}if(!Yf.safeParse(r).success){Xf(`Received an invalid server message`);return}Promise.resolve(n()).catch(()=>{Xf(`Failed to pull after a server poke`)})},c=()=>{Xf(`Connection failed`)},l=()=>{i||Xf(`Connection closed; reconnecting`)};return e.addEventListener(z.open,o),e.addEventListener(z.message,s),e.addEventListener(z.error,c),e.addEventListener(z.close,l),{close:()=>{i||(i=!0,e.removeEventListener(z.open,o),e.removeEventListener(z.message,s),e.removeEventListener(z.error,c),e.removeEventListener(z.close,l),e.close())}}}catch{return Xf(`Failed to create connection`),{close:()=>{}}}},Qf=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({});function $f(e){return Object.keys(e).length>0?e:void 0}function ep(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&`promptTokens`in e}function tp(e,t){return ep(e)?e:np(Array.isArray(e)?e:void 0,t)}function np(e,t){let n=e?.[0];if(n==null&&t==null)return;let{promptTokensDetails:r,completionTokensDetails:i,...a}=t??{},o=$f({...n?.cachedInputTokens===void 0?{}:{cachedTokens:n.cachedInputTokens},...r}),s=$f({...n?.reasoningTokens===void 0?{}:{reasoningTokens:n.reasoningTokens},...i});return{promptTokens:n?.inputTokens??0,completionTokens:n?.outputTokens??0,totalTokens:n?.totalTokens??0,...a,...o===void 0?{}:{promptTokensDetails:o},...s===void 0?{}:{completionTokensDetails:s}}}function rp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ip(e,t){if(t==null)return e;if(e==null)return{...t};let n={...e,...t};return rp(e.tanstack)&&rp(t.tanstack)&&(n.tanstack={...e.tanstack,...t.tanstack}),n}function B(e){if(e==null)return;let t=`metadata`in e?e.metadata:void 0,n=(typeof t==`object`&&t&&!Array.isArray(t)?t:e).tanstack;if(typeof n==`object`&&n&&!Array.isArray(n))return n}function ap(e,t){let n=e.metadata,r=B(e)??{};return{...e,metadata:{...n??{},tanstack:{...r,...t}}}}function op(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}var sp=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function cp(e,t){return e>>>t|e<<32-t}function lp(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=cp(t,7)^cp(t,18)^t>>>3,i=cp(n,17)^cp(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=cp(a,6)^cp(a,11)^cp(a,25),s=a&g^~a&_,c=v+o+s+(sp[e]??0)+(h[e]??0)>>>0,l=(cp(t,2)^cp(t,13)^cp(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function up(e){return`sha256:${lp(e)}`}function dp(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(dp(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${dp(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function fp(e){return dp(e,new WeakSet)}function pp(e,t=up){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function mp(e){typeof e==`object`&&e&&!Object.isFrozen(e)&&(Object.values(e).forEach(mp),Object.freeze(e))}function hp(e){let t=JSON.parse(fp(e));return mp(t),t}function gp(e){let t=hp([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=fp(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:pp(n)})}function _p(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function vp(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function yp(e){if(!vp(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function bp(e){return vp(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function xp(e){return Object.keys(e).length>0?e:void 0}function Sp(e){if(Array.isArray(e)){let t=e.map(e=>Cp(e,e.required||[])),n=t.map(e=>e.nullWidening??{});return{schema:t.map(e=>e.schema),itemMap:n.some(e=>Object.keys(e).length>0)?n:void 0}}let t=Cp(e,e.required||[]);return{schema:t.schema,itemMap:t.nullWidening}}function Cp(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=Cp(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Sp(r.items);e[n]={...r,items:t.schema,...i?{type:[`array`,`null`]}:{}},o=i,s=t.itemMap?{items:t.itemMap}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Sp(n.items);n.items=e.schema,e.itemMap&&(r.items=e.itemMap)}return{schema:n,nullWidening:xp(r)}}function wp(e){if(yp(e)){let t=_p(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(bp(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?_p(e):e}function Tp(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!yp(e)&&!bp(e))return e;let r=wp(e);return!r||typeof r!=`object`||!n?r:Cp(r,r.required||[]).schema}var Ep=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function Dp(e,t){if(!bp(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new Ep(n.issues)}var Op=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function kp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function Ap(e){return kp(e)&&Object.keys(e).some(e=>Op.has(e))}function jp(e){return bp(e)||yp(e)||Ap(e)}function Mp(e){if(!kp(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>jp(e[t]))}function Np(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Pp(e){if(bp(e)){let t=yp(e)?Np(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(Ap(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Fp(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Ip(e,t){let n=t===void 0?null:Pp(t),r=null,i=null;if(e!==void 0){if(bp(e)||Ap(e))r=Pp(e),i=r;else if(Mp(e))r=e.approve===void 0?null:Pp(e.approve),i=e.reject===void 0?null:Pp(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Fp({approved:!0,payload:r,inputSchema:n}),Fp({approved:!1,payload:i,inputSchema:null})]},o=fp(a),s=fp({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:pp(o),approvalSchemaHash:pp(s)}}function Lp(e){return pp(e===void 0?`undefined`:fp(Pp(e).jsonSchema??{standardValidator:`unserialized`}))}var Rp=`tanstack:interruptBinding`,zp=Rp;function Bp(e){return e&&typeof e==`object`?e:null}function Vp(e,t){return typeof e[t]==`string`?e[t]:void 0}function Hp(e){let t=e.v;return t===void 0||t===1}function Up(e){let t=Bp(e.metadata),n=t?Bp(t[zp]):null;if(!n||Vp(n,`interruptId`)!==e.id||!Hp(n))return;let r=Vp(n,`kind`),i=Vp(n,`interruptId`),a=Vp(n,`responseSchemaHash`),o=Vp(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Vp(n,`definitionId`),t=Vp(n,`key`),s=n.batchIndex,c=Vp(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Vp(n,`toolName`),c=Vp(n,`toolCallId`);if(s&&c){if(r===`client-tool-execution`){let e=Vp(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Vp(n,`inputSchemaHash`),t=Vp(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Wp(e){let t=Up(e);if(!t)return;let n=Bp(e.metadata),r=n?Bp(n[zp]):null;if(!r)return;let i=Vp(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Gp=`tanstack:interruptPayload`;function Kp(e,t){if(!yp(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:fp(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function qp(e){return pp(Kp(e,`Interrupt schema`).canonicalJson)}var Jp=`tanstack:interruptContinuation`;function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e){return{[Jp]:e}}function Zp(e){let t=Up(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Yp(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Gp]}:{}}}var Qp=new Set([`text`,`image`,`audio`,`video`,`document`]);function $p(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Qp.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function em(e){return Array.isArray(e)&&e.length>0&&e.every($p)}function tm(e){return typeof e==`string`||em(e)?e:JSON.stringify(e)}function nm(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function rm(e){return nm(e)!==null}function im(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function am(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function om(e){try{return JSON.stringify(e)??``}catch{return``}}function sm(e){return typeof e==`string`&&e!==``?e:void 0}function cm(e){if(`encryptedValue`in e){let t=sm(e.encryptedValue);if(t!==void 0)return t}return sm(B(e)?.signature)}function lm(e,t){let n=typeof t==`object`&&t&&!Array.isArray(t)?t:void 0,r=cm(e);return t===null&&r===void 0?{...e,metadata:null}:n===void 0&&r===void 0?e:{...e,metadata:{...n??{},...r===void 0?{}:{thoughtSignature:r}}}}function um(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function dm(e){return e==null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function fm(e){return Array.isArray(e)?e:dm(e)}function pm(e){let t=new Set;for(let n of e)if(`parts`in n)for(let e of n.parts)e.type===`tool-result`&&t.add(e.toolCallId);let n=[],r=[];for(let i of e){if(`parts`in i){n.push(...Tm(i));continue}let e=mm(hm(i)),a=e.role;if(!(a===`tool`&&e.toolCallId&&t.has(e.toolCallId))){if(a===`reasoning`){let e=i.content,t=cm(i);(e||t!==void 0)&&r.push({content:typeof e==`string`?e:``,...t===void 0?{}:{signature:t}});continue}if(a!==`activity`){if(a===`developer`){n.push({role:`system`,content:i.content,...bm(e),...ym(e),...e.metadata!==void 0&&{metadata:e.metadata}});continue}if(a===`user`&&Array.isArray(i.content)){let t=i.content;if(!t.some(e=>e.type===`text`&&`text`in e&&!(`content`in e))){n.push(e);continue}let r=Pm(t).filter(am);n.push({role:`user`,content:um(r),...i.id!==void 0&&{id:i.id},...bm(e),...ym(e),...e.metadata!==void 0&&{metadata:e.metadata}});continue}if(a===`assistant`){let t=e,a=B(i)?.toolCallMetadata,o=t.toolCalls?.map(e=>lm(e,a?.[e.id]));n.push({...t,...o===void 0?{}:{toolCalls:o},...r.length>0?{thinking:[...t.thinking??[],...r]}:{}}),r=[];continue}n.push(e)}}}return n}function mm(e){let t=gm(e.createdAt)??vm(e);if(t===void 0){if(e.createdAt===void 0)return e;let{createdAt:t,...n}=e;return n}return Object.is(e.createdAt,t)?e:{...e,createdAt:t}}function hm(e){if(!(`role`in e)||e.role!==`tool`)return e;let t=e,n=B(t)?.toolResult;if(!im(n)||`content`in n&&!em(n.content))return e;let r={...e};if(`id`in n||Reflect.deleteProperty(r,`id`),`createdAt`in n||Reflect.deleteProperty(r,`createdAt`),typeof n.id==`string`&&Reflect.set(r,`id`,n.id),typeof n.createdAt==`string`){let e=gm(n.createdAt);e&&Reflect.set(r,`createdAt`,e)}em(n.content)&&Reflect.set(r,`content`,n.content);let i=Reflect.get(t,`metadata`);if(im(i)){let e=i.tanstack;if(im(e)){let{toolResult:t,...n}=e,a={...i};Object.keys(n).length?a.tanstack=n:delete a.tanstack,Object.keys(a).length?Reflect.set(r,`metadata`,a):Reflect.deleteProperty(r,`metadata`)}}return r}function gm(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!=`string`)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function _m(e){if(e.type!==`tool-result`)return e;let t=gm(e.createdAt),{createdAt:n,...r}=e;return t===void 0?r:{...r,createdAt:t}}function vm(e){return gm(B(e)?.createdAt)}function ym(e){let t=gm(e.createdAt);return t===void 0?{}:{createdAt:t}}function bm(e){return e.name===void 0?{}:{name:e.name}}function xm(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`type`in e)||e.type!==`ui-resource`||!(`toolCallId`in e)||typeof e.toolCallId!=`string`||!(`toolName`in e)||typeof e.toolName!=`string`||!(`resource`in e)||e.resource==null||typeof e.resource!=`object`||Array.isArray(e.resource))return!1;let t=e.resource;return`uri`in t&&typeof t.uri==`string`&&`mimeType`in t&&typeof t.mimeType==`string`}function Sm(e){return`${e.toolCallId}\0${e.toolName}\0${e.resource.uri}`}function Cm(e,t){if(t.length===0)return e;let n=new Set(e.parts.filter(xm).map(e=>Sm(e))),r=t.filter(e=>!n.has(Sm(e)));return r.length===0?e:{...e,parts:[...e.parts,...r]}}function wm(e){let t=e.parts.filter(xm),n=e.metadata??{},r=B(e),i={};r?.model!==void 0&&(i.model=r.model),r?.signature!==void 0&&(i.signature=r.signature),t.length>0&&(i.uiResources=t);let a={...n};return Object.keys(i).length>0?a.tanstack=i:delete a.tanstack,Object.keys(a).length>0?a:void 0}function Tm(e){return e.role===`system`?[]:e.role===`assistant`?km(e):[Em(e)]}function Em(e){let t=[];for(let n of e.parts)am(n)&&t.push(n);return{id:e.id,role:e.role,content:um(t),...bm(e),...ym(e),...e.metadata!==void 0&&{metadata:e.metadata}}}function Dm(){return{contentParts:[],toolCalls:[]}}function Om(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function km(e){let t=[],n=Dm(),r=[],i=new Set,a={id:e.id,...bm(e),...ym(e)},o=wm(e),s={...a,...o!==void 0&&{metadata:o}};function c(e=!1){let i=um(n.contentParts),a=i!==null,o=n.toolCalls.length>0,c=r.length>0;(e||a||o||c)&&(t.push({...s,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...c&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput}}),r=[]),n=Dm()}for(let a of e.parts)switch(a.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(a);break;case`tool-call`:Om(a)&&n.toolCalls.push({id:a.id,type:`function`,function:{name:a.name,arguments:a.arguments},...a.metadata!==void 0&&{metadata:a.metadata}});break;case`tool-result`:c(t.length===0),(a.state===`complete`||a.state===`error`)&&!i.has(a.toolCallId)&&(t.push({...a.id!==void 0&&{id:a.id},...ym(a),role:`tool`,content:a.content,toolCallId:a.toolCallId,...a.name!==void 0&&{name:a.name},...a.metadata!==void 0&&{metadata:a.metadata},...a.error!==void 0&&{error:a.error}}),i.add(a.toolCallId));break;case`thinking`:(a.content||a.signature)&&(n.toolCalls.some(rm)&&c(),r.push({content:a.content,...a.signature&&{signature:a.signature}}));break;case`structured-output`:if(a.status===`complete`){let e=a.raw===``?a.data===void 0?``:om(a.data):a.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=a)}}c();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({role:`tool`,content:tm(n.output),toolCallId:n.id}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let e=n.approval.approved;t.push({role:`tool`,content:JSON.stringify({approved:e,...e&&{pendingExecution:!0},message:e?`User approved this action`:`User denied this action`}),toolCallId:n.id}),i.add(n.id)}return t.length===0&&t.push({...s,role:`assistant`,content:null}),t}function Am(e,t){let n=[],r=gm(e.createdAt);if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)(t.content||t.signature)&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});let i=e.structuredOutput??Nm(B(e)?.structuredOutput);if(e.role===`assistant`&&i){if(typeof e.content==`string`&&e.content&&e.content!==i.raw){let t=i.raw,r=t!==``&&e.content.endsWith(t)?e.content.slice(0,-t.length):e.content;r&&n.push({type:`text`,content:r})}n.push(i)}else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:fm(e.content),state:e.error===void 0?`complete`:`error`,...e.id!==void 0&&{id:e.id},...e.name!==void 0&&{name:e.name},...e.metadata!==void 0&&{metadata:e.metadata},...r!==void 0&&{createdAt:r},...e.error!==void 0&&{error:e.error}});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=dm(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}let a={id:t||Im(),role:e.role===`tool`?`assistant`:e.role,parts:n,...bm(e),...r!==void 0&&{createdAt:r},...e.metadata!==void 0&&{metadata:e.metadata}},o=B(e)?.uiResources;return Cm(a,Array.isArray(o)?o.filter(xm):[])}function jm(e){if(`parts`in e)return Mm(e,{...e,id:e.id||Im()});let t=e.id||Im();switch(e.role){case`user`:return Mm(e,{id:t,role:`user`,parts:Pm(e.content)});case`assistant`:{let n=B(e),r=n?.toolCallMetadata,i=Nm(n?.structuredOutput),a=e.toolCalls?.map(e=>{let t=typeof r==`object`&&r?r[e.id]:void 0;return t===void 0?e:{...e,metadata:t}});return Mm(e,Am({role:`assistant`,content:e.content??null,...bm(e),...a&&{toolCalls:a},...i&&{structuredOutput:i}},t))}case`tool`:{e=hm(e);let n=gm(`createdAt`in e?e.createdAt:void 0)??vm(e);return Mm(e,Am({role:`tool`,content:e.content,toolCallId:e.toolCallId,...`name`in e&&typeof e.name==`string`?{name:e.name}:{},...`id`in e&&typeof e.id==`string`?{id:e.id}:{},...`metadata`in e&&e.metadata!=null?{metadata:e.metadata}:{},...n===void 0?{}:{createdAt:n},...e.error!==void 0&&{error:e.error}},t))}case`system`:case`developer`:return Mm(e,{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]});case`reasoning`:{let n=cm(e),r=typeof e.content==`string`?e.content:``;return Mm(e,{id:t,role:`assistant`,parts:r||n!==void 0?[{type:`thinking`,content:r,...n===void 0?{}:{signature:n}}]:[]})}default:return Mm(e,{id:t,role:`assistant`,parts:[]})}}function Mm(e,t){let n=t.parts.map(e=>_m(e));n!==t.parts&&(t={...t,parts:n});let r=`name`in e&&typeof e.name==`string`?e.name:void 0,i=r===void 0?t:{...t,name:r},a;if(`metadata`in e){let t=e.metadata;typeof t==`object`&&t&&!Array.isArray(t)&&(a=t,i={...i,metadata:a})}let o=gm(i.createdAt)??(a===void 0?void 0:vm(a));if(o!==void 0&&!Object.is(o,i.createdAt))i={...i,createdAt:o};else if(o===void 0&&i.createdAt!==void 0){let{createdAt:e,...t}=i;i=t}let s=B(a)?.uiResources,c=Array.isArray(s)?s.filter(xm):[];return Cm(i,c)}function Nm(e){if(!(e==null||e.status!==`streaming`&&e.status!==`complete`&&e.status!==`error`||typeof e.raw!=`string`))return{type:`structured-output`,status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage}}}function Pm(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function Fm(e,t){if(`parts`in e){let n=e.parts.map(e=>_m(e));return{...e,parts:n,id:e.id||t(),createdAt:gm(e.createdAt)??new Date}}return{...Am(e,t()),createdAt:gm(e.createdAt)??new Date}}function Im(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function Lm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rm(e,t,n,r,i=!1){let a=Lm(e)?e:{},o=Lm(a.tanstack)?{...a.tanstack}:{};i&&delete o.uiResources;let s=gm(t),c={...n===void 0?{}:{id:n},...s&&{createdAt:s.toISOString()},...Array.isArray(r)&&{content:r}},l={...a,tanstack:{...o,toolResult:c}};return Object.keys(l).length?l:void 0}function zm(e,t){let n=[],r=new Set(e.flatMap(e=>`id`in e&&e.id&&e.role!==`tool`?[e.id]:[])),i=t?.includeSnapshotStructuredOutput??!1,a=new Set;for(let t of e)t.role===`assistant`&&t.id!==void 0&&a.add(t.id);for(let t of e){if(!(`parts`in t)&&t.role===`tool`&&t.toolCallId){let e=Xm(Qm(t.id,t.toolCallId,a),r),i=Rm(t.metadata,t.createdAt,t.id,t.content);n.push({role:`tool`,id:e,...t.name!==void 0&&{name:t.name},toolCallId:t.toolCallId,content:typeof t.content==`string`?t.content:JSON.stringify(t.content),...t.error!==void 0&&{error:t.error},...i!==void 0&&{metadata:i}});continue}let e=`parts`in t?t:Am(t,t.id),o=e.parts;if(r.add(e.id),t.role===`system`){n.push(Bm(e,`system`,{content:o.length>0?Wm(o):t.content??``},o,i));continue}if(t.role===`user`){n.push(Bm(e,`user`,{content:o.length>0?Gm(o):t.content??``},o,i));continue}for(let t of o)if(t.type===`thinking`){let i={role:`reasoning`,id:Zm(Jm(e.id,t),r),content:t.content};t.signature&&(i.encryptedValue=t.signature),n.push(i)}let s=Wm(o),c=qm(o);n.push(Bm(e,`assistant`,{...s!==``&&{content:s},...c&&{toolCalls:c}},o,i));let l=new Set(o.flatMap(e=>e.type===`tool-result`?[e.toolCallId]:[]));for(let e of o)if(e.type===`tool-result`){let t=Xm(e.id??Ym(e.toolCallId),r),i=Rm(e.metadata,e.createdAt,e.id,e.content,!0);n.push({role:`tool`,id:t,toolCallId:e.toolCallId,...e.name!==void 0&&{name:e.name},content:typeof e.content==`string`?e.content:JSON.stringify(e.content),...e.error!==void 0&&{error:e.error},...i!==void 0&&{metadata:i}})}else if(e.type===`tool-call`){let t=e.approval?.approved;if(l.has(e.id)||e.output===void 0&&(e.state!==`approval-responded`||t===void 0))continue;let i=e.output===void 0?JSON.stringify({approved:t,...t&&{pendingExecution:!0},message:t?`User approved this action`:`User denied this action`}):tm(e.output),a=typeof i==`string`?i:JSON.stringify(i);n.push({role:`tool`,id:Xm(Ym(e.id),r),toolCallId:e.id,content:a,metadata:Rm(void 0,void 0,void 0,i)})}}return n}function Bm(e,t,n,r,i){let a=Vm(e,r,i),o={id:e.id,...e.name!==void 0&&{name:e.name},...a!==void 0&&{metadata:a}};return t===`system`?{...o,role:t,content:String(n.content??``)}:t===`user`?{...o,role:t,content:n.content??``}:{...o,role:t,...typeof n.content==`string`&&{content:n.content},...n.toolCalls!==void 0&&{toolCalls:n.toolCalls}}}function Vm(e,t,n){let r={...e.metadata??{}},i=B(e),a={};i?.model!==void 0&&(a.model=i.model),i?.signature!==void 0&&(a.signature=i.signature);let o=gm(e.createdAt);o!==void 0&&(a.createdAt=o.toISOString());let s=Hm(t,n);s&&(a.structuredOutput=s);let c={};for(let e of t)e.type===`tool-call`&&e.metadata!==void 0&&(c[e.id]=e.metadata);Object.keys(c).length>0&&(a.toolCallMetadata=c);let l=t.filter(e=>e.type===`ui-resource`);return l.length>0&&(a.uiResources=l),Object.keys(a).length>0?r.tanstack=a:delete r.tanstack,Object.keys(r).length>0?r:void 0}function Hm(e,t){for(let n of e)if(n.type===`structured-output`&&(t||n.status!==`complete`))return Um(n,t)}function Um(e,t){return{status:e.status,raw:e.raw,...t&&e.partial!==void 0?{partial:e.partial}:{},...t&&e.data!==void 0?{data:e.data}:{},...t&&e.reasoning?{reasoning:e.reasoning}:{},...e.errorMessage!==void 0&&{errorMessage:e.errorMessage}}}function Wm(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Gm(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Wm(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function Km(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`thoughtSignature`in e))return;let t=e.thoughtSignature;return typeof t==`string`&&t!==``?t:void 0}function qm(e){let t=[];for(let n of e)if(n.type===`tool-call`){let e=Km(n.metadata);t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...e===void 0?{}:{encryptedValue:e}})}return t.length>0?t:void 0}function Jm(e,t){return`${e}-reasoning-${t.id??$m(t.content)}`}function Ym(e){return`tool-${e}`}function Xm(e,t){return Zm(e,t)}function Zm(e,t){if(!t.has(e))return t.add(e),e;let n=2;for(;t.has(`${e}-${n}`);)n++;let r=`${e}-${n}`;return t.add(r),r}function Qm(e,t,n){let r=Ym(t);return e===void 0||n.has(e)?r:e}function $m(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}function eh(e){if((e.type===Qf.RUN_FINISHED||e.type===Qf.RUN_ERROR)&&(Array.isArray(e.usage)||ep(e.usage))){let t=tp(e.usage,B(e)?.usage);t!==void 0&&(e.usage=t)}if(e.type===Qf.TOOL_CALL_START&&e.toolName===void 0&&e.toolCallName&&(e.toolName=e.toolCallName),e.type===Qf.TOOL_CALL_END&&e.input===void 0){let t=B(e)?.input;t!==void 0&&(e.input=t)}return e}function th(e){eh(e);let t=B(e),n=e;if(t==null)return n;for(let[e,r]of Object.entries(t))e!==`usage`&&e!==`interruptErrors`&&n[e]===void 0&&r!==void 0&&(n[e]=r);return t.interruptErrors!==void 0&&(n[`tanstack:interruptErrors`]=t.interruptErrors),n}function nh(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}function rh(e){return typeof e==`string`&&e!==``?e:void 0}function ih(e){if(`runId`in e){let t=rh(e.runId);if(t!==void 0)return t}return rh(B(e)?.runId)}var ah=b((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),oh=b((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=ah();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(ah(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
|
|
12
|
+
\r `.includes(e[o]);)o++};return l()};e.parse=o}))(),sh=new class{parse(e){if(e&&e.trim()!==``)try{return(0,oh.parse)(e)}catch{return}}};function ch(e){return sh.parse(e)}var lh=class{shouldEmit(e,t){return!0}};function uh(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function dh(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function fh(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function ph(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function mh(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function hh(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function gh(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=ch(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function _h(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function vh(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function yh(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var bh=12;function xh(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Rp];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Sh=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;streamEndEmitted=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new lh,this.events=e.events||{},this.jsonParser=e.jsonParser||sh,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t,n){let r=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),i={id:t??Im(),role:`user`,parts:r,createdAt:new Date,...n==null?{}:{metadata:n}};return this.messages=[...this.messages,i],this.emitMessagesChange(),i}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=mh(this.messages,e,t,n?`error`:void 0,n),a=tm(t),o=n?`error`:`complete`;i=fh(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=hh(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Tm(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||rm(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`REASONING_ENCRYPTED_VALUE`:this.handleReasoningEncryptedValueEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}for(let[e,t]of[...this.messageStates].reverse())if(t.role===`assistant`)return e;return null}resumeAssistantState(e,t){this.activeMessageIds.add(e),(t.isComplete||this.isDone)&&(t.isComplete=!1,this.isDone=!1)}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return this.resumeAssistantState(e,t),{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return this.resumeAssistantState(t,e),{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||Im(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}mergeMessageMetadata(e,t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n=this.messages.find(t=>t.id===e);if(!n)return;let r=t,i=B(r),a=i!=null&&(`content`in i||`args`in i)?{...r,tanstack:Object.fromEntries(Object.entries(i).filter(([e])=>e!==`content`&&e!==`args`))}:r,o=ip(n.metadata,a),s=gm(B(r)?.createdAt),c=s!==void 0;this.messages=this.messages.map(t=>t.id===e?{...t,...o===void 0?{}:{metadata:o},...c?{createdAt:s}:{}}:t),this.emitMessagesChange()}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let n=this.pendingManualMessageId;if(this.pendingManualMessageId=null,n!==t){this.messages=this.messages.map(e=>e.id===n?{...e,id:t}:e);let e=this.messageStates.get(n);e&&(e.id=t,this.messageStates.delete(n),this.messageStates.set(t,e)),this.activeMessageIds.delete(n),this.activeMessageIds.add(t);for(let[e,r]of this.toolCallToMessage)r===n&&this.toolCallToMessage.set(e,t)}let i=this.messageStates.get(t);i?i.hasToolCallsSinceTextStart&&(i.currentSegmentText!==i.lastEmittedText&&this.emitTextUpdateForMessage(t),i.currentSegmentText=``,i.lastEmittedText=``,i.hasToolCallsSinceTextStart=!1):(i=this.createMessageState(t,r),this.activeMessageIds.add(t)),this.mergeMessageMetadata(t,e.metadata),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let n=this.messageStates.get(t);n?n.hasToolCallsSinceTextStart&&=(n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,!1):this.createMessageState(t,r),this.mergeMessageMetadata(t,e.metadata);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.mergeMessageMetadata(t,e.metadata),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e;this.mergeMessageMetadata(t,e.metadata);let n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=new Map(t.map(e=>[e.id,e])),r=this.mergeReasoningFanOut(e.messages.map(jm));this.messages=this.reconcileSnapshotToolCalls(r,t).map(e=>{if(e.metadata!=null)return e;let t=n.get(e.id);return t?.metadata==null?e:{...e,metadata:t.metadata}}),this.emitMessagesChange()}mergeReasoningFanOut(e){let t=[],n=[],r=e=>e.parts.filter(e=>e.type===`thinking`),i=e=>e.role===`assistant`&&e.parts.length>0&&e.parts.every(e=>e.type===`thinking`),a=e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-result`)&&e.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`),o=()=>{t.push(...n),n=[]};for(let s of e){if(i(s)){n.push(s);continue}if(s.role===`assistant`&&n.length>0&&!a(s)){t.push({...s,parts:[...n.flatMap(r),...s.parts]}),n=[];continue}o(),t.push(s)}return o(),t}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.parts.filter(e=>e.type===`tool-result`),a=t.role===`assistant`&&e.length===1&&t.parts.every(e=>e.type===`tool-result`||e.type===`ui-resource`)?e[0]:void 0;if(!a){i.push(t);continue}let o=i.findLast(e=>e.parts.some(e=>e.type===`tool-call`&&e.id===a.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!o){r.has(a.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${a.toolCallId}") will not be able to locate this call`),i.push(t);continue}let s=[...o.parts];if(!r.has(a.toolCallId)&&!s.some(e=>e.type===`tool-call`&&e.id===a.toolCallId)){let e=n.get(a.toolCallId);e?(s.push({...e}),r.add(e.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${a.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${a.toolCallId}") will not be able to locate this call`)}s.push(...t.parts),o.parts=s}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.mergeMessageMetadata(t,e.metadata),this.structuredMessageIds.has(t)){let r=e.delta||``;r!==``&&(this.messages=gh(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1),n.hasToolCallsSinceTextStart=!1;let i=n.currentSegmentText,a=e.delta||``,o=a===``?i:i+a,s=o.slice(i.length);n.currentSegmentText=o,n.totalTextContent+=s;let c=e.delta||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=dh(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=dh(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=e.input===void 0?B(e)?.input:e.input,i=n.toolCalls.get(e.toolCallId);if(i&&i.state!==`input-complete`){if(r!==void 0&&!i.arguments)try{i.arguments=JSON.stringify(r)}catch{}let a=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,a,i),r!==void 0&&(i.parsedArguments=r,this.messages=dh(this.messages,t,{id:i.id,name:i.name,arguments:i.arguments,state:`input-complete`,input:r,...i.metadata!==void 0&&{metadata:i.metadata}}),this.emitMessagesChange())}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId)??this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))?.id;if(!t)return;let n=e.state===`output-error`||B(e)?.state===`output-error`,r;try{r=JSON.parse(e.content)}catch{r=e.content}this.messages=mh(this.messages,e.toolCallId,r,n?`error`:void 0);let i=n?`error`:`complete`;this.messages=fh(this.messages,t,e.toolCallId,e.content,i,i===`error`?this.extractToolResultError(r):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){let t=e;if(this.finishReason=t.finishReason===void 0?B(e)?.finishReason??null:t.finishReason,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0){if(this.completeAllToolCalls(),this.finishReason===`tool_calls`&&e.outcome?.type!==`interrupt`)return;this.isDone=!0,this.finalizeStream()}}handleInterrupts(e){let t=xh(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=ph(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=ih(e);t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||`An error occurred`;e.message||console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=vh(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(op(e))}handleStepStartedEvent(e){let t=e.stepName||Im(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let t=e,n=t.signature;if(!n)return;let{messageId:r,state:i}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),a=i.currentThinkingStepId??t.stepId;if(!a)return;let o=i.thinkingSteps.get(a);o!==void 0&&(i.thinkingStepSignatures.set(a,n),this.messages=yh(this.messages,r,a,o,n),this.emitMessagesChange())}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=yh(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleReasoningEncryptedValueEvent(e){let t=e.encryptedValue;if(typeof t!=`string`||t===``)return;if(e.subtype===`tool-call`){this.attachToolCallSignature(e.entityId,t);return}let{messageId:n,state:r}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0),i=r.currentThinkingStepId??e.entityId;r.thinkingStepSignatures.set(i,t);let a=r.thinkingSteps.get(i)??``;r.thinkingSteps.has(i)||(r.thinkingSteps.set(i,a),r.thinkingStepOrder.push(i)),this.messages=yh(this.messages,n,i,a,t),this.emitMessagesChange()}attachToolCallSignature(e,t){this.messages=this.messages.map(n=>{let r=!1,i=n.parts.map(n=>n.type!==`tool-call`||n.id!==e?n:(r=!0,{...n,metadata:{...n.metadata!=null&&typeof n.metadata==`object`?n.metadata:{},thoughtSignature:t}}));return r?{...n,parts:i}:n});for(let n of this.messageStates.values()){let r=n.toolCalls.get(e);r&&(r.metadata={...r.metadata??{},thoughtSignature:t})}this.emitMessagesChange()}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=_h(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=ph(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return!0}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=dh(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=uh(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=bh&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);t&&t.chunkCount!==0&&(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){this.isDone=!0;let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=vh(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&!this.streamEndEmitted&&(this.streamEndEmitted=!0,this.events.onStreamEnd?.(e))}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.streamEndEmitted=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Ch(t))}};function Ch(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}var wh=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Th=e.object({type:e.enum([`query`,`mutation`,`subscription`]),id:e.string(),name:e.string(),description:e.string(),inputSchema:e.unknown(),outputSchema:e.unknown(),outputSample:e.unknown()}),Eh=nh({name:`getCapabilities`,description:`Get the APIs available to the generated Rough feature`,inputSchema:e.object({}),outputSchema:e.array(Th)}),Dh=nh({name:`getLogs`,description:`Get Rough feature logs`,inputSchema:e.object({spriteBuildId:e.string().min(1)}),outputSchema:e.array(e.object({id:e.string().min(1),spriteBuildId:e.string().min(1),actionedAt:e.number(),type:e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_USAGE`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`]),detail:e.unknown()}))}),Oh=nh({name:`startBuild`,description:`Start a Rough feature build`,inputSchema:e.object({}),outputSchema:e.object({spriteBuildId:e.string().min(1)})}),kh=e=>{let{content:t}=e;return t?typeof t==`string`?t:t.map(e=>e.type===`text`?e.content??``:e.type===`image`?``:``).filter(Boolean).join(`
|
|
13
|
+
`):``},Ah=e=>`${e.role}:\n${e.text}`,jh=(e,t)=>{let n=`
|
|
14
14
|
|
|
15
15
|
---
|
|
16
16
|
|
|
@@ -18,41 +18,41 @@ with cause:
|
|
|
18
18
|
${t.length?`
|
|
19
19
|
# chat history
|
|
20
20
|
|
|
21
|
-
${t.map(
|
|
21
|
+
${t.map(Ah).join(n)}${n}
|
|
22
22
|
`.trim():``}
|
|
23
23
|
# current user message
|
|
24
24
|
|
|
25
|
-
${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`)return[];let t=Rm(e);return t.trim().length===0?[]:[{role:e.role,text:t}]}),r=n.findLastIndex(e=>e.role===`user`),i=n[r];return i?Bm(i,n.slice(0,r)):Error(`Could not find a user message in the sprite chat`)},Hm=new Map,Um=e=>{let{clientId:t,replicacheName:n}=e,r=()=>{},i={clientId:t,state:`starting`,released:new Promise(e=>{r=e})};Hm.set(n,i);let a=!1;return{replicacheName:n,markActive:()=>{!a&&i.state===`starting`&&(i.state=`active`)},markDestroying:()=>{a||(i.state=`destroying`)},release:()=>{a||(a=!0,Hm.get(n)===i&&Hm.delete(n),r())}}},Wm=async e=>{let{clientId:t,replicacheName:n,signal:r}=e;for(;;){if(r?.aborted)throw r.reason instanceof Error?r.reason:Error(`Replicache identity acquisition aborted`);let e=Hm.get(n);if(!e)return Um({clientId:t,replicacheName:n});if(e.state===`destroying`){await e.released;continue}throw new Tt({replicacheName:n})}},Gm=e=>{let{baseUrl:t,personId:n,projectId:r}=e;return[`rough-feature`,t,r,n].join(`:`)},Km=e=>{let{auth:t,baseUrl:n,clientId:r,projectId:i,signal:a,store:o}=e,s=`/api/v1/project/${encodeURIComponent(i)}`,c,l,u,d=!1,f,p=()=>{if(a.aborted)throw At(a)},m=async e=>{let{name:r}=e,{sessionToken:i}=e,a=i.personId;return Hf({name:r,pushURL:se({baseUrl:n,path:`${s}/replicache/push`}),pullURL:se({baseUrl:n,path:`${s}/replicache/pull`}),auth:`Bearer ${i.token}`,pullInterval:6e4,getAuth:async()=>{t.invalidateToken(i.token);let e=await t.getSessionToken();if(e.personId!==a)throw Error(`Session person changed during auth refresh. Destroy this Rough client and create a new one.`);return i=e,`Bearer ${i.token}`},sessionPersonId:a})},h=async()=>{if(typeof window>`u`)return;p();let e=await Promise.race([t.getSessionToken(),jt(a)]);p();let f=Gm({baseUrl:n,projectId:i,personId:e.personId});c=await Wm({clientId:r,replicacheName:f,signal:a}),d&&c.markDestroying(),p();let h=await m({name:f,sessionToken:e});if(h instanceof Error)throw h;if(d||a.aborted)throw await h.close(),new wt(`Replicache finished starting after the Rough client was destroyed`);l=h,c.markActive(),o.bind(h);let g=new URL(se({baseUrl:n,path:`${s}/replicache/poke`}));g.protocol=g.protocol===`https:`?`wss:`:`ws:`;let _=Jf({url:g.toString(),getToken:async()=>(await t.getSessionToken()).token,onPoke:()=>h.pull()});if(d||a.aborted)throw _.close(),await h.close(),l=void 0,new wt(`Replicache finished starting after the Rough client was destroyed`);u=_,await Promise.race([h.pull({now:!0}),jt(a)])},g=()=>l,_=()=>{d=!0,c?.markDestroying()};return{start:h,peek:g,markDestroying:_,destroy:()=>(f??=(async()=>{_();let e=u;u=void 0,e?.close();let t=l;l=void 0,await t?.close()})(),f),releaseIdentity:()=>{c?.release()}}},qm=e.enum([`ACTIVE`,`DELETED`]),Jm=e.enum([`DOCUMENTS_ENABLED`,`TASKS_ENABLED`]),H=e.string();e.object({id:H,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string(),strategy:e.string(),vision:e.string(),icon:e.string(),status:qm,deletedAt:e.number().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:H,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string(),status:qm,deletedAt:e.number().optional().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:H.optional(),publicId:e.string().optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string().optional(),status:qm.optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),flagList:Jm.array().optional()});var Ym=e.string();e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym.optional(),name:e.string().optional(),url:e.string().optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Xm=e.enum([`authorization_code`,`client_credentials`,`refresh_token`]),Zm=e.enum([`read:workspace`,`write:workspace`,`create:sprite`,`read:sprite`]),Qm=e.string();e.object({id:Qm,name:e.string(),secret:e.string().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm,name:e.string(),secret:e.string().optional().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm.optional(),name:e.string().optional(),secret:e.string().optional().nullable(),redirectUris:e.string().array().optional(),allowedGrants:Xm.array().optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var $m=e.enum([`UNKNOWN`]),U=e.string();e.object({id:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().optional().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:U.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),state:e.instanceof(Uint8Array).optional(),serialized:e.record(e.string(),e.json()).optional(),plaintext:e.string().optional(),version:e.number().optional(),documentMentionList:e.string().array().optional(),hash:e.instanceof(Uint8Array).optional(),dirtyAt:e.number().optional().nullable(),flagList:$m.array().optional(),personMentionList:e.string().array().optional()});var eh=e=>{let t=e.toLowerCase().trim().split(`@`),n=t.at(0)?.trim(),r=t.at(1)?.split(`,`).at(0)?.trim();return!n||!r?Error(`Invalid email address`):`${n}@${r}`},W=e.string().min(1).transform((t,n)=>{let r=eh(t);return r instanceof Error?(n.issues.push({code:`custom`,message:r.message,input:t}),e.NEVER):r}).pipe(e.string()),th=e.enum([`WORKSPACE`,`USER`]),nh=e.enum([`PENDING`,`UPLOADING`,`READY`,`ERROR`]),rh=e.enum([`IMAGE`,`VIDEO`,`AUDIO`,`OTHER`]),ih=e.string();e.object({id:ih,scope:th,userId:e.lazy(()=>G),workspaceId:H.nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().nullable(),version:e.number(),originalAssetId:ih.nullable()}),e.object({id:ih,scope:th,userId:e.lazy(()=>G),workspaceId:H.optional().nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().optional().nullable(),version:e.number(),originalAssetId:ih.optional().nullable()}),e.object({id:ih.optional(),scope:th.optional(),userId:e.lazy(()=>G.optional()),workspaceId:H.optional().nullable(),storageBucket:e.string().optional(),storageKey:e.string().optional(),status:nh.optional(),type:rh.optional(),mimeType:e.string().optional(),originalFileName:e.string().optional(),byteSize:e.number().optional(),metadata:e.record(e.string(),e.json()).optional(),tusUploadToken:e.string().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),originalAssetId:ih.optional().nullable()});var G=e.string();e.object({id:G,name:e.string(),email:W,isDemoAccount:e.boolean(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().nullable(),googleUid:e.string().nullable(),totpSecret:e.string().nullable(),totpEnabledAt:e.number().nullable(),recoveryHash:e.string().nullable(),recoveryCodeGeneratedAt:e.number().nullable(),avatarAssetId:ih.nullable()}),e.object({id:G,name:e.string(),email:W,isDemoAccount:e.boolean().optional(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()}),e.object({id:G.optional(),name:e.string().optional(),email:W.optional(),isDemoAccount:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()});var ah=e.enum([`DRAFT`,`ACTIVE`]),K=e.string();e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.nullable()}),e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.optional().nullable()}),e.object({id:K.optional(),name:e.string().optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),avatarAssetId:ih.optional().nullable()});var q=e.string();e.object({id:q,workspaceId:H,contentId:U,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:K,referenceId:Ym.nullable(),publicId:e.number(),parentNoteId:q.nullable(),sortOrder:e.number(),transcriptContentId:U.nullable()}),e.object({id:q,workspaceId:H,contentId:U,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:K,referenceId:Ym.optional().nullable(),publicId:e.number(),parentNoteId:q.optional().nullable(),sortOrder:e.number(),transcriptContentId:U.optional().nullable()}),e.object({id:q.optional(),workspaceId:H.optional(),contentId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),userId:G.optional(),version:e.number().optional(),lastModifiedAt:e.number().optional(),status:ah.optional(),personId:K.optional(),referenceId:Ym.optional().nullable(),publicId:e.number().optional(),parentNoteId:q.optional().nullable(),sortOrder:e.number().optional(),transcriptContentId:U.optional().nullable()});var oh=e.enum([`NOTE`,`TASK`]),sh=e.string();e.object({id:sh,workspaceId:H,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh,workspaceId:H,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh.optional(),workspaceId:H.optional(),name:e.string().optional(),color:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),description:e.string().optional(),type:oh.optional()}),e.object({noteId:q,labelId:sh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:q,labelId:sh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:q.optional(),labelId:sh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),labelType:oh.optional()});var ch=e.string();e.object({code:ch,redirectUri:e.string().nullable(),codeChallenge:e.string().nullable(),codeChallengeMethod:e.string().nullable(),expiresAt:e.number(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch,redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch.optional(),redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number().optional(),userId:G.optional(),workspaceId:H.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var lh=e.string();e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().nullable(),refreshTokenExpiresAt:e.number().nullable(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh.optional(),accessTokenExpiresAt:e.number().optional(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G.optional(),workspaceId:H.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var uh=e.string();e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var dh=e.enum([`TEXT`,`IMAGE`]),fh=e.string();e.object({id:fh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:dh.array(),outputModalityList:dh.array()}),e.object({id:fh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:dh.array(),outputModalityList:dh.array()}),e.object({id:fh.optional(),llmProviderId:uh.optional(),providerModelId:e.string().optional(),name:e.string().optional(),releasedOn:e.iso.date().optional(),isSelectable:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),inputModalityList:dh.array().optional(),outputModalityList:dh.array().optional()});var J=e.string();e.object({id:J,workspaceId:H,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().nullable(),publicId:e.string(),spriteLlmModelId:fh.nullable()}),e.object({id:J,workspaceId:H,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string(),spriteLlmModelId:fh.optional().nullable()}),e.object({id:J.optional(),workspaceId:H.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string().optional(),spriteLlmModelId:fh.optional().nullable()});var ph=e.string();e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,personId:K,key:e.string(),name:e.string(),email:W.nullable().nullable(),lastSeenAt:e.number().nullable()}),e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,personId:K,key:e.string(),name:e.string(),email:W.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()}),e.object({id:ph.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional(),personId:K.optional(),key:e.string().optional(),name:e.string().optional(),email:W.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()});var mh=e.string();e.object({id:mh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,key:e.string(),name:e.string(),lastSeenAt:e.number().nullable()}),e.object({id:mh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,key:e.string(),name:e.string(),lastSeenAt:e.number().optional().nullable()}),e.object({id:mh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional(),key:e.string().optional(),name:e.string().optional(),lastSeenAt:e.number().optional().nullable()});var hh=e.string();e.object({id:hh,publicId:e.string(),workspaceId:H,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().nullable(),revokedByUserId:G.nullable(),lastUsedAt:e.number().nullable()}),e.object({id:hh,publicId:e.string(),workspaceId:H,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()}),e.object({id:hh.optional(),publicId:e.string().optional(),workspaceId:H.optional(),name:e.string().optional(),publicKey:e.string().optional(),createdByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()});var gh=e.string();e.object({id:gh,workspaceId:H,projectId:J,projectUserId:ph,projectAccountId:mh,signingKeyId:hh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:gh,workspaceId:H,projectId:J,projectUserId:ph,projectAccountId:mh,signingKeyId:hh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:gh.optional(),workspaceId:H.optional(),projectId:J.optional(),projectUserId:ph.optional(),projectAccountId:mh.optional(),signingKeyId:hh.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var _h=e.enum([`PENDING`,`INSTALLED`]),vh=e.string();e.object({id:vh,fizzyIntegrationId:e.lazy(()=>yh),fizzyAccountId:e.lazy(()=>bh),workspaceId:H,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:vh,fizzyIntegrationId:e.lazy(()=>yh),fizzyAccountId:e.lazy(()=>bh),workspaceId:H,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:vh.optional(),fizzyIntegrationId:e.lazy(()=>yh.optional()),fizzyAccountId:e.lazy(()=>bh.optional()),workspaceId:H.optional(),publicId:e.string().optional(),name:e.string().optional(),url:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var yh=e.string();e.object({id:yh,workspaceId:H,email:e.string(),state:_h,pendingAuthenticationToken:e.string().nullable(),sessionToken:e.string().nullable(),defaultFizzyBoardId:vh.nullable(),syncAccountListStartedAt:e.number().nullable(),syncAccountListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().nullable()}),e.object({id:yh,workspaceId:H,email:e.string(),state:_h,pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:vh.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().optional().nullable()}),e.object({id:yh.optional(),workspaceId:H.optional(),email:e.string().optional(),state:_h.optional(),pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:vh.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),lastRequestedMagicLinkAt:e.number().optional().nullable()});var bh=e.string();e.object({id:bh,fizzyIntegrationId:yh,workspaceId:H,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().nullable(),syncBoardListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:bh,fizzyIntegrationId:yh,workspaceId:H,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:bh.optional(),fizzyIntegrationId:yh.optional(),workspaceId:H.optional(),slug:e.string().optional(),name:e.string().optional(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var xh=e.string();e.object({id:xh,userId:G.nullable(),workspaceId:H,pullCount:e.number(),projectUserId:ph.nullable(),projectAccountId:mh.nullable()}),e.object({id:xh,userId:G.optional().nullable(),workspaceId:H,pullCount:e.number(),projectUserId:ph.optional().nullable(),projectAccountId:mh.optional().nullable()}),e.object({id:xh.optional(),userId:G.optional().nullable(),workspaceId:H.optional(),pullCount:e.number().optional(),projectUserId:ph.optional().nullable(),projectAccountId:mh.optional().nullable()});var Sh=e.enum([`GITHUB`]),Ch=e.enum([`PENDING`,`INSTALLED`,`DELETED`]),Y=e.string();e.object({id:Y,createdAt:e.number(),updatedAt:e.number(),workspaceId:H,type:Sh,state:Ch,token:e.string().nullable(),ghInstallationId:e.number().nullable(),ghSettingsUrl:e.string().nullable(),version:e.number(),ghInstallationUrl:e.string().nullable(),name:e.string().nullable(),avatarUrl:e.string().nullable(),syncRepoListStartedAt:e.number().nullable(),syncRepoListFinishedAt:e.number().nullable()}),e.object({id:Y,createdAt:e.number(),updatedAt:e.number(),workspaceId:H,type:Sh,state:Ch,token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()}),e.object({id:Y.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),workspaceId:H.optional(),type:Sh.optional(),state:Ch.optional(),token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number().optional(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()});var wh=e.string();e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:Y,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().nullable(),version:e.number(),activatedAt:e.number().nullable(),unavailableAt:e.number().nullable(),defaultBranch:e.string(),workspaceId:H,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().nullable(),syncCommitListFinishedAt:e.number().nullable(),originId:e.string().nullable(),originUpdatedAt:e.number().nullable(),syncBranchListStartedAt:e.number().nullable(),syncBranchListFinishedAt:e.number().nullable()}),e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:Y,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string(),workspaceId:H,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()}),e.object({id:wh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),vcsIntegrationId:Y.optional(),owner:e.string().optional(),name:e.string().optional(),branch:e.string().optional(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number().optional(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string().optional(),workspaceId:H.optional(),description:e.string().optional(),url:e.string().optional(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()});var Th=e.string();e.object({id:Th,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:wh,vcsIntegrationId:Y,workspaceId:H,name:e.string(),commitSha:e.string()}),e.object({id:Th,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:wh,vcsIntegrationId:Y,workspaceId:H,name:e.string(),commitSha:e.string()}),e.object({id:Th.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsRepoId:wh.optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),name:e.string().optional(),commitSha:e.string().optional()});var Eh=e.enum([`SUGGESTED`,`APPROVED`,`REJECTED`]);e.object({noteIdA:q,noteIdB:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({noteIdA:q,noteIdB:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({noteIdA:q.optional(),noteIdB:q.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var Dh=e.string();e.object({id:Dh,workspaceId:H,projectId:J,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Dh,workspaceId:H,projectId:J,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Dh.optional(),workspaceId:H.optional(),projectId:J.optional(),key:e.string().optional(),name:e.string().optional(),toolList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional()});var X=e.string();e.object({id:X,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:J,surfaceId:Dh,ownedByPersonId:K}),e.object({id:X,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:J,surfaceId:Dh,ownedByPersonId:K}),e.object({id:X.optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),projectId:J.optional(),surfaceId:Dh.optional(),ownedByPersonId:K.optional()});var Oh=e.enum([`PENDING`,`IN_PROGRESS`,`READY`,`ERROR`,`CANCELED`]),kh=e.string();e.object({id:kh,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:X,parentSpriteBuildId:kh.nullable(),prompt:e.string(),artifactUrl:e.string().nullable(),sourceUrl:e.string().nullable(),status:Oh,startedAt:e.number().nullable(),stoppedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().nullable(),publishedAt:e.number().nullable(),createdByPersonId:K,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().nullable()}),e.object({id:kh,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:X,parentSpriteBuildId:kh.optional().nullable(),prompt:e.string(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Oh,startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:K,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().optional().nullable()}),e.object({id:kh.optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),spriteId:X.optional(),parentSpriteBuildId:kh.optional().nullable(),prompt:e.string().optional(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Oh.optional(),startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()).optional(),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:K.optional(),agentProvider:e.string().optional(),agentModel:e.string().optional(),agentInputTokens:e.number().optional(),agentOutputTokens:e.number().optional(),agentCacheReadTokens:e.number().optional(),agentCacheWriteTokens:e.number().optional(),agentEstimatedCostUsd:e.number().optional(),cancelRequestedAt:e.number().optional().nullable()});var Ah=e.string();e.object({id:Ah,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).nullable()}),e.object({id:Ah,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).optional().nullable()}),e.object({id:Ah.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),snapshot:e.record(e.string(),e.json()).optional().nullable()});var jh=e.enum(`DOCUMENT_COMMENT_CREATE.DOCUMENT_COMMENT_DELETE.DOCUMENT_COMMENT_RESOLVE.DOCUMENT_COMMENT_UPDATE.DOCUMENT_CREATE.DOCUMENT_DELETE.DOCUMENT_PERSON_MENTION.DOCUMENT_UPDATE_BLOCK_CONTENT.DOCUMENT_UPDATE_STATUS.DOCUMENT_UPDATE_TITLE.NOTE_COMMENT_CREATE.NOTE_COMMENT_DELETE.NOTE_COMMENT_RESOLVE.NOTE_COMMENT_UPDATE.NOTE_CREATE.NOTE_PERSON_MENTION.NOTE_UPDATE_CONTENT.NOTE_UPDATE_LABEL.NOTE_UPDATE_PERSON.NOTE_UPDATE_REFERENCE.NOTE_UPDATE_STATUS.NOTE_UPDATE_TITLE.SEQUENCE_DOCUMENT_DELETE.SEQUENCE_DOCUMENT_INSERT.SEQUENCE_DOCUMENT_STATUS_IN.SEQUENCE_DOCUMENT_STATUS_OUT.SEQUENCE_DOCUMENT_UPDATE_ORDER.SEQUENCE_COMMENT_CREATE.SEQUENCE_COMMENT_DELETE.SEQUENCE_COMMENT_RESOLVE.SEQUENCE_COMMENT_UPDATE.SEQUENCE_PERSON_MENTION.SPRITE_CREATE.SPRITE_COMMENT_CREATE`.split(`.`)),Mh=e.enum([`CANCELED`,`IDEA`,`DEVELOPMENT`,`RELEASED`,`DRAFT`,`ARCHIVED`]),Z=e.string();e.object({id:Z,title:e.string(),status:Mh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:H,vcsTagList:e.string().array(),archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().nullable(),ownedByPersonId:K}),e.object({id:Z,title:e.string(),status:Mh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:H,vcsTagList:e.string().array(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().optional().nullable(),ownedByPersonId:K}),e.object({id:Z.optional(),title:e.string().optional(),status:Mh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),publicId:e.number().optional(),createdByUserId:G.optional(),workspaceId:H.optional(),vcsTagList:e.string().array().optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),releasedAt:e.number().optional().nullable(),ownedByPersonId:K.optional()});var Nh=e.enum([`USER`,`STATUS`,`WISH`]),Ph=e.enum([`NONE`,`STATUS`]),Q=e.string();e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:H,publicId:e.string(),type:Nh,status:Mh.nullable().nullable(),version:e.number(),icon:e.string(),pinned:e.number().nullable(),groupBy:Ph,ownedByPersonId:K.nullable()}),e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:H,publicId:e.string(),type:Nh,status:Mh.nullable().optional().nullable(),version:e.number(),icon:e.string(),pinned:e.number().optional().nullable(),groupBy:Ph,ownedByPersonId:K.optional().nullable()}),e.object({id:Q.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),workspaceId:H.optional(),publicId:e.string().optional(),type:Nh.optional(),status:Mh.nullable().optional().nullable(),version:e.number().optional(),icon:e.string().optional(),pinned:e.number().optional().nullable(),groupBy:Ph.optional(),ownedByPersonId:K.optional().nullable()});var Fh=e.string();e.object({id:Fh,workspaceId:H,type:jh,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:Z.nullable(),noteId:q.nullable(),sequenceId:Q.nullable(),spriteId:X.nullable(),actionedByPersonId:K}),e.object({id:Fh,workspaceId:H,type:jh,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),spriteId:X.optional().nullable(),actionedByPersonId:K}),e.object({id:Fh.optional(),workspaceId:H.optional(),type:jh.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),spriteId:X.optional().nullable(),actionedByPersonId:K.optional()});var Ih=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`SPRITE`]),Lh=e.enum([`TEXT`,`DRAWING`]),Rh=e.enum([`UNKNOWN`]),zh=e.string();e.object({id:zh,sortOrder:e.number(),documentId:Z,createdAt:e.number(),updatedAt:e.number(),type:Lh,lockedAt:e.number().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:H,archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),flagList:Rh.array(),title:e.string(),contentId:U.nullable(),canvasId:Ah.nullable(),lastModifiedByUserId:G}),e.object({id:zh,sortOrder:e.number(),documentId:Z,createdAt:e.number(),updatedAt:e.number(),type:Lh,lockedAt:e.number().optional().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:H,archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Rh.array(),title:e.string(),contentId:U.optional().nullable(),canvasId:Ah.optional().nullable(),lastModifiedByUserId:G}),e.object({id:zh.optional(),sortOrder:e.number().optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),type:Lh.optional(),lockedAt:e.number().optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),workspaceId:H.optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Rh.array().optional(),title:e.string().optional(),contentId:U.optional().nullable(),canvasId:Ah.optional().nullable(),lastModifiedByUserId:G.optional()});var Bh=e.string();e.object({id:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:U,completedAt:e.number().nullable(),createdByPersonId:K}),e.object({id:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:U,completedAt:e.number().optional().nullable(),createdByPersonId:K}),e.object({id:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),title:e.string().optional(),contentId:U.optional(),completedAt:e.number().optional().nullable(),createdByPersonId:K.optional()});var Vh=e.string();e.object({id:Vh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().nullable(),resolvedByUserId:G.nullable(),documentId:Z.nullable(),blockId:zh.nullable(),sequenceId:Q.nullable(),eventId:Fh.nullable(),noteId:q.nullable(),spriteId:X.nullable(),taskId:Bh.nullable()}),e.object({id:Vh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:Z.optional().nullable(),blockId:zh.optional().nullable(),sequenceId:Q.optional().nullable(),eventId:Fh.optional().nullable(),noteId:q.optional().nullable(),spriteId:X.optional().nullable(),taskId:Bh.optional().nullable()}),e.object({id:Vh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),openedAt:e.number().optional(),openedByUserId:G.optional(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:Z.optional().nullable(),blockId:zh.optional().nullable(),sequenceId:Q.optional().nullable(),eventId:Fh.optional().nullable(),noteId:q.optional().nullable(),spriteId:X.optional().nullable(),taskId:Bh.optional().nullable()});var Hh=e.string();e.object({id:Hh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:H,version:e.number(),contentId:U,commentThreadId:Vh}),e.object({id:Hh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:H,version:e.number(),contentId:U,commentThreadId:Vh}),e.object({id:Hh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),postedAt:e.number().optional(),userId:G.optional(),workspaceId:H.optional(),version:e.number().optional(),contentId:U.optional(),commentThreadId:Vh.optional()});var Uh=e.string();e.object({id:Uh,workspaceId:H,userId:G,eventId:Fh,readAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ih,documentId:Z.nullable(),noteId:q.nullable(),sequenceId:Q.nullable(),commentId:Hh.nullable(),spriteId:X.nullable(),commentThreadId:Vh.nullable()}),e.object({id:Uh,workspaceId:H,userId:G,eventId:Fh,readAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ih,documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),commentId:Hh.optional().nullable(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()}),e.object({id:Uh.optional(),workspaceId:H.optional(),userId:G.optional(),eventId:Fh.optional(),readAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Ih.optional(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),commentId:Hh.optional().nullable(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()});var Wh=e.string();e.object({id:Wh,userId:G,contentId:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Wh,userId:G,contentId:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Wh.optional(),userId:G.optional(),contentId:U.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),state:e.instanceof(Uint8Array).optional()});var Gh=e.string();e.object({id:Gh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Gh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Gh.optional(),createdAt:e.number().optional(),record:e.record(e.string(),e.json()).optional()}),e.object({spriteId:X,projectAccountId:mh,workspaceId:H,projectId:J,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:X,projectAccountId:mh,workspaceId:H,projectId:J,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:X.optional(),projectAccountId:mh.optional(),workspaceId:H.optional(),projectId:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({projectAccountId:mh,projectUserId:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J}),e.object({projectAccountId:mh,projectUserId:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J}),e.object({projectAccountId:mh.optional(),projectUserId:ph.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional()});var Kh=e.string();e.object({id:Kh,workspaceId:H,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Hh.nullable(),noteId:q.nullable()}),e.object({id:Kh,workspaceId:H,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Hh.optional().nullable(),noteId:q.optional().nullable()}),e.object({id:Kh.optional(),workspaceId:H.optional(),userId:G.optional(),emoji:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),commentId:Hh.optional().nullable(),noteId:q.optional().nullable()}),e.object({taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional()});var qh=e.string();e.object({id:qh,workspaceId:H,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:qh,workspaceId:H,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:qh.optional(),workspaceId:H.optional(),token:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Jh=e.string();e.object({id:Jh,workspaceId:H,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Jh,workspaceId:H,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Jh.optional(),workspaceId:H.optional(),userId:G.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var Yh=e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`,`AGENT_USAGE`]),Xh=e.string();e.object({id:Xh,workspaceId:H,spriteBuildId:kh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Yh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Xh,workspaceId:H,spriteBuildId:kh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Yh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Xh.optional(),workspaceId:H.optional(),spriteBuildId:kh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Yh.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional()}),e.object({blockId:zh,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:zh,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:zh.optional(),userId:G.optional(),workspaceId:H.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Zh=e.enum([`NOTE`,`DOCUMENT`]),Qh=e.string();e.object({id:Qh,workspaceId:H,userId:G,type:Zh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Qh,workspaceId:H,userId:G,type:Zh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Qh.optional(),workspaceId:H.optional(),userId:G.optional(),type:Zh.optional(),matchAll:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var $h=e.enum([`ADMIN`,`GUEST`,`ARCHIVED`,`DEMO`]);e.object({workspaceId:H,userId:G,createdAt:e.number(),updatedAt:e.number(),role:$h,version:e.number(),personId:K,lastReadNotificationsAt:e.number().nullable()}),e.object({workspaceId:H,userId:G,createdAt:e.number(),updatedAt:e.number(),role:$h,version:e.number(),personId:K,lastReadNotificationsAt:e.number().optional().nullable()}),e.object({workspaceId:H.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),role:$h.optional(),version:e.number().optional(),personId:K.optional(),lastReadNotificationsAt:e.number().optional().nullable()});var eg=e.string();e.object({id:eg,workspaceId:H,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:jh.array(),createdByPersonId:K,createdAt:e.number(),updatedAt:e.number()}),e.object({id:eg,workspaceId:H,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:jh.array(),createdByPersonId:K,createdAt:e.number(),updatedAt:e.number()}),e.object({id:eg.optional(),workspaceId:H.optional(),name:e.string().optional(),url:e.string().optional(),secret:e.string().optional(),eventTypeList:jh.array().optional(),createdByPersonId:K.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var tg=e.enum([`FEATURE`,`FIX`,`RELEASE`,`CHORE`]),ng=e.string();e.object({id:ng,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:Y,workspaceId:H,name:e.string(),email:e.string(),avatarUrl:e.string().nullable()}),e.object({id:ng,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:Y,workspaceId:H,name:e.string(),email:e.string(),avatarUrl:e.string().optional().nullable()}),e.object({id:ng.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),name:e.string().optional(),email:e.string().optional(),avatarUrl:e.string().optional().nullable()});var rg=e.string();e.object({id:rg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:wh,url:e.string(),message:e.string(),parentShaList:e.string().array().nullable(),version:e.number(),authoredAt:e.number().nullable(),committedAt:e.number().nullable(),vcsIntegrationId:Y,workspaceId:H,type:tg,subject:e.string(),scope:e.string().nullable(),authorId:ng.nullable(),committerId:ng.nullable()}),e.object({id:rg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:wh,url:e.string(),message:e.string(),parentShaList:e.string().array().optional().nullable(),version:e.number(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:Y,workspaceId:H,type:tg,subject:e.string(),scope:e.string().optional().nullable(),authorId:ng.optional().nullable(),committerId:ng.optional().nullable()}),e.object({id:rg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sha:e.string().optional(),vcsRepoId:wh.optional(),url:e.string().optional(),message:e.string().optional(),parentShaList:e.string().array().optional().nullable(),version:e.number().optional(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),type:tg.optional(),subject:e.string().optional(),scope:e.string().optional().nullable(),authorId:ng.optional().nullable(),committerId:ng.optional().nullable()}),e.object({vcsCommitId:rg,documentId:Z,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:Y,workspaceId:H}),e.object({vcsCommitId:rg,documentId:Z,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:Y,workspaceId:H}),e.object({vcsCommitId:rg.optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional()}),e.object({documentId:Z,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:Z,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:Z.optional(),userId:G.optional(),workspaceId:H.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({personId:K,taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:K,taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:K.optional(),taskId:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional(),date:e.iso.date().optional()});var ig=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`NEW_NOTE`,`SPRITE`,`COMMENT_THREAD`]),ag=e.string();e.object({id:ag,workspaceId:H,userId:G,type:ig,noteId:q.nullable(),documentId:Z.nullable(),sequenceId:Q.nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:X.nullable(),commentThreadId:Vh.nullable()}),e.object({id:ag,workspaceId:H,userId:G,type:ig,noteId:q.optional().nullable(),documentId:Z.optional().nullable(),sequenceId:Q.optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()}),e.object({id:ag.optional(),workspaceId:H.optional(),userId:G.optional(),type:ig.optional(),noteId:q.optional().nullable(),documentId:Z.optional().nullable(),sequenceId:Q.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()});var og=e.string();e.object({id:og,workspaceId:H,email:W,lastSentAt:e.number().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().nullable()}),e.object({id:og,workspaceId:H,email:W,lastSentAt:e.number().optional().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().optional().nullable()}),e.object({id:og.optional(),workspaceId:H.optional(),email:W.optional(),lastSentAt:e.number().optional().nullable(),invitedByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),token:e.string().optional().nullable()});var sg=e.string();e.object({id:sg,workspaceId:H,projectId:J,spriteId:X,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:sg,workspaceId:H,projectId:J,spriteId:X,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:sg.optional(),workspaceId:H.optional(),projectId:J.optional(),spriteId:X.optional(),messageList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var cg=e.string();e.object({id:cg,clientGroupId:xh,lastMutationId:e.number(),version:e.number()}),e.object({id:cg,clientGroupId:xh,lastMutationId:e.number(),version:e.number()}),e.object({id:cg.optional(),clientGroupId:xh.optional(),lastMutationId:e.number().optional(),version:e.number().optional()}),e.object({documentIdA:Z,documentIdB:Z,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentIdA:Z,documentIdB:Z,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentIdA:Z.optional(),documentIdB:Z.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var lg=e.string();e.object({id:lg,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().nullable()}),e.object({id:lg,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().optional().nullable()}),e.object({id:lg.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),twoFactorVerifiedAt:e.number().optional().nullable()});var ug=e.string();e.object({id:ug,workspaceId:H,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:U,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:ug,workspaceId:H,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:U,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:ug.optional(),workspaceId:H.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),contentHash:e.instanceof(Uint8Array).optional(),contentId:U.optional(),offset:e.number().optional(),size:e.number().optional(),tokenCount:e.number().optional(),plaintext:e.string().optional()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh.optional(),encryptedValue:e.string().optional(),plaintextSuffix:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var dg=e.enum([`IS_IN`,`IS_NOT_IN`]),fg=e.string();e.object({id:fg,filterId:Qh,workspaceId:H,field:e.string(),comparator:dg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg,filterId:Qh,workspaceId:H,field:e.string(),comparator:dg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg.optional(),filterId:Qh.optional(),workspaceId:H.optional(),field:e.string().optional(),comparator:dg.optional(),value:e.record(e.string(),e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({spriteIdA:X,spriteIdB:X,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({spriteIdA:X,spriteIdB:X,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({spriteIdA:X.optional(),spriteIdB:X.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({taskId:Bh,labelId:sh,labelType:oh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Bh,labelId:sh,labelType:oh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Bh.optional(),labelId:sh.optional(),labelType:oh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var pg=e.enum([`SIGNUP_REQUEST`,`SIGNUP_ATTEMPT_TOKEN`,`SIGNUP_SUCCESS`,`LOGIN_VIA_GOOGLE_SUCCESS`,`LOGIN_VIA_PASSWORD_ATTEMPT`,`LOGIN_VIA_PASSWORD_SUCCESS`,`RESET_PASSWORD_REQUEST`,`RESET_PASSWORD_ATTEMPT_TOKEN`,`RESET_PASSWORD_SUCCESS`,`PASSWORD_CHANGE`,`TOTP_ENABLE`,`TOTP_DISABLE`,`TOTP_VERIFY_ATTEMPT`,`TOTP_VERIFY_SUCCESS`,`RECOVERY_CODE_REGENERATED`,`RECOVERY_CODE_ATTEMPT`,`RECOVERY_CODE_SUCCESS`,`VALIDATE_INVITE_LINK_ATTEMPT`,`VALIDATE_INVITE_LINK_SUCCESS`,`VALIDATE_INVITATION_ATTEMPT`,`VALIDATE_INVITATION_SUCCESS`]),mg=e.string();e.object({id:mg,type:pg,userId:G.nullable(),email:W.nullable().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:mg,type:pg,userId:G.optional().nullable(),email:W.nullable().optional().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:mg.optional(),type:pg.optional(),userId:G.optional().nullable(),email:W.nullable().optional().nullable(),clientAddress:e.string().optional(),userAgent:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var hg=W;e.object({workspaceId:H,personId:K,email:hg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:H,personId:K,email:hg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:H.optional(),personId:K.optional(),email:hg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),isPrimary:e.boolean().optional()}),e.object({documentId:Z,noteId:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentId:Z,noteId:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentId:Z.optional(),noteId:q.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var gg=e.string();e.object({id:gg,workspaceId:H,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:gg,workspaceId:H,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:gg.optional(),workspaceId:H.optional(),name:e.string().optional(),hash:e.instanceof(Uint8Array).optional(),createdByUserId:G.optional(),lastUsedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),scopeList:Zm.array().optional()});var _g=e.enum([`MXBAI_EMBED_LARGE_V1`,`TEST`,`STELLA_EN_400M_V5`,`GTE_MULTILINGUAL_BASE`]),vg=e.enum([`DIM_1024`,`DIM_768`]),yg=e.string();e.object({id:yg,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:_g,dimension:vg,vector1024:e.array(e.number()).nullable(),vector768:e.array(e.number()).nullable()}),e.object({id:yg,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:_g,dimension:vg,vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()}),e.object({id:yg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),hash:e.instanceof(Uint8Array).optional(),model:_g.optional(),dimension:vg.optional(),vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()});var bg=e.string(),xg=e.string(),Sg=e.string();e.object({tableName:bg,idA:xg,idB:Sg,workspaceId:H,deletedAt:e.number(),version:e.number()}),e.object({tableName:bg,idA:xg,idB:Sg,workspaceId:H,deletedAt:e.number(),version:e.number()}),e.object({tableName:bg.optional(),idA:xg.optional(),idB:Sg.optional(),workspaceId:H.optional(),deletedAt:e.number().optional(),version:e.number().optional()}),e.object({sequenceId:Q,documentId:Z,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:H}),e.object({sequenceId:Q,documentId:Z,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:H}),e.object({sequenceId:Q.optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sortOrder:e.number().optional(),version:e.number().optional(),workspaceId:H.optional()});var Cg=e.enum([`SPRITE_BUILD`]);e.object({useCase:Cg,llmModelId:fh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:Cg,llmModelId:fh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:Cg.optional(),llmModelId:fh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()}),e.object({spriteId:X,workspaceId:H,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:X,workspaceId:H,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:X.optional(),workspaceId:H.optional(),hash:e.instanceof(Uint8Array).optional(),version:e.number().optional(),updatedAt:e.number().optional(),plaintext:e.string().optional()});var wg=e.enum([`SIGNUP`,`PASSWORD_RESET`]),Tg=e.string();e.object({id:Tg,type:wg,userId:G.nullable(),email:W,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().nullable(),retryCount:e.number()}),e.object({id:Tg,type:wg,userId:G.optional().nullable(),email:W,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().optional().nullable(),retryCount:e.number()}),e.object({id:Tg.optional(),type:wg.optional(),userId:G.optional().nullable(),email:W.optional(),tokenHash:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),verifiedAt:e.number().optional().nullable(),retryCount:e.number().optional()}),e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),avatarAssetId:ih.nullable(),description:e.string(),emailList:W.array()}),e.enum([`PENDING`,`CREATED`,`FINISHED`,`TERMINATED`]);var Eg=e.number();e.object({id:Eg,jobQueueId:e.number().nullable(),taskId:e.number(),payload:e.unknown(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable(),isAvailable:e.boolean()}),e.object({id:Eg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean()}),e.object({id:Eg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number().optional(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean().optional()});var Dg=e.number();e.object({id:Dg,ts:e.date(),breaking:e.boolean()}),e.object({id:Dg,ts:e.date().optional(),breaking:e.boolean().optional()}),e.object({id:Dg.optional(),ts:e.date().optional(),breaking:e.boolean().optional()});var Og=e.enum([`IN_PROGRESS`,`SUCCESS`,`ERROR`]),kg=e.string();e.object({id:kg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().nullable(),queueName:e.string().nullable(),workerId:e.string(),status:Og,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:kg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string(),status:Og,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:kg.optional(),graphileWorkerJobId:e.string().optional(),serviceName:e.string().optional(),machineId:e.string().optional(),attempt:e.number().optional(),taskIdentifier:e.string().optional(),payload:e.record(e.string(),e.json()).optional(),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string().optional(),status:Og.optional(),runnableAt:e.number().optional(),startedAt:e.number().optional(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Ag=e.number();e.object({id:Ag,identifier:e.string()}),e.object({id:Ag.optional(),identifier:e.string()}),e.object({id:Ag.optional(),identifier:e.string().optional()});var jg=e.enum([`MISSING_HEARTBEAT`,`STALE_HEARTBEAT`,`STOPPED_WITH_LOCKS`,`ALREADY_RECOVERED_WITH_LOCKS`]),Mg=e.string();e.object({workerPoolId:Mg,serviceName:e.string(),machineId:e.string(),startedAt:e.number().nullable(),lastHeartbeatAt:e.number().nullable(),stoppedAt:e.number().nullable(),recoveredAt:e.number().nullable(),recoveryReason:jg.nullable().nullable(),recoveredJobCount:e.number().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Mg,serviceName:e.string(),machineId:e.string(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:jg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Mg.optional(),serviceName:e.string().optional(),machineId:e.string().optional(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:jg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Ng=e.string();e.object({identifier:Ng,knownSince:e.date(),lastExecution:e.date().nullable()}),e.object({identifier:Ng,knownSince:e.date(),lastExecution:e.date().optional().nullable()}),e.object({identifier:Ng.optional(),knownSince:e.date().optional(),lastExecution:e.date().optional().nullable()});var Pg=e.number();e.object({id:Pg,queueName:e.string(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),isAvailable:e.boolean()}),e.object({id:Pg.optional(),queueName:e.string(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean()}),e.object({id:Pg.optional(),queueName:e.string().optional(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean().optional()}),e.object({id:Eg,queueName:e.string(),taskIdentifier:e.string(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable()}),e.object({identifier:e.string().nullable(),payload:e.unknown().nullable(),queueName:e.string().nullable(),runAt:e.date().nullable(),maxAttempts:e.number().nullable(),jobKey:e.string().nullable(),priority:e.number().nullable(),flags:e.string().nullable()});var Fg=e=>r.object({token:r.string().check(r.minLength(1),r.refine(e=>e.trim()!==``,{message:`Token must not be empty or whitespace`})),expiresAt:r.number().check(r.int(),r.gt(e)),personId:K}),Ig=(e,t=Date.now())=>{let n=Fg(t).safeParse(e);return n.success?n.data:Error(r.prettifyError(n.error))},Lg=class extends Error{status;constructor(e,t){super(t),this.name=`GatewayHttpError`,this.status=e}},Rg=r.object({message:r.string()}),zg=async e=>{let t=`Gateway request failed with status ${e.status}`;try{let n=await e.json(),r=Rg.safeParse(n);r.success&&(t=r.data.message)}catch{}return new Lg(e.status,t)},Bg=async e=>{try{return await e.json()}catch{return Error(`Gateway returned an invalid JSON response`)}},Vg=async e=>{let{baseUrl:n,projectId:r,userToken:i}=e,a=await t(()=>fetch(se({baseUrl:n,path:`/api/v1/project/${encodeURIComponent(r)}/session-token`}),{method:`POST`,headers:{authorization:`Bearer ${i}`}}));if(a instanceof Error)return a;if(!a.ok)return zg(a);let o=await Bg(a);return o instanceof Error?o:Ig(o)},Hg=r.object({token:r.string(),expiresAt:r.number(),personId:r.string()}),Ug=e=>Hg.safeParse(e).success,Wg=1e3,Gg=3e4,Kg=6e4,qg=e=>Math.min(Wg*2**Math.max(e-1,0),Gg),Jg=(e,t)=>t>=e.expiresAt-Kg,Yg=e=>{let{fetchSessionToken:t,now:n=Date.now}=e,r,i,a=0,o=0,s=0,c=()=>{r=void 0,i=void 0,a=0,o=0,s+=1},l=e=>{r&&(e===void 0||r.token===e)&&(r=void 0)},u=()=>{let e=o-n();if(e>0)return Promise.reject(Error(`fetchSessionToken is rate limited after repeated failures; retry in ${e}ms`));let c=s;return i=t().then(e=>{if(c!==s)throw Error(`Session token fetch was reset before it completed`);return r=e,a=0,o=0,e}).catch(e=>{throw c===s&&(r=void 0,a+=1,o=n()+qg(a)),e}).finally(()=>{c===s&&(i=void 0)}),i};return{getSessionToken:()=>r&&!Jg(r,n())?Promise.resolve(r):i===void 0?u():i,invalidateToken:l,reset:c}},Xg=e=>{let{baseUrl:t,projectId:n,fetchUserToken:r,exchangeIdentityTokenForSessionToken:i=Vg}=e,a=Yg({fetchSessionToken:async()=>{let e=await r();if(typeof e==`string`){if(e.trim()===``)throw Error(`fetchUserToken must return a non-empty string`);let r=await i({baseUrl:t,projectId:n,userToken:e});if(r instanceof Error)throw r;return r}if(Ug(e)){let t=Ig(e);if(t instanceof Error)throw t;return t}throw Error(`fetchUserToken must return a non-empty string`)}});return{getSessionToken:()=>a.getSessionToken(),invalidateToken:e=>{a.invalidateToken(e)},destroy:async()=>{a.reset()}}},Zg=Symbol(`rough.client.runtime`),Qg=e=>{let t=e?.[Zg];if(!t)throw new Ot;return t},$g=e=>{let{fetchUserToken:t,projectId:n}=e,r=e.baseUrl??`https://gateway.rough.app`;if(typeof n!=`string`||n.trim()===``)throw TypeError(`createRoughClient: "projectId" is required`);if(typeof t!=`function`)throw TypeError(`createRoughClient: "fetchUserToken" is required`);let i=Symbol(`rough.client:${n}`),a=new AbortController,o=`starting`,s,c=Xg({baseUrl:r,fetchUserToken:t,projectId:n}),l=et(),u=Bt(),d=zt({getRuntime:()=>h}),f=Km({auth:c,baseUrl:r,clientId:i,projectId:n,signal:a.signal,store:l}),p=()=>{if(o===`destroying`||o===`destroyed`)throw new wt},m=(async()=>{await f.start();let e=f.peek();if(!e||a.signal.aborted)return;let t=await ce({projectId:n,replicache:e});t instanceof Error&&!a.signal.aborted&&console.error(`[Rough] Failed to ping project`,t)})().then(()=>{o===`starting`&&(o=`active`)},e=>{throw o===`starting`&&(o=`failed`),kt(e)});m.catch(()=>{});let h={clientId:i,baseUrl:r,projectId:n,auth:c,store:l,surfaces:d,operations:u,getState:()=>o,assertUsable:p,whenReady:()=>m,getReplicache:async()=>{p(),await m,p();let e=f.peek();if(!e)throw Error(`Replicache is not available in this environment. Rough clients only open a local database in the browser.`);return e},buildUrl:e=>se({baseUrl:r,...e})},g=async()=>{let e=[],t=async(t,n)=>{try{await n()}catch(n){let r=kt(n);r.message=`${t}: ${r.message}`,e.push(r)}};try{await t(`operations`,()=>u.closeAll()),await t(`surfaces`,()=>d.destroy()),await Promise.allSettled([m]),await t(`replicache`,()=>f.destroy()),await Promise.all([t(`store`,()=>l.destroy()),t(`auth`,()=>c.destroy())])}finally{f.releaseIdentity(),o=`destroyed`}if(e.length>0)throw new Dt({errors:e})},_={get projectId(){return n},destroy:()=>s||(o=`destroying`,f.markDestroying(),a.abort(new wt),s=g(),s)};return Object.defineProperty(_,Zg,{value:h,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(_)},e_=async e=>{await Qg(e.client).whenReady()},t_=e=>e.filter(e=>e.publishedAt!==null).toSorted((e,t)=>{let n=(t.publishedAt??0)-(e.publishedAt??0);return n===0?t.id.localeCompare(e.id):n}).at(0)??null,n_=e=>{let{sprite:t,spriteBuildList:n}=e;return{id:t.id,name:t.name,ownedByPersonId:t.ownedByPersonId,publishedSpriteBuildId:t_(n)?.id??null}},r_=(e,t)=>{let n=new Map;for(let t of e.spriteBuild.asList.value){let e=n.get(t.spriteId);e||(e=[],n.set(t.spriteId,e)),e.push(t)}let r=[];for(let i of e.sprite.asList.value){if(i.surfaceId!==t)continue;let e=n_({sprite:i,spriteBuildList:n.get(i.id)??[]});e.publishedSpriteBuildId&&r.push(e)}return r.toSorted((e,t)=>t.id.localeCompare(e.id))},i_=e=>{let{client:t,onError:n,onFeatures:r,signal:i}=e,a=Qg(t);a.assertUsable();let o=Lt(e.surface),s=a.surfaces.acquire({surface:o}),c=new AbortController,l,u,d,f=(async()=>{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Mt(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)return;let t=e.resolution.id,n=()=>{c.signal.aborted||r(r_(a.store,t))};l=a.store.subscribe(n),n()})();f.catch(e=>{c.signal.aborted||n?.(kt(e))});let p=()=>(d??=(async()=>{c.abort(),l?.(),l=void 0,s.release(),u?.(),u=void 0,await Promise.allSettled([f])})(),d);return u=a.operations.register({label:`getRoughFeatures(${o.key})`,close:p}),i&&(i.aborted?p():i.addEventListener(`abort`,()=>void p(),{once:!0})),{get ready(){return f},unsubscribe:p}},a_={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},o_=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},s_=Symbol(`lucide-context`),c_=()=>i(s_),l_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`,`name`,`color`,`size`,`strokeWidth`,`absoluteStrokeWidth`,`iconNode`,`children`]),u_=l.from_svg(`<svg><!><!></svg>`);function d_(e,t){l.push(t,!0);let n=c_()??{},r=l.prop(t,`name`,7),i=l.prop(t,`color`,23,()=>n.color??`currentColor`),a=l.prop(t,`size`,23,()=>n.size??24),o=l.prop(t,`strokeWidth`,23,()=>n.strokeWidth??2),s=l.prop(t,`absoluteStrokeWidth`,23,()=>n.absoluteStrokeWidth??!1),c=l.prop(t,`iconNode`,23,()=>[]),u=l.prop(t,`children`,7),d=l.rest_props(t,l_),f=l.derived(()=>s()?Number(o())*24/Number(a()):o());var p={get name(){return r()},set name(e){r(e),l.flush()},get color(){return i()},set color(e=n.color??`currentColor`){i(e),l.flush()},get size(){return a()},set size(e=n.size??24){a(e),l.flush()},get strokeWidth(){return o()},set strokeWidth(e=n.strokeWidth??2){o(e),l.flush()},get absoluteStrokeWidth(){return s()},set absoluteStrokeWidth(e=n.absoluteStrokeWidth??!1){s(e),l.flush()},get iconNode(){return c()},set iconNode(e=[]){c(e),l.flush()},get children(){return u()},set children(e){u(e),l.flush()}},m=u_();l.attribute_effect(m,e=>({...a_,...e,...d,width:a(),height:a(),stroke:i(),"stroke-width":l.get(f),class:[`lucide-icon lucide`,n.class,r()&&`lucide-${r()}`,t.class]}),[()=>!u()&&!o_(d)&&{"aria-hidden":`true`}]);var h=l.child(m);l.each(h,17,c,l.index,(e,t)=>{var n=l.derived(()=>l.to_array(l.get(t),2));let r=()=>l.get(n)[0],i=()=>l.get(n)[1];var a=l.comment(),o=l.first_child(a);l.element(o,r,!0,(e,t)=>{l.attribute_effect(e,()=>({...i()}))}),l.append(e,a)});var g=l.sibling(h);return l.snippet(g,()=>u()??l.noop),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(d_,{name:{},color:{},size:{},strokeWidth:{},absoluteStrokeWidth:{},iconNode:{},children:{}},[],[],{mode:`open`});var f_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function p_(e,t){let n=l.rest_props(t,f_),r=[[`path`,{d:`m5 12 7-7 7 7`}],[`path`,{d:`M12 19V5`}]];d_(e,l.spread_props({name:`arrow-up`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(p_,{},[],[],{mode:`open`});var m_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function h_(e,t){let n=l.rest_props(t,m_),r=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}]];d_(e,l.spread_props({name:`square`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(h_,{},[],[],{mode:`open`});var g_=class extends Error{missingFeature;constructor(e){super(__(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function __(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function v_(e){if(!e.body)throw new g_(`Response.body`);if(typeof e.body.getReader!=`function`)throw new g_(`Response.body.getReader`);return e.body.getReader()}function y_(){if(typeof globalThis.TextDecoder!=`function`)throw new g_(`TextDecoder`);return new globalThis.TextDecoder}function b_(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}var x_=new WeakMap;function S_(e){return x_.get(e)??(`runId`in e&&typeof e.runId==`string`?e.runId:void 0)}var C_=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},w_=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},T_=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},E_=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function D_(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function O_(e){let t=D_(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new E_(t.maxAttempts);await k_(t.delayMs,n)}}}function k_(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function A_(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function j_(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function M_(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var N_=`X-Run-Id`;function P_(e){return e===void 0?{}:{[N_]:e}}function F_(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*I_(e,t){try{let n=y_(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new w_(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
26
|
-
`);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new C_}finally{e.releaseLock()}}async function*L_(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=b_(o);if(e===`[DONE]`){yield{chunk:{type:Nm.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,model:i??``,timestamp:Date.now(),finishReason:`stop`}};return}let s=JSON.parse(e);`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId),`model`in s&&typeof s.model==`string`&&(i=s.model);let c=a;a=void 0,yield{chunk:s,...c===void 0?{}:{id:c}}}}function R_(e){if(!e.ok)throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}async function z_(e,t,n,r,i){let a=await e(F_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});R_(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?o.messages:[],activeRun:s,interrupts:c}}async function B_(e,t,n,r,i){let a=await e(F_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});R_(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*V_(e,t,n){R_(e),yield*L_(I_(v_(e),t),n)}async function*H_(e,t){for await(let{chunk:n}of V_(e,t))yield n}function U_(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new w_(e)}yield*r(o,a)}}async function*W_(e,t,n){let r=O_(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof C_||e instanceof w_)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new T_}return}}function G_(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[];function o(e,t){t&&x_.set(e,t);let n=a.shift();n?n(e):i.push(e)}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}})()},async send(t,n,r,i){let a=!1,s,c;try{let l=e.connect(t,n,r,i);for await(let e of l)`threadId`in e&&typeof e.threadId==`string`&&(s=e.threadId),`runId`in e&&typeof e.runId==`string`&&(c=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o({type:Nm.RUN_FINISHED,threadId:j_(s??i?.threadId,`threadId`),runId:j_(c??i?.runId,`runId`),model:`connect-wrapper`,timestamp:Date.now(),finishReason:`stop`},i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:Nm.RUN_ERROR,threadId:j_(s??i?.threadId,`threadId`),runId:j_(c??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function K_(e,t,n,r){let i=Em(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??A_(`thread`),runId:n?.runId??A_(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function q_(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...M_(s.headers),...P_(a?.runId)},l=K_(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*W_(U_(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>V_(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=F_(i,{offset:`-1`,runId:n}),s={...M_(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*W_(U_(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>V_(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return z_(i.fetchClient??fetch,r,M_(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return B_(i.fetchClient??fetch,r,M_(i.headers),i.credentials||`same-origin`,n)}}}function J_(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r});a instanceof Response?yield*H_(a,r):yield*Y_(a,r)}}}async function*Y_(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function X_(e){return e.resumable}function Z_(e,t){let n=Rp(e.descriptor);return n?{...t,metadata:Lp(n)}:t}function Q_(e){return`cancel`in e&&`clearResolution`in e}var $_=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),ev=new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`,`legacy-submit-failed`]);function tv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nv(e){return tv(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function rv(e){return tv(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function iv(e){return nv(e.metadata)||rv(e.metadata)}function av(e){return jp(e)}function ov(e){if(!tv(e.metadata))return!1;let t=e.metadata[Tp];return!tv(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function sv(e){if(!tv(e.metadata))return!1;let t=e.metadata[Tp];return!tv(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function cv(e){return e.metadata?.[`tanstack:interruptPayload`]}function lv(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function uv(e){if(e.responseSchema!==void 0)try{return np(tp(e.responseSchema))}catch{return}}function dv(e){if(e!==void 0)try{return Pp(e)}catch{return}}function fv(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function pv(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(cp(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return fv(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function mv(e){for(let t of $_)if(t===e)return!0;return!1}function hv(e){for(let t of ev)if(t===e)return!0;return!1}function gv(e){if(!tv(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?mv(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&hv(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function _v(e){return gv(e)?[e]:!tv(e)||!Array.isArray(e.errors)?[]:e.errors.every(gv)?e.errors:[]}function vv(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function yv(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&vv(e.interruptIds,t.interruptIds)}function bv(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>yv(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>yv(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function xv(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):vv(e.interruptIds,n)}function Sv(e,t,n){let r=uv(e)??n?.responseSchemaHash;return V({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function Cv(e,t){let n=V(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([V(e.error)]),i=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var wv=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:V(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=av(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)X_(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Z_(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&lv(t.descriptor.reason)&&t.descriptor.toolCallId===e&&rv(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&nv(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=V(e),i=av(r),a=i===void 0&&iv(r);if(i===void 0&&!a)return ov(r)?{descriptor:r,binding:Sv(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&uv(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(uv(r)??i.responseSchemaHash);if(i!==void 0&&sv(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Sv(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(s&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Cp(e.approvalSchema,e.inputSchema);if(wp(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:V(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&wp(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:V(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:V(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(o&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&dv(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===dv(e.payloadSchema))){let t=cv(r);return{descriptor:r,binding:V(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:V(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||uv(r)===void 0||i.responseSchemaHash===uv(r));return{descriptor:r,binding:Sv(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=Cv(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=V(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:V(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=tv(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?V(n.binding):V({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);if(fv(a)){r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Z_(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>X_(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=ip(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(!(`valid`in t)){e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=V(Z_(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=pv(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return fv(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?pv(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!tv(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=pv(e.tool?.inputSchema,r,`invalid-edited-args`);return fv(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=pv(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return fv(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!tv(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>X_(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0){this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=V({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(Q_),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:fv(n)?`async-resolver`:`inactive-transaction`,message:fv(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>X_(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)X_(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(e)}async performSubmission(e){try{await this.options.submit(e)}catch(t){this.handleSubmissionFailure(t,e)}finally{this.resuming=!1,this.publish()}}handleSubmissionFailure(e,t){let n=_v(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)X_(e)&&(e.status=`error`);return}let r=n.filter(e=>xv(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>X_(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=V(e))}else o.push(V(e));let s=bv(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)X_(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(X_).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},Tv=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Ev=class extends Tv{emitEvent(){}},Dv=class{events;constructor(e){this.events=new Ev(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Ov=e=>new Dv(e);function kv(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Av(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function jv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Mv(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Nv=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(kv).catch(()=>void 0);let t=kv(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;e.then(e=>{!e||this.messagesGeneration!==t||(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=S_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Av(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Mv(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=jv(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=jv(e);t&&this.clearedMessageIds.add(t);let n=Av(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return S_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Pv(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Fv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Iv(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Lv=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=S_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Pv(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Iv(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Fv(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Fv(e);t&&this.clearedMessageIds.add(t);let n=Pv(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return S_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Rv(e){let t=new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function zv(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return J_(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Bv(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function Vv(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
|
|
27
|
-
`),...t===void 0?{}:{body:t}};let r=[];for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content);return{content:{content:r},...t===void 0?{}:{body:t}}}function Hv(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function Uv(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(!(typeof n!=`object`||!n||!(`threadId`in n)||typeof n.threadId!=`string`||n.threadId.length===0||!(`runId`in n)||typeof n.runId!=`string`||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var Wv=2e3,Gv=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),Kv=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new Lv;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){Rv(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new Nv(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.queueConfig=Bv(e.queue),this.connection=G_(zv(e)),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Ov)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new wv({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,i=r?r.messages:e.initialMessages,a=null;if(r?.resume){let e=r.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(a=e.resumeState.runId)}if(!a&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(a=t.resumeState.runId)}this.processor=new wm({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(n){let r=this.devtoolsBridge.getCurrentRunEventContext(),i=(async()=>{try{let i=this.activeClientTools===null?this.context:this.activeContext,a=await n(e.input,{toolCallId:e.toolCallId,context:i,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:a,state:`output-available`},t,r)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,i)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(n),this.rejoinRunId=a,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=Uv(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){let e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(t.messages),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=S_(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),S_(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=S_(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=S_(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=S_(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.isLoading?new Promise((t,r)=>{this.queuePostStreamAction(async()=>{try{t(await this.resumeInterruptsUnsafe(e,n))}catch(e){r(e)}})}):(this.pendingResumeThreadId=n.threadId,this.pendingResumeParentRunId=n.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=Hv(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!t)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},Wv);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&Gv.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)&&(this.interruptSubmissionFailure={errors:e[`tanstack:interruptErrors`]??[]}),this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(S_(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=e[`tanstack:interruptErrors`];if(!t||!n||n.length===0)return!1;let r=S_(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=S_(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),!(typeof e==`string`&&!e.trim())){if(this.hasBlockingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);if(this.isSendBusy()){let{action:r,id:i}=this.decideWhenBusy(e,n);if(r===`drop`)return;if(r===`queue`){this.enqueueMessage(e,t,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,t)}finally{this.sendInFlight=!1}}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id}}async append(e){if(this.mountDevtools(),this.hasBlockingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=im(e,am);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration,t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?fp(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{}};if(this.devtoolsBridge.beginRun(m.runId,m.threadId),s=m.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,m.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,m.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,m),e!==this.streamGeneration||a.aborted||(await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){if(t instanceof Error){if(t.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;e===this.streamGeneration&&(this.reportStreamError(t),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:t.message}),c=!0))}}finally{if(e===this.streamGeneration){if(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o){let e=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:t}=this.processor.getState();if(e?.type===`tool-result`&&t!==`stop`&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(e){console.error(`Failed to continue flow after tool result:`,e),await this.drainQueue()}else this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()}else this.flushQueue()}}return o}subscribe(e){let t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t)}async addToolResultForClientTool(e,t,n){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,n),this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output)){if(this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&cp(e.outputSchema)?mp(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(e)}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=Vv(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`),this.connection=G_(zv({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Bv(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function qv(){return{name:`streaming`,transformDocument(e){let t=Jv(e.children);return t===e.children?e:{...e,children:t}}}}function Jv(e){let t=e.at(-1);if(!t)return e;let n=Yv(t);return n===t?e:n?[...e.slice(0,-1),n]:e.slice(0,-1)}function Yv(e){if(e.type===`heading`&&e.children.length===0)return;if(e.type===`blockquote`){let t=Jv(e.children);return t.length===0?void 0:t===e.children?e:{...e,children:t}}if(e.type!==`list`)return e;let t=e.items.at(-1);if(!t)return;let n=Xv(t);if(n===t)return e;let r=n?[...e.items.slice(0,-1),n]:e.items.slice(0,-1);return r.length===0?void 0:{...e,items:r}}function Xv(e){let t=Jv(e.children);if(t.length!==0)return t===e.children?e:{...e,children:t}}var Zv={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};function Qv(e){return e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
|
|
28
|
-
`)}function
|
|
29
|
-
`){o(),r.push({type:`break`}),i+=2;continue}if(c&&/[\\`*_[\]{}()#+\-.!|~<>]/.test(c)){a+=c,i+=2;continue}}if(s==="`"){let t=
|
|
25
|
+
${Ah(e)}`.trim()},Mh=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`)return[];let t=kh(e);return t.trim().length===0?[]:[{role:e.role,text:t}]}),r=n.findLastIndex(e=>e.role===`user`),i=n[r];return i?jh(i,n.slice(0,r)):Error(`Could not find a user message in the sprite chat`)},Nh=new Map,Ph=e=>{let{clientId:t,replicacheName:n}=e,r=()=>{},i={clientId:t,state:`starting`,released:new Promise(e=>{r=e})};Nh.set(n,i);let a=!1;return{replicacheName:n,markActive:()=>{!a&&i.state===`starting`&&(i.state=`active`)},markDestroying:()=>{a||(i.state=`destroying`)},release:()=>{a||(a=!0,Nh.get(n)===i&&Nh.delete(n),r())}}},Fh=async e=>{let{clientId:t,replicacheName:n,signal:r}=e;for(;;){if(r?.aborted)throw r.reason instanceof Error?r.reason:Error(`Replicache identity acquisition aborted`);let e=Nh.get(n);if(!e)return Ph({clientId:t,replicacheName:n});if(e.state===`destroying`){await e.released;continue}throw new xt({replicacheName:n})}},Ih=e=>{let{baseUrl:t,personId:n,projectId:r}=e;return[`rough-feature`,t,r,n].join(`:`)},Lh=e=>{let{auth:t,baseUrl:n,clientId:r,projectId:i,signal:a,store:o}=e,s=`/api/v1/project/${encodeURIComponent(i)}`,c,l,u,d=!1,f,p=()=>{if(a.aborted)throw Et(a)},m=async e=>{let{name:r}=e,{sessionToken:i}=e,a=i.personId;return Gf({name:r,pushURL:T({baseUrl:n,path:`${s}/replicache/push`}),pullURL:T({baseUrl:n,path:`${s}/replicache/pull`}),auth:`Bearer ${i.token}`,pullInterval:6e4,getAuth:async()=>{t.invalidateToken(i.token);let e=await t.getSessionToken();if(e.personId!==a)throw Error(`Session person changed during auth refresh. Destroy this Rough client and create a new one.`);return i=e,`Bearer ${i.token}`},sessionPersonId:a})},h=async()=>{if(typeof window>`u`)return;p();let e=await Promise.race([t.getSessionToken(),Dt(a)]);p();let f=Ih({baseUrl:n,projectId:i,personId:e.personId});c=await Fh({clientId:r,replicacheName:f,signal:a}),d&&c.markDestroying(),p();let h=await m({name:f,sessionToken:e});if(h instanceof Error)throw h;if(d||a.aborted)throw await h.close(),new bt(`Replicache finished starting after the Rough client was destroyed`);l=h,c.markActive(),o.bind(h);let g=new URL(T({baseUrl:n,path:`${s}/replicache/poke`}));g.protocol=g.protocol===`https:`?`wss:`:`ws:`;let _=Zf({url:g.toString(),getToken:async()=>(await t.getSessionToken()).token,onPoke:()=>h.pull()});if(d||a.aborted)throw _.close(),await h.close(),l=void 0,new bt(`Replicache finished starting after the Rough client was destroyed`);u=_,await Promise.race([h.pull({now:!0}),Dt(a)])},g=()=>l,_=()=>{d=!0,c?.markDestroying()};return{start:h,peek:g,markDestroying:_,destroy:()=>(f??=(async()=>{_();let e=u;u=void 0,e?.close();let t=l;l=void 0,await t?.close()})(),f),releaseIdentity:()=>{c?.release()}}},Rh=e.enum([`ACTIVE`,`DELETED`]),zh=e.enum([`DOCUMENTS_ENABLED`,`TASKS_ENABLED`]),V=e.string();e.object({id:V,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string(),strategy:e.string(),vision:e.string(),icon:e.string(),status:Rh,deletedAt:e.number().nullable(),version:e.number(),flagList:zh.array()}),e.object({id:V,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string(),status:Rh,deletedAt:e.number().optional().nullable(),version:e.number(),flagList:zh.array()}),e.object({id:V.optional(),publicId:e.string().optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string().optional(),status:Rh.optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),flagList:zh.array().optional()});var Bh=e.string();e.object({id:Bh,name:e.string(),url:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Bh,name:e.string(),url:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Bh.optional(),name:e.string().optional(),url:e.string().optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Vh=e.enum([`authorization_code`,`client_credentials`,`refresh_token`]),Hh=e.enum([`read:workspace`,`write:workspace`,`create:sprite`,`read:sprite`]),Uh=e.string();e.object({id:Uh,name:e.string(),secret:e.string().nullable(),redirectUris:e.string().array(),allowedGrants:Vh.array(),scopes:Hh.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Uh,name:e.string(),secret:e.string().optional().nullable(),redirectUris:e.string().array(),allowedGrants:Vh.array(),scopes:Hh.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Uh.optional(),name:e.string().optional(),secret:e.string().optional().nullable(),redirectUris:e.string().array().optional(),allowedGrants:Vh.array().optional(),scopes:Hh.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Wh=e.enum([`UNKNOWN`]),H=e.string();e.object({id:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().nullable(),flagList:Wh.array(),personMentionList:e.string().array()}),e.object({id:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().optional().nullable(),flagList:Wh.array(),personMentionList:e.string().array()}),e.object({id:H.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),state:e.instanceof(Uint8Array).optional(),serialized:e.record(e.string(),e.json()).optional(),plaintext:e.string().optional(),version:e.number().optional(),documentMentionList:e.string().array().optional(),hash:e.instanceof(Uint8Array).optional(),dirtyAt:e.number().optional().nullable(),flagList:Wh.array().optional(),personMentionList:e.string().array().optional()});var Gh=e=>{let t=e.toLowerCase().trim().split(`@`),n=t.at(0)?.trim(),r=t.at(1)?.split(`,`).at(0)?.trim();return!n||!r?Error(`Invalid email address`):`${n}@${r}`},Kh=e.string().min(1).transform((t,n)=>{let r=Gh(t);return r instanceof Error?(n.issues.push({code:`custom`,message:r.message,input:t}),e.NEVER):r}).pipe(e.string()),qh=e.enum([`WORKSPACE`,`USER`,`PROJECT`]),Jh=e.enum([`PENDING`,`UPLOADING`,`READY`,`ERROR`]),Yh=e.enum([`IMAGE`,`VIDEO`,`AUDIO`,`OTHER`]),U=e.string();e.object({id:U,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:e.lazy(()=>$h.nullable())}),e.object({id:U,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:e.lazy(()=>$h.optional().nullable())}),e.object({id:U.optional(),name:e.string().optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),avatarAssetId:e.lazy(()=>$h.optional().nullable())});var Xh=e.string();e.object({id:Xh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Xh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Xh.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Zh=e.enum([`TEXT`,`IMAGE`]),Qh=e.string();e.object({id:Qh,llmProviderId:Xh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:Zh.array(),outputModalityList:Zh.array()}),e.object({id:Qh,llmProviderId:Xh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:Zh.array(),outputModalityList:Zh.array()}),e.object({id:Qh.optional(),llmProviderId:Xh.optional(),providerModelId:e.string().optional(),name:e.string().optional(),releasedOn:e.iso.date().optional(),isSelectable:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),inputModalityList:Zh.array().optional(),outputModalityList:Zh.array().optional()});var W=e.string();e.object({id:W,workspaceId:V,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().nullable(),publicId:e.string(),spriteLlmModelId:Qh.nullable()}),e.object({id:W,workspaceId:V,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string(),spriteLlmModelId:Qh.optional().nullable()}),e.object({id:W.optional(),workspaceId:V.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string().optional(),spriteLlmModelId:Qh.optional().nullable()});var $h=e.string();e.object({id:$h,scope:qh,userId:e.lazy(()=>G.nullable()),workspaceId:V.nullable(),storageBucket:e.string(),storageKey:e.string(),status:Jh,type:Yh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().nullable(),version:e.number(),originalAssetId:$h.nullable(),personId:U.nullable(),projectId:W.nullable()}),e.object({id:$h,scope:qh,userId:e.lazy(()=>G.optional().nullable()),workspaceId:V.optional().nullable(),storageBucket:e.string(),storageKey:e.string(),status:Jh,type:Yh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().optional().nullable(),version:e.number(),originalAssetId:$h.optional().nullable(),personId:U.optional().nullable(),projectId:W.optional().nullable()}),e.object({id:$h.optional(),scope:qh.optional(),userId:e.lazy(()=>G.optional().nullable()),workspaceId:V.optional().nullable(),storageBucket:e.string().optional(),storageKey:e.string().optional(),status:Jh.optional(),type:Yh.optional(),mimeType:e.string().optional(),originalFileName:e.string().optional(),byteSize:e.number().optional(),metadata:e.record(e.string(),e.json()).optional(),tusUploadToken:e.string().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),originalAssetId:$h.optional().nullable(),personId:U.optional().nullable(),projectId:W.optional().nullable()});var G=e.string();e.object({id:G,name:e.string(),email:Kh,isDemoAccount:e.boolean(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().nullable(),googleUid:e.string().nullable(),totpSecret:e.string().nullable(),totpEnabledAt:e.number().nullable(),recoveryHash:e.string().nullable(),recoveryCodeGeneratedAt:e.number().nullable(),avatarAssetId:$h.nullable()}),e.object({id:G,name:e.string(),email:Kh,isDemoAccount:e.boolean().optional(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:$h.optional().nullable()}),e.object({id:G.optional(),name:e.string().optional(),email:Kh.optional(),isDemoAccount:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:$h.optional().nullable()});var eg=e.enum([`DRAFT`,`ACTIVE`]),K=e.string();e.object({id:K,workspaceId:V,contentId:H,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:eg,personId:U,referenceId:Bh.nullable(),publicId:e.number(),parentNoteId:K.nullable(),sortOrder:e.number(),transcriptContentId:H.nullable()}),e.object({id:K,workspaceId:V,contentId:H,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:eg,personId:U,referenceId:Bh.optional().nullable(),publicId:e.number(),parentNoteId:K.optional().nullable(),sortOrder:e.number(),transcriptContentId:H.optional().nullable()}),e.object({id:K.optional(),workspaceId:V.optional(),contentId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),userId:G.optional(),version:e.number().optional(),lastModifiedAt:e.number().optional(),status:eg.optional(),personId:U.optional(),referenceId:Bh.optional().nullable(),publicId:e.number().optional(),parentNoteId:K.optional().nullable(),sortOrder:e.number().optional(),transcriptContentId:H.optional().nullable()});var tg=e.enum([`NOTE`,`TASK`]),ng=e.string();e.object({id:ng,workspaceId:V,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:tg}),e.object({id:ng,workspaceId:V,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:tg}),e.object({id:ng.optional(),workspaceId:V.optional(),name:e.string().optional(),color:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),description:e.string().optional(),type:tg.optional()}),e.object({noteId:K,labelId:ng,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:tg}),e.object({noteId:K,labelId:ng,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:tg}),e.object({noteId:K.optional(),labelId:ng.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),labelType:tg.optional()});var rg=e.string();e.object({code:rg,redirectUri:e.string().nullable(),codeChallenge:e.string().nullable(),codeChallengeMethod:e.string().nullable(),expiresAt:e.number(),userId:G,workspaceId:V,oauthClientId:Uh,scopes:Hh.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:rg,redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number(),userId:G,workspaceId:V,oauthClientId:Uh,scopes:Hh.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:rg.optional(),redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number().optional(),userId:G.optional(),workspaceId:V.optional(),oauthClientId:Uh.optional(),scopes:Hh.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var ig=e.string();e.object({accessToken:ig,accessTokenExpiresAt:e.number(),refreshToken:e.string().nullable(),refreshTokenExpiresAt:e.number().nullable(),userId:G,workspaceId:V,oauthClientId:Uh,scopes:Hh.array(),originatingAuthCodeId:rg.nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:ig,accessTokenExpiresAt:e.number(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G,workspaceId:V,oauthClientId:Uh,scopes:Hh.array(),originatingAuthCodeId:rg.optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:ig.optional(),accessTokenExpiresAt:e.number().optional(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G.optional(),workspaceId:V.optional(),oauthClientId:Uh.optional(),scopes:Hh.array().optional(),originatingAuthCodeId:rg.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var ag=e.string();e.object({id:ag,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W,personId:U,key:e.string(),name:e.string(),email:Kh.nullable().nullable(),lastSeenAt:e.number().nullable()}),e.object({id:ag,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W,personId:U,key:e.string(),name:e.string(),email:Kh.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()}),e.object({id:ag.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:W.optional(),personId:U.optional(),key:e.string().optional(),name:e.string().optional(),email:Kh.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()});var og=e.string();e.object({id:og,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W,key:e.string(),name:e.string(),lastSeenAt:e.number().nullable()}),e.object({id:og,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W,key:e.string(),name:e.string(),lastSeenAt:e.number().optional().nullable()}),e.object({id:og.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:W.optional(),key:e.string().optional(),name:e.string().optional(),lastSeenAt:e.number().optional().nullable()});var sg=e.string();e.object({id:sg,publicId:e.string(),workspaceId:V,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().nullable(),revokedByUserId:G.nullable(),lastUsedAt:e.number().nullable()}),e.object({id:sg,publicId:e.string(),workspaceId:V,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()}),e.object({id:sg.optional(),publicId:e.string().optional(),workspaceId:V.optional(),name:e.string().optional(),publicKey:e.string().optional(),createdByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()});var cg=e.string();e.object({id:cg,workspaceId:V,projectId:W,projectUserId:ag,projectAccountId:og,signingKeyId:sg,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:cg,workspaceId:V,projectId:W,projectUserId:ag,projectAccountId:og,signingKeyId:sg,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:cg.optional(),workspaceId:V.optional(),projectId:W.optional(),projectUserId:ag.optional(),projectAccountId:og.optional(),signingKeyId:sg.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var lg=e.enum([`PENDING`,`INSTALLED`]),ug=e.string();e.object({id:ug,fizzyIntegrationId:e.lazy(()=>dg),fizzyAccountId:e.lazy(()=>fg),workspaceId:V,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:ug,fizzyIntegrationId:e.lazy(()=>dg),fizzyAccountId:e.lazy(()=>fg),workspaceId:V,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:ug.optional(),fizzyIntegrationId:e.lazy(()=>dg.optional()),fizzyAccountId:e.lazy(()=>fg.optional()),workspaceId:V.optional(),publicId:e.string().optional(),name:e.string().optional(),url:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var dg=e.string();e.object({id:dg,workspaceId:V,email:e.string(),state:lg,pendingAuthenticationToken:e.string().nullable(),sessionToken:e.string().nullable(),defaultFizzyBoardId:ug.nullable(),syncAccountListStartedAt:e.number().nullable(),syncAccountListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().nullable()}),e.object({id:dg,workspaceId:V,email:e.string(),state:lg,pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:ug.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().optional().nullable()}),e.object({id:dg.optional(),workspaceId:V.optional(),email:e.string().optional(),state:lg.optional(),pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:ug.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),lastRequestedMagicLinkAt:e.number().optional().nullable()});var fg=e.string();e.object({id:fg,fizzyIntegrationId:dg,workspaceId:V,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().nullable(),syncBoardListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg,fizzyIntegrationId:dg,workspaceId:V,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg.optional(),fizzyIntegrationId:dg.optional(),workspaceId:V.optional(),slug:e.string().optional(),name:e.string().optional(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var pg=e.string();e.object({id:pg,userId:G.nullable(),workspaceId:V,pullCount:e.number(),projectUserId:ag.nullable(),projectAccountId:og.nullable()}),e.object({id:pg,userId:G.optional().nullable(),workspaceId:V,pullCount:e.number(),projectUserId:ag.optional().nullable(),projectAccountId:og.optional().nullable()}),e.object({id:pg.optional(),userId:G.optional().nullable(),workspaceId:V.optional(),pullCount:e.number().optional(),projectUserId:ag.optional().nullable(),projectAccountId:og.optional().nullable()});var mg=e.enum([`GITHUB`]),hg=e.enum([`PENDING`,`INSTALLED`,`DELETED`]),gg=e.string();e.object({id:gg,createdAt:e.number(),updatedAt:e.number(),workspaceId:V,type:mg,state:hg,token:e.string().nullable(),ghInstallationId:e.number().nullable(),ghSettingsUrl:e.string().nullable(),version:e.number(),ghInstallationUrl:e.string().nullable(),name:e.string().nullable(),avatarUrl:e.string().nullable(),syncRepoListStartedAt:e.number().nullable(),syncRepoListFinishedAt:e.number().nullable()}),e.object({id:gg,createdAt:e.number(),updatedAt:e.number(),workspaceId:V,type:mg,state:hg,token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()}),e.object({id:gg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),workspaceId:V.optional(),type:mg.optional(),state:hg.optional(),token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number().optional(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()});var _g=e.string();e.object({id:_g,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:gg,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().nullable(),version:e.number(),activatedAt:e.number().nullable(),unavailableAt:e.number().nullable(),defaultBranch:e.string(),workspaceId:V,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().nullable(),syncCommitListFinishedAt:e.number().nullable(),originId:e.string().nullable(),originUpdatedAt:e.number().nullable(),syncBranchListStartedAt:e.number().nullable(),syncBranchListFinishedAt:e.number().nullable()}),e.object({id:_g,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:gg,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string(),workspaceId:V,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()}),e.object({id:_g.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),vcsIntegrationId:gg.optional(),owner:e.string().optional(),name:e.string().optional(),branch:e.string().optional(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number().optional(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string().optional(),workspaceId:V.optional(),description:e.string().optional(),url:e.string().optional(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()});var vg=e.string();e.object({id:vg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:_g,vcsIntegrationId:gg,workspaceId:V,name:e.string(),commitSha:e.string()}),e.object({id:vg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:_g,vcsIntegrationId:gg,workspaceId:V,name:e.string(),commitSha:e.string()}),e.object({id:vg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsRepoId:_g.optional(),vcsIntegrationId:gg.optional(),workspaceId:V.optional(),name:e.string().optional(),commitSha:e.string().optional()});var yg=e.enum([`SUGGESTED`,`APPROVED`,`REJECTED`]);e.object({noteIdA:K,noteIdB:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:yg,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({noteIdA:K,noteIdB:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:yg,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({noteIdA:K.optional(),noteIdB:K.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:yg.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var bg=e.string();e.object({id:bg,workspaceId:V,projectId:W,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:bg,workspaceId:V,projectId:W,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:bg.optional(),workspaceId:V.optional(),projectId:W.optional(),key:e.string().optional(),name:e.string().optional(),toolList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional()});var q=e.string();e.object({id:q,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:W,surfaceId:bg,ownedByPersonId:U}),e.object({id:q,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:W,surfaceId:bg,ownedByPersonId:U}),e.object({id:q.optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),projectId:W.optional(),surfaceId:bg.optional(),ownedByPersonId:U.optional()});var xg=e.enum([`PENDING`,`IN_PROGRESS`,`READY`,`ERROR`,`CANCELED`]),Sg=e.string();e.object({id:Sg,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:q,parentSpriteBuildId:Sg.nullable(),prompt:e.string(),artifactUrl:e.string().nullable(),sourceUrl:e.string().nullable(),status:xg,startedAt:e.number().nullable(),stoppedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().nullable(),publishedAt:e.number().nullable(),createdByPersonId:U,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().nullable()}),e.object({id:Sg,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:q,parentSpriteBuildId:Sg.optional().nullable(),prompt:e.string(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:xg,startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:U,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().optional().nullable()}),e.object({id:Sg.optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),spriteId:q.optional(),parentSpriteBuildId:Sg.optional().nullable(),prompt:e.string().optional(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:xg.optional(),startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()).optional(),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:U.optional(),agentProvider:e.string().optional(),agentModel:e.string().optional(),agentInputTokens:e.number().optional(),agentOutputTokens:e.number().optional(),agentCacheReadTokens:e.number().optional(),agentCacheWriteTokens:e.number().optional(),agentEstimatedCostUsd:e.number().optional(),cancelRequestedAt:e.number().optional().nullable()});var Cg=e.string();e.object({id:Cg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).nullable()}),e.object({id:Cg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).optional().nullable()}),e.object({id:Cg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),snapshot:e.record(e.string(),e.json()).optional().nullable()});var wg=e.enum(`DOCUMENT_COMMENT_CREATE.DOCUMENT_COMMENT_DELETE.DOCUMENT_COMMENT_RESOLVE.DOCUMENT_COMMENT_UPDATE.DOCUMENT_CREATE.DOCUMENT_DELETE.DOCUMENT_PERSON_MENTION.DOCUMENT_UPDATE_BLOCK_CONTENT.DOCUMENT_UPDATE_STATUS.DOCUMENT_UPDATE_TITLE.NOTE_COMMENT_CREATE.NOTE_COMMENT_DELETE.NOTE_COMMENT_RESOLVE.NOTE_COMMENT_UPDATE.NOTE_CREATE.NOTE_PERSON_MENTION.NOTE_UPDATE_CONTENT.NOTE_UPDATE_LABEL.NOTE_UPDATE_PERSON.NOTE_UPDATE_REFERENCE.NOTE_UPDATE_STATUS.NOTE_UPDATE_TITLE.SEQUENCE_DOCUMENT_DELETE.SEQUENCE_DOCUMENT_INSERT.SEQUENCE_DOCUMENT_STATUS_IN.SEQUENCE_DOCUMENT_STATUS_OUT.SEQUENCE_DOCUMENT_UPDATE_ORDER.SEQUENCE_COMMENT_CREATE.SEQUENCE_COMMENT_DELETE.SEQUENCE_COMMENT_RESOLVE.SEQUENCE_COMMENT_UPDATE.SEQUENCE_PERSON_MENTION.SPRITE_CREATE.SPRITE_COMMENT_CREATE`.split(`.`)),Tg=e.enum([`CANCELED`,`IDEA`,`DEVELOPMENT`,`RELEASED`,`DRAFT`,`ARCHIVED`]),J=e.string();e.object({id:J,title:e.string(),status:Tg,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:V,vcsTagList:e.string().array(),archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().nullable(),ownedByPersonId:U}),e.object({id:J,title:e.string(),status:Tg,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:V,vcsTagList:e.string().array(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().optional().nullable(),ownedByPersonId:U}),e.object({id:J.optional(),title:e.string().optional(),status:Tg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),publicId:e.number().optional(),createdByUserId:G.optional(),workspaceId:V.optional(),vcsTagList:e.string().array().optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),releasedAt:e.number().optional().nullable(),ownedByPersonId:U.optional()});var Eg=e.enum([`USER`,`STATUS`,`WISH`]),Dg=e.enum([`NONE`,`STATUS`]),Og=e.string();e.object({id:Og,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:V,publicId:e.string(),type:Eg,status:Tg.nullable().nullable(),version:e.number(),icon:e.string(),pinned:e.number().nullable(),groupBy:Dg,ownedByPersonId:U.nullable()}),e.object({id:Og,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:V,publicId:e.string(),type:Eg,status:Tg.nullable().optional().nullable(),version:e.number(),icon:e.string(),pinned:e.number().optional().nullable(),groupBy:Dg,ownedByPersonId:U.optional().nullable()}),e.object({id:Og.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),workspaceId:V.optional(),publicId:e.string().optional(),type:Eg.optional(),status:Tg.nullable().optional().nullable(),version:e.number().optional(),icon:e.string().optional(),pinned:e.number().optional().nullable(),groupBy:Dg.optional(),ownedByPersonId:U.optional().nullable()});var kg=e.string();e.object({id:kg,workspaceId:V,type:wg,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:J.nullable(),noteId:K.nullable(),sequenceId:Og.nullable(),spriteId:q.nullable(),actionedByPersonId:U}),e.object({id:kg,workspaceId:V,type:wg,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:J.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Og.optional().nullable(),spriteId:q.optional().nullable(),actionedByPersonId:U}),e.object({id:kg.optional(),workspaceId:V.optional(),type:wg.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),documentId:J.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Og.optional().nullable(),spriteId:q.optional().nullable(),actionedByPersonId:U.optional()});var Ag=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`SPRITE`]),jg=e.enum([`TEXT`,`DRAWING`]),Mg=e.enum([`UNKNOWN`]),Ng=e.string();e.object({id:Ng,sortOrder:e.number(),documentId:J,createdAt:e.number(),updatedAt:e.number(),type:jg,lockedAt:e.number().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:V,archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),flagList:Mg.array(),title:e.string(),contentId:H.nullable(),canvasId:Cg.nullable(),lastModifiedByUserId:G}),e.object({id:Ng,sortOrder:e.number(),documentId:J,createdAt:e.number(),updatedAt:e.number(),type:jg,lockedAt:e.number().optional().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:V,archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Mg.array(),title:e.string(),contentId:H.optional().nullable(),canvasId:Cg.optional().nullable(),lastModifiedByUserId:G}),e.object({id:Ng.optional(),sortOrder:e.number().optional(),documentId:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),type:jg.optional(),lockedAt:e.number().optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),workspaceId:V.optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Mg.array().optional(),title:e.string().optional(),contentId:H.optional().nullable(),canvasId:Cg.optional().nullable(),lastModifiedByUserId:G.optional()});var Pg=e.string();e.object({id:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:H,completedAt:e.number().nullable(),createdByPersonId:U}),e.object({id:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:H,completedAt:e.number().optional().nullable(),createdByPersonId:U}),e.object({id:Pg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),title:e.string().optional(),contentId:H.optional(),completedAt:e.number().optional().nullable(),createdByPersonId:U.optional()});var Fg=e.string();e.object({id:Fg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().nullable(),resolvedByUserId:G.nullable(),documentId:J.nullable(),blockId:Ng.nullable(),sequenceId:Og.nullable(),eventId:kg.nullable(),noteId:K.nullable(),spriteId:q.nullable(),taskId:Pg.nullable()}),e.object({id:Fg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:J.optional().nullable(),blockId:Ng.optional().nullable(),sequenceId:Og.optional().nullable(),eventId:kg.optional().nullable(),noteId:K.optional().nullable(),spriteId:q.optional().nullable(),taskId:Pg.optional().nullable()}),e.object({id:Fg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),openedAt:e.number().optional(),openedByUserId:G.optional(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:J.optional().nullable(),blockId:Ng.optional().nullable(),sequenceId:Og.optional().nullable(),eventId:kg.optional().nullable(),noteId:K.optional().nullable(),spriteId:q.optional().nullable(),taskId:Pg.optional().nullable()});var Ig=e.string();e.object({id:Ig,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:V,version:e.number(),contentId:H,commentThreadId:Fg}),e.object({id:Ig,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:V,version:e.number(),contentId:H,commentThreadId:Fg}),e.object({id:Ig.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),postedAt:e.number().optional(),userId:G.optional(),workspaceId:V.optional(),version:e.number().optional(),contentId:H.optional(),commentThreadId:Fg.optional()});var Lg=e.string();e.object({id:Lg,workspaceId:V,userId:G,eventId:kg,readAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ag,documentId:J.nullable(),noteId:K.nullable(),sequenceId:Og.nullable(),commentId:Ig.nullable(),spriteId:q.nullable(),commentThreadId:Fg.nullable()}),e.object({id:Lg,workspaceId:V,userId:G,eventId:kg,readAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ag,documentId:J.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Og.optional().nullable(),commentId:Ig.optional().nullable(),spriteId:q.optional().nullable(),commentThreadId:Fg.optional().nullable()}),e.object({id:Lg.optional(),workspaceId:V.optional(),userId:G.optional(),eventId:kg.optional(),readAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Ag.optional(),documentId:J.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Og.optional().nullable(),commentId:Ig.optional().nullable(),spriteId:q.optional().nullable(),commentThreadId:Fg.optional().nullable()});var Rg=e.string();e.object({id:Rg,userId:G,contentId:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Rg,userId:G,contentId:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Rg.optional(),userId:G.optional(),contentId:H.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),state:e.instanceof(Uint8Array).optional()});var zg=e.string();e.object({id:zg,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:zg,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:zg.optional(),createdAt:e.number().optional(),record:e.record(e.string(),e.json()).optional()}),e.object({spriteId:q,projectAccountId:og,workspaceId:V,projectId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:q,projectAccountId:og,workspaceId:V,projectId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:q.optional(),projectAccountId:og.optional(),workspaceId:V.optional(),projectId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({projectAccountId:og,projectUserId:ag,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W}),e.object({projectAccountId:og,projectUserId:ag,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:W}),e.object({projectAccountId:og.optional(),projectUserId:ag.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:W.optional()});var Bg=e.string();e.object({id:Bg,workspaceId:V,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Ig.nullable(),noteId:K.nullable()}),e.object({id:Bg,workspaceId:V,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Ig.optional().nullable(),noteId:K.optional().nullable()}),e.object({id:Bg.optional(),workspaceId:V.optional(),userId:G.optional(),emoji:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),commentId:Ig.optional().nullable(),noteId:K.optional().nullable()}),e.object({taskId:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Pg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional()});var Vg=e.string();e.object({id:Vg,workspaceId:V,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Vg,workspaceId:V,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Vg.optional(),workspaceId:V.optional(),token:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Hg=e.string();e.object({id:Hg,workspaceId:V,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Hg,workspaceId:V,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Hg.optional(),workspaceId:V.optional(),userId:G.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var Ug=e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`,`AGENT_USAGE`]),Wg=e.string();e.object({id:Wg,workspaceId:V,spriteBuildId:Sg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ug,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Wg,workspaceId:V,spriteBuildId:Sg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ug,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Wg.optional(),workspaceId:V.optional(),spriteBuildId:Sg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Ug.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional()}),e.object({blockId:Ng,userId:G,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:Ng,userId:G,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:Ng.optional(),userId:G.optional(),workspaceId:V.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Gg=e.enum([`NOTE`,`DOCUMENT`]),Kg=e.string();e.object({id:Kg,workspaceId:V,userId:G,type:Gg,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Kg,workspaceId:V,userId:G,type:Gg,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Kg.optional(),workspaceId:V.optional(),userId:G.optional(),type:Gg.optional(),matchAll:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var qg=e.enum([`ADMIN`,`GUEST`,`ARCHIVED`,`DEMO`]);e.object({workspaceId:V,userId:G,createdAt:e.number(),updatedAt:e.number(),role:qg,version:e.number(),personId:U,lastReadNotificationsAt:e.number().nullable()}),e.object({workspaceId:V,userId:G,createdAt:e.number(),updatedAt:e.number(),role:qg,version:e.number(),personId:U,lastReadNotificationsAt:e.number().optional().nullable()}),e.object({workspaceId:V.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),role:qg.optional(),version:e.number().optional(),personId:U.optional(),lastReadNotificationsAt:e.number().optional().nullable()});var Jg=e.string();e.object({id:Jg,workspaceId:V,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:wg.array(),createdByPersonId:U,createdAt:e.number(),updatedAt:e.number()}),e.object({id:Jg,workspaceId:V,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:wg.array(),createdByPersonId:U,createdAt:e.number(),updatedAt:e.number()}),e.object({id:Jg.optional(),workspaceId:V.optional(),name:e.string().optional(),url:e.string().optional(),secret:e.string().optional(),eventTypeList:wg.array().optional(),createdByPersonId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Yg=e.enum([`FEATURE`,`FIX`,`RELEASE`,`CHORE`]),Xg=e.string();e.object({id:Xg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:gg,workspaceId:V,name:e.string(),email:e.string(),avatarUrl:e.string().nullable()}),e.object({id:Xg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:gg,workspaceId:V,name:e.string(),email:e.string(),avatarUrl:e.string().optional().nullable()}),e.object({id:Xg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsIntegrationId:gg.optional(),workspaceId:V.optional(),name:e.string().optional(),email:e.string().optional(),avatarUrl:e.string().optional().nullable()});var Zg=e.string();e.object({id:Zg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:_g,url:e.string(),message:e.string(),parentShaList:e.string().array().nullable(),version:e.number(),authoredAt:e.number().nullable(),committedAt:e.number().nullable(),vcsIntegrationId:gg,workspaceId:V,type:Yg,subject:e.string(),scope:e.string().nullable(),authorId:Xg.nullable(),committerId:Xg.nullable()}),e.object({id:Zg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:_g,url:e.string(),message:e.string(),parentShaList:e.string().array().optional().nullable(),version:e.number(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:gg,workspaceId:V,type:Yg,subject:e.string(),scope:e.string().optional().nullable(),authorId:Xg.optional().nullable(),committerId:Xg.optional().nullable()}),e.object({id:Zg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sha:e.string().optional(),vcsRepoId:_g.optional(),url:e.string().optional(),message:e.string().optional(),parentShaList:e.string().array().optional().nullable(),version:e.number().optional(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:gg.optional(),workspaceId:V.optional(),type:Yg.optional(),subject:e.string().optional(),scope:e.string().optional().nullable(),authorId:Xg.optional().nullable(),committerId:Xg.optional().nullable()}),e.object({vcsCommitId:Zg,documentId:J,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:gg,workspaceId:V}),e.object({vcsCommitId:Zg,documentId:J,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:gg,workspaceId:V}),e.object({vcsCommitId:Zg.optional(),documentId:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional(),vcsIntegrationId:gg.optional(),workspaceId:V.optional()}),e.object({documentId:J,userId:G,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:J,userId:G,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:J.optional(),userId:G.optional(),workspaceId:V.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({personId:U,taskId:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:U,taskId:Pg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:U.optional(),taskId:Pg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional(),date:e.iso.date().optional()});var Qg=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`NEW_NOTE`,`SPRITE`,`COMMENT_THREAD`]),$g=e.string();e.object({id:$g,workspaceId:V,userId:G,type:Qg,noteId:K.nullable(),documentId:J.nullable(),sequenceId:Og.nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:q.nullable(),commentThreadId:Fg.nullable()}),e.object({id:$g,workspaceId:V,userId:G,type:Qg,noteId:K.optional().nullable(),documentId:J.optional().nullable(),sequenceId:Og.optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:q.optional().nullable(),commentThreadId:Fg.optional().nullable()}),e.object({id:$g.optional(),workspaceId:V.optional(),userId:G.optional(),type:Qg.optional(),noteId:K.optional().nullable(),documentId:J.optional().nullable(),sequenceId:Og.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),spriteId:q.optional().nullable(),commentThreadId:Fg.optional().nullable()});var e_=e.string();e.object({id:e_,workspaceId:V,email:Kh,lastSentAt:e.number().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().nullable()}),e.object({id:e_,workspaceId:V,email:Kh,lastSentAt:e.number().optional().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().optional().nullable()}),e.object({id:e_.optional(),workspaceId:V.optional(),email:Kh.optional(),lastSentAt:e.number().optional().nullable(),invitedByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),token:e.string().optional().nullable()});var t_=e.string();e.object({id:t_,workspaceId:V,projectId:W,spriteId:q,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:t_,workspaceId:V,projectId:W,spriteId:q,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:t_.optional(),workspaceId:V.optional(),projectId:W.optional(),spriteId:q.optional(),messageList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var n_=e.string();e.object({id:n_,clientGroupId:pg,lastMutationId:e.number(),version:e.number()}),e.object({id:n_,clientGroupId:pg,lastMutationId:e.number(),version:e.number()}),e.object({id:n_.optional(),clientGroupId:pg.optional(),lastMutationId:e.number().optional(),version:e.number().optional()}),e.object({documentIdA:J,documentIdB:J,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:yg,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentIdA:J,documentIdB:J,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:yg,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentIdA:J.optional(),documentIdB:J.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:yg.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var r_=e.string();e.object({id:r_,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().nullable()}),e.object({id:r_,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().optional().nullable()}),e.object({id:r_.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),twoFactorVerifiedAt:e.number().optional().nullable()});var i_=e.string();e.object({id:i_,workspaceId:V,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:H,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:i_,workspaceId:V,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:H,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:i_.optional(),workspaceId:V.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),contentHash:e.instanceof(Uint8Array).optional(),contentId:H.optional(),offset:e.number().optional(),size:e.number().optional(),tokenCount:e.number().optional(),plaintext:e.string().optional()}),e.object({llmProviderId:Xh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:Xh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:Xh.optional(),encryptedValue:e.string().optional(),plaintextSuffix:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var a_=e.enum([`IS_IN`,`IS_NOT_IN`]),o_=e.string();e.object({id:o_,filterId:Kg,workspaceId:V,field:e.string(),comparator:a_,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:o_,filterId:Kg,workspaceId:V,field:e.string(),comparator:a_,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:o_.optional(),filterId:Kg.optional(),workspaceId:V.optional(),field:e.string().optional(),comparator:a_.optional(),value:e.record(e.string(),e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({spriteIdA:q,spriteIdB:q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:yg,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({spriteIdA:q,spriteIdB:q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:yg,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({spriteIdA:q.optional(),spriteIdB:q.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:yg.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({taskId:Pg,labelId:ng,labelType:tg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Pg,labelId:ng,labelType:tg,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Pg.optional(),labelId:ng.optional(),labelType:tg.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var s_=e.enum([`SIGNUP_REQUEST`,`SIGNUP_ATTEMPT_TOKEN`,`SIGNUP_SUCCESS`,`LOGIN_VIA_GOOGLE_SUCCESS`,`LOGIN_VIA_PASSWORD_ATTEMPT`,`LOGIN_VIA_PASSWORD_SUCCESS`,`RESET_PASSWORD_REQUEST`,`RESET_PASSWORD_ATTEMPT_TOKEN`,`RESET_PASSWORD_SUCCESS`,`PASSWORD_CHANGE`,`TOTP_ENABLE`,`TOTP_DISABLE`,`TOTP_VERIFY_ATTEMPT`,`TOTP_VERIFY_SUCCESS`,`RECOVERY_CODE_REGENERATED`,`RECOVERY_CODE_ATTEMPT`,`RECOVERY_CODE_SUCCESS`,`VALIDATE_INVITE_LINK_ATTEMPT`,`VALIDATE_INVITE_LINK_SUCCESS`,`VALIDATE_INVITATION_ATTEMPT`,`VALIDATE_INVITATION_SUCCESS`]),c_=e.string();e.object({id:c_,type:s_,userId:G.nullable(),email:Kh.nullable().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:c_,type:s_,userId:G.optional().nullable(),email:Kh.nullable().optional().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:c_.optional(),type:s_.optional(),userId:G.optional().nullable(),email:Kh.nullable().optional().nullable(),clientAddress:e.string().optional(),userAgent:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var l_=Kh;e.object({workspaceId:V,personId:U,email:l_,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:V,personId:U,email:l_,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:V.optional(),personId:U.optional(),email:l_.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),isPrimary:e.boolean().optional()}),e.object({documentId:J,noteId:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:yg,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentId:J,noteId:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:yg,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentId:J.optional(),noteId:K.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:yg.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var u_=e.string();e.object({id:u_,workspaceId:V,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Hh.array()}),e.object({id:u_,workspaceId:V,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Hh.array()}),e.object({id:u_.optional(),workspaceId:V.optional(),name:e.string().optional(),hash:e.instanceof(Uint8Array).optional(),createdByUserId:G.optional(),lastUsedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),scopeList:Hh.array().optional()});var d_=e.enum([`MXBAI_EMBED_LARGE_V1`,`TEST`,`STELLA_EN_400M_V5`,`GTE_MULTILINGUAL_BASE`]),f_=e.enum([`DIM_1024`,`DIM_768`]),p_=e.string();e.object({id:p_,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:d_,dimension:f_,vector1024:e.array(e.number()).nullable(),vector768:e.array(e.number()).nullable()}),e.object({id:p_,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:d_,dimension:f_,vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()}),e.object({id:p_.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),hash:e.instanceof(Uint8Array).optional(),model:d_.optional(),dimension:f_.optional(),vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()});var m_=e.string(),h_=e.string(),g_=e.string();e.object({tableName:m_,idA:h_,idB:g_,workspaceId:V,deletedAt:e.number(),version:e.number()}),e.object({tableName:m_,idA:h_,idB:g_,workspaceId:V,deletedAt:e.number(),version:e.number()}),e.object({tableName:m_.optional(),idA:h_.optional(),idB:g_.optional(),workspaceId:V.optional(),deletedAt:e.number().optional(),version:e.number().optional()}),e.object({sequenceId:Og,documentId:J,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:V}),e.object({sequenceId:Og,documentId:J,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:V}),e.object({sequenceId:Og.optional(),documentId:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sortOrder:e.number().optional(),version:e.number().optional(),workspaceId:V.optional()});var __=e.enum([`SPRITE_BUILD`]);e.object({useCase:__,llmModelId:Qh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:__,llmModelId:Qh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:__.optional(),llmModelId:Qh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()}),e.object({spriteId:q,workspaceId:V,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:q,workspaceId:V,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:q.optional(),workspaceId:V.optional(),hash:e.instanceof(Uint8Array).optional(),version:e.number().optional(),updatedAt:e.number().optional(),plaintext:e.string().optional()});var v_=e.enum([`SIGNUP`,`PASSWORD_RESET`]),y_=e.string();e.object({id:y_,type:v_,userId:G.nullable(),email:Kh,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().nullable(),retryCount:e.number()}),e.object({id:y_,type:v_,userId:G.optional().nullable(),email:Kh,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().optional().nullable(),retryCount:e.number()}),e.object({id:y_.optional(),type:v_.optional(),userId:G.optional().nullable(),email:Kh.optional(),tokenHash:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),verifiedAt:e.number().optional().nullable(),retryCount:e.number().optional()}),e.object({id:U,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),avatarAssetId:$h.nullable(),description:e.string(),emailList:Kh.array()}),e.enum([`PENDING`,`CREATED`,`FINISHED`,`TERMINATED`]);var b_=e.number();e.object({id:b_,jobQueueId:e.number().nullable(),taskId:e.number(),payload:e.unknown(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable(),isAvailable:e.boolean()}),e.object({id:b_.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean()}),e.object({id:b_.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number().optional(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean().optional()});var x_=e.number();e.object({id:x_,ts:e.date(),breaking:e.boolean()}),e.object({id:x_,ts:e.date().optional(),breaking:e.boolean().optional()}),e.object({id:x_.optional(),ts:e.date().optional(),breaking:e.boolean().optional()});var S_=e.enum([`IN_PROGRESS`,`SUCCESS`,`ERROR`]),C_=e.string();e.object({id:C_,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().nullable(),queueName:e.string().nullable(),workerId:e.string(),status:S_,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:C_,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string(),status:S_,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:C_.optional(),graphileWorkerJobId:e.string().optional(),serviceName:e.string().optional(),machineId:e.string().optional(),attempt:e.number().optional(),taskIdentifier:e.string().optional(),payload:e.record(e.string(),e.json()).optional(),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string().optional(),status:S_.optional(),runnableAt:e.number().optional(),startedAt:e.number().optional(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var w_=e.number();e.object({id:w_,identifier:e.string()}),e.object({id:w_.optional(),identifier:e.string()}),e.object({id:w_.optional(),identifier:e.string().optional()});var T_=e.enum([`MISSING_HEARTBEAT`,`STALE_HEARTBEAT`,`STOPPED_WITH_LOCKS`,`ALREADY_RECOVERED_WITH_LOCKS`]),E_=e.string();e.object({workerPoolId:E_,serviceName:e.string(),machineId:e.string(),startedAt:e.number().nullable(),lastHeartbeatAt:e.number().nullable(),stoppedAt:e.number().nullable(),recoveredAt:e.number().nullable(),recoveryReason:T_.nullable().nullable(),recoveredJobCount:e.number().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:E_,serviceName:e.string(),machineId:e.string(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:T_.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:E_.optional(),serviceName:e.string().optional(),machineId:e.string().optional(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:T_.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var D_=e.string();e.object({identifier:D_,knownSince:e.date(),lastExecution:e.date().nullable()}),e.object({identifier:D_,knownSince:e.date(),lastExecution:e.date().optional().nullable()}),e.object({identifier:D_.optional(),knownSince:e.date().optional(),lastExecution:e.date().optional().nullable()});var O_=e.number();e.object({id:O_,queueName:e.string(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),isAvailable:e.boolean()}),e.object({id:O_.optional(),queueName:e.string(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean()}),e.object({id:O_.optional(),queueName:e.string().optional(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean().optional()}),e.object({id:b_,queueName:e.string(),taskIdentifier:e.string(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable()}),e.object({identifier:e.string().nullable(),payload:e.unknown().nullable(),queueName:e.string().nullable(),runAt:e.date().nullable(),maxAttempts:e.number().nullable(),jobKey:e.string().nullable(),priority:e.number().nullable(),flags:e.string().nullable()});var k_=e=>r.object({token:r.string().check(r.minLength(1),r.refine(e=>e.trim()!==``,{message:`Token must not be empty or whitespace`})),expiresAt:r.number().check(r.int(),r.gt(e)),personId:U}),A_=(e,t=Date.now())=>{let n=k_(t).safeParse(e);return n.success?n.data:Error(r.prettifyError(n.error))},j_=class extends Error{status;constructor(e,t){super(t),this.name=`GatewayHttpError`,this.status=e}},M_=r.object({message:r.string()}),N_=async e=>{let t=`Gateway request failed with status ${e.status}`;try{let n=await e.json(),r=M_.safeParse(n);r.success&&(t=r.data.message)}catch{}return new j_(e.status,t)},P_=async e=>{try{return await e.json()}catch{return Error(`Gateway returned an invalid JSON response`)}},F_=async e=>{let{baseUrl:n,projectId:r,userToken:i}=e,a=await t(()=>fetch(T({baseUrl:n,path:`/api/v1/project/${encodeURIComponent(r)}/session-token`}),{method:`POST`,headers:{authorization:`Bearer ${i}`}}));if(a instanceof Error)return a;if(!a.ok)return N_(a);let o=await P_(a);return o instanceof Error?o:A_(o)},I_=r.object({token:r.string(),expiresAt:r.number(),personId:r.string()}),L_=e=>I_.safeParse(e).success,R_=1e3,z_=3e4,B_=6e4,V_=e=>Math.min(R_*2**Math.max(e-1,0),z_),H_=(e,t)=>t>=e.expiresAt-B_,U_=e=>{let{fetchSessionToken:t,now:n=Date.now}=e,r,i,a=0,o=0,s=0,c=()=>{r=void 0,i=void 0,a=0,o=0,s+=1},l=e=>{r&&(e===void 0||r.token===e)&&(r=void 0)},u=()=>{let e=o-n();if(e>0)return Promise.reject(Error(`fetchSessionToken is rate limited after repeated failures; retry in ${e}ms`));let c=s;return i=t().then(e=>{if(c!==s)throw Error(`Session token fetch was reset before it completed`);return r=e,a=0,o=0,e}).catch(e=>{throw c===s&&(r=void 0,a+=1,o=n()+V_(a)),e}).finally(()=>{c===s&&(i=void 0)}),i};return{getSessionToken:()=>r&&!H_(r,n())?Promise.resolve(r):i===void 0?u():i,invalidateToken:l,reset:c}},W_=e=>{let{baseUrl:t,projectId:n,fetchUserToken:r,exchangeIdentityTokenForSessionToken:i=F_}=e,a=U_({fetchSessionToken:async()=>{let e=await r();if(typeof e==`string`){if(e.trim()===``)throw Error(`fetchUserToken must return a non-empty string`);let r=await i({baseUrl:t,projectId:n,userToken:e});if(r instanceof Error)throw r;return r}if(L_(e)){let t=A_(e);if(t instanceof Error)throw t;return t}throw Error(`fetchUserToken must return a non-empty string`)}});return{getSessionToken:()=>a.getSessionToken(),invalidateToken:e=>{a.invalidateToken(e)},destroy:async()=>{a.reset()}}},G_=Symbol(`rough.client.runtime`),K_=e=>{let t=e?.[G_];if(!t)throw new wt;return t},q_=e=>{let{fetchUserToken:t,projectId:n}=e,r=e.baseUrl??`https://gateway.rough.app`,i=e.mediaBaseUrl??`https://cdn.rough.app`;if(typeof n!=`string`||n.trim()===``)throw TypeError(`createRoughClient: "projectId" is required`);if(typeof t!=`function`)throw TypeError(`createRoughClient: "fetchUserToken" is required`);try{new URL(i)}catch{throw TypeError(`createRoughClient: "mediaBaseUrl" must be a URL`)}let a=Symbol(`rough.client:${n}`),o=new AbortController,s=`starting`,c,l=W_({baseUrl:r,fetchUserToken:t,projectId:n}),u=Xe(),d=It(),f=Ft({getRuntime:()=>g}),p=Lh({auth:l,baseUrl:r,clientId:a,projectId:n,signal:o.signal,store:u}),m=()=>{if(s===`destroying`||s===`destroyed`)throw new bt},h=(async()=>{await p.start();let e=p.peek();if(!e||o.signal.aborted)return;let t=await ae({projectId:n,replicache:e});t instanceof Error&&!o.signal.aborted&&console.error(`[Rough] Failed to ping project`,t)})().then(()=>{s===`starting`&&(s=`active`)},e=>{throw s===`starting`&&(s=`failed`),Tt(e)});h.catch(()=>{});let g={clientId:a,baseUrl:r,mediaBaseUrl:i,projectId:n,auth:l,store:u,surfaces:f,operations:d,getState:()=>s,assertUsable:m,whenReady:()=>h,getReplicache:async()=>{m(),await h,m();let e=p.peek();if(!e)throw Error(`Replicache is not available in this environment. Rough clients only open a local database in the browser.`);return e},buildUrl:e=>T({baseUrl:r,...e})},_=async()=>{let e=[],t=async(t,n)=>{try{await n()}catch(n){let r=Tt(n);r.message=`${t}: ${r.message}`,e.push(r)}};try{await t(`operations`,()=>d.closeAll()),await t(`surfaces`,()=>f.destroy()),await Promise.allSettled([h]),await t(`replicache`,()=>p.destroy()),await Promise.all([t(`store`,()=>u.destroy()),t(`auth`,()=>l.destroy())])}finally{p.releaseIdentity(),s=`destroyed`}if(e.length>0)throw new Ct({errors:e})},v={get projectId(){return n},destroy:()=>c||(s=`destroying`,p.markDestroying(),o.abort(new bt),c=_(),c)};return Object.defineProperty(v,G_,{value:g,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(v)},J_=async e=>{await K_(e.client).whenReady()},Y_=e=>e.filter(e=>e.publishedAt!==null).toSorted((e,t)=>{let n=(t.publishedAt??0)-(e.publishedAt??0);return n===0?t.id.localeCompare(e.id):n}).at(0)??null,X_=e=>{let{sprite:t,spriteBuildList:n}=e;return{id:t.id,name:t.name,ownedByPersonId:t.ownedByPersonId,publishedSpriteBuildId:Y_(n)?.id??null}},Z_=(e,t)=>{let n=new Map;for(let t of e.spriteBuild.asList.value){let e=n.get(t.spriteId);e||(e=[],n.set(t.spriteId,e)),e.push(t)}let r=[];for(let i of e.sprite.asList.value){if(i.surfaceId!==t)continue;let e=X_({sprite:i,spriteBuildList:n.get(i.id)??[]});e.publishedSpriteBuildId&&r.push(e)}return r.toSorted((e,t)=>t.id.localeCompare(e.id))},Q_=e=>{let{client:t,onError:n,onFeatures:r,signal:i}=e,a=K_(t);a.assertUsable();let o=Nt(e.surface),s=a.surfaces.acquire({surface:o}),c=new AbortController,l,u,d,f=(async()=>{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Ot(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)return;let t=e.resolution.id,n=()=>{c.signal.aborted||r(Z_(a.store,t))};l=a.store.subscribe(n),n()})();f.catch(e=>{c.signal.aborted||n?.(Tt(e))});let p=()=>(d??=(async()=>{c.abort(),l?.(),l=void 0,s.release(),u?.(),u=void 0,await Promise.allSettled([f])})(),d);return u=a.operations.register({label:`getRoughFeatures(${o.key})`,close:p}),i&&(i.aborted?p():i.addEventListener(`abort`,()=>void p(),{once:!0})),{get ready(){return f},unsubscribe:p}},$_={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},ev=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},tv=Symbol(`lucide-context`),nv=()=>i(tv),rv=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`,`name`,`color`,`size`,`strokeWidth`,`absoluteStrokeWidth`,`iconNode`,`children`]),iv=u.from_svg(`<svg><!><!></svg>`);function av(e,t){u.push(t,!0);let n=nv()??{},r=u.prop(t,`name`,7),i=u.prop(t,`color`,23,()=>n.color??`currentColor`),a=u.prop(t,`size`,23,()=>n.size??24),o=u.prop(t,`strokeWidth`,23,()=>n.strokeWidth??2),s=u.prop(t,`absoluteStrokeWidth`,23,()=>n.absoluteStrokeWidth??!1),c=u.prop(t,`iconNode`,23,()=>[]),l=u.prop(t,`children`,7),d=u.rest_props(t,rv),f=u.derived(()=>s()?Number(o())*24/Number(a()):o());var p={get name(){return r()},set name(e){r(e),u.flush()},get color(){return i()},set color(e=n.color??`currentColor`){i(e),u.flush()},get size(){return a()},set size(e=n.size??24){a(e),u.flush()},get strokeWidth(){return o()},set strokeWidth(e=n.strokeWidth??2){o(e),u.flush()},get absoluteStrokeWidth(){return s()},set absoluteStrokeWidth(e=n.absoluteStrokeWidth??!1){s(e),u.flush()},get iconNode(){return c()},set iconNode(e=[]){c(e),u.flush()},get children(){return l()},set children(e){l(e),u.flush()}},m=iv();u.attribute_effect(m,e=>({...$_,...e,...d,width:a(),height:a(),stroke:i(),"stroke-width":u.get(f),class:[`lucide-icon lucide`,n.class,r()&&`lucide-${r()}`,t.class]}),[()=>!l()&&!ev(d)&&{"aria-hidden":`true`}]);var h=u.child(m);u.each(h,17,c,u.index,(e,t)=>{var n=u.derived(()=>u.to_array(u.get(t),2));let r=()=>u.get(n)[0],i=()=>u.get(n)[1];var a=u.comment(),o=u.first_child(a);u.element(o,r,!0,(e,t)=>{u.attribute_effect(e,()=>({...i()}))}),u.append(e,a)});var g=u.sibling(h);return u.snippet(g,()=>l()??u.noop),u.reset(m),u.append(e,m),u.pop(p)}u.create_custom_element(av,{name:{},color:{},size:{},strokeWidth:{},absoluteStrokeWidth:{},iconNode:{},children:{}},[],[],{mode:`open`});var ov=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function sv(e,t){let n=u.rest_props(t,ov),r=[[`path`,{d:`m5 12 7-7 7 7`}],[`path`,{d:`M12 19V5`}]];av(e,u.spread_props({name:`arrow-up`},()=>n,{get iconNode(){return r}}))}u.create_custom_element(sv,{},[],[],{mode:`open`});var cv=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function lv(e,t){let n=u.rest_props(t,cv),r=[[`path`,{d:`M5 12h14`}],[`path`,{d:`M12 5v14`}]];av(e,u.spread_props({name:`plus`},()=>n,{get iconNode(){return r}}))}u.create_custom_element(lv,{},[],[],{mode:`open`});var uv=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function dv(e,t){let n=u.rest_props(t,uv),r=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}]];av(e,u.spread_props({name:`square`},()=>n,{get iconNode(){return r}}))}u.create_custom_element(dv,{},[],[],{mode:`open`});var fv=(e,t)=>{let{mediaBaseUrl:n}=t;return new URL(e.storageKey,n).href},pv=e=>{let{url:t}=e,n=new URL(e.mediaBaseUrl),r=new URL(t,n);return r.origin===n.origin?/^\/cdn-cgi\/image\/[^/]+\/(?<storageKey>.*)$/.exec(r.pathname)?.groups?.storageKey||r.pathname.replace(/^\//,``):void 0},mv=`/cdn-cgi/image`,hv=e=>Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>`${e}=${t}`).join(`,`),gv=(e,t)=>{let{mediaBaseUrl:n,format:r,fit:i,width:a,height:o,quality:s}=t;if(e.startsWith(`https://api.dicebear.com/`)||e.startsWith(`/src/lib/test/sample-files/`))return e;let c=`${mv}/${hv({quality:s,format:r,width:a,height:o,fit:typeof a==`number`||typeof o==`number`?i:void 0})}/${pv({url:e,mediaBaseUrl:n})??e}`;return new URL(c,n).href},_v=class extends Error{missingFeature;constructor(e){super(vv(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function vv(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function yv(e){if(!e.body)throw new _v(`Response.body`);if(typeof e.body.getReader!=`function`)throw new _v(`Response.body.getReader`);return e.body.getReader()}function bv(){if(typeof globalThis.TextDecoder!=`function`)throw new _v(`TextDecoder`);return new globalThis.TextDecoder}function xv(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}function Sv(e){if(e instanceof Date)return Number.isNaN(e.getTime())?void 0:e;if(typeof e!=`string`)return;let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t}function Cv(e){let t=Sv(e.createdAt),n=e.parts.map(e=>{if(e.type!==`tool-result`)return e;let t=Sv(e.createdAt),{createdAt:n,...r}=e;return t?{...r,createdAt:t}:r}),{createdAt:r,...i}=e;return t?{...i,parts:n,createdAt:t}:{...i,parts:n}}function wv(e){return e.map(Cv)}var Tv=/^[a-z][a-z0-9-]{0,63}$/;function Ev(e){return typeof e==`string`&&Tv.test(e)}function Dv(e){if(typeof e!=`object`||!e||!(`error`in e))return!1;let t=e.error;return!(typeof t!=`object`||!t||!(`type`in t)||t.type!==`byok_missing`||!(`provider`in t)||typeof t.provider!=`string`||!Ev(t.provider)||!(`message`in t)||typeof t.message!=`string`)}var Ov=class extends Error{provider;constructor(e){super(`Missing ${e} API key`),this.name=`ByokMissingError`,this.provider=e}},kv=class extends Error{provider;reason;constructor(e,t){super(t===`locked`?`${e} key is locked`:`Missing ${e} API key`),this.name=`ByokBlockedError`,this.provider=e,this.reason=t}},Av=class extends Error{constructor(){super(`BYOK is enabled but no provider slug was resolved. Pass byokProvider or forwardedProps.provider.`),this.name=`ByokUnresolvedProviderError`}},jv=new WeakMap;function Mv(e){return jv.get(e)??ih(e)}var Nv=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},Pv=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},Fv=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},Iv=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function Lv(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function Rv(e){let t=Lv(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new Iv(t.maxAttempts);await zv(t.delayMs,n)}}}function zv(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function Bv(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Vv(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function Hv(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var Uv=`X-Run-Id`;function Wv(e){return e===void 0?{}:{[Uv]:e}}function Gv(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*Kv(e,t){try{let n=bv(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new Pv(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
26
|
+
`);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new Nv}finally{e.releaseLock()}}function qv(e){return th(e)}function Jv(e){let t=B(e)?.model;if(typeof t==`string`)return t;let n=`usage`in e?e.usage:void 0;if(Array.isArray(n)){let e=n[0]?.model;if(typeof e==`string`)return e}}async function*Yv(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=xv(o);if(e===`[DONE]`){yield{chunk:ap({type:wh.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,timestamp:Date.now()},{finishReason:`stop`,...i===void 0?{}:{model:i}})};return}let s=qv(JSON.parse(e));`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId);let c=Jv(s);c!==void 0&&(i=c);let l=a;a=void 0,yield{chunk:s,...l===void 0?{}:{id:l}}}}async function Xv(e){if(!e.ok){if(e.status===401){let t=await e.clone().json().catch(()=>null);if(Dv(t))throw new Ov(t.error.provider)}throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}}async function Zv(e,t,n,r,i){let a=await e(Gv(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Xv(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?wv(o.messages):[],activeRun:s,interrupts:c}}async function Qv(e,t,n,r,i){let a=await e(Gv(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});await Xv(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*$v(e,t,n){await Xv(e),yield*Yv(Kv(yv(e),t),n)}async function*ey(e,t){for await(let{chunk:n}of $v(e,t))yield n}function ty(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new Pv(e)}yield*r(o,a)}}async function*ny(e,t,n){let r=Rv(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof Nv||e instanceof Pv)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new Fv}return}}function ry(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[];function o(e,t){t&&jv.set(e,t);let n=a.shift();n?n(e):i.push(e)}async function s(e){let t=()=>i.length===0&&(a.length>0||e?.aborted);for(let n=0;n<16&&!e?.aborted;n++){if(t())return;await Promise.resolve()}let n=0;for(;!e?.aborted;)if(t()||(await new Promise(e=>setTimeout(e,0)),n++,a.length===0&&n>=32))return}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}})()},async send(t,n,r,i){let a=!1,c,l;try{let s=e.connect(t,n,r,i);for await(let e of s)`threadId`in e&&typeof e.threadId==`string`&&(c=e.threadId),`runId`in e&&typeof e.runId==`string`&&(l=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o(ap({type:wh.RUN_FINISHED,threadId:Vv(c??i?.threadId,`threadId`),runId:Vv(l??i?.runId,`runId`),timestamp:Date.now()},{finishReason:`stop`,model:`connect-wrapper`}),i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:wh.RUN_ERROR,threadId:Vv(c??i?.threadId,`threadId`),runId:Vv(l??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}await s(r)},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function iy(e,t,n,r){let i=zm(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??Bv(`thread`),runId:n?.runId??Bv(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function ay(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...Hv(s.headers),...Hv(a?.headers),...Wv(a?.runId)},l=iy(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*ny(ty(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>$v(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=Gv(i,{offset:`-1`,runId:n}),s={...Hv(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*ny(ty(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>$v(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return Zv(i.fetchClient??fetch,r,Hv(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return Qv(i.fetchClient??fetch,r,Hv(i.headers),i.credentials||`same-origin`,n)}}}function oy(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r,headers:i.headers});a instanceof Response?yield*ey(a,r):yield*sy(a,r)}}}async function*sy(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function cy(e){return e.resumable}function ly(e,t){let n=Zp(e.descriptor);return n?{...t,metadata:Xp(n)}:t}function uy(e){return`cancel`in e&&`clearResolution`in e}var dy=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),fy=new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`,`legacy-submit-failed`]);function py(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function my(e){return py(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function hy(e){return py(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function gy(e){return my(e.metadata)||hy(e.metadata)}function _y(e){return Wp(e)}function vy(e){if(!py(e.metadata))return!1;let t=e.metadata[Rp];return!py(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function yy(e){if(!py(e.metadata))return!1;let t=e.metadata[Rp];return!py(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function by(e){return e.metadata?.[`tanstack:interruptPayload`]}function xy(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function Sy(e){if(e.responseSchema!==void 0)try{return pp(fp(e.responseSchema))}catch{return}}function Cy(e){if(e!==void 0)try{return qp(e)}catch{return}}function wy(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function Ty(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(bp(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return wy(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function Ey(e){for(let t of dy)if(t===e)return!0;return!1}function Dy(e){for(let t of fy)if(t===e)return!0;return!1}function Oy(e){if(!py(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?Ey(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&Dy(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function ky(e){return Oy(e)?[e]:!py(e)||!Array.isArray(e.errors)?[]:e.errors.every(Oy)?e.errors:[]}function Ay(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function jy(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&Ay(e.interruptIds,t.interruptIds)}function My(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>jy(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>jy(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function Ny(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):Ay(e.interruptIds,n)}function Py(e,t,n){let r=Sy(e)??n?.responseSchemaHash;return hp({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function Fy(e,t){let n=hp(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([hp(e.error)]),i=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var Iy=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;activeSubmissionOperation;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.activeSubmissionOperation=void 0,this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:hp(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=_y(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.activeSubmissionOperation=void 0,this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)cy(e)&&(e.validationGeneration++,e.resolution=Object.freeze(ly(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&xy(t.descriptor.reason)&&t.descriptor.toolCallId===e&&hy(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&my(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=hp(e),i=_y(r),a=i===void 0&&gy(r);if(i===void 0&&!a)return vy(r)?{descriptor:r,binding:Py(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&Sy(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(Sy(r)??i.responseSchemaHash);if(i!==void 0&&yy(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Py(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(s&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Ip(e.approvalSchema,e.inputSchema);if(Lp(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:hp(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&Lp(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:hp(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:hp(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(o&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&Cy(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===Cy(e.payloadSchema))){let t=by(r);return{descriptor:r,binding:hp(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:hp(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||Sy(r)===void 0||i.responseSchemaHash===Sy(r));return{descriptor:r,binding:Py(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=Fy(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=hp(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:hp(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=py(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?hp(n.binding):hp({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);if(wy(a)){r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(ly(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>cy(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=gp(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(!(`valid`in t)){e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=hp(ly(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=Ty(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return wy(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?Ty(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!py(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=Ty(e.tool?.inputSchema,r,`invalid-edited-args`);return wy(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=Ty(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return wy(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!py(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>cy(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0){this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=hp({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(uy),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:wy(n)?`async-resolver`:`inactive-transaction`,message:wy(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>cy(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){let t={submission:e};this.activeSubmissionOperation=t,this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)cy(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(t)}async performSubmission(e){try{await this.options.submit(e.submission)}catch(t){if(this.activeSubmissionOperation!==e)return;this.handleSubmissionFailure(t,e.submission)}finally{this.activeSubmissionOperation===e&&(this.activeSubmissionOperation=void 0,this.resuming=!1,this.publish())}}handleSubmissionFailure(e,t){let n=ky(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)cy(e)&&(e.status=`error`);return}let r=n.filter(e=>Ny(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>cy(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=hp(e))}else o.push(hp(e));let s=My(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)cy(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(cy).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}};function Ly(e,...t){let n=e?.();if(Ev(n))return n;for(let e of t)if(Ev(e))return e}async function Ry(e,t){if(!t)throw new Av;return await e.prepare(t),e.headers(t)}var zy=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},By=class extends zy{emitEvent(){}},Vy=class{events;constructor(e){this.events=new By(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}recordCompactionEvent(e,t){}recordCompactionState(e){}recordSkillsState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Hy=e=>new Vy(e);function Uy(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Wy(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Gy(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Ky(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var qy=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(Uy).catch(()=>void 0);let t=Uy(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;e.then(e=>{e&&this.messagesGeneration===t&&(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=Mv(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Wy(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Ky(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Gy(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Gy(e);t&&this.clearedMessageIds.add(t);let n=Wy(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Mv(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Jy(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Yy(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Xy(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Zy=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=Mv(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Jy(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Xy(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Yy(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Yy(e);t&&this.clearedMessageIds.add(t);let n=Jy(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return Mv(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Qy(e){let t=new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function $y(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return oy(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function eb(e){return`connect`in e}function tb(e){if(e.type!==`RUN_FINISHED`||e.outcome?.type===`interrupt`)return!1;let t=e;return t.finishReason===void 0?B(e)?.finishReason===`tool_calls`:t.finishReason===`tool_calls`}function nb(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function rb(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
|
|
27
|
+
`),...t===void 0?{}:{body:t}};let r=[],i;for(let t of e){if(typeof t.content==`string`){r.push({type:`text`,content:t.content});continue}typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content),i=ip(i,t.content.metadata)}return{content:{content:r,...i===void 0?{}:{metadata:i}},...t===void 0?{}:{body:t}}}function ib(e){if(typeof e==`object`&&e&&!Array.isArray(e)&&`approved`in e&&typeof e.approved==`boolean`)return e.approved}function ab(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(typeof n==`object`&&n&&`threadId`in n&&typeof n.threadId==`string`&&n.threadId.length!==0&&`runId`in n&&typeof n.runId==`string`&&n.runId.length!==0)return{threadId:n.threadId,runId:n.runId}}var ob=2e3,sb=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),cb=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new Zy;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};byok;byokProvider;context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;connectionDrainsOnSend=!1;errorReportedGeneration=null;streamGeneration=0;continuationGeneration=0;streamContinuationGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){Qy(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new qy(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.byok=e.byok,this.byokProvider=e.byokProvider,this.context=e.context,this.queueConfig=nb(e.queue);let n=$y(e);if(this.connectionDrainsOnSend=eb(n),this.connection=ry(n),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Hy)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Iy({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let r=this.persistor?.readInitial(),i=r instanceof Promise?void 0:r,a=i?i.messages:e.initialMessages,o=null;if(i?.resume){let e=i.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(o=e.resumeState.runId)}if(!o&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(o=t.resumeState.runId)}this.processor=new Sh({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...a?{initialMessages:a}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(n){let r=this.continuationGeneration,i=this.devtoolsBridge.getCurrentRunEventContext(),a=(async()=>{try{let a=this.activeClientTools===null?this.context:this.activeContext,o=await n(e.input,{toolCallId:e.toolCallId,context:a,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:o,state:`output-available`},t,r,i)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r,i)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,a)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),(e===`compaction:started`||e===`compaction:state`||e===`compaction:ended`)&&this.devtoolsBridge.recordCompactionEvent(e,t),e===`skills:state`&&this.devtoolsBridge.recordSkillsState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(r),this.rejoinRunId=o,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=ab(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&!this.disposed&&this.tailing&&this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e)))}hydrateFromServer(){let e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}!this.disposed&&this.tailing&&(this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(wv(t.messages)),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId)))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Mv(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),Mv(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=Mv(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=Mv(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0);let r=e.type===`RUN_FINISHED`&&tb(e);t?.resolveProcessing!==!1&&!r&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=Mv(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!(!this.isLoading||!t||t!==this.activeResumeRunId&&t!==this.currentRunId),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.resumeInterruptsUnsafeForGeneration(e,n,this.continuationGeneration):Promise.resolve(!1)}resumeInterruptsUnsafeForGeneration(e,t,n){return n===this.continuationGeneration?this.isLoading?new Promise((r,i)=>{this.queuePostStreamAction(async()=>{try{r(await this.resumeInterruptsUnsafeForGeneration(e,t,n))}catch(e){i(e)}})}):(this.pendingResumeThreadId=t.threadId,this.pendingResumeParentRunId=t.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){let t=this.continuationGeneration;this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=ib(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let n=await this.resumeInterruptsUnsafeForGeneration([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId},t).finally(()=>{this.activeInterruptSubmission===e&&(this.activeInterruptSubmission=void 0)});if(t!==this.continuationGeneration)return;let r=this.takeInterruptSubmissionFailure();if(r!==void 0)throw{errors:r.errors};if(!n)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.streamContinuationGeneration=this.continuationGeneration,this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},ob);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&sb.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e=th(e),e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)){let t=B(e)?.interruptErrors;this.interruptSubmissionFailure={errors:Array.isArray(t)?t:[]}}if(this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(Mv(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=B(e)?.interruptErrors;if(!t||!Array.isArray(n)||n.length===0)return!1;let r=Mv(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>typeof e!=`object`||!e||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=Mv(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),typeof e==`string`&&!e.trim())return;if(this.hasPendingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let r={...t,...n?.body};if(this.isSendBusy()){let{action:t,id:i}=this.decideWhenBusy(e,n);if(t===`drop`)return;if(t===`queue`){this.enqueueMessage(e,r,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,r)}finally{this.sendInFlight=!1}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id,n.metadata);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id,...e.metadata===void 0?{}:{metadata:e.metadata}}}async append(e){if(this.mountDevtools(),this.hasPendingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=Fm(e,Im);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration;this.streamContinuationGeneration=this.continuationGeneration;let t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m;if(this.byok){let e=Ly(this.byokProvider,f.provider);m=await Ry(this.byok,e)}let h={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?Tp(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{},...m?{headers:m}:{}};if(this.devtoolsBridge.beginRun(h.runId,h.threadId),s=h.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,h.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,h.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,h),e!==this.streamGeneration||a.aborted||(this.connectionDrainsOnSend&&this.resolveProcessing(),await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){let n=t instanceof Error?t:Error(String(t));if(n.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;if(n instanceof Ov&&this.byok?.request(n.provider,`missing`),n instanceof kv&&n.reason===`locked`&&this.byok?.request(n.provider,`locked`),e===this.streamGeneration&&(this.reportStreamError(n),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:n.message}),c=!0)),e===this.streamGeneration&&(n instanceof Ov||n instanceof kv||n instanceof Av))throw n}finally{e===this.streamGeneration&&(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o?(this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()):this.flushQueue())}return o}subscribe(e){let t=e?.restart===!0;(!this.isSubscribed||t)&&(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){this.continuationGeneration++;let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),this.lastResume=null,this.activeInterruptSubmission=void 0,this.interruptManager.reset(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t,this.streamContinuationGeneration)}async addToolResultForClientTool(e,t,n,r){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,r),n===this.continuationGeneration&&(this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output))){if(this.isLoading){this.queuePostStreamAction(()=>n===this.continuationGeneration?this.checkForContinuation():Promise.resolve());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&bp(e.outputSchema)?Dp(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){let t=this.continuationGeneration;this.postStreamActions.push(async()=>{t===this.continuationGeneration&&await e()})}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(this.streamContinuationGeneration===this.continuationGeneration&&!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=rb(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`);let n=$y({connection:e.connection,fetcher:e.fetcher});this.connectionDrainsOnSend=eb(n),this.connection=ry(n),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),e.byok!==void 0&&(this.byok=e.byok),e.byokProvider!==void 0&&(this.byokProvider=e.byokProvider),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=nb(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function lb(){return{name:`streaming`,transformDocument(e){let t=ub(e.children);return t===e.children?e:{...e,children:t}}}}function ub(e){let t=e.at(-1);if(!t)return e;let n=db(t);return n===t?e:n?[...e.slice(0,-1),n]:e.slice(0,-1)}function db(e){if(e.type===`heading`&&e.children.length===0)return;if(e.type===`blockquote`){let t=ub(e.children);return t.length===0?void 0:t===e.children?e:{...e,children:t}}if(e.type!==`list`)return e;let t=e.items.at(-1);if(!t)return;let n=fb(t);if(n===t)return e;let r=n?[...e.items.slice(0,-1),n]:e.items.slice(0,-1);return r.length===0?void 0:{...e,items:r}}function fb(e){let t=ub(e.children);if(t.length!==0)return t===e.children?e:{...e,children:t}}var pb={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};function mb(e){return e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
|
|
28
|
+
`)}function hb(e){return e.replace(/[&<>"']/g,e=>pb[e])}function Y(e){return hb(e).replace(/`/g,```)}function gb(e){return/^\s*$/.test(e)}function _b(e,t){let n=0;for(;n<e.length&&n<t&&e[n]===` `;)n++;return e.slice(n)}function vb(e){let t=``;for(let n of e)n.type===`text`||n.type===`inlineCode`?t+=n.value:`children`in n?t+=vb(n.children):n.type===`image`&&(t+=n.alt);return t}function yb(){let e=new Map;return t=>{let n=t.toLowerCase().normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).replace(/&[a-z0-9#]+;/gi,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`section`,r=e.get(n)??0;return e.set(n,r+1),r===0?n:`${n}-${r+1}`}}function bb(e){let t=e.trim().replace(/[\u0000-\u001F\u007F\s]+/g,``);return t?/^(#|\/|\.\/|\.\.\/)/.test(t)||/^(https?:|mailto:|tel:)/i.test(t)?t:/^[a-z][a-z0-9+.-]*:/i.test(t)?``:t:``}function xb(e){return e.trim().toLowerCase()}function Sb(e){return xb(e).replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)}function Cb(e,t={}){let n=Ub(Eb(e,t));for(let e of t.extensions??[])n=e.transformInline?.(n,{options:t})??n;return n}var wb=32,Tb=16;function Eb(e,t,n={scans:Math.max(e.length*Tb,1024),depth:0}){if(n.depth>=wb)return e?[{type:`text`,value:e}]:[];n.depth++;let r=[],i=0,a=``,o=()=>{a&&=(r.push({type:`text`,value:a}),``)};for(;i<e.length;){let s=e[i],c=e[i+1];if(s===`\\`){if(c===`
|
|
29
|
+
`){o(),r.push({type:`break`}),i+=2;continue}if(c&&/[\\`*_[\]{}()#+\-.!|~<>]/.test(c)){a+=c,i+=2;continue}}if(s==="`"){let t=Mb(e,i,"`"),s=Nb(e,i+t,"`",t,n);if(s!==-1){o(),r.push({type:`inlineCode`,value:e.slice(i+t,s).replace(/\s+/g,` `).trim()}),i=s+t;continue}a+=e.slice(i,i+t),i+=t;continue}if(s===`!`&&c===`[`){let a=Ob(e,i+1,t,n);if(a){o(),r.push({type:`image`,src:bb(a.href),alt:Hb(a.label,n),...a.title?{title:a.title}:{}}),i=a.end;continue}}if(s===`[`){let a=Db(e,i,t,n);if(a){o(),r.push(a.node),i=a.end;continue}let s=Ob(e,i,t,n);if(s){let e=bb(s.href);o(),e?r.push({type:`link`,href:e,...s.title?{title:s.title}:{},children:Eb(s.label,t,n)}):r.push(...Eb(s.label,t,n)),i=s.end;continue}}if(s===`*`&&c===`*`&&e[i+2]===`*`){let a=Pb(e,i+3,`***`,n);if(a!==-1){o(),r.push({type:`emphasis`,children:Eb(e.slice(i+1,a+2),t,n)}),i=a+3;continue}}if(s===`*`&&c===`*`||s===`_`&&c===`_`){let l=s===`_`&&!Rb(e,i,2,!0)?-1:Pb(e,i+2,s+s,n);if(l!==-1){o(),r.push({type:`strong`,children:Eb(e.slice(i+2,l),t,n)}),i=l+2;continue}a+=s+c,i+=2;continue}if(s===`~`&&c===`~`&&e[i+2]===`~`){let t=Mb(e,i,`~`);a+=e.slice(i,i+t),i+=t;continue}if(s===`~`&&c===`~`){let s=Pb(e,i+2,`~~`,n);if(s!==-1){o(),r.push({type:`strike`,children:Eb(e.slice(i+2,s),t,n)}),i=s+2;continue}a+=`~~`,i+=2;continue}if(s===`~`){let a=Fb(e,i+1,n);if(a!==-1){o(),r.push({type:`strike`,children:Eb(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`*`||s===`_`){let a=s===`_`&&!Rb(e,i,1,!0)?-1:Pb(e,i+1,s,n);if(a!==-1){o(),r.push({type:`emphasis`,children:Eb(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`<`&&t.allowHtml){let t=Ib(e,i+1,`>`,n);if(t!==-1&&kb(e.slice(i,t+1))){o(),r.push({type:`inlineHtml`,value:e.slice(i,t+1)}),i=t+1;continue}}a+=s,i++}return o(),n.depth--,r}function Db(e,t,n,r){if(e[t+1]!==`^`)return;let i=Ib(e,t+2,`]`,r);if(i===-1)return;let a=xb(e.slice(t+2,i)),o=n.footnotes?.[a];if(!o||!n.footnoteOrder)return;let s=n.footnoteOrder.indexOf(a);s===-1&&(n.footnoteOrder.push(a),s=n.footnoteOrder.length-1);let c=(n.footnoteCounts?.[a]??0)+1;return n.footnoteCounts&&(n.footnoteCounts[a]=c),{node:{type:`footnoteReference`,id:o.id??(Sb(o.label)||`footnote`),number:s+1,...c>1?{referenceIndex:c}:{}},end:i+1}}function Ob(e,t,n,r){let i=jb(e,t,`[`,`]`,r);if(i===-1)return;let a=e.slice(t+1,i);if(e[i+1]===`(`){let t=jb(e,i+1,`(`,`)`,r);if(t===-1)return;let n=Ab(e.slice(i+2,t).trim());return n?{label:a,href:n.href,...n.title?{title:n.title}:{},end:t+1}:void 0}if(e[i+1]===`[`){let t=jb(e,i+1,`[`,`]`,r);if(t===-1)return;let o=e.slice(i+2,t),s=n.references?.[xb(o||a)];return s?{label:a,href:s.href,...s.title?{title:s.title}:{},end:t+1}:void 0}let o=n.references?.[xb(a)];if(o)return{label:a,href:o.href,...o.title?{title:o.title}:{},end:i+1}}function kb(e){return/^<!--(?:[\s\S]*--|-?)>$/.test(e)||/^<\?[\s\S]*\?>$/.test(e)||/^<![A-Z][\s\S]*>$/.test(e)||/^<!\[CDATA\[[\s\S]*\]\]>$/.test(e)||/^<\/[A-Za-z][\w:-]*\s*>$/.test(e)?!0:/^<[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>$/.test(e)}function Ab(e){let t=e.match(/^(\S+)(?:\s+["']([^"']*)["'])?$/);return t?{href:t[1].replace(/^<|>$/g,``),...t[2]?{title:t[2]}:{}}:{href:e}}function jb(e,t,n,r,i){let a=0;for(let o=t;o<e.length;o++){if(!Lb(i))return-1;if(e[o-1]!==`\\`&&(e[o]===n&&a++,e[o]===r&&(a--,a===0)))return o}return-1}function Mb(e,t,n,r){let i=0;for(;e[t+i]===n&&(!r||Lb(r));)i++;return i}function Nb(e,t,n,r,i){for(let a=t;a<e.length;a++){if(!Lb(i))return-1;if(e[a]===n&&Mb(e,a,n,i)>=r)return a}return-1}function Pb(e,t,n,r){for(let i=t;i<e.length;i++){if(!Lb(r))return-1;if(e[i-1]!==`\\`&&e.startsWith(n,i)){if(e[i+1]===n){let t=Pb(e,i+2,n+n,r);if(t>i+2){i=t+1;continue}}if((n!==`~~`||e[i-1]!==`~`&&e[i+2]!==`~`)&&(n[0]!==`_`||Rb(e,i,n.length,!1)))return i}}return-1}function Fb(e,t,n){if(Vb(e[t]??``)||/\d/.test(e[t]??``))return-1;for(let r=t;r<e.length;r++){if(!Lb(n))return-1;if(e[r-1]!==`\\`&&e[r]===`~`&&e[r-1]!==`~`&&e[r+1]!==`~`)return Vb(e[r-1]??``)?-1:r}return-1}function Ib(e,t,n,r){for(let i=t;i<e.length;i++){if(!Lb(r))return-1;if(e[i]===n)return i}return-1}function Lb(e){return e.scans<=0?!1:(e.scans--,!0)}function Rb(e,t,n,r){let i=e[t-1],a=e[t+n],o=!zb(a)&&(!Bb(a)||zb(i)||Bb(i)),s=!zb(i)&&(!Bb(i)||zb(a)||Bb(a));return r?o&&(!s||Bb(i)):s&&(!o||Bb(a))}function zb(e){return e===void 0||/\s/.test(e)}function Bb(e){return e!==void 0&&/[^\p{L}\p{N}\s]/u.test(e)}function Vb(e){return/\s/.test(e)}function Hb(e,t){return Eb(e,{},t).map(e=>e.type===`text`||e.type===`inlineCode`?e.value:``).join(``)}function Ub(e){let t=[];for(let n of e){let e=t.at(-1);e?.type===`text`&&n.type===`text`?e.value+=n.value:t.push(n)}return t}var Wb=64;function Gb(e,t={}){let n=mb(e),r=t.frontmatter!==!1,i=n.split(`
|
|
30
30
|
`),a;if(r&&i[0]===`---`){let e=i.findIndex((e,t)=>t>0&&e===`---`);e>0&&(a=i.slice(1,e).join(`
|
|
31
|
-
`),i=i.slice(e+1))}let o=
|
|
32
|
-
`);return this.index=this.lines.length,e?[{type:`paragraph`,children:
|
|
31
|
+
`),i=i.slice(e+1))}let o=Jb(i);i=o.lines;let s=[],c=Object.create(null),l=Object.keys(o.references).length>0,u=Object.keys(o.footnotes).length>0,d=l||u?{...t,...l?{references:o.references}:{},...u?{footnotes:o.footnotes,footnoteOrder:s,footnoteCounts:c}:{}}:t,f=new Kb(i,d,yb()).parse();u&&s.length>0&&f.push(Yb(o.footnotes,s,d));let p=a===void 0?{type:`root`,children:f}:{type:`root`,frontmatter:a,children:f};for(let e of d.extensions??[])p=e.transformDocument?.(p,{options:d})??p;return p}var Kb=class e{lines;options;slugger;budget;index=0;constructor(e,t,n,r={depth:0}){this.lines=e,this.options=t,this.slugger=n,this.budget=r}parse(){if(this.budget.depth>=Wb){let e=this.lines.slice(this.index).join(`
|
|
32
|
+
`);return this.index=this.lines.length,e?[{type:`paragraph`,children:Cb(e,this.options)}]:[]}this.budget.depth++;let e=[];for(;this.index<this.lines.length;){if(gb(this.current())){this.index++;continue}let t=this.parseExtensionBlock();if(t){e.push(t);continue}let n=this.parseFence()??this.parseHeading()??this.parseThematicBreak()??this.parseBlockquote()??this.parseList()??this.parseTable()??this.parseHtmlBlock()??this.parseParagraph();e.push(n)}return this.budget.depth--,e}parseExtensionBlock(){for(let t of this.options.extensions??[]){let n=0,r=t.parseBlock?.({lines:this.lines,index:this.index,options:this.options,parseInline:e=>Cb(e,this.options),parseBlocks:t=>new e(mb(t).split(`
|
|
33
33
|
`),this.options,this.slugger,this.budget).parse(),consume:e=>{n=e}});if(r)return this.index+=Math.max(n,1),r}}parseFence(){let e=this.current().match(/^ {0,3}(`{3,}|~{3,})(.*)$/);if(!e)return;let t=e[1],n=t[0],r=t.length,i=e[2].trim(),a=[];for(this.index++;this.index<this.lines.length;){let e=this.current(),t=e.match(/^ {0,3}(`{3,}|~{3,})\s*$/);if(t&&t[1][0]===n&&t[1].length>=r){this.index++;break}a.push(e),this.index++}return{type:`code`,value:a.join(`
|
|
34
|
-
`),...
|
|
35
|
-
`)}}for(;this.index<this.lines.length&&!
|
|
36
|
-
`)}}parseParagraph(){let e=[];for(;this.index<this.lines.length;){let t=this.current();if(
|
|
37
|
-
`),this.options)}}createHeadingId(e){if(this.options.headingIds===!1)return;let t=
|
|
38
|
-
`),id:i===1?e:`${e}-${i}`}}continue}let a=c.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);if(a){let e=a[3]??a[4]??a[5];t[
|
|
39
|
-
`),n,
|
|
40
|
-
`)}function
|
|
41
|
-
`)}\n</${n}>`}case`blockquote`:return`<blockquote>\n${e.children.map(e=>
|
|
42
|
-
`)}\n</blockquote>`;case`table`:return`<table>${`<thead><tr>${e.header.map((n,r)=>
|
|
43
|
-
`)}`:``;return`${n?`<p>${t}</p>`:t}${o}`}return`${a}${e.map(e=>
|
|
44
|
-
`)}`}function
|
|
45
|
-
`);return`<div class="markdown-alert markdown-alert-${
|
|
46
|
-
`);return`<section data-footnotes="" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes${
|
|
47
|
-
`)}function
|
|
48
|
-
`)}</${n}>`}function
|
|
34
|
+
`),...qb(i)}}parseHeading(){let e=this.current().match(/^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/);if(!e)return;let t=e[1].length,n=e[2]??``,r=Cb((/^#+[ \t]*$/.test(n)?``:n.replace(/[ \t]+#+[ \t]*$/,``)).trim(),this.options),i=this.createHeadingId(r);return this.index++,i?{type:`heading`,depth:t,id:i,children:r}:{type:`heading`,depth:t,children:r}}parseThematicBreak(){if(/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(this.current()))return this.index++,{type:`thematicBreak`}}parseBlockquote(){if(!/^ {0,3}>\s?/.test(this.current()))return;let t=[];for(;this.index<this.lines.length;){let e=this.current();if(gb(e)){t.push(``),this.index++;continue}let n=e.match(/^ {0,3}>\s?(.*)$/);if(!n)break;t.push(n[1]),this.index++}return{type:`blockquote`,children:new e(t,this.options,this.slugger,this.budget).parse()}}parseList(){let t=Zb(this.current());if(!t)return;let n=[],r=t.ordered,i=t.indent,a=r?t.number:void 0,o=!1;for(;this.index<this.lines.length;){let r=Zb(this.current());if(!r||!Qb(r,t)||r.indent!==i)break;let a=r.content,s=a.match(/^\[([ xX])\]\s+(.*)$/),c=s?s[1].toLowerCase()===`x`:void 0;s&&(a=s[2]);let l=[a];for(this.index++;this.index<this.lines.length;){let e=this.current(),n=Zb(e);if(n&&n.indent===i)break;if(gb(e)){let e=this.index;for(;e<this.lines.length&&gb(this.lines[e]);)e++;let n=this.lines[e];if(n===void 0)break;let a=Zb(n);if(a?.indent===i){if(!Qb(a,t))break;o=!0,this.index=e;break}if($b(n)<r.contentIndent)break;o=!0,l.push(``),this.index=e;continue}if($b(e)>=r.contentIndent){l.push(_b(e,r.contentIndent)),this.index++;continue}if(ex(e,this.next()))break;l.push(e.trimStart()),this.index++}let u={type:`listItem`,children:new e(l,this.options,this.slugger,this.budget).parse()};c!==void 0&&(u.checked=c),n.push(u)}return{type:`list`,ordered:r,...r&&a!==void 0?{start:a}:{},...o&&{loose:!0},items:n}}parseTable(){let e=this.current(),t=this.next();if(!t||!tx(e,t))return;let n=nx(e),r=nx(t).map(rx),i=n.length,a=[];for(this.index+=2;this.index<this.lines.length;){let e=this.current();if(gb(e)||ex(e,this.next()))break;let t=nx(e);a.push(Array.from({length:i},(e,n)=>ix(t[n]??``,this.options))),this.index++}return{type:`table`,align:r,header:n.map(e=>ix(e,this.options)),rows:a}}parseHtmlBlock(){if(!this.options.allowHtml||!/^ {0,3}<([A-Za-z][\w:-]*|!--|\/[A-Za-z])/.test(this.current()))return;let e=[];if(/^ {0,3}<!--/.test(this.current())){for(;this.index<this.lines.length;){let t=this.current();if(e.push(t),this.index++,t.includes(`-->`))break}return{type:`html`,value:e.join(`
|
|
35
|
+
`)}}for(;this.index<this.lines.length&&!gb(this.current());)e.push(this.current()),this.index++;return{type:`html`,value:e.join(`
|
|
36
|
+
`)}}parseParagraph(){let e=[];for(;this.index<this.lines.length;){let t=this.current();if(gb(t)||e.length>0&&ex(t,this.next()))break;e.push(t.trim()),this.index++}return{type:`paragraph`,children:Cb(e.join(`
|
|
37
|
+
`),this.options)}}createHeadingId(e){if(this.options.headingIds===!1)return;let t=vb(e);return typeof this.options.headingIds==`function`?this.options.headingIds(t,this.index):this.slugger(t)}current(){return this.lines[this.index]??``}next(){return this.lines[this.index+1]}};function qb(e){if(!e)return{};let t=e.match(/^([A-Za-z0-9_+.#-]+)/)?.[1],n=t?e.slice(t.length).trim():e,r=n.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),i=n.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),a=n.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/),o=Xb(a?.[1]??a?.[2]??``),s=r?r[1]??r[2]??r[3]:void 0,c=i?i[1]??i[2]??i[3]:void 0;return{...t?{lang:t}:{},...n?{meta:n}:{},...s?{title:s,file:s}:{},...c?{framework:c.toLowerCase()}:{},...o.length?{highlightLines:o}:{}}}function Jb(e){let t=Object.create(null),n=Object.create(null),r=new Map,i=[],a,o=0,s=0;for(;s<e.length;){let c=e[s],l=c.match(/^ {0,3}(`{3,}|~{3,})/);if(l){let e=l[1][0];a?e===a&&l[1].length>=o&&(a=void 0,o=0):(a=e,o=l[1].length),i.push(c),s++;continue}if(!a){let i=c.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/);if(i){let t=i[1],a=[i[2]??``];for(s++;s<e.length;){let t=e[s];if(!/^(?: {4,}|\t)/.test(t))break;a.push(t.replace(/^(?: {4}|\t)/,``)),s++}let o=xb(t);if(!n[o]){let e=Sb(t)||`footnote`,i=(r.get(e)??0)+1;r.set(e,i),n[o]={label:t,content:a.join(`
|
|
38
|
+
`),id:i===1?e:`${e}-${i}`}}continue}let a=c.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);if(a){let e=a[3]??a[4]??a[5];t[xb(a[1])]={href:a[2].replace(/^<|>$/g,``),...e===void 0?{}:{title:e}},s++;continue}}i.push(c),s++}return{lines:i,references:t,footnotes:n}}function Yb(e,t,n){let r=[];for(let i=0;i<t.length;i++){let a=e[t[i]];a&&r.push({id:a.id??(Sb(a.label)||`footnote`),number:i+1,children:new Kb(mb(a.content).split(`
|
|
39
|
+
`),n,yb()).parse()})}for(let e of r){let r=n.footnoteCounts?.[t[e.number-1]]??1;r>1&&(e.referenceCount=r)}return{type:`footnotes`,items:r}}function Xb(e){let t=new Set;for(let n of e.split(`,`)){let e=n.trim().match(/^(\d+)(?:-(\d+))?$/);if(!e)continue;let r=Number(e[1]),i=Number(e[2]??e[1]);for(let e=r;e<=i&&e<r+1e3;e++)t.add(e)}return[...t].sort((e,t)=>e-t)}function Zb(e){let t=e.match(/^(\s{0,8})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/);if(!t)return;let n=t[2],r=/\d/.test(n[0]);return{ordered:r,...r?{number:Number.parseInt(n,10)}:{},indent:t[1].length,marker:r?n.at(-1):n,contentIndent:t[1].length+n.length+(t[3]?.length??1),content:t[4]??``}}function Qb(e,t){return e.ordered===t.ordered&&e.marker===t.marker}function $b(e){return e.match(/^ */)?.[0].length??0}function ex(e,t){let n=Zb(e);return/^ {0,3}(`{3,}|~{3,})/.test(e)||/^ {0,3}#{1,6}(?:\s+|$)/.test(e)||/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(e)||/^ {0,3}>\s?/.test(e)||n!==void 0&&(!n.ordered||n.number===1)||!!t&&tx(e,t)}function tx(e,t){if(!e.includes(`|`))return!1;let n=nx(t);return n.length===nx(e).length&&n.every(e=>/^:?-+:?$/.test(e.trim()))}function nx(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`){r+=`|`,e++;continue}if(i===`|`){n.push(r.trim()),r=``;continue}r+=i}return n.push(r.trim()),n}function rx(e){let t=e.trim();if(t.startsWith(`:`)&&t.endsWith(`:`))return`center`;if(t.endsWith(`:`))return`right`;if(t.startsWith(`:`))return`left`}function ix(e,t){return{type:`tableCell`,children:Cb(e,t)}}function ax(e,t={}){return(typeof e==`string`?Gb(e,t):e).children.map(e=>ox(e,t)).join(`
|
|
40
|
+
`)}function ox(e,t={}){let n=vx(e,t);if(n!==void 0)return n;switch(e.type){case`heading`:{let n=e.id?` id="${Y(e.id)}"`:``,r=e.framework?` data-framework="${Y(e.framework)}"`:``;return`<h${e.depth}${n}${r}>${cx(e.children,t)}${yx(e.id,t)}</h${e.depth}>`}case`paragraph`:return`<p>${cx(e.children,t)}</p>`;case`code`:return lx(e,t);case`list`:{let n=e.ordered?`ol`:`ul`;return`<${n}${e.ordered&&e.start&&e.start!==1?` start="${e.start}"`:``}>\n${e.items.map(n=>`<li>${ux(n.children,n.checked,e.loose,t)}</li>`).join(`
|
|
41
|
+
`)}\n</${n}>`}case`blockquote`:return`<blockquote>\n${e.children.map(e=>ox(e,t)).join(`
|
|
42
|
+
`)}\n</blockquote>`;case`table`:return`<table>${`<thead><tr>${e.header.map((n,r)=>_x(`th`,n,e.align[r],t)).join(``)}</tr></thead>`}${e.rows.length?`<tbody>${e.rows.map(n=>`<tr>${n.map((n,r)=>_x(`td`,n,e.align[r],t)).join(``)}</tr>`).join(``)}</tbody>`:``}</table>`;case`footnotes`:return fx(e.items,t);case`thematicBreak`:return`<hr>`;case`html`:return t.allowHtml?e.value:hb(e.value);case`callout`:return dx(e,t);case`component`:return gx(e,t)}}function sx(e,t={}){let n=vx(e,t);if(n!==void 0)return n;switch(e.type){case`text`:return hb(e.value);case`inlineCode`:return`<code>${hb(e.value)}</code>`;case`strong`:return`<strong>${cx(e.children,t)}</strong>`;case`emphasis`:return`<em>${cx(e.children,t)}</em>`;case`strike`:return`<del>${cx(e.children,t)}</del>`;case`footnoteReference`:return`<sup><a id="user-content-fnref-${Y(hx(e))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${Y(e.id)}">${e.number}</a></sup>`;case`link`:return`<a href="${Y(e.href)}"${e.title?` title="${Y(e.title)}"`:``}>${cx(e.children,t)}</a>`;case`image`:return`<img src="${Y(e.src)}" alt="${Y(e.alt)}"${e.title?` title="${Y(e.title)}"`:``}>`;case`break`:return`<br>`;case`inlineHtml`:return t.allowHtml?e.value:hb(e.value)}}function cx(e,t){return e.map(e=>sx(e,t)).join(``)}function lx(e,t){let n=e.lang??`plaintext`,r=[`class="tm-code${t.codeLineNumbers?` tm-code--line-numbers`:``}"`,`data-lang="${Y(n)}"`,e.title?`data-code-title="${Y(e.title)}"`:``,e.file?`data-filename="${Y(e.file)}"`:``,e.framework?`data-framework="${Y(e.framework)}"`:``].filter(Boolean).join(` `),i=t.highlighter?.(e.value,n,{...e.highlightLines&&{highlightLines:e.highlightLines},...t.codeLineNumbers!==void 0&&{lineNumbers:t.codeLineNumbers}})??hb(e.value),a=`<pre ${r}><code class="language-${Y(n)}">${i}</code></pre>`;return e.title?`<figure class="tm-code-frame" data-lang="${Y(n)}"><figcaption>${hb(e.title)}</figcaption>${a}</figure>`:a}function ux(e,t,n,r){let i=e[0],a=t===void 0?``:`<input type="checkbox" disabled${t?` checked`:``}> `;if(i?.type===`paragraph`){let t=`${a}${cx(i.children,r)}`,o=e.length>1?`\n${e.slice(1).map(e=>ox(e,r)).join(`
|
|
43
|
+
`)}`:``;return`${n?`<p>${t}</p>`:t}${o}`}return`${a}${e.map(e=>ox(e,r)).join(`
|
|
44
|
+
`)}`}function dx(e,t){let n=e.kind.toLowerCase(),r=e.children.map(e=>ox(e,t)).join(`
|
|
45
|
+
`);return`<div class="markdown-alert markdown-alert-${Y(n)}"><p class="markdown-alert-title">${hb(e.title)}</p><div class="markdown-alert-content">${r}</div></div>`}function fx(e,t){let n=e.map(e=>`<li id="user-content-fn-${Y(e.id)}">\n${px(e,t)}\n</li>`).join(`
|
|
46
|
+
`);return`<section data-footnotes="" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes${yx(`footnote-label`,t)}</h2>\n<ol>\n${n}\n</ol>\n</section>`}function px(e,t){let n=mx(e),r=e.children.length-1;return r<0?`<p>${n.trimStart()}</p>`:e.children.map((e,i)=>i===r&&e.type===`paragraph`?`<p>${cx(e.children,t)}${n}</p>`:ox(e,t)).join(`
|
|
47
|
+
`)}function mx(e){let t=``;for(let n=1;n<=(e.referenceCount??1);n++){let r=n===1?e.id:`${e.id}-${n}`,i=n===1?`${e.number}`:`${e.number}-${n}`;t+=` <a data-footnote-backref="" aria-label="Back to reference ${i}" class="data-footnote-backref" href="#user-content-fnref-${Y(r)}">↩</a>`}return t}function hx(e){return e.referenceIndex&&e.referenceIndex>1?`${e.id}-${e.referenceIndex}`:e.id}function gx(e,t){let n=e.tagName??`md-comment-component`;return`<${n}${bx(e)}>${e.children.map(e=>ox(e,t)).join(`
|
|
48
|
+
`)}</${n}>`}function _x(e,t,n,r){return`<${e}${n?` style="text-align:${n}"`:``}>${cx(t.children,r)}</${e}>`}function vx(e,t){for(let n of t.extensions??[]){let r=n.renderHtml?.(e,{options:t,renderBlock:e=>ox(e,t),renderInline:e=>sx(e,t)});if(r!==void 0)return r}}function yx(e,t){let n=t.headingAnchors;if(!e||!n)return``;let r=typeof n==`object`?n:{};return`<a href="#${Y(e)}" aria-hidden="${r.ariaHidden??!0}" class="${Y(r.className??`anchor-heading anchor-heading-link`)}" tabindex="${r.tabIndex??-1}">${hb(r.content??`#`)}</a>`}function bx(e){let t={...e.properties};e.tagName||(t[`data-component`]=e.name,t[`data-attributes`]||=JSON.stringify(e.attributes));let n=Object.entries(t);return n.length?` ${n.map(([e,t])=>`${e}="${Y(t)}"`).join(` `)}`:``}var xx=async e=>{let{replicache:n,spriteId:r,spriteBuildId:i,signal:a}=e;return a?.aborted?Error(`Publish sprite aborted`):t(async()=>(await n.mutate.spriteBuild_publish_v2({spriteBuildId:i,context:{actionedAt:Date.now()}}),await n.push({now:!0}),{spriteId:r,spriteBuildId:i}))},Sx=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function Cx(e,t){let n=u.rest_props(t,Sx),r=[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`}]];av(e,u.spread_props({name:`loader-circle`},()=>n,{get iconNode(){return r}}))}u.create_custom_element(Cx,{},[],[],{mode:`open`});var wx=u.from_html(`<span class="loader-circle svelte-galthg" aria-hidden="true"><!></span>`),Tx={hash:`svelte-galthg`,code:`.loader-circle.svelte-galthg {display:inline-flex;
|
|
49
49
|
animation: svelte-galthg-spin 700ms linear infinite;}
|
|
50
50
|
|
|
51
51
|
@keyframes svelte-galthg-spin {
|
|
52
52
|
to {
|
|
53
53
|
transform: rotate(360deg);
|
|
54
54
|
}
|
|
55
|
-
}`};function
|
|
55
|
+
}`};function Ex(e){u.append_styles(e,Tx);var t=wx();Cx(u.child(t),{size:16}),u.reset(t),u.append(e,t)}u.create_custom_element(Ex,{},[],[],{mode:`open`});var Dx=e=>{let t=u.state(e.value);return u.user_effect(()=>Ie(`watch(${e.name})`,()=>{u.set(t,e.value)})),{get _(){return u.get(t)}}};Dx.undefined={_:void 0},Dx.lit=e=>({_:e});var Ox=u.from_html(`<div class="summary dots svelte-qp0d57">Planning</div>`),kx=u.from_html(`<span class="svelte-qp0d57">Done</span>`),Ax=u.from_html(`<span class="cancel-duration svelte-qp0d57"> </span>`),jx=u.from_html(`<span class="cancel-label svelte-qp0d57"><span class="svelte-qp0d57">Canceled</span> <!></span>`),Mx=u.from_html(`<span class="svelte-qp0d57">Failed</span>`),Nx=u.from_html(`<span class="chip svelte-qp0d57"> </span>`),Px=u.from_html(`<span class="svelte-qp0d57"> </span> <!>`,1),Fx=u.from_html(`<span class="phase svelte-qp0d57"> </span>`),Ix=u.from_html(`<div class="trailing svelte-qp0d57"><!></div>`),Lx=u.from_html(`<span class="dots svelte-qp0d57"></span>`),Rx=u.from_html(`<div class="summary svelte-qp0d57"> <!></div>`),zx=u.from_html(`<div class="summary placeholder svelte-qp0d57">Just getting started<span class="dots svelte-qp0d57"></span></div>`),Bx=u.from_html(`<div class="top svelte-qp0d57"><div class="label svelte-qp0d57"><!></div> <!></div> <!>`,1),Vx=u.from_html(`<div><!></div>`),Hx={hash:`svelte-qp0d57`,code:`.card.svelte-qp0d57 {display:flex;gap:0.4rem;flex-direction:column;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.top.svelte-qp0d57 {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:600;}.label.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;min-width:0;}.trailing.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.chip.svelte-qp0d57 {max-width:16rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1rem 0.45rem;overflow:hidden;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:0.75rem;font-weight:500;white-space:nowrap;text-overflow:ellipsis;}.phase.svelte-qp0d57 {text-transform:capitalize;}.cancel-label.svelte-qp0d57 {display:inline-flex;gap:0.25em;align-items:baseline;}.cancel-duration.svelte-qp0d57 {font-weight:400;}.summary.svelte-qp0d57 {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.summary.placeholder.svelte-qp0d57 {color:color-mix(in oklch, var(--rough-muted-foreground, oklch(0.556 0 0)) 60%, transparent);}.terminal.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-foreground, oklch(0.145 0 0));}.failed.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.dots.svelte-qp0d57::after {content:'';
|
|
56
56
|
animation: svelte-qp0d57-ellipsis 1.5s steps(4, end) infinite;}
|
|
57
57
|
|
|
58
58
|
@keyframes svelte-qp0d57-ellipsis {
|
|
@@ -60,7 +60,7 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
|
|
|
60
60
|
25% { content: '.'; }
|
|
61
61
|
50% { content: '..'; }
|
|
62
62
|
75% { content: '...'; }
|
|
63
|
-
}`};function Db(e,t){l.push(t,!0),l.append_styles(e,Eb);let n=l.prop(t,`activity`,7),r=l.prop(t,`summaryText`,7),i=l.derived(()=>n().status===`ready`||n().status===`error`||n().status===`canceled`),a=l.derived(()=>n().status===`error`||n().toolOutcome===`failed`||n().phase?.outcome===`failed`);var o={get activity(){return n()},set activity(e){n(e),l.flush()},get summaryText(){return r()},set summaryText(e){r(e),l.flush()}},s=Tb();let c;var u=l.child(s),d=e=>{var t=fb();l.append(e,t)},f=e=>{var t=wb(),a=l.first_child(t),o=l.child(a),s=l.child(o),c=e=>{var t=pb();l.append(e,t)},u=e=>{var t=hb(),r=l.sibling(l.child(t),2),i=e=>{var t=mb(),r=l.child(t);l.reset(t),l.template_effect(()=>l.set_text(r,`after ${n().elapsedSeconds??``} ${n().elapsedSeconds===1?`second`:`seconds`}`)),l.append(e,t)};l.if(r,e=>{n().elapsedSeconds!=null&&e(i)}),l.reset(t),l.append(e,t)},d=e=>{var t=gb();l.append(e,t)},f=e=>{var t=vb(),r=l.first_child(t),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var t=_b(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().action.filename)),l.append(e,t)};l.if(a,e=>{n().action.filename&&e(o)}),l.template_effect(()=>l.set_text(i,n().action.verb)),l.append(e,t)},p=e=>{var t=yb(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().phase.name)),l.append(e,t)};l.if(s,e=>{n().status===`ready`?e(c):n().status===`canceled`?e(u,1):n().status===`error`?e(d,2):n().action?e(f,3):n().phase&&e(p,4)}),l.reset(o);var m=l.sibling(o,2),h=e=>{var t=bb();ub(l.child(t),{}),l.reset(t),l.append(e,t)};l.if(m,e=>{n().status===`working`&&!n().toolOutcome&&!n().phase?.outcome&&e(h)}),l.reset(a);var g=l.sibling(a,2),_=e=>{var t=Sb(),i=l.child(t,!0),a=l.sibling(i),o=e=>{var t=xb();l.append(e,t)};l.if(a,e=>{n().status===`working`&&e(o)}),l.reset(t),l.template_effect(()=>l.set_text(i,r())),l.append(e,t)},v=e=>{var t=Cb();l.append(e,t)};l.if(g,e=>{r()&&!l.get(i)?e(_):n().status===`working`&&e(v,1)}),l.append(e,t)};return l.if(u,e=>{n().status===`idle`?e(d):e(f,-1)}),l.reset(s),l.template_effect(()=>c=l.set_class(s,1,`card svelte-qp0d57`,null,c,{terminal:l.get(i),failed:l.get(a)})),l.append(e,s),l.pop(o)}l.create_custom_element(Db,{activity:{},summaryText:{}},[],[],{mode:`open`});var Ob=e=>{switch(e.name){case`edit`:return`Editing`;case`write`:return`Writing`;case`read`:return`Reading`;case`bash`:return`Running`;default:return`Using tool`}},kb=(e,t)=>{let{status:n,startedAt:r,stoppedAt:i}=t,a,o,s;for(let t of e){let e=t;switch(e.type){case`AGENT_TOOL_STARTED`:{let{toolCallId:t,tool:n}=e.detail;a={tool:n.name,toolCallId:t,verb:Ob(n),filename:`path`in n?n.path:n.command},o=void 0;break}case`AGENT_TOOL_COMPLETED`:a?.toolCallId===e.detail.toolCallId&&(o=`success`);break;case`AGENT_TOOL_FAILED`:a?.toolCallId===e.detail.toolCallId&&(o=`failed`);break;case`AGENT_STARTED`:s={name:`agent`,outcome:void 0};break;case`AGENT_COMPLETED`:s={name:`agent`,outcome:`success`}}}let c;c=n===`READY`?`ready`:n===`CANCELED`?`canceled`:n===`ERROR`?`error`:a||s?`working`:`idle`;let l=r!=null&&i!=null?Math.max(0,Math.round((i-r)/1e3)):void 0;return{activity:c===`ready`?{status:c}:c===`canceled`?{status:c,elapsedSeconds:l}:{status:c,action:a,toolOutcome:o,phase:s}}},Ab=l.from_html(`<div class="panel pending svelte-rsawb0"><!> <span>Waiting for build to start</span></div>`),jb=l.from_html(`<div class="build-log svelte-rsawb0"><!></div>`),Mb={hash:`svelte-rsawb0`,code:`.build-log.svelte-rsawb0 {display:flex;gap:0.5rem;flex-direction:column;width:100%;}.panel.svelte-rsawb0 {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.pending.svelte-rsawb0 {display:flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:500;}`};function Nb(e,t){l.push(t,!0),l.append_styles(e,Mb);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.derived(()=>Qg(n()).store),a=l.derived(()=>db(l.get(i).spriteBuildEvent.filter(`build-log:${r().id}`,e=>e.spriteBuildId===r().id))),o=l.derived(()=>l.get(a)._),s=l.derived(()=>l.get(o).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-100)),c=l.derived(()=>r().status),u=l.derived(()=>kb(l.get(s),r())),d=l.derived(()=>r().reasoningSummary??void 0),f=l.derived(()=>l.get(c)===`PENDING`);var p={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()}},m=jb(),h=l.child(m),g=e=>{var t=Ab();ub(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)},_=e=>{Db(e,{get activity(){return l.get(u).activity},get summaryText(){return l.get(d)}})};return l.if(h,e=>{l.get(f)?e(g):e(_,-1)}),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(Nb,{client:{},spriteBuild:{}},[],[],{mode:`open`});var Pb=100,Fb=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Ib=e=>{let t=Math.round(e*Pb*10)/10;return Math.abs(t)<Pb?`${t.toFixed(1)}c`:Fb.format(e)},Lb=e=>e.toLowerCase().split(/[_-]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),Rb=e=>{switch(e.name){case`edit`:case`read`:case`write`:return`${e.name} ${e.path}`;case`bash`:return e.command;default:return`tool call`}},zb=e=>{switch(e?.name){case`bash`:return`command`;case`read`:case`edit`:case`write`:return`path`;default:return`plain`}},Bb=e=>{let t=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:2}),{tokens:n}=e.detail;return[`${e.detail.provider}/${e.detail.model}`,`${t.format(n.input)} input`,`${t.format(n.output)} output`,`${t.format(n.cacheRead)} cache read`,`${t.format(n.cacheWrite)} cache write`,`${t.format(n.total)} total`,Ib(e.detail.estimatedCostUsd)].join(` · `)},Vb=e=>{if(!(!e||typeof e!=`object`)){if(`message`in e&&typeof e.message==`string`)return e.message;if(`error`in e&&e.error&&typeof e.error==`object`){let t=Vb(e.error);if(t)return t}if(`url`in e&&typeof e.url==`string`)return e.url;if(`command`in e&&typeof e.command==`string`)return e.command}},Hb=e=>{let t=new Map,n=new Map,r=new Map;return e.map(e=>{let i=e,a,o=`plain`,s=`neutral`;switch(i.type){case`STEP_STARTED`:a=Lb(i.detail.stepName),o=`xml-open`,s=`active`;break;case`STEP_COMPLETED`:a=Lb(i.detail.stepName),o=`xml-close`,s=`success`;break;case`STEP_FAILED`:a=Vb(i.detail.error)??Lb(i.detail.stepName),s=`error`;break;case`EXEC_STARTED`:n.set(i.detail.execId,{command:i.detail.command,cwd:i.detail.cwd}),a=i.detail.command,o=`command`,s=`active`;break;case`EXEC_COMPLETED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`success`;break;case`EXEC_FAILED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`error`;break;case`FETCH_STARTED`:r.set(i.detail.fetchId,{url:i.detail.url}),a=i.detail.url,s=`active`;break;case`FETCH_COMPLETED`:a=r.get(i.detail.fetchId)?.url,s=`success`;break;case`FETCH_FAILED`:{let e=r.get(i.detail.fetchId);a=Vb(i.detail.error)??e?.url,s=`error`;break}case`AGENT_STARTED`:s=`active`;break;case`AGENT_COMPLETED`:s=`success`;break;case`AGENT_USAGE`:a=Bb(i),s=`neutral`;break;case`AGENT_TOOL_STARTED`:t.set(i.detail.toolCallId,i.detail.tool),a=Rb(i.detail.tool),o=zb(i.detail.tool),s=`active`;break;case`AGENT_TOOL_COMPLETED`:{let e=t.get(i.detail.toolCallId);a=e?Rb(e):i.detail.toolCallId,o=zb(e),s=`success`;break}case`AGENT_TOOL_FAILED`:{let e=t.get(i.detail.toolCallId);a=e?Rb(e):i.detail.toolCallId,o=zb(e),s=`error`;break}case`AGENT_META`:a=i.detail.message,s=`neutral`;break;case`AGENT_MESSAGE`:a=i.detail.message,s=`neutral`;break;case`AGENT_THOUGHT`:a=i.detail.message,s=`neutral`;break;default:a=Vb(e.detail),s=`neutral`}return{id:e.id,actionedAt:e.actionedAt,type:e.type,detailText:a,detailStyle:o,tone:s}})},Ub=l.from_html(`<div class="polling-indicator svelte-5iw9fb"><!> <span>Live</span></div>`),Wb=l.from_html(`<div class="panel state-panel empty-panel svelte-5iw9fb"><div class="state-title svelte-5iw9fb"><!></div> <div class="state-detail"><!></div></div>`),Gb=l.from_html(`<code class="svelte-5iw9fb"><strong class="svelte-5iw9fb"> </strong> </code>`),Kb=l.from_html(`<code class="svelte-5iw9fb"> </code>`),qb=l.from_html(`<div><!></div>`),Jb=l.from_html(`<span class="event-detail-empty svelte-5iw9fb">—</span>`),Yb=l.from_html(`<li><time class="event-date svelte-5iw9fb"> </time> <div class="event-type-cell svelte-5iw9fb"><span class="event-type svelte-5iw9fb"> </span></div> <div class="event-detail-cell svelte-5iw9fb"><!></div></li>`),Xb=l.from_html(`<ol class="event-list svelte-5iw9fb"></ol>`),Zb=l.from_html(`<div class="detailed-build-log svelte-5iw9fb" aria-live="polite"><div class="header svelte-5iw9fb"><div><div class="eyebrow svelte-5iw9fb">Detailed logs</div> <div class="title svelte-5iw9fb">Build event stream</div></div> <!></div> <!></div>`),Qb={hash:`svelte-5iw9fb`,code:`.detailed-build-log.svelte-5iw9fb {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-card-foreground, oklch(0.145 0 0));}.header.svelte-5iw9fb {display:flex;align-items:center;justify-content:space-between;gap:1rem;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 1rem;background:var(--rough-muted, oklch(0.97 0 0));}.eyebrow.svelte-5iw9fb {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.title.svelte-5iw9fb {margin-top:0.15rem;color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.polling-indicator.svelte-5iw9fb {display:inline-flex;align-items:center;gap:0.45rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:999px;padding:0.15rem 0.55rem;background:var(--rough-background, white);color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;font-weight:600;}.panel.svelte-5iw9fb {padding:0.85rem 1rem;}.state-panel.svelte-5iw9fb {display:flex;gap:0.35rem;flex-direction:column;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.state-title.svelte-5iw9fb {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.event-list.svelte-5iw9fb {display:grid;grid-template-columns:minmax(7.5rem, auto) minmax(12rem, auto) minmax(0, 1fr);margin:0;padding:0;list-style:none;}.event.svelte-5iw9fb {display:contents;}.event-date.svelte-5iw9fb,
|
|
63
|
+
}`};function Ux(e,t){u.push(t,!0),u.append_styles(e,Hx);let n=u.prop(t,`activity`,7),r=u.prop(t,`summaryText`,7),i=u.derived(()=>n().status===`ready`||n().status===`error`||n().status===`canceled`),a=u.derived(()=>n().status===`error`||n().toolOutcome===`failed`||n().phase?.outcome===`failed`);var o={get activity(){return n()},set activity(e){n(e),u.flush()},get summaryText(){return r()},set summaryText(e){r(e),u.flush()}},s=Vx();let c;var l=u.child(s),d=e=>{var t=Ox();u.append(e,t)},f=e=>{var t=Bx(),a=u.first_child(t),o=u.child(a),s=u.child(o),c=e=>{var t=kx();u.append(e,t)},l=e=>{var t=jx(),r=u.sibling(u.child(t),2),i=e=>{var t=Ax(),r=u.only_child(t);u.template_effect(()=>u.set_text(r,`after ${n().elapsedSeconds??``} ${n().elapsedSeconds===1?`second`:`seconds`}`)),u.append(e,t)};u.if(r,e=>{n().elapsedSeconds!=null&&e(i)}),u.reset(t),u.append(e,t)},d=e=>{var t=Mx();u.append(e,t)},f=e=>{var t=Px(),r=u.first_child(t),i=u.only_child(r,!0),a=u.sibling(r,2),o=e=>{var t=Nx(),r=u.only_child(t,!0);u.template_effect(()=>u.set_text(r,n().action.filename)),u.append(e,t)};u.if(a,e=>{n().action.filename&&e(o)}),u.template_effect(()=>u.set_text(i,n().action.verb)),u.append(e,t)},p=e=>{var t=Fx(),r=u.only_child(t,!0);u.template_effect(()=>u.set_text(r,n().phase.name)),u.append(e,t)};u.if(s,e=>{n().status===`ready`?e(c):n().status===`canceled`?e(l,1):n().status===`error`?e(d,2):n().action?e(f,3):n().phase&&e(p,4)}),u.reset(o);var m=u.sibling(o,2),h=e=>{var t=Ix();Ex(u.child(t),{}),u.reset(t),u.append(e,t)};u.if(m,e=>{n().status===`working`&&!n().toolOutcome&&!n().phase?.outcome&&e(h)}),u.reset(a);var g=u.sibling(a,2),_=e=>{var t=Rx(),i=u.child(t,!0),a=u.sibling(i),o=e=>{var t=Lx();u.append(e,t)};u.if(a,e=>{n().status===`working`&&e(o)}),u.reset(t),u.template_effect(()=>u.set_text(i,r())),u.append(e,t)},v=e=>{var t=zx();u.append(e,t)};u.if(g,e=>{r()&&!u.get(i)?e(_):n().status===`working`&&e(v,1)}),u.append(e,t)};return u.if(l,e=>{n().status===`idle`?e(d):e(f,-1)}),u.reset(s),u.template_effect(()=>c=u.set_class(s,1,`card svelte-qp0d57`,null,c,{terminal:u.get(i),failed:u.get(a)})),u.append(e,s),u.pop(o)}u.create_custom_element(Ux,{activity:{},summaryText:{}},[],[],{mode:`open`});var Wx=e=>{switch(e.name){case`edit`:return`Editing`;case`write`:return`Writing`;case`read`:return`Reading`;case`bash`:return`Running`;default:return`Using tool`}},Gx=(e,t)=>{let{status:n,startedAt:r,stoppedAt:i}=t,a,o,s;for(let t of e){let e=t;switch(e.type){case`AGENT_TOOL_STARTED`:{let{toolCallId:t,tool:n}=e.detail;a={tool:n.name,toolCallId:t,verb:Wx(n),filename:`path`in n?n.path:n.command},o=void 0;break}case`AGENT_TOOL_COMPLETED`:a?.toolCallId===e.detail.toolCallId&&(o=`success`);break;case`AGENT_TOOL_FAILED`:a?.toolCallId===e.detail.toolCallId&&(o=`failed`);break;case`AGENT_STARTED`:s={name:`agent`,outcome:void 0};break;case`AGENT_COMPLETED`:s={name:`agent`,outcome:`success`}}}let c;c=n===`READY`?`ready`:n===`CANCELED`?`canceled`:n===`ERROR`?`error`:a||s?`working`:`idle`;let l=r!=null&&i!=null?Math.max(0,Math.round((i-r)/1e3)):void 0;return{activity:c===`ready`?{status:c}:c===`canceled`?{status:c,elapsedSeconds:l}:{status:c,action:a,toolOutcome:o,phase:s}}},Kx=u.from_html(`<div class="panel pending svelte-rsawb0"><!> <span>Waiting for build to start</span></div>`),qx=u.from_html(`<div class="build-log svelte-rsawb0"><!></div>`),Jx={hash:`svelte-rsawb0`,code:`.build-log.svelte-rsawb0 {display:flex;gap:0.5rem;flex-direction:column;width:100%;}.panel.svelte-rsawb0 {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.pending.svelte-rsawb0 {display:flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:500;}`};function Yx(e,t){u.push(t,!0),u.append_styles(e,Jx);let n=u.prop(t,`client`,7),r=u.prop(t,`spriteBuild`,7),i=u.derived(()=>K_(n()).store),a=u.derived(()=>Dx(u.get(i).spriteBuildEvent.filter(`build-log:${r().id}`,e=>e.spriteBuildId===r().id))),o=u.derived(()=>u.get(a)._),s=u.derived(()=>u.get(o).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-100)),c=u.derived(()=>r().status),l=u.derived(()=>Gx(u.get(s),r())),d=u.derived(()=>r().reasoningSummary??void 0),f=u.derived(()=>u.get(c)===`PENDING`);var p={get client(){return n()},set client(e){n(e),u.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),u.flush()}},m=qx(),h=u.child(m),g=e=>{var t=Kx();Ex(u.child(t),{}),u.next(2),u.reset(t),u.append(e,t)},_=e=>{Ux(e,{get activity(){return u.get(l).activity},get summaryText(){return u.get(d)}})};return u.if(h,e=>{u.get(f)?e(g):e(_,-1)}),u.reset(m),u.append(e,m),u.pop(p)}u.create_custom_element(Yx,{client:{},spriteBuild:{}},[],[],{mode:`open`});var Xx=100,Zx=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Qx=e=>{let t=Math.round(e*Xx*10)/10;return Math.abs(t)<Xx?`${t.toFixed(1)}c`:Zx.format(e)},$x=e=>e.toLowerCase().split(/[_-]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),eS=e=>{switch(e.name){case`edit`:case`read`:case`write`:return`${e.name} ${e.path}`;case`bash`:return e.command;default:return`tool call`}},tS=e=>{switch(e?.name){case`bash`:return`command`;case`read`:case`edit`:case`write`:return`path`;default:return`plain`}},nS=e=>{let t=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:2}),{tokens:n}=e.detail;return[`${e.detail.provider}/${e.detail.model}`,`${t.format(n.input)} input`,`${t.format(n.output)} output`,`${t.format(n.cacheRead)} cache read`,`${t.format(n.cacheWrite)} cache write`,`${t.format(n.total)} total`,Qx(e.detail.estimatedCostUsd)].join(` · `)},rS=e=>{if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`error`in e&&e.error&&typeof e.error==`object`){let t=rS(e.error);if(t)return t}if(`url`in e&&typeof e.url==`string`)return e.url;if(`command`in e&&typeof e.command==`string`)return e.command}},iS=e=>{let t=new Map,n=new Map,r=new Map;return e.map(e=>{let i=e,a,o=`plain`,s=`neutral`;switch(i.type){case`STEP_STARTED`:a=$x(i.detail.stepName),o=`xml-open`,s=`active`;break;case`STEP_COMPLETED`:a=$x(i.detail.stepName),o=`xml-close`,s=`success`;break;case`STEP_FAILED`:a=rS(i.detail.error)??$x(i.detail.stepName),s=`error`;break;case`EXEC_STARTED`:n.set(i.detail.execId,{command:i.detail.command,cwd:i.detail.cwd}),a=i.detail.command,o=`command`,s=`active`;break;case`EXEC_COMPLETED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`success`;break;case`EXEC_FAILED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`error`;break;case`FETCH_STARTED`:r.set(i.detail.fetchId,{url:i.detail.url}),a=i.detail.url,s=`active`;break;case`FETCH_COMPLETED`:a=r.get(i.detail.fetchId)?.url,s=`success`;break;case`FETCH_FAILED`:{let e=r.get(i.detail.fetchId);a=rS(i.detail.error)??e?.url,s=`error`;break}case`AGENT_STARTED`:s=`active`;break;case`AGENT_COMPLETED`:s=`success`;break;case`AGENT_USAGE`:a=nS(i),s=`neutral`;break;case`AGENT_TOOL_STARTED`:t.set(i.detail.toolCallId,i.detail.tool),a=eS(i.detail.tool),o=tS(i.detail.tool),s=`active`;break;case`AGENT_TOOL_COMPLETED`:{let e=t.get(i.detail.toolCallId);a=e?eS(e):i.detail.toolCallId,o=tS(e),s=`success`;break}case`AGENT_TOOL_FAILED`:{let e=t.get(i.detail.toolCallId);a=e?eS(e):i.detail.toolCallId,o=tS(e),s=`error`;break}case`AGENT_META`:a=i.detail.message,s=`neutral`;break;case`AGENT_MESSAGE`:a=i.detail.message,s=`neutral`;break;case`AGENT_THOUGHT`:a=i.detail.message,s=`neutral`;break;default:a=rS(e.detail),s=`neutral`}return{id:e.id,actionedAt:e.actionedAt,type:e.type,detailText:a,detailStyle:o,tone:s}})},aS=u.from_html(`<div class="polling-indicator svelte-5iw9fb"><!> <span>Live</span></div>`),oS=u.from_html(`<div class="panel state-panel empty-panel svelte-5iw9fb"><div class="state-title svelte-5iw9fb"><!></div> <div class="state-detail"><!></div></div>`),sS=u.from_html(`<code class="svelte-5iw9fb"><strong class="svelte-5iw9fb"> </strong> </code>`),cS=u.from_html(`<code class="svelte-5iw9fb"> </code>`),lS=u.from_html(`<div><!></div>`),uS=u.from_html(`<span class="event-detail-empty svelte-5iw9fb">—</span>`),dS=u.from_html(`<li><time class="event-date svelte-5iw9fb"> </time> <div class="event-type-cell svelte-5iw9fb"><span class="event-type svelte-5iw9fb"> </span></div> <div class="event-detail-cell svelte-5iw9fb"><!></div></li>`),fS=u.from_html(`<ol class="event-list svelte-5iw9fb"></ol>`),pS=u.from_html(`<div class="detailed-build-log svelte-5iw9fb" aria-live="polite"><div class="header svelte-5iw9fb"><div><div class="eyebrow svelte-5iw9fb">Detailed logs</div> <div class="title svelte-5iw9fb">Build event stream</div></div> <!></div> <!></div>`),mS={hash:`svelte-5iw9fb`,code:`.detailed-build-log.svelte-5iw9fb {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-card-foreground, oklch(0.145 0 0));}.header.svelte-5iw9fb {display:flex;align-items:center;justify-content:space-between;gap:1rem;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 1rem;background:var(--rough-muted, oklch(0.97 0 0));}.eyebrow.svelte-5iw9fb {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.title.svelte-5iw9fb {margin-top:0.15rem;color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.polling-indicator.svelte-5iw9fb {display:inline-flex;align-items:center;gap:0.45rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:999px;padding:0.15rem 0.55rem;background:var(--rough-background, white);color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;font-weight:600;}.panel.svelte-5iw9fb {padding:0.85rem 1rem;}.state-panel.svelte-5iw9fb {display:flex;gap:0.35rem;flex-direction:column;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.state-title.svelte-5iw9fb {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.event-list.svelte-5iw9fb {display:grid;grid-template-columns:minmax(7.5rem, auto) minmax(12rem, auto) minmax(0, 1fr);margin:0;padding:0;list-style:none;}.event.svelte-5iw9fb {display:contents;}.event-date.svelte-5iw9fb,
|
|
64
64
|
.event-type-cell.svelte-5iw9fb,
|
|
65
65
|
.event-detail-cell.svelte-5iw9fb {border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding-top:0.85rem;padding-bottom:0.85rem;}.event-date.svelte-5iw9fb {padding-left:1rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;}.event-type-cell.svelte-5iw9fb,
|
|
66
66
|
.event-detail-cell.svelte-5iw9fb {min-width:0;}.event-detail-cell.svelte-5iw9fb {padding-right:1rem;}.event.svelte-5iw9fb:first-child .event-date:where(.svelte-5iw9fb),
|
|
@@ -89,21 +89,32 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
|
|
|
89
89
|
@media (max-width: 720px) {.event-list.svelte-5iw9fb {grid-template-columns:1fr;column-gap:0;}.event.svelte-5iw9fb {display:block;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 0;}.event.svelte-5iw9fb:first-child {border-top:none;}.event-date.svelte-5iw9fb,
|
|
90
90
|
.event-type-cell.svelte-5iw9fb,
|
|
91
91
|
.event-detail-cell.svelte-5iw9fb {display:block;border-top:none;padding-top:0;padding-right:1rem;padding-bottom:0;padding-left:1rem;}.event-type-cell.svelte-5iw9fb {margin-top:0.35rem;}.event-detail-cell.svelte-5iw9fb {margin-top:0.55rem;}
|
|
92
|
-
}`};function $b(e,t){l.push(t,!0),l.append_styles(e,Qb);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.prop(t,`eventList`,7),a=l.derived(()=>Qg(n()).store),o=l.derived(()=>r().status),s=l.derived(()=>db(l.get(a).spriteBuildEvent.filter(`detailed-build-log:${r().id}`,e=>e.spriteBuildId===r().id))),c=l.derived(()=>l.get(s)._),u=l.derived(()=>(i()??l.get(c)).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-500)),d=l.derived(()=>Hb(l.get(u))),f=l.derived(()=>l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`),p=e=>new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`,second:`2-digit`}).format(new Date(e)),m=e=>{let t=e.trim(),n=t.match(/^(\S+)(?:\s+(.*))?$/);return n?{head:n[1]??t,tail:n[2]??``}:{head:t,tail:``}};var h={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()},get eventList(){return i()},set eventList(e){i(e),l.flush()}},g=Zb(),_=l.child(g),v=l.sibling(l.child(_),2),y=e=>{var t=Ub();ub(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)};l.if(v,e=>{l.get(f)&&e(y)}),l.reset(_);var b=l.sibling(_,2),ee=e=>{var t=Wb(),n=l.child(t),r=l.child(n),i=e=>{var t=l.text(`Waiting for the build to emit logs`);l.append(e,t)},a=e=>{var t=l.text(`No build events yet`);l.append(e,t)};l.if(r,e=>{l.get(o)===`PENDING`?e(i):e(a,-1)}),l.reset(n);var s=l.sibling(n,2),c=l.child(s),u=e=>{var t=l.text(`Events will appear here as the build progresses.`);l.append(e,t)},d=e=>{var t=l.text(`This build did not record any events.`);l.append(e,t)};l.if(c,e=>{l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`?e(u):e(d,-1)}),l.reset(s),l.reset(t),l.append(e,t)},x=e=>{var t=Xb();l.each(t,21,()=>l.get(d),e=>e.id,(e,t)=>{var n=Yb(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=l.child(a),s=l.child(o,!0);l.reset(o),l.reset(a);var c=l.sibling(a,2),u=l.child(c),d=e=>{var n=qb();let r;var i=l.child(n),a=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Gb(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},o=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Gb(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},s=e=>{var n=Kb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`<${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},c=e=>{var n=Kb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`</${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},u=e=>{var n=l.text();l.template_effect(()=>l.set_text(n,l.get(t).detailText)),l.append(e,n)};l.if(i,e=>{l.get(t).detailStyle===`command`?e(a):l.get(t).detailStyle===`path`?e(o,1):l.get(t).detailStyle===`xml-open`?e(s,2):l.get(t).detailStyle===`xml-close`?e(c,3):e(u,-1)}),l.reset(n),l.template_effect(()=>r=l.set_class(n,1,`event-detail svelte-5iw9fb`,null,r,{"event-detail-xml":l.get(t).detailStyle===`xml-open`||l.get(t).detailStyle===`xml-close`,"event-detail-command":l.get(t).detailStyle===`command`,"event-detail-path":l.get(t).detailStyle===`path`})),l.append(e,n)},f=e=>{var t=Jb();l.append(e,t)};l.if(u,e=>{l.get(t).detailText?e(d):e(f,-1)}),l.reset(c),l.reset(n),l.template_effect((e,a)=>{l.set_class(n,1,`event tone-${l.get(t).tone}`,`svelte-5iw9fb`),l.set_attribute(r,`datetime`,e),l.set_text(i,a),l.set_text(s,l.get(t).type)},[()=>new Date(l.get(t).actionedAt).toISOString(),()=>p(l.get(t).actionedAt)]),l.append(e,n)}),l.reset(t),l.append(e,t)};return l.if(b,e=>{l.get(d).length===0?e(ee):e(x,-1)}),l.reset(g),l.append(e,g),l.pop(h)}l.create_custom_element($b,{client:{},spriteBuild:{},eventList:{}},[],[],{mode:`open`});var ex=l.from_html(`<p class="detail svelte-elh43j"> </p>`),tx=l.from_html(`<div class="error svelte-elh43j"><div class="error-label svelte-elh43j">Error</div> <div class="error-detail svelte-elh43j"> </div></div>`),nx=l.from_html(`<div class="overlay svelte-elh43j" role="dialog" aria-modal="true" aria-labelledby="confirm-overlay-title"><div class="panel svelte-elh43j"><h4 id="confirm-overlay-title" class="title svelte-elh43j"> </h4> <!> <!> <div class="actions svelte-elh43j"><!></div></div></div>`),rx={hash:`svelte-elh43j`,code:`.overlay.svelte-elh43j {position:absolute;inset:0;z-index:10;display:flex;align-items:center;justify-content:center;background:rgb(0 0 0 / 0.5);}.panel.svelte-elh43j {display:flex;gap:0.75rem;flex-direction:column;width:min(28rem, 90%);border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:1.5rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.title.svelte-elh43j {margin:0;color:var(--rough-card-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.detail.svelte-elh43j {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;}.error.svelte-elh43j {border:1px solid color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 30%, transparent);border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 10%, var(--rough-card, white));}.error-label.svelte-elh43j {color:var(--rough-destructive, oklch(0.577 0.245 27.325));font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.error-detail.svelte-elh43j {margin-top:0.25rem;color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;}.actions.svelte-elh43j {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}`};function ix(e,t){l.push(t,!0),l.append_styles(e,rx);let n=l.prop(t,`title`,7),r=l.prop(t,`detail`,7),i=l.prop(t,`error`,7),a=l.prop(t,`actions`,7);var o={get title(){return n()},set title(e){n(e),l.flush()},get detail(){return r()},set detail(e){r(e),l.flush()},get error(){return i()},set error(e){i(e),l.flush()},get actions(){return a()},set actions(e){a(e),l.flush()}},s=nx(),c=l.child(s),u=l.child(c),d=l.child(u,!0);l.reset(u);var f=l.sibling(u,2),p=e=>{var t=ex(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,r())),l.append(e,t)};l.if(f,e=>{r()&&e(p)});var m=l.sibling(f,2),h=e=>{var t=tx(),n=l.sibling(l.child(t),2),r=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(()=>l.set_text(r,i().message)),l.append(e,t)};l.if(m,e=>{i()&&e(h)});var g=l.sibling(m,2),_=l.child(g);return l.snippet(_,a),l.reset(g),l.reset(c),l.reset(s),l.template_effect(()=>l.set_text(d,n())),l.append(e,s),l.pop(o)}l.create_custom_element(ix,{title:{},detail:{},error:{},actions:{}},[],[],{mode:`open`});var ax=e=>{let{client:t,spriteId:n,toolList:r,getSpriteBuildEventList:i,onStartBuild:a,onMessagesChange:o,onLoadingChange:s,onErrorChange:c}=e,l,u=Fm.client(()=>r.map(e=>e.toJSON())),d=Lm.client(e=>a(e,l.getMessages())),f=Im.client(({spriteBuildId:e})=>[...i(e)]);return l=new Kv({threadId:n,persistence:!0,connection:q_(()=>Qg(t).buildUrl({path:`/api/v1/project/${encodeURIComponent(t.projectId)}/chat`}),async()=>({headers:{Authorization:`Bearer ${(await Qg(t).auth.getSessionToken()).token}`}})),tools:[u,f,d],queue:`drop`,onMessagesChange:e=>o([...e]),onLoadingChange:s,onErrorChange:c}),l},ox=l.from_html(`<button type="button" role="tab"> </button>`),sx=l.from_html(`<footer class="MobileTabBar svelte-17gs0md"><div class="tabs svelte-17gs0md" role="tablist"></div></footer>`),cx={hash:`svelte-17gs0md`,code:`.MobileTabBar.svelte-17gs0md {display:none;flex:none;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.5rem 0.75rem calc(0.5rem + env(safe-area-inset-bottom));background:var(--rough-card, white);}.tabs.svelte-17gs0md {display:grid;grid-template-columns:repeat(var(--mobile-tab-count, 3), minmax(0, 1fr));gap:0.125rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-17gs0md {appearance:none;height:2.25rem;min-width:0;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.5rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;line-height:1;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
92
|
+
}`};function hS(e,t){u.push(t,!0),u.append_styles(e,mS);let n=u.prop(t,`client`,7),r=u.prop(t,`spriteBuild`,7),i=u.prop(t,`eventList`,7),a=u.derived(()=>K_(n()).store),o=u.derived(()=>r().status),s=u.derived(()=>Dx(u.get(a).spriteBuildEvent.filter(`detailed-build-log:${r().id}`,e=>e.spriteBuildId===r().id))),c=u.derived(()=>u.get(s)._),l=u.derived(()=>(i()??u.get(c)).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-500)),d=u.derived(()=>iS(u.get(l))),f=u.derived(()=>u.get(o)===`PENDING`||u.get(o)===`IN_PROGRESS`),p=e=>new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`,second:`2-digit`}).format(new Date(e)),m=e=>{let t=e.trim(),n=t.match(/^(\S+)(?:\s+(.*))?$/);return n?{head:n[1]??t,tail:n[2]??``}:{head:t,tail:``}};var h={get client(){return n()},set client(e){n(e),u.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),u.flush()},get eventList(){return i()},set eventList(e){i(e),u.flush()}},g=pS(),_=u.child(g),v=u.sibling(u.child(_),2),y=e=>{var t=aS();Ex(u.child(t),{}),u.next(2),u.reset(t),u.append(e,t)};u.if(v,e=>{u.get(f)&&e(y)}),u.reset(_);var b=u.sibling(_,2),x=e=>{var t=oS(),n=u.child(t),r=u.child(n),i=e=>{var t=u.text(`Waiting for the build to emit logs`);u.append(e,t)},a=e=>{var t=u.text(`No build events yet`);u.append(e,t)};u.if(r,e=>{u.get(o)===`PENDING`?e(i):e(a,-1)}),u.reset(n);var s=u.sibling(n,2),c=u.child(s),l=e=>{var t=u.text(`Events will appear here as the build progresses.`);u.append(e,t)},d=e=>{var t=u.text(`This build did not record any events.`);u.append(e,t)};u.if(c,e=>{u.get(o)===`PENDING`||u.get(o)===`IN_PROGRESS`?e(l):e(d,-1)}),u.reset(s),u.reset(t),u.append(e,t)},S=e=>{var t=fS();u.each(t,21,()=>u.get(d),e=>e.id,(e,t)=>{var n=dS(),r=u.child(n),i=u.only_child(r,!0),a=u.sibling(r,2),o=u.child(a),s=u.only_child(o,!0);u.reset(a);var c=u.sibling(a,2),l=u.child(c),d=e=>{var n=lS();let r;var i=u.child(n),a=e=>{let n=u.derived(()=>m(u.get(t).detailText));var r=sS(),i=u.child(r),a=u.only_child(i,!0),o=u.sibling(i,1,!0);u.reset(r),u.template_effect(()=>{u.set_text(a,u.get(n).head),u.set_text(o,u.get(n).tail?` ${u.get(n).tail}`:``)}),u.append(e,r)},o=e=>{let n=u.derived(()=>m(u.get(t).detailText));var r=sS(),i=u.child(r),a=u.only_child(i,!0),o=u.sibling(i,1,!0);u.reset(r),u.template_effect(()=>{u.set_text(a,u.get(n).head),u.set_text(o,u.get(n).tail?` ${u.get(n).tail}`:``)}),u.append(e,r)},s=e=>{var n=cS(),r=u.only_child(n);u.template_effect(e=>u.set_text(r,`<${e??``}>`),[()=>u.get(t).detailText.replaceAll(` `,``)]),u.append(e,n)},c=e=>{var n=cS(),r=u.only_child(n);u.template_effect(e=>u.set_text(r,`</${e??``}>`),[()=>u.get(t).detailText.replaceAll(` `,``)]),u.append(e,n)},l=e=>{var n=u.text();u.template_effect(()=>u.set_text(n,u.get(t).detailText)),u.append(e,n)};u.if(i,e=>{u.get(t).detailStyle===`command`?e(a):u.get(t).detailStyle===`path`?e(o,1):u.get(t).detailStyle===`xml-open`?e(s,2):u.get(t).detailStyle===`xml-close`?e(c,3):e(l,-1)}),u.reset(n),u.template_effect(()=>r=u.set_class(n,1,`event-detail svelte-5iw9fb`,null,r,{"event-detail-xml":u.get(t).detailStyle===`xml-open`||u.get(t).detailStyle===`xml-close`,"event-detail-command":u.get(t).detailStyle===`command`,"event-detail-path":u.get(t).detailStyle===`path`})),u.append(e,n)},f=e=>{var t=uS();u.append(e,t)};u.if(l,e=>{u.get(t).detailText?e(d):e(f,-1)}),u.reset(c),u.reset(n),u.template_effect((e,a)=>{u.set_class(n,1,`event tone-${u.get(t).tone}`,`svelte-5iw9fb`),u.set_attribute(r,`datetime`,e),u.set_text(i,a),u.set_text(s,u.get(t).type)},[()=>new Date(u.get(t).actionedAt).toISOString(),()=>p(u.get(t).actionedAt)]),u.append(e,n)}),u.reset(t),u.append(e,t)};return u.if(b,e=>{u.get(d).length===0?e(x):e(S,-1)}),u.reset(g),u.append(e,g),u.pop(h)}u.create_custom_element(hS,{client:{},spriteBuild:{},eventList:{}},[],[],{mode:`open`});var gS=u.from_html(`<p class="detail svelte-elh43j"> </p>`),_S=u.from_html(`<div class="error svelte-elh43j"><div class="error-label svelte-elh43j">Error</div> <div class="error-detail svelte-elh43j"> </div></div>`),vS=u.from_html(`<div class="overlay svelte-elh43j" role="dialog" aria-modal="true" aria-labelledby="confirm-overlay-title"><div class="panel svelte-elh43j"><h4 id="confirm-overlay-title" class="title svelte-elh43j"> </h4> <!> <!> <div class="actions svelte-elh43j"><!></div></div></div>`),yS={hash:`svelte-elh43j`,code:`.overlay.svelte-elh43j {position:absolute;inset:0;z-index:10;display:flex;align-items:center;justify-content:center;background:rgb(0 0 0 / 0.5);}.panel.svelte-elh43j {display:flex;gap:0.75rem;flex-direction:column;width:min(28rem, 90%);border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:1.5rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.title.svelte-elh43j {margin:0;color:var(--rough-card-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.detail.svelte-elh43j {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;}.error.svelte-elh43j {border:1px solid color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 30%, transparent);border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 10%, var(--rough-card, white));}.error-label.svelte-elh43j {color:var(--rough-destructive, oklch(0.577 0.245 27.325));font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.error-detail.svelte-elh43j {margin-top:0.25rem;color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;}.actions.svelte-elh43j {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}`};function bS(e,t){u.push(t,!0),u.append_styles(e,yS);let n=u.prop(t,`title`,7),r=u.prop(t,`detail`,7),i=u.prop(t,`error`,7),a=u.prop(t,`actions`,7);var o={get title(){return n()},set title(e){n(e),u.flush()},get detail(){return r()},set detail(e){r(e),u.flush()},get error(){return i()},set error(e){i(e),u.flush()},get actions(){return a()},set actions(e){a(e),u.flush()}},s=vS(),c=u.child(s),l=u.child(c),d=u.only_child(l,!0),f=u.sibling(l,2),p=e=>{var t=gS(),n=u.only_child(t,!0);u.template_effect(()=>u.set_text(n,r())),u.append(e,t)};u.if(f,e=>{r()&&e(p)});var m=u.sibling(f,2),h=e=>{var t=_S(),n=u.sibling(u.child(t),2),r=u.only_child(n,!0);u.reset(t),u.template_effect(()=>u.set_text(r,i().message)),u.append(e,t)};u.if(m,e=>{i()&&e(h)});var g=u.sibling(m,2),_=u.child(g);return u.snippet(_,a),u.reset(g),u.reset(c),u.reset(s),u.template_effect(()=>u.set_text(d,n())),u.append(e,s),u.pop(o)}u.create_custom_element(bS,{title:{},detail:{},error:{},actions:{}},[],[],{mode:`open`});var xS=e=>{let{client:t,spriteId:n,toolList:r,getSpriteBuildEventList:i,onStartBuild:a,onMessagesChange:o,onLoadingChange:s,onErrorChange:c}=e,l,u=Eh.client(()=>r.map(e=>e.toJSON())),d=Oh.client(()=>a(l.getMessages())),f=Dh.client(({spriteBuildId:e})=>[...i(e)]);return l=new cb({threadId:n,persistence:!0,connection:ay(()=>K_(t).buildUrl({path:`/api/v1/project/${encodeURIComponent(t.projectId)}/chat`}),async()=>({headers:{Authorization:`Bearer ${(await K_(t).auth.getSessionToken()).token}`}})),tools:[u,f,d],queue:`drop`,onMessagesChange:e=>o([...e]),onLoadingChange:s,onErrorChange:c}),l},SS=e=>{switch(e.split(`/`).at(0)){case`image`:return Ef.IMAGE;case`video`:return Ef.VIDEO;case`audio`:return Ef.AUDIO;default:return Ef.OTHER}},CS=b(((e,t)=>{t.exports={}})),wS=b((e=>{(function(e){e.parser=function(e,t){return new n(e,t)},e.SAXParser=n,e.SAXStream=u,e.createStream=c,e.MAX_BUFFER_LENGTH=65536;var t=[`comment`,`sgmlDecl`,`textNode`,`tagName`,`doctype`,`procInstName`,`procInstBody`,`entity`,`attribName`,`attribValue`,`cdata`,`script`];e.EVENTS=[`text`,`processinginstruction`,`sgmldeclaration`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`opencdata`,`cdata`,`closecdata`,`error`,`end`,`ready`,`script`,`opennamespace`,`closenamespace`];function n(t,r){if(!(this instanceof n))return new n(t,r);var a=this;i(a),a.q=a.c=``,a.bufferCheckPosition=e.MAX_BUFFER_LENGTH,a.encoding=null,a.opt=r||{},a.opt.lowercase=a.opt.lowercase||a.opt.lowercasetags,a.looseCase=a.opt.lowercase?`toLowerCase`:`toUpperCase`,a.opt.maxEntityCount=a.opt.maxEntityCount||512,a.opt.maxEntityDepth=a.opt.maxEntityDepth||4,a.entityCount=a.entityDepth=0,a.tags=[],a.closed=a.closedRoot=a.sawRoot=!1,a.tag=a.error=null,a.strict=!!t,a.noscript=!!(t||a.opt.noscript),a.state=w.BEGIN,a.strictEntities=a.opt.strictEntities,a.ENTITIES=a.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),a.attribList=[],a.opt.xmlns&&(a.ns=Object.create(h)),a.opt.unquotedAttributeValues===void 0&&(a.opt.unquotedAttributeValues=!t),a.trackPosition=a.opt.position!==!1,a.trackPosition&&(a.position=a.line=a.column=0),ne(a,`onready`)}Object.create||(Object.create=function(e){function t(){}return t.prototype=e,new t}),Object.keys||(Object.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t});function r(n){for(var r=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,a=0,o=t.length;a<o;a++){var s=n[t[a]].length;if(s>r)switch(t[a]){case`textNode`:D(n);break;case`cdata`:E(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:E(n,`onscript`,n.script),n.script=``;break;default:k(n,`Max buffer length exceeded: `+t[a])}i=Math.max(i,s)}n.bufferCheckPosition=e.MAX_BUFFER_LENGTH-i+n.position}function i(e){for(var n=0,r=t.length;n<r;n++)e[t[n]]=``}function a(e){D(e),e.cdata!==``&&(E(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(E(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){oe(this)},write:he,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var o;try{o=CS().Stream}catch{o=function(){}}o||=function(){};var s=e.EVENTS.filter(function(e){return e!==`error`&&e!==`end`});function c(e,t){return new u(e,t)}function l(e,t){if(e.length>=2){if(e[0]===255&&e[1]===254)return`utf-16le`;if(e[0]===254&&e[1]===255)return`utf-16be`}return e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?`utf8`:e.length>=4?e[0]===60&&e[1]===0&&e[2]===63&&e[3]===0?`utf-16le`:e[0]===0&&e[1]===60&&e[2]===0&&e[3]===63?`utf-16be`:`utf8`:t?`utf8`:null}function u(e,t){if(!(this instanceof u))return new u(e,t);o.apply(this),this._parser=new n(e,t),this.writable=!0,this.readable=!0;var r=this;this._parser.onend=function(){r.emit(`end`)},this._parser.onerror=function(e){r.emit(`error`,e),r._parser.error=null},this._decoder=null,this._decoderBuffer=null,s.forEach(function(e){Object.defineProperty(r,`on`+e,{get:function(){return r._parser[`on`+e]},set:function(t){if(!t)return r.removeAllListeners(e),r._parser[`on`+e]=t,t;r.on(e,t)},enumerable:!0,configurable:!1})})}u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype._decodeBuffer=function(e,t){if(this._decoderBuffer&&=(e=Buffer.concat([this._decoderBuffer,e]),null),!this._decoder){var n=l(e,t);if(!n)return this._decoderBuffer=e,``;this._parser.encoding=n,this._decoder=new TextDecoder(n)}return this._decoder.decode(e,{stream:!t})},u.prototype.write=function(e){if(typeof Buffer==`function`&&typeof Buffer.isBuffer==`function`&&Buffer.isBuffer(e))e=this._decodeBuffer(e,!1);else if(this._decoderBuffer){var t=this._decodeBuffer(Buffer.alloc(0),!0);t&&(this._parser.write(t),this.emit(`data`,t))}return this._parser.write(e.toString()),this.emit(`data`,e),!0},u.prototype.end=function(e){if(e&&e.length&&this.write(e),this._decoderBuffer){var t=this._decodeBuffer(Buffer.alloc(0),!0);t&&(this._parser.write(t),this.emit(`data`,t))}else if(this._decoder){var n=this._decoder.decode();n&&(this._parser.write(n),this.emit(`data`,n))}return this._parser.end(),!0},u.prototype.on=function(e,t){var n=this;return!n._parser[`on`+e]&&s.indexOf(e)!==-1&&(n._parser[`on`+e]=function(){var t=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),o.prototype.on.call(n,e,t)};var d=/^\[CDATA\[$/i,f=/^DOCTYPE$/i,p=`http://www.w3.org/XML/1998/namespace`,m=`http://www.w3.org/2000/xmlns/`,h={xml:p,xmlns:m},g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,_=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function b(e){return e===` `||e===`
|
|
93
|
+
`||e===`\r`||e===` `}function x(e){return e===`"`||e===`'`}function S(e){return e===`>`||b(e)}function C(e,t){return e.test(t)}function ee(e,t){return!C(e,t)}var w=0;for(var te in e.STATE={BEGIN:w++,BEGIN_WHITESPACE:w++,TEXT:w++,TEXT_ENTITY:w++,OPEN_WAKA:w++,SGML_DECL:w++,SGML_DECL_QUOTED:w++,DOCTYPE:w++,DOCTYPE_QUOTED:w++,DOCTYPE_DTD:w++,DOCTYPE_DTD_QUOTED:w++,COMMENT_STARTING:w++,COMMENT:w++,COMMENT_ENDING:w++,COMMENT_ENDED:w++,CDATA:w++,CDATA_ENDING:w++,CDATA_ENDING_2:w++,PROC_INST:w++,PROC_INST_BODY:w++,PROC_INST_ENDING:w++,OPEN_TAG:w++,OPEN_TAG_SLASH:w++,ATTRIB:w++,ATTRIB_NAME:w++,ATTRIB_NAME_SAW_WHITE:w++,ATTRIB_VALUE:w++,ATTRIB_VALUE_QUOTED:w++,ATTRIB_VALUE_CLOSED:w++,ATTRIB_VALUE_UNQUOTED:w++,ATTRIB_VALUE_ENTITY_Q:w++,ATTRIB_VALUE_ENTITY_U:w++,CLOSE_TAG:w++,CLOSE_TAG_SAW_WHITE:w++,SCRIPT:w++,SCRIPT_ENDING:w++},e.XML_ENTITIES=Object.assign(Object.create(null),{amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`}),e.ENTITIES=Object.assign(Object.create(null),{amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`,AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830}),Object.keys(e.ENTITIES).forEach(function(t){var n=e.ENTITIES[t],r=typeof n==`number`?String.fromCharCode(n):n;e.ENTITIES[t]=r}),e.STATE)e.STATE[e.STATE[te]]=te;w=e.STATE;function ne(e,t,n){e[t]&&e[t](n)}function re(e){var t=e&&e.match(/(?:^|\s)encoding\s*=\s*(['"])([^'"]+)\1/i);return t?t[2]:null}function ie(e){return e?e.toLowerCase().replace(/[^a-z0-9]/g,``):null}function T(e,t){let n=ie(e),r=ie(t);return!n||!r?!0:r===`utf16`?n===`utf16le`||n===`utf16be`:n===r}function ae(e,t){if(e.strict&&e.encoding&&t&&t.name===`xml`){var n=re(t.body);n&&!T(e.encoding,n)&&A(e,`XML declaration encoding `+n+` does not match detected stream encoding `+e.encoding.toUpperCase())}}function E(e,t,n){e.textNode&&D(e),ne(e,t,n)}function D(e){e.textNode=O(e.opt,e.textNode),e.textNode&&ne(e,`ontext`,e.textNode),e.textNode=``}function O(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g,` `)),t}function k(e,t){return D(e),e.trackPosition&&(t+=`
|
|
94
|
+
Line: `+e.line+`
|
|
95
|
+
Column: `+e.column+`
|
|
96
|
+
Char: `+e.c),t=Error(t),e.error=t,ne(e,`onerror`,t),e}function oe(e){return e.sawRoot&&!e.closedRoot&&A(e,`Unclosed root tag`),e.state!==w.BEGIN&&e.state!==w.BEGIN_WHITESPACE&&e.state!==w.TEXT&&k(e,`Unexpected end`),D(e),e.c=``,e.closed=!0,ne(e,`onend`),n.call(e,e.strict,e.opt),e}function A(e,t){if(typeof e!=`object`||!(e instanceof n))throw Error(`bad call to strictFail`);e.strict&&k(e,t)}function se(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,n=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(n.ns=t.ns),e.attribList.length=0,E(e,`onopentagstart`,n)}function ce(e,t){var n=e.indexOf(`:`)<0?[``,e]:e.split(`:`),r=n[0],i=n[1];return t&&e===`xmlns`&&(r=`xmlns`,i=``),{prefix:r,local:i}}function le(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),e.attribList.indexOf(e.attribName)!==-1||e.tag.attributes.hasOwnProperty(e.attribName)){e.attribName=e.attribValue=``;return}if(e.opt.xmlns){var t=ce(e.attribName,!0),n=t.prefix,r=t.local;if(n===`xmlns`){if(r===`xml`&&e.attribValue!==p)A(e,`xml: prefix must be bound to `+p+`
|
|
97
|
+
Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==m)A(e,`xmlns: prefix must be bound to `+m+`
|
|
98
|
+
Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,E(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function j(e,t){if(e.opt.xmlns){var n=e.tag,r=ce(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(A(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){E(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=ce(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(A(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,E(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),E(e,`onopentag`,e.tag),t||(e.state=!e.noscript&&e.tagName.toLowerCase()===`script`?w.SCRIPT:w.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function ue(e){if(!e.tagName){A(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=w.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=w.SCRIPT;return}E(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)A(e,`Unexpected close tag`);if(t<0){A(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=w.TEXT;return}e.tagName=n;for(var i=e.tags.length;i-->t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,E(e,`onclosetag`,e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var n=a.ns[t];E(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=w.TEXT}function de(e){var t=e.entity,n=t.toLowerCase(),r,i=``;return e.ENTITIES[t]?e.ENTITIES[t]:e.ENTITIES[n]?e.ENTITIES[n]:(t=n,t.charAt(0)===`#`&&(t.charAt(1)===`x`?(t=t.slice(2),r=parseInt(t,16),i=r.toString(16)):(t=t.slice(1),r=parseInt(t,10),i=r.toString(10))),t=t.replace(/^0+/,``),isNaN(r)||i.toLowerCase()!==t||r<0||r>1114111||!fe(r)?(A(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function fe(e){return e===9||e===10||e===13||e>=32&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}function pe(e,t){t===`<`?(e.state=w.OPEN_WAKA,e.startTagPosition=e.position):b(t)||(A(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=w.TEXT)}function me(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function he(t){var n=this;if(this.error)throw this.error;if(n.closed)return k(n,`Cannot write after close. Assign an onready handler.`);if(t===null)return oe(n);typeof t==`object`&&(t=t.toString());for(var i=0,a=``;a=me(t,i++),n.c=a,a;)switch(n.trackPosition&&(n.position++,a===`
|
|
99
|
+
`?(n.line++,n.column=0):n.column++),n.state){case w.BEGIN:if(n.state=w.BEGIN_WHITESPACE,a===``)continue;pe(n,a);continue;case w.BEGIN_WHITESPACE:pe(n,a);continue;case w.TEXT:if(n.sawRoot&&!n.closedRoot){for(var o=i-1;a&&a!==`<`&&a!==`&`;)a=me(t,i++),a&&n.trackPosition&&(n.position++,a===`
|
|
100
|
+
`?(n.line++,n.column=0):n.column++);n.textNode+=t.substring(o,i-1)}a===`<`&&!(n.sawRoot&&n.closedRoot&&!n.strict)?(n.state=w.OPEN_WAKA,n.startTagPosition=n.position):(!b(a)&&(!n.sawRoot||n.closedRoot)&&A(n,`Text data outside of root node.`),a===`&`?n.state=w.TEXT_ENTITY:n.textNode+=a);continue;case w.SCRIPT:a===`<`?n.state=w.SCRIPT_ENDING:n.script+=a;continue;case w.SCRIPT_ENDING:a===`/`?n.state=w.CLOSE_TAG:(n.script+=`<`+a,n.state=w.SCRIPT);continue;case w.OPEN_WAKA:if(a===`!`)n.state=w.SGML_DECL,n.sgmlDecl=``;else if(!b(a)){if(C(g,a))n.state=w.OPEN_TAG,n.tagName=a;else if(a===`/`)n.state=w.CLOSE_TAG,n.tagName=``;else if(a===`?`)n.state=w.PROC_INST,n.procInstName=n.procInstBody=``;else{if(A(n,`Unencoded <`),n.startTagPosition+1<n.position){var s=n.position-n.startTagPosition;a=Array(s).join(` `)+a}n.textNode+=`<`+a,n.state=w.TEXT}}continue;case w.SGML_DECL:if(n.sgmlDecl+a===`--`){n.state=w.COMMENT,n.comment=``,n.sgmlDecl=``;continue}n.doctype&&n.doctype!==!0&&n.sgmlDecl?(n.state=w.DOCTYPE_DTD,n.doctype+=`<!`+n.sgmlDecl+a,n.sgmlDecl=``):d.test(n.sgmlDecl+a)?(E(n,`onopencdata`),n.state=w.CDATA,n.sgmlDecl=``,n.cdata=``):f.test(n.sgmlDecl+a)?(n.state=w.DOCTYPE,(n.doctype||n.sawRoot)&&A(n,`Inappropriately located doctype declaration`),n.doctype=``,n.sgmlDecl=``):a===`>`?(E(n,`onsgmldeclaration`,n.sgmlDecl),n.sgmlDecl=``,n.state=w.TEXT):(x(a)&&(n.state=w.SGML_DECL_QUOTED),n.sgmlDecl+=a);continue;case w.SGML_DECL_QUOTED:a===n.q&&(n.state=w.SGML_DECL,n.q=``),n.sgmlDecl+=a;continue;case w.DOCTYPE:a===`>`?(n.state=w.TEXT,E(n,`ondoctype`,n.doctype),n.doctype=!0):(n.doctype+=a,a===`[`?n.state=w.DOCTYPE_DTD:x(a)&&(n.state=w.DOCTYPE_QUOTED,n.q=a));continue;case w.DOCTYPE_QUOTED:n.doctype+=a,a===n.q&&(n.q=``,n.state=w.DOCTYPE);continue;case w.DOCTYPE_DTD:a===`]`?(n.doctype+=a,n.state=w.DOCTYPE):a===`<`?(n.state=w.OPEN_WAKA,n.startTagPosition=n.position):x(a)?(n.doctype+=a,n.state=w.DOCTYPE_DTD_QUOTED,n.q=a):n.doctype+=a;continue;case w.DOCTYPE_DTD_QUOTED:n.doctype+=a,a===n.q&&(n.state=w.DOCTYPE_DTD,n.q=``);continue;case w.COMMENT:a===`-`?n.state=w.COMMENT_ENDING:n.comment+=a;continue;case w.COMMENT_ENDING:a===`-`?(n.state=w.COMMENT_ENDED,n.comment=O(n.opt,n.comment),n.comment&&E(n,`oncomment`,n.comment),n.comment=``):(n.comment+=`-`+a,n.state=w.COMMENT);continue;case w.COMMENT_ENDED:a===`>`?n.state=n.doctype&&n.doctype!==!0?w.DOCTYPE_DTD:w.TEXT:(A(n,`Malformed comment`),n.comment+=`--`+a,n.state=w.COMMENT);continue;case w.CDATA:for(var o=i-1;a&&a!==`]`;)a=me(t,i++),a&&n.trackPosition&&(n.position++,a===`
|
|
101
|
+
`?(n.line++,n.column=0):n.column++);n.cdata+=t.substring(o,i-1),a===`]`&&(n.state=w.CDATA_ENDING);continue;case w.CDATA_ENDING:a===`]`?n.state=w.CDATA_ENDING_2:(n.cdata+=`]`+a,n.state=w.CDATA);continue;case w.CDATA_ENDING_2:a===`>`?(n.cdata&&E(n,`oncdata`,n.cdata),E(n,`onclosecdata`),n.cdata=``,n.state=w.TEXT):a===`]`?n.cdata+=`]`:(n.cdata+=`]]`+a,n.state=w.CDATA);continue;case w.PROC_INST:a===`?`?n.state=w.PROC_INST_ENDING:b(a)?n.state=w.PROC_INST_BODY:n.procInstName+=a;continue;case w.PROC_INST_BODY:if(!n.procInstBody&&b(a))continue;a===`?`?n.state=w.PROC_INST_ENDING:n.procInstBody+=a;continue;case w.PROC_INST_ENDING:if(a===`>`){let e={name:n.procInstName,body:n.procInstBody};ae(n,e),E(n,`onprocessinginstruction`,e),n.procInstName=n.procInstBody=``,n.state=w.TEXT}else n.procInstBody+=`?`+a,n.state=w.PROC_INST_BODY;continue;case w.OPEN_TAG:C(_,a)?n.tagName+=a:(se(n),a===`>`?j(n):a===`/`?n.state=w.OPEN_TAG_SLASH:(b(a)||A(n,`Invalid character in tag name`),n.state=w.ATTRIB));continue;case w.OPEN_TAG_SLASH:a===`>`?(j(n,!0),ue(n)):(A(n,`Forward-slash in opening tag not followed by >`),n.state=w.ATTRIB);continue;case w.ATTRIB:if(b(a))continue;a===`>`?j(n):a===`/`?n.state=w.OPEN_TAG_SLASH:C(g,a)?(n.attribName=a,n.attribValue=``,n.state=w.ATTRIB_NAME):A(n,`Invalid attribute name`);continue;case w.ATTRIB_NAME:a===`=`?n.state=w.ATTRIB_VALUE:a===`>`?(A(n,`Attribute without value`),n.attribValue=n.attribName,le(n),j(n)):b(a)?n.state=w.ATTRIB_NAME_SAW_WHITE:C(_,a)?n.attribName+=a:A(n,`Invalid attribute name`);continue;case w.ATTRIB_NAME_SAW_WHITE:if(a===`=`)n.state=w.ATTRIB_VALUE;else if(b(a))continue;else A(n,`Attribute without value`),n.tag.attributes[n.attribName]=``,n.attribValue=``,E(n,`onattribute`,{name:n.attribName,value:``}),n.attribName=``,a===`>`?j(n):C(g,a)?(n.attribName=a,n.state=w.ATTRIB_NAME):(A(n,`Invalid attribute name`),n.state=w.ATTRIB);continue;case w.ATTRIB_VALUE:if(b(a))continue;x(a)?(n.q=a,n.state=w.ATTRIB_VALUE_QUOTED):(n.opt.unquotedAttributeValues||k(n,`Unquoted attribute value`),n.state=w.ATTRIB_VALUE_UNQUOTED,n.attribValue=a);continue;case w.ATTRIB_VALUE_QUOTED:if(a!==n.q){a===`&`?n.state=w.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=a;continue}le(n),n.q=``,n.state=w.ATTRIB_VALUE_CLOSED;continue;case w.ATTRIB_VALUE_CLOSED:b(a)?n.state=w.ATTRIB:a===`>`?j(n):a===`/`?n.state=w.OPEN_TAG_SLASH:C(g,a)?(A(n,`No whitespace between attributes`),n.attribName=a,n.attribValue=``,n.state=w.ATTRIB_NAME):A(n,`Invalid attribute name`);continue;case w.ATTRIB_VALUE_UNQUOTED:if(!S(a)){a===`&`?n.state=w.ATTRIB_VALUE_ENTITY_U:n.attribValue+=a;continue}le(n),a===`>`?j(n):n.state=w.ATTRIB;continue;case w.CLOSE_TAG:if(n.tagName)a===`>`?ue(n):C(_,a)?n.tagName+=a:n.script?(n.script+=`</`+n.tagName+a,n.tagName=``,n.state=w.SCRIPT):(b(a)||A(n,`Invalid tagname in closing tag`),n.state=w.CLOSE_TAG_SAW_WHITE);else{if(b(a))continue;ee(g,a)?n.script?(n.script+=`</`+a,n.state=w.SCRIPT):A(n,`Invalid tagname in closing tag.`):n.tagName=a}continue;case w.CLOSE_TAG_SAW_WHITE:if(b(a))continue;a===`>`?ue(n):A(n,`Invalid characters in closing tag`);continue;case w.TEXT_ENTITY:case w.ATTRIB_VALUE_ENTITY_Q:case w.ATTRIB_VALUE_ENTITY_U:var c,l;switch(n.state){case w.TEXT_ENTITY:c=w.TEXT,l=`textNode`;break;case w.ATTRIB_VALUE_ENTITY_Q:c=w.ATTRIB_VALUE_QUOTED,l=`attribValue`;break;case w.ATTRIB_VALUE_ENTITY_U:c=w.ATTRIB_VALUE_UNQUOTED,l=`attribValue`}if(a===`;`){var u=de(n);n.opt.unparsedEntities&&!Object.values(e.XML_ENTITIES).includes(u)?((n.entityCount+=1)>n.opt.maxEntityCount&&k(n,`Parsed entity count exceeds max entity count`),(n.entityDepth+=1)>n.opt.maxEntityDepth&&k(n,`Parsed entity depth exceeds max entity depth`),n.entity=``,n.state=c,n.write(u),--n.entityDepth):(n[l]+=u,n.entity=``,n.state=c)}else C(n.entity.length?y:v,a)?n.entity+=a:(A(n,`Invalid character in entity name`),n[l]+=`&`+n.entity+a,n.entity=``,n.state=c);continue;default:throw Error(n,`Unknown state: `+n.state)}return n.position>=n.bufferCheckPosition&&r(n),n}String.fromCodePoint||(function(){var e=String.fromCharCode,t=Math.floor,n=function(){var n=16384,r=[],i,a,o=-1,s=arguments.length;if(!s)return``;for(var c=``;++o<s;){var l=Number(arguments[o]);if(!isFinite(l)||l<0||l>1114111||t(l)!==l)throw RangeError(`Invalid code point: `+l);l<=65535?r.push(l):(l-=65536,i=(l>>10)+55296,a=l%1024+56320,r.push(i,a)),(o+1===s||r.length>n)&&(c+=e.apply(null,r),r.length=0)}return c};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:n,configurable:!0,writable:!0}):String.fromCodePoint=n})()})(e===void 0?e.sax={}:e)}));function TS(e){let t=e.replace(/\s+/g,` `).trim(),n,r=t,i=t.indexOf(`[`);i!==-1&&t.endsWith(`]`)&&(r=t.slice(0,i).trim(),n=t.slice(i+1,-1).trim());let a=/^([^\s]+)\b/.exec(r)?.[1],o=/\bPUBLIC\s+(?:'([^']*)'|"([^"]*)")\s+(?:'([^']*)'|"([^"]*)")/i,s=/\bSYSTEM\s+(?:'([^']*)'|"([^"]*)")/i,c=o.exec(r);if(c)return{raw:e,name:a,kind:`PUBLIC`,publicId:c[1]??c[2]??``,systemId:c[3]??c[4]??``,internalSubset:n};let l=s.exec(r);return l?{raw:e,name:a,kind:`SYSTEM`,systemId:l[1]??l[2]??``,internalSubset:n}:{raw:e,name:a,kind:`UNKNOWN`,internalSubset:n}}var ES=C(wS(),1);function DS(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function OS(e){return/^<\s*\w+(?=\s+[^<>]*=|>)/.test(e)}function kS(e,t){return OS(new TextDecoder(t).decode(e))}function AS(e){if(DS(e,[60,63,120,109,108,32]))return{xml:!0,encoding:`utf-8`,offset:0};if(DS(e,[239,187,191])){let t=`utf-8`;if(DS(e.subarray(3),[60,63,120,109,108,32])||kS(e,t))return{xml:!0,encoding:t,offset:3}}if(DS(e,[254,255])){let t=`utf-16be`;if(DS(e.subarray(2),[0,60,0,63,0,120,0,109,0,108,0,32])||kS(e,t))return{xml:!0,encoding:t,offset:2}}if(DS(e,[255,254])){let t=`utf-16le`;if(DS(e.subarray(2),[60,0,63,0,120,0,109,0,108,0,32,0])||kS(e,t))return{xml:!0,encoding:t,offset:2}}return DS(e,[0,60,0,63,0,120,0,109,0,108,0,32])?{xml:!0,encoding:`utf-16be`,offset:0}:DS(e,[60,0,63,0,120,0,109,0,108,0,32,0])?{xml:!0,encoding:`utf-16le`,offset:0}:kS(e,`utf-8`)?{xml:!0,encoding:`utf-8`,offset:0}:{xml:!1}}var jS={docBook:{ext:`dbk`,mime:`application/docbook+xml`},gpx:{ext:`gpx`,mime:`application/gpx+xml`},musicXml:{ext:`musicxml`,mime:`application/vnd.recordare.musicxml+xml`},plist:{ext:`plist`,mime:`application/x-plist`},smil:{ext:`smil`,mime:`application/smil+xml`},svg:{ext:`svg`,mime:`image/svg+xml`},x3d:{ext:`x3d`,mime:`model/x3d+xml`}},MS={"http://www.w3.org/2000/svg":jS.svg,"http://www.w3.org/1999/xhtml":{ext:`xhtml`,mime:`application/xhtml+xml`},"http://www.opengis.net/kml/2.2":{ext:`kml`,mime:`application/vnd.google-earth.kml+xml`},"http://www.opengis.net/gml":{ext:`gml`,mime:`application/gml+xml`},"http://www.w3.org/ns/ttml":{ext:`ttml`,mime:`application/ttml+xml`},"http://www.w3.org/2001/SMIL20/Language":jS.smil,"http://www.w3.org/2005/Atom":{ext:`atom`,mime:`application/atom+xml`},"urn:oasis:names:tc:xliff:document:2.0":{ext:`xlf`,mime:`application/xliff+xml`},"http://docbook.org/ns/docbook":jS.docBook,"http://www.tei-c.org/ns/1.0":{ext:`tei`,mime:`application/tei+xml`},"http://www.w3.org/1998/Math/MathML":{ext:`mml`,mime:`application/mathml+xml`},"http://www.topografix.com/GPX/1/0":jS.gpx,"http://www.topografix.com/GPX/1/1":jS.gpx},NS={opml:{ext:`opml`,mime:`text/x-opml`},plist:jS.plist,rss:{ext:`rss`,mime:`application/rss+xml`},"score-partwise":jS.musicXml,smil:jS.smil,svg:jS.svg},PS={"-//OASIS//DTD DocBook XML V4.0//EN":jS.docBook,"-//OASIS//DTD DocBook XML V4.1//EN":jS.docBook,"-//OASIS//DTD DocBook XML V4.2//EN":jS.docBook,"-//OASIS//DTD DocBook XML V4.3//EN":jS.docBook,"-//OASIS//DTD DocBook XML V4.4//EN":jS.docBook,"-//OASIS//DTD DocBook XML V4.5//EN":jS.docBook,"-//Recordare//DTD MusicXML 4.0 Partwise//EN":jS.musicXml,"-//Apple//DTD PLIST 1.0//EN":jS.plist,"ISO//Web3D//DTD X3D 3.3//EN":jS.x3d},FS=class{constructor(e){this.options=e??{},this.firstTag=!0,this.onEnd=!1,this.parser=ES.default.parser(!0,{xmlns:!0}),this.nesting=0,this.parser.onerror=e=>{e.message.startsWith(`Invalid character entity`)||(this.fileType=void 0,this.onEnd=!0)},this.parser.onopentag=e=>{++this.nesting,this.firstTag&&!this.onEnd&&(this.firstTag=!1,e.uri?this.fileType=MS[e.uri]:e.name&&(this.fileType=NS[e.name.toLowerCase()]),this.fileType&&!this.options.fullScan&&(this.onEnd=!0))},this.parser.ondoctype=e=>{if(this.fileType||this.onEnd)return;let t=TS(e);t.kind===`PUBLIC`&&t.publicId&&(this.fileType=PS[t.publicId],this.fileType&&!this.options.fullScan&&(this.onEnd=!0))},this.parser.onclosetag=()=>{--this.nesting}}write(e){this.parser.write(e)}close(){this.parser.close(),this.onEnd=!0}isValid(){return this.nesting===0}},IS={id:`xml`,detect:async e=>{let t=new Uint8Array(512);await e.peekBuffer(t,{length:128,mayBeLess:!0});let n=AS(t);if(n.xml){await e.ignore(n.offset);let r=new FS,i=new TextDecoder(n.encoding);do{let n=await e.readBuffer(t,{mayBeLess:!0}),a=t.subarray(0,n),o=i.decode(a);r.write(o),n<t.length&&r.close()}while(!r.onEnd);return r.fileType??{ext:`xml`,mime:`application/xml`}}}},LS=e=>{let t=!1,n;return()=>t?n:(n=e(),t=!0,n)},RS={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},zS={};for(let[e,t]of Object.entries(RS))zS[t]=Number.parseInt(e,10);var BS;function VS(){if(globalThis.TextDecoder!==void 0)return BS??=new globalThis.TextDecoder(`utf-8`)}var HS=32768,US=65533;function WS(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=VS();return t?t.decode(e):qS(e)}case`utf-16le`:return JS(e);case`us-ascii`:case`ascii`:return YS(e);case`latin1`:case`iso-8859-1`:return XS(e);case`windows-1252`:return ZS(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function GS(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function X(e,t,n){t.push(n),t.length>=HS&&GS(e,t)}function KS(e,t,n){if(n<=65535){X(e,t,n);return}n-=65536,X(e,t,55296+(n>>10)),X(e,t,56320+(n&1023))}function qS(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){X(t,n,i),r++;continue}if(i<194||i>244){X(t,n,US),r++;continue}if(i<=223){if(r+1>=e.length){X(t,n,US),r++;continue}let a=e[r+1];if((a&192)!=128){X(t,n,US),r++;continue}X(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){X(t,n,US),r++;continue}let a=e[r+1],o=e[r+2];if((a&192)!=128||(o&192)!=128||i===224&&a<160||i===237&&a>=160){X(t,n,US),r++;continue}X(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){X(t,n,US),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if((a&192)!=128||(o&192)!=128||(s&192)!=128||i===240&&a<144||i===244&&a>143){X(t,n,US),r++;continue}KS(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return GS(t,n),t.join(``)}function JS(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(X(t,n,a),X(t,n,r),i+=2):X(t,n,US)}else X(t,n,US);continue}if(a>=56320&&a<=57343){X(t,n,US);continue}X(t,n,a)}return i<r&&X(t,n,US),GS(t,n),t.join(``)}function YS(e){let t=[];for(let n=0;n<e.length;n+=HS){let r=Math.min(e.length,n+HS),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function XS(e){let t=[];for(let n=0;n<e.length;n+=HS){let r=Math.min(e.length,n+HS),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function ZS(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?RS[i]:void 0;n+=a??String.fromCharCode(i),n.length>=HS&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function QS(e){return new DataView(e.buffer,e.byteOffset)}var $S={len:1,get(e,t){return QS(e).getUint8(t)},put(e,t,n){return QS(e).setUint8(t,n),t+1}},Z={len:2,get(e,t){return QS(e).getUint16(t,!0)},put(e,t,n){return QS(e).setUint16(t,n,!0),t+2}},eC={len:2,get(e,t){return QS(e).getUint16(t)},put(e,t,n){return QS(e).setUint16(t,n),t+2}},Q={len:4,get(e,t){return QS(e).getUint32(t,!0)},put(e,t,n){return QS(e).setUint32(t,n,!0),t+4}},tC={len:4,get(e,t){return QS(e).getUint32(t)},put(e,t,n){return QS(e).setUint32(t,n),t+4}},nC={len:4,get(e,t){return QS(e).getInt32(t)},put(e,t,n){return QS(e).setInt32(t,n),t+4}},rC={len:8,get(e,t){return QS(e).getBigUint64(t,!0)},put(e,t,n){return QS(e).setBigUint64(t,n,!0),t+8}},iC=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return WS(e.subarray(t,t+this.len),this.encoding)}},aC=`End-Of-Stream`,$=class extends Error{constructor(){super(aC),this.name=`EndOfStreamError`}},oC=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},sC=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new $;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new oC;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new $;return n}},cC=class extends sC{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},lC=class extends cC{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},uC=class extends sC{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),this.buffer=n<t.length?t.subarray(n):null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new $;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function dC(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new uC(t):new lC(t)}catch(t){if(t instanceof TypeError)return new uC(e.getReader());throw t}}var fC=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new $;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new $;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new $;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new $;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},pC=256e3,mC=class extends fC{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new $;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof $)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new $}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(pC,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},hC=class extends fC{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new $;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},gC=class extends fC{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new $;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function _C(e,t){let n=dC(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new mC(n,r)}function vC(e,t){return new hC(e,t)}function yC(e,t){return new gC(e,t)}var bC=b(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),xC=b(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=bC(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),SC=b(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=xC()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),CC={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},wC={get(e){return{signature:Q.get(e,0),compressedSize:Q.get(e,8),uncompressedSize:Q.get(e,12)}},len:16},TC={get(e){let t=Z.get(e,6);return{signature:Q.get(e,0),minVersion:Z.get(e,4),dataDescriptor:!!(t&8),compressedMethod:Z.get(e,8),compressedSize:Q.get(e,18),uncompressedSize:Q.get(e,22),filenameLength:Z.get(e,26),extraFieldLength:Z.get(e,28),filename:null}},len:30},EC={get(e){return{signature:Q.get(e,0),nrOfThisDisk:Z.get(e,4),nrOfThisDiskWithTheStart:Z.get(e,6),nrOfEntriesOnThisDisk:Z.get(e,8),nrOfEntriesOfSize:Z.get(e,10),sizeOfCd:Q.get(e,12),offsetOfStartOfCd:Q.get(e,16),zipFileCommentLength:Z.get(e,20)}},len:22},DC={get(e){let t=Z.get(e,8);return{signature:Q.get(e,0),minVersion:Z.get(e,6),dataDescriptor:!!(t&8),compressedMethod:Z.get(e,10),compressedSize:Q.get(e,20),uncompressedSize:Q.get(e,24),filenameLength:Z.get(e,28),extraFieldLength:Z.get(e,30),fileCommentLength:Z.get(e,32),relativeOffsetOfLocalHeader:Q.get(e,42),filename:null}},len:46},OC=C(SC(),1);function kC(e){let t=new Uint8Array(Q.len);return Q.put(t,0,e),t}var AC=(0,OC.default)(`tokenizer:inflate`),jC=262144,MC=kC(CC.DataDescriptor),NC=kC(CC.EndOfCentralDirectory),PC=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(jC)}async isZip(){return await this.peekSignature()===CC.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(Q)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===NC[0]&&n[r+1]===NC[1]&&n[r+2]===NC[2]&&n[r+3]===NC[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){AC(`Cannot reading central-directory without random-read support`);return}AC(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){AC(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(EC,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(DC);if(t.signature!==CC.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new iC(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),AC(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=jC;AC(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===jC;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=FC(this.syncBuffer.subarray(0,n),MC);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}AC(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,IC(e),r.handler)}else r.handler?(AC(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(AC(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(AC(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(wC)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-wC.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return AC(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(Q);if(e===CC.LocalFileHeader){let e=await this.tokenizer.readToken(TC);return e.filename=await this.tokenizer.readToken(new iC(e.filenameLength,`utf-8`)),e}if(e===CC.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function FC(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function IC(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var LC=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}},RC=Object.prototype.toString,zC=`[object Uint8Array]`;function BC(e,t,n){return e?e.constructor===t||RC.call(e)===n:!1}function VC(e){return BC(e,Uint8Array,zC)}function HC(e){if(!VC(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function UC(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)HC(t),n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function WC(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function GC(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function KC(e,t=0){let n=Number.parseInt(new iC(6).get(e,148).replace(RegExp(`\\0.*$`,`v`),``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}var qC={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},JC=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),YC=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),XC=16777216,ZC=class extends Error{};function QC(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new ZC(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function $C(e,t,{maximumLength:n=XC,reason:r=`skip`}={}){let i=QC(t,n,r);await e.ignore(i)}async function ew(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=QC(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function tw(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function nw(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function rw(e,t,n){return nw(e)&&e.position-t>n}var iw=1048576,aw=1024,ow=2**31-1,sw=iw,cw=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),lw=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],uw=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function dw(e,{maximumLength:t=iw}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel().catch(()=>{}),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}catch(e){if(e.code!==`ERR_TRAILING_JUNK_AFTER_STREAM_END`)throw e}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function fw(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function pw(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,ow)}function mw(e){if(e instanceof $||e instanceof ZC)return!0;if(!(e instanceof Error))return!1;if(cw.has(e.message)||uw.has(e.code))return!0;for(let t of lw)if(e.message.startsWith(t))return!0;return!1}function hw(e,t=iw){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function gw(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function _w(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function vw(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function yw(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`}}}function bw(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function xw(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function Sw(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function Cw(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return Sw(e)}function ww(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}var Tw=134695760,Ew=16,Dw=15;function Ow(e,t){if(e.length<Ew)return-1;let n=e.length-Ew;for(let r=0;r<=n;r++)if(Q.get(e,r)===Tw&&Q.get(e,r+8)===t+r)return r;return-1}async function kw(e,{shouldBuffer:t,maximumLength:n=iw}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=Ow(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(Dw,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(nw(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return fw(a,o)}function Aw(e,t){return nw(e.tokenizer)?Math.max(0,XC-(e.tokenizer.position-t)):Math.max(0,iw-e.knownSizeDescriptorScannedBytes)}async function jw(e,t,{shouldBuffer:n,maximumDescriptorLength:r=iw}={}){if(t.dataDescriptor&&t.compressedSize===0)return kw(e,{shouldBuffer:n,maximumLength:r});if(!n){await $C(e.tokenizer,t.compressedSize,{maximumLength:nw(e.tokenizer)?iw:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=pw(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}PC.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await dw(t,{maximumLength:iw}))},PC.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(rw(this.tokenizer,r,16777216))throw new ZC(`ZIP stream probing exceeds ${XC} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>aw)throw Error(`ZIP entry count exceeds ${aw}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await jw(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(iw,Aw(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(Ew);if(await this.tokenizer.readBuffer(e),Q.get(e,0)!==Tw)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(rw(this.tokenizer,r,16777216))throw new ZC(`ZIP stream probing exceeds ${XC} bytes`)}while(!t)};async function Mw(e){let t,n=bw(),r=gw();try{await new PC(e).unzip(e=>{if(xw(n,e.filename),_w(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=vw(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=Cw(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return hw(e,sw)?{async handler(e){t=yw(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,hw(e,sw)?(n.isParsingContentTypes=!0,{async handler(e){let r=ww(new TextDecoder(`utf-8`).decode(e));r&&(t=yw(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return RegExp(`classes\\d*\\.dex`,`v`).test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!mw(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof $&&!n.hasContentTypesEntry&&(t=Sw(n))}let i=nw(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:vw(r);return t??Cw(n)??i??{ext:`zip`,mime:`application/zip`}}var Nw=64,Pw=1048576,Fw=256;async function Iw(e){async function t(){let t=await e.peekNumber($S),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await ew(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:WC(i),len:WC(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>Fw||rw(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>Nw)return;let t=QC(o.len,Nw,`EBML DocType`);return(await e.readToken(new iC(t))).replaceAll(RegExp(`\\0.*$`,`gv`),``)}if(nw(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>Pw)||(await $C(e,o.len,{maximumLength:nw(e)?Pw:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`}}}var Lw=512,Rw=16777216,zw=1048576;function Bw(e){return!!(e.codePointAt(0)&32)}async function Vw(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(nC),type:await e.readToken(new iC(4,`latin1`))}}let i=nw(e),a=e.position,o=0,s=!1;do{if(o++,o>Lw||rw(e,a,Rw))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>zw)return s&&Bw(l.type)?t:void 0;try{await $C(e,l.length+4,{maximumLength:i?1048580:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof ZC||e instanceof $))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}var Hw=512,Uw=1048576;async function Ww(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await ew(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(rC))}}await $C(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=nw(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>Hw||rw(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(tw(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await ew(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),tw(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(tw(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>Uw){t=!0;break}if(await $C(e,o,{maximumLength:r?Uw:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof $||n instanceof ZC)nw(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}var Gw=4100,Kw=4096,qw=XC,Jw=1,Yw=100,Xw=XC,Zw=512,Qw=256,$w=1048576,eT=XC;function tT(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):Gw}function nT(e){return Number.isFinite(e)?Math.max(0,Math.min(Kw,Math.trunc(e))):0}function rT(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function iT(e){return import(e)}function aT(e){return e.pipeThrough(new TransformStream)}function oT(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function sT(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}var cT=class e{constructor(e){let t=nT(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return _C(aT(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof $||e instanceof ZC)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(vC(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=yC(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([iT(`node:fs/promises`),iT(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=tT(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await oT(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await oT(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:UC(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof $))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=Jw)return{ext:`gz`,mime:`application/gzip`};let n=sT(new LC(t).inflate(),qw),r=nw(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after ${Yw} ms`,`TimeoutError`))},Yw),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return tw(this.buffer,e,t)}checkString(e,t){return this.check(GC(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(Gw),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,nw(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=Qw?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await $C(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(qC),n=nw(e);if(!Number.isFinite(t)||t<0||n&&(t>Xw||e.position+t>Xw))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await $C(e,t,{maximumLength:n?Xw:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof $)return;throw e}return this.detectionReentryCount>=Qw?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return Mw(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),tw(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:tw(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:tw(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:tw(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:tw(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:tw(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return Iw(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=tC.get(this.buffer,4),t=eC.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new iC(4,`latin1`).get(this.buffer,2);if(RegExp(`^\\d+$`,`v`).test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new iC(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
102
|
+
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return Vw(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new iC(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
|
|
103
|
+
`))return{ext:`reg`,mime:`application/x-ms-regedit`};if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217]))return Ww(e);if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new iC(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.checkString(`<?xml `,{offset:2,encoding:`utf-16be`})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x-ms-shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x-ft-apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x-ft-fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(this.check([255,255,0,0,7,0,0,0,4,0,0,0,1,0,1,0])||this.check([0,0,255,255,0,0,0,7,0,0,0,4,0,1,0,1]))return{ext:`jmp`,mime:`application/x-jmp-data`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&KC(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254])){let e=`utf-16le`;return this.checkString(`<?xml `,{offset:2,encoding:e})?{ext:`xml`,mime:`application/xml`}:this.check([255,14],{offset:2})&&this.checkString(`SketchUp Model`,{offset:4,encoding:e})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:this.checkString(`Windows Registry Editor Version 5.00\r
|
|
104
|
+
`,{offset:2,encoding:e})?{ext:`reg`,mime:`application/x-ms-regedit`}:void 0}if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}};detectImprecise=async e=>{this.buffer=new Uint8Array(Gw);let t=rT(e.fileInfo.size);if(await e.peekBuffer(this.buffer,{length:Math.min(8,t),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(4+this.options.mpegOffsetTolerance,t),mayBeLess:!0}),this.buffer.length>=4+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?eC:Z);switch(await this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`}}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?eC:Z);if(!(t>Zw)&&!(nw(this.tokenizer)&&2+t*12>eT))for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t={ext:`tif`,mime:`image/tiff`},n=(e?eC:Z).get(this.buffer,2),r=(e?tC:Q).get(this.buffer,4);if(n===42){if(r>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(r>=8){let t=(e?eC:Z).get(this.buffer,8),n=(e?eC:Z).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}if(nw(this.tokenizer)&&r>$w)return t;let n=nw(this.tokenizer)?eT:this.tokenizer.fileInfo.size;try{await $C(this.tokenizer,r,{maximumLength:n,reason:`TIFF IFD offset`})}catch(e){if(e instanceof $)return;throw e}let i;try{i=await this.readTiffIFD(e)}catch(e){if(e instanceof $)return;throw e}return i??t}if(n===43)return t}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return{ext:`aac`,mime:`audio/aac`};if(this.check([255,254],{offset:e})||this.check([8],{offset:e+1,mask:[24]})||this.check([240],{offset:e+2,mask:[240]})||this.check([12],{offset:e+2,mask:[12]}))return;if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}};new Set(JC),new Set(YC);var lT=LS(()=>{try{return new ReadableStream({type:`bytes`,pull(e){e.close()}}).getReader({mode:`byob`}).releaseLock(),!0}catch{return!1}}),uT=e=>`arrayBuffer`in e?e.arrayBuffer():new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{t(r.result||new ArrayBuffer(0))},r.onerror=n,r.readAsArrayBuffer(e)}),dT=LS(()=>new cT({customDetectors:[IS]})),fT=e=>t(async()=>{let t=dT(),n=e.type,r;if(lT())r=await t.fromBlob(e);else{let n=await uT(e);r=await t.fromBuffer(n)}return r?n=r.mime:n||=`application/octet-stream`,n}),pT=typeof document<`u`,mT=async(e,t=e.type)=>{if(!pT)return Error(`Cannot extract metadata from video in Node.js.`);let n=URL.createObjectURL(e),r=document.createElement(`video`);if(await new Promise(e=>{if(!r)return e();r.preload=`metadata`,r.onloadedmetadata=()=>e(),r.onerror=()=>e(),r.src=n}),!r)return URL.revokeObjectURL(n),Error(`Failed to load video`);let i=r.videoWidth,a=r.videoHeight,o=r.duration;return r.remove(),r=void 0,URL.revokeObjectURL(n),{type:Ef.VIDEO,mimeType:t,width:i,height:a,duration:o}},hT=async(e,t=e.type)=>{if(!pT)return Error(`Cannot extract metadata from audio in Node.js.`);let n=URL.createObjectURL(e),r=document.createElement(`audio`);if(await new Promise(e=>{if(!r)return e();r.preload=`metadata`,r.onloadedmetadata=()=>e(),r.onerror=()=>e(),r.src=n}),!r)return URL.revokeObjectURL(n),Error(`Failed to load audio`);let i=Number.isFinite(r.duration)?r.duration:void 0;return r.remove(),r=void 0,URL.revokeObjectURL(n),{type:Ef.AUDIO,mimeType:t,duration:i}},gT=async(e,t=e.type)=>{if(!pT)return Error(`Cannot extract metadata from image in Node.js.`);let n=URL.createObjectURL(e),r=document.createElement(`img`);if(await new Promise(e=>{if(!r)return e();r.onload=()=>e(),r.onerror=()=>e(),r.src=n}),!r)return URL.revokeObjectURL(n),Error(`Failed to load image`);let i=r.naturalWidth,a=r.naturalHeight;return r.remove(),r=void 0,URL.revokeObjectURL(n),{type:Ef.IMAGE,mimeType:t,width:i,height:a}},_T=(e,t=e.type)=>Promise.resolve({type:Ef.OTHER,mimeType:t}),vT=async e=>{let t=await fT(e);if(t instanceof Error)return t;let n=SS(t);switch(n){case Ef.IMAGE:return gT(e,t);case Ef.VIDEO:return mT(e,t);case Ef.AUDIO:return hT(e,t);case Ef.OTHER:return _T(e,t);default:throw Error(`Unexpected asset type: ${n}`)}},yT=e.object({type:e.literal(null)}),bT={type:null},xT=e.object({type:e.literal(Ef.VIDEO),mimeType:e.optional(e.string()),duration:e.optional(e.number()),width:e.optional(e.number()),height:e.optional(e.number())}),ST=e.object({type:e.literal(Ef.AUDIO),mimeType:e.optional(e.string()),duration:e.optional(e.number())}),CT=e.object({type:e.literal(Ef.IMAGE),mimeType:e.optional(e.string()),width:e.optional(e.number()),height:e.optional(e.number())}),wT=e.object({type:e.literal(Ef.OTHER),mimeType:e.optional(e.string())});e.discriminatedUnion(`type`,[yT,xT,ST,CT,wT]);function TT(e){"@babel/helpers - typeof";return TT=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},TT(e)}function ET(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,OT(r.key),r)}}function DT(e,t,n){return t&&ET(e.prototype,t),n&&ET(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function OT(e){var t=kT(e,`string`);return TT(t)==`symbol`?t:t+``}function kT(e,t){if(TT(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(TT(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function AT(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function jT(e,t,n){return t=BT(t),MT(e,LT()?Reflect.construct(t,n||[],BT(e).constructor):t.apply(e,n))}function MT(e,t){if(t&&(TT(t)===`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return NT(e)}function NT(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function PT(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&zT(e,t)}function FT(e){var t=typeof Map==`function`?new Map:void 0;return FT=function(e){if(e===null||!RT(e))return e;if(typeof e!=`function`)throw TypeError(`Super expression must either be null or a function`);if(t!==void 0){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return IT(e,arguments,BT(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),zT(n,e)},FT(e)}function IT(e,t,n){if(LT())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&zT(i,n.prototype),i}function LT(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(LT=function(){return!!e})()}function RT(e){try{return Function.toString.call(e).indexOf(`[native code]`)!==-1}catch{return typeof e==`function`}}function zT(e,t){return zT=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},zT(e,t)}function BT(e){return BT=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},BT(e)}var VT=function(e){function t(e){var n,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(AT(this,t),n=jT(this,t,[e]),n.originalRequest=i,n.originalResponse=a,n.causingError=r,r!=null&&(e+=`, caused by ${r.toString()}`),i!=null){var o=i.getHeader(`X-Request-ID`)||`n/a`,s=i.getMethod(),c=i.getURL(),l=a?a.getStatus():`n/a`,u=a?a.getBody()||``:`n/a`;e+=`, originated from request (method: ${s}, url: ${c}, response code: ${l}, response text: ${u}, request id: ${o})`}return n.message=e,n}return PT(t,e),DT(t)}(FT(Error));function HT(e){"@babel/helpers - typeof";return HT=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},HT(e)}function UT(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function WT(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,KT(r.key),r)}}function GT(e,t,n){return t&&WT(e.prototype,t),n&&WT(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function KT(e){var t=qT(e,`string`);return HT(t)==`symbol`?t:t+``}function qT(e,t){if(HT(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(HT(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var JT=function(){function e(){UT(this,e)}return GT(e,[{key:`listAllUploads`,value:function(){return Promise.resolve([])}},{key:`findUploadsByFingerprint`,value:function(e){return Promise.resolve([])}},{key:`removeUpload`,value:function(e){return Promise.resolve()}},{key:`addUpload`,value:function(e,t){return Promise.resolve(null)}}])}(),YT=`3.9.3`,XT=YT,ZT=typeof TextDecoder==`function`?new TextDecoder(`utf-8`,{ignoreBOM:!0}):void 0,QT=typeof TextEncoder==`function`?new TextEncoder:void 0,$T=Array.prototype.slice.call(`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`),eE=(e=>{let t={};return e.forEach((e,n)=>t[e]=n),t})($T),tE=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,nE=String.fromCharCode.bind(String),rE=typeof Uint8Array.from==`function`?Uint8Array.from.bind(Uint8Array):e=>new Uint8Array(Array.prototype.slice.call(e,0)),iE=e=>e.replace(/=/g,``).replace(/[+\/]/g,e=>e==`+`?`-`:`_`),aE=e=>e.replace(/[^A-Za-z0-9\+\/]/g,``),oE=e=>{let t,n,r,i,a=``,o=e.length%3;for(let o=0;o<e.length;){if((n=e.charCodeAt(o++))>255||(r=e.charCodeAt(o++))>255||(i=e.charCodeAt(o++))>255)throw TypeError(`invalid character found`);t=n<<16|r<<8|i,a+=$T[t>>18&63]+$T[t>>12&63]+$T[t>>6&63]+$T[t&63]}return o?a.slice(0,o-3)+`===`.substring(o):a},sE=typeof btoa==`function`?e=>btoa(e):oE,cE=typeof Uint8Array.prototype.toBase64==`function`?e=>e.toBase64():e=>{let t=4096,n=[];for(let r=0,i=e.length;r<i;r+=t)n.push(nE.apply(null,e.subarray(r,r+t)));return sE(n.join(``))},lE=(e,t=!1)=>t?iE(cE(e)):cE(e),uE=e=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?nE(192|t>>>6)+nE(128|t&63):nE(224|t>>>12&15)+nE(128|t>>>6&63)+nE(128|t&63)}var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return nE(240|t>>>18&7)+nE(128|t>>>12&63)+nE(128|t>>>6&63)+nE(128|t&63)},dE=/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\x00-\x7F]/g,fE=e=>e.replace(dE,uE),pE=QT?e=>cE(QT.encode(e)):e=>sE(fE(e)),mE=(e,t=!1)=>t?iE(pE(e)):pE(e),hE=e=>mE(e,!0),gE=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,_E=e=>{switch(e.length){case 4:var t=((7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3))-65536;return nE((t>>>10)+55296)+nE((t&1023)+56320);case 3:return nE((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return nE((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},vE=e=>e.replace(gE,_E),yE=e=>{if(e=e.replace(/\s+/g,``),!tE.test(e))throw TypeError(`malformed base64.`);e+=`==`.slice(2-(e.length&3));let t,n,r,i=[];for(let a=0;a<e.length;)t=eE[e.charAt(a++)]<<18|eE[e.charAt(a++)]<<12|(n=eE[e.charAt(a++)])<<6|(r=eE[e.charAt(a++)]),n===64?i.push(nE(t>>16&255)):r===64?i.push(nE(t>>16&255,t>>8&255)):i.push(nE(t>>16&255,t>>8&255,t&255));return i.join(``)},bE=typeof atob==`function`?e=>atob(aE(e)):yE,xE=typeof Uint8Array.fromBase64==`function`?e=>Uint8Array.fromBase64(e):e=>rE(bE(e).split(``).map(e=>e.charCodeAt(0))),SE=e=>xE(wE(e)),CE=ZT?e=>ZT.decode(xE(e)):e=>vE(bE(e)),wE=e=>aE(e.replace(/[-_]/g,e=>e==`-`?`+`:`/`)),TE=e=>CE(wE(e)),EE=e=>{if(typeof e!=`string`)return!1;let t=e.replace(/\s+/g,``).replace(/={0,2}$/,``);return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},DE=e=>({value:e,enumerable:!1,writable:!0,configurable:!0}),OE=function(){let e=(e,t)=>Object.defineProperty(String.prototype,e,DE(t));e(`fromBase64`,function(){return TE(this)}),e(`toBase64`,function(e){return mE(this,e)}),e(`toBase64URI`,function(){return mE(this,!0)}),e(`toBase64URL`,function(){return mE(this,!0)}),e(`toUint8Array`,function(){return SE(this)})},kE=function(){let e=(e,t)=>Object.defineProperty(Uint8Array.prototype,e,DE(t));e(`toBase64`,function(e){return lE(this,e)}),e(`toBase64URI`,function(){return lE(this,!0)}),e(`toBase64URL`,function(){return lE(this,!0)})},AE={version:YT,VERSION:XT,atob:bE,atobPolyfill:yE,btoa:sE,btoaPolyfill:oE,fromBase64:TE,toBase64:mE,encode:mE,encodeURI:hE,encodeURL:hE,utob:fE,btou:vE,decode:TE,isValid:EE,fromUint8Array:lE,toUint8Array:SE,extendString:OE,extendUint8Array:kE,extendBuiltins:()=>{OE(),kE()}},jE=b(((e,t)=>{t.exports=function(e,t){if(t=t.split(`:`)[0],e=+e,!e)return!1;switch(t){case`http`:case`ws`:return e!==80;case`https`:case`wss`:return e!==443;case`ftp`:return e!==21;case`gopher`:return e!==70;case`file`:return!1}return e!==0}})),ME=b((e=>{var t=Object.prototype.hasOwnProperty,n;function r(e){try{return decodeURIComponent(e.replace(/\+/g,` `))}catch{return null}}function i(e){try{return encodeURIComponent(e)}catch{return null}}function a(e){for(var t=/([^=?#&]+)=?([^&]*)/g,n={},i;i=t.exec(e);){var a=r(i[1]),o=r(i[2]);a===null||o===null||a in n||(n[a]=o)}return n}function o(e,r){r||=``;var a=[],o,s;for(s in typeof r!=`string`&&(r=`?`),e)if(t.call(e,s)){if(o=e[s],!o&&(o===null||o===n||isNaN(o))&&(o=``),s=i(s),o=i(o),s===null||o===null)continue;a.push(s+`=`+o)}return a.length?r+a.join(`&`):``}e.stringify=o,e.parse=a})),NE=b(((e,t)=>{var n=jE(),r=ME(),i=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,a=/[\n\r\t]/g,o=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,s=/:\d+$/,c=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,l=/^[a-zA-Z]:/;function u(e){return(e||``).toString().replace(i,``)}var d=[[`#`,`hash`],[`?`,`query`],function(e,t){return m(t.protocol)?e.replace(/\\/g,`/`):e},[`/`,`pathname`],[`@`,`auth`,1],[NaN,`host`,void 0,1,1],[/:(\d*)$/,`port`,void 0,1],[NaN,`hostname`,void 0,1,1]],f={hash:1,query:1};function p(e){var t=(typeof window<`u`?window:typeof global<`u`?global:typeof self<`u`?self:{}).location||{};e||=t;var n={},r=typeof e,i;if(e.protocol===`blob:`)n=new _(unescape(e.pathname),{});else if(r===`string`)for(i in n=new _(e,{}),f)delete n[i];else if(r===`object`){for(i in e)i in f||(n[i]=e[i]);n.slashes===void 0&&(n.slashes=o.test(e.href))}return n}function m(e){return e===`file:`||e===`ftp:`||e===`http:`||e===`https:`||e===`ws:`||e===`wss:`}function h(e,t){e=u(e),e=e.replace(a,``),t||={};var n=c.exec(e),r=n[1]?n[1].toLowerCase():``,i=!!n[2],o=!!n[3],s=0,l;return i?o?(l=n[2]+n[3]+n[4],s=n[2].length+n[3].length):(l=n[2]+n[4],s=n[2].length):o?(l=n[3]+n[4],s=n[3].length):l=n[4],r===`file:`?s>=2&&(l=l.slice(2)):m(r)?l=n[4]:r?i&&(l=l.slice(2)):s>=2&&m(t.protocol)&&(l=n[4]),{protocol:r,slashes:i||m(r),slashesCount:s,rest:l}}function g(e,t){if(e===``)return t;for(var n=(t||`/`).split(`/`).slice(0,-1).concat(e.split(`/`)),r=n.length,i=n[r-1],a=!1,o=0;r--;)n[r]===`.`?n.splice(r,1):n[r]===`..`?(n.splice(r,1),o++):o&&(r===0&&(a=!0),n.splice(r,1),o--);return a&&n.unshift(``),(i===`.`||i===`..`)&&n.push(``),n.join(`/`)}function _(e,t,i){if(e=u(e),e=e.replace(a,``),!(this instanceof _))return new _(e,t,i);var o,s,c,f,v,y,b=d.slice(),x=typeof t,S=this,C=0;for(x!==`object`&&x!==`string`&&(i=t,t=null),i&&typeof i!=`function`&&(i=r.parse),t=p(t),s=h(e||``,t),o=!s.protocol&&!s.slashes,S.slashes=s.slashes||o&&t.slashes,S.protocol=s.protocol||t.protocol||``,e=s.rest,(s.protocol===`file:`&&(s.slashesCount!==2||l.test(e))||!s.slashes&&(s.protocol||s.slashesCount<2||!m(S.protocol)))&&(b[3]=[/(.*)/,`pathname`]);C<b.length;C++){if(f=b[C],typeof f==`function`){e=f(e,S);continue}c=f[0],y=f[1],c===c?typeof c==`string`?(v=c===`@`?e.lastIndexOf(c):e.indexOf(c),~v&&(typeof f[2]==`number`?(S[y]=e.slice(0,v),e=e.slice(v+f[2])):(S[y]=e.slice(v),e=e.slice(0,v)))):(v=c.exec(e))&&(S[y]=v[1],e=e.slice(0,v.index)):S[y]=e,S[y]=S[y]||o&&f[3]&&t[y]||``,f[4]&&(S[y]=S[y].toLowerCase())}i&&(S.query=i(S.query)),o&&t.slashes&&S.pathname.charAt(0)!==`/`&&(S.pathname!==``||t.pathname!==``)&&(S.pathname=g(S.pathname,t.pathname)),S.pathname.charAt(0)!==`/`&&m(S.protocol)&&(S.pathname=`/`+S.pathname),n(S.port,S.protocol)||(S.host=S.hostname,S.port=``),S.username=S.password=``,S.auth&&=(v=S.auth.indexOf(`:`),~v?(S.username=S.auth.slice(0,v),S.username=encodeURIComponent(decodeURIComponent(S.username)),S.password=S.auth.slice(v+1),S.password=encodeURIComponent(decodeURIComponent(S.password))):S.username=encodeURIComponent(decodeURIComponent(S.auth)),S.password?S.username+`:`+S.password:S.username),S.origin=S.protocol!==`file:`&&m(S.protocol)&&S.host?S.protocol+`//`+S.host:`null`,S.href=S.toString()}function v(e,t,i){var a=this;switch(e){case`query`:typeof t==`string`&&t.length&&(t=(i||r.parse)(t)),a[e]=t;break;case`port`:a[e]=t,n(t,a.protocol)?t&&(a.host=a.hostname+`:`+t):(a.host=a.hostname,a[e]=``);break;case`hostname`:a[e]=t,a.port&&(t+=`:`+a.port),a.host=t;break;case`host`:a[e]=t,s.test(t)?(t=t.split(`:`),a.port=t.pop(),a.hostname=t.join(`:`)):(a.hostname=t,a.port=``);break;case`protocol`:a.protocol=t.toLowerCase(),a.slashes=!i;break;case`pathname`:case`hash`:if(t){var o=e===`pathname`?`/`:`#`;a[e]=t.charAt(0)===o?t:o+t}else a[e]=t;break;case`username`:case`password`:a[e]=encodeURIComponent(t);break;case`auth`:var c=t.indexOf(`:`);~c?(a.username=t.slice(0,c),a.username=encodeURIComponent(decodeURIComponent(a.username)),a.password=t.slice(c+1),a.password=encodeURIComponent(decodeURIComponent(a.password))):a.username=encodeURIComponent(decodeURIComponent(t))}for(var l=0;l<d.length;l++){var u=d[l];u[4]&&(a[u[1]]=a[u[1]].toLowerCase())}return a.auth=a.password?a.username+`:`+a.password:a.username,a.origin=a.protocol!==`file:`&&m(a.protocol)&&a.host?a.protocol+`//`+a.host:`null`,a.href=a.toString(),a}function y(e){(!e||typeof e!=`function`)&&(e=r.stringify);var t,n=this,i=n.host,a=n.protocol;a&&a.charAt(a.length-1)!==`:`&&(a+=`:`);var o=a+(n.protocol&&n.slashes||m(n.protocol)?`//`:``);return n.username?(o+=n.username,n.password&&(o+=`:`+n.password),o+=`@`):n.password?(o+=`:`+n.password,o+=`@`):n.protocol!==`file:`&&m(n.protocol)&&!i&&n.pathname!==`/`&&(o+=`@`),(i[i.length-1]===`:`||s.test(n.hostname)&&!n.port)&&(i+=`:`),o+=i+n.pathname,t=typeof n.query==`object`?e(n.query):n.query,t&&(o+=t.charAt(0)===`?`?t:`?`+t),n.hash&&(o+=n.hash),o}_.prototype={set:v,toString:y},_.extractProtocol=h,_.location=p,_.trimLeft=u,_.qs=r,t.exports=_}));function PE(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,function(e){var t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var FE=C(NE());function IE(){IE=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},a=typeof Symbol==`function`?Symbol:{},o=a.iterator||`@@iterator`,s=a.asyncIterator||`@@asyncIterator`,c=a.toStringTag||`@@toStringTag`;function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},``)}catch{l=function(e,t,n){return e[t]=n}}function u(e,t,n,r){var a=t&&t.prototype instanceof _?t:_,o=Object.create(a.prototype);return i(o,`_invoke`,{value:te(e,n,new T(r||[]))}),o}function d(e,t,n){try{return{type:`normal`,arg:e.call(t,n)}}catch(e){return{type:`throw`,arg:e}}}t.wrap=u;var f=`suspendedStart`,p=`suspendedYield`,m=`executing`,h=`completed`,g={};function _(){}function v(){}function y(){}var b={};l(b,o,function(){return this});var x=Object.getPrototypeOf,S=x&&x(x(ae([])));S&&S!==n&&r.call(S,o)&&(b=S);var C=y.prototype=_.prototype=Object.create(b);function ee(e){[`next`,`throw`,`return`].forEach(function(t){l(e,t,function(e){return this._invoke(t,e)})})}function w(e,t){function n(i,a,o,s){var c=d(e[i],e,a);if(c.type!==`throw`){var l=c.arg,u=l.value;return u&&UE(u)==`object`&&r.call(u,`__await`)?t.resolve(u.__await).then(function(e){n(`next`,e,o,s)},function(e){n(`throw`,e,o,s)}):t.resolve(u).then(function(e){l.value=e,o(l)},function(e){return n(`throw`,e,o,s)})}s(c.arg)}var a;i(this,`_invoke`,{value:function(e,r){function i(){return new t(function(t,i){n(e,r,t,i)})}return a=a?a.then(i,i):i()}})}function te(t,n,r){var i=f;return function(a,o){if(i===m)throw Error(`Generator is already running`);if(i===h){if(a===`throw`)throw o;return{value:e,done:!0}}for(r.method=a,r.arg=o;;){var s=r.delegate;if(s){var c=ne(s,r);if(c){if(c===g)continue;return c}}if(r.method===`next`)r.sent=r._sent=r.arg;else if(r.method===`throw`){if(i===f)throw i=h,r.arg;r.dispatchException(r.arg)}else r.method===`return`&&r.abrupt(`return`,r.arg);i=m;var l=d(t,n,r);if(l.type===`normal`){if(i=r.done?h:p,l.arg===g)continue;return{value:l.arg,done:r.done}}l.type===`throw`&&(i=h,r.method=`throw`,r.arg=l.arg)}}}function ne(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,r===`throw`&&t.iterator.return&&(n.method=`return`,n.arg=e,ne(t,n),n.method===`throw`)||r!==`return`&&(n.method=`throw`,n.arg=TypeError(`The iterator does not provide a '`+r+`' method`)),g;var a=d(i,t.iterator,n.arg);if(a.type===`throw`)return n.method=`throw`,n.arg=a.arg,n.delegate=null,g;var o=a.arg;return o?o.done?(n[t.resultName]=o.value,n.next=t.nextLoc,n.method!==`return`&&(n.method=`next`,n.arg=e),n.delegate=null,g):o:(n.method=`throw`,n.arg=TypeError(`iterator result is not an object`),n.delegate=null,g)}function re(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function ie(e){var t=e.completion||{};t.type=`normal`,delete t.arg,e.completion=t}function T(e){this.tryEntries=[{tryLoc:`root`}],e.forEach(re,this),this.reset(!0)}function ae(t){if(t||t===``){var n=t[o];if(n)return n.call(t);if(typeof t.next==`function`)return t;if(!isNaN(t.length)){var i=-1,a=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return a.next=a}}throw TypeError(UE(t)+` is not iterable`)}return v.prototype=y,i(C,`constructor`,{value:y,configurable:!0}),i(y,`constructor`,{value:v,configurable:!0}),v.displayName=l(y,c,`GeneratorFunction`),t.isGeneratorFunction=function(e){var t=typeof e==`function`&&e.constructor;return!!t&&(t===v||(t.displayName||t.name)===`GeneratorFunction`)},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,l(e,c,`GeneratorFunction`)),e.prototype=Object.create(C),e},t.awrap=function(e){return{__await:e}},ee(w.prototype),l(w.prototype,s,function(){return this}),t.AsyncIterator=w,t.async=function(e,n,r,i,a){a===void 0&&(a=Promise);var o=new w(u(e,n,r,i),a);return t.isGeneratorFunction(n)?o:o.next().then(function(e){return e.done?e.value:o.next()})},ee(C),l(C,c,`Generator`),l(C,o,function(){return this}),l(C,`toString`,function(){return`[object Generator]`}),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=ae,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method=`next`,this.arg=e,this.tryEntries.forEach(ie),!t)for(var n in this)n.charAt(0)===`t`&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if(e.type===`throw`)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return s.type=`throw`,s.arg=t,n.next=r,i&&(n.method=`next`,n.arg=e),!!i}for(var a=this.tryEntries.length-1;a>=0;--a){var o=this.tryEntries[a],s=o.completion;if(o.tryLoc===`root`)return i(`end`);if(o.tryLoc<=this.prev){var c=r.call(o,`catchLoc`),l=r.call(o,`finallyLoc`);if(c&&l){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!l)throw Error(`try statement without catch or finally`);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,`finallyLoc`)&&this.prev<i.finallyLoc){var a=i;break}}a&&(e===`break`||e===`continue`)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var o=a?a.completion:{};return o.type=e,o.arg=t,a?(this.method=`next`,this.next=a.finallyLoc,g):this.complete(o)},complete:function(e,t){if(e.type===`throw`)throw e.arg;return e.type===`break`||e.type===`continue`?this.next=e.arg:e.type===`return`?(this.rval=this.arg=e.arg,this.method=`return`,this.next=`end`):e.type===`normal`&&t&&(this.next=t),g},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),ie(n),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if(r.type===`throw`){var i=r.arg;ie(n)}return i}}throw Error(`illegal catch attempt`)},delegateYield:function(t,n,r){return this.delegate={iterator:ae(t),resultName:n,nextLoc:r},this.method===`next`&&(this.arg=e),g}},t}function LE(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function RE(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){LE(a,r,i,o,s,`next`,e)}function s(e){LE(a,r,i,o,s,`throw`,e)}o(void 0)})}}function zE(e,t){return HE(e)||VE(e,t)||GE(e,t)||BE()}function BE(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
105
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VE(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function HE(e){if(Array.isArray(e))return e}function UE(e){"@babel/helpers - typeof";return UE=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},UE(e)}function WE(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=GE(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
106
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a=!0,o=!1,s;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){o=!0,s=e},f:function(){try{!a&&n.return!=null&&n.return()}finally{if(o)throw s}}}}function GE(e,t){if(e){if(typeof e==`string`)return KE(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if(n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`)return Array.from(e);if(n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return KE(e,t)}}function KE(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function qE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function JE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?qE(Object(n),!0).forEach(function(t){YE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function YE(e,t,n){return t=$E(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function XE(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function ZE(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,$E(r.key),r)}}function QE(e,t,n){return t&&ZE(e.prototype,t),n&&ZE(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function $E(e){var t=eD(e,`string`);return UE(t)==`symbol`?t:t+``}function eD(e,t){if(UE(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(UE(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var tD=`tus-v1`,nD=`ietf-draft-03`,rD=`ietf-draft-05`,iD={endpoint:null,uploadUrl:null,metadata:{},metadataForPartialUploads:{},fingerprint:null,uploadSize:null,onProgress:null,onChunkComplete:null,onSuccess:null,onError:null,onUploadUrlAvailable:null,overridePatchMethod:!1,headers:{},addRequestId:!1,onBeforeRequest:null,onAfterResponse:null,onShouldRetry:pD,chunkSize:1/0,retryDelays:[0,1e3,3e3,5e3],parallelUploads:1,parallelUploadBoundaries:null,storeFingerprintForResuming:!0,removeFingerprintOnSuccess:!1,uploadLengthDeferred:!1,uploadDataDuringCreation:!1,urlStorage:null,fileReader:null,httpStack:null,protocol:tD},aD=function(){function e(t,n){XE(this,e),`resume`in n&&console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."),this.options=n,this.options.chunkSize=Number(this.options.chunkSize),this._urlStorage=this.options.urlStorage,this.file=t,this.url=null,this._req=null,this._fingerprint=null,this._urlStorageKey=null,this._offset=null,this._aborted=!1,this._size=null,this._source=null,this._retryAttempt=0,this._retryTimeout=null,this._offsetBeforeRetry=0,this._parallelUploads=null,this._parallelUploadUrls=null}return QE(e,[{key:`findPreviousUploads`,value:function(){var e=this;return this.options.fingerprint(this.file,this.options).then(function(t){return e._urlStorage.findUploadsByFingerprint(t)})}},{key:`resumeFromPreviousUpload`,value:function(e){this.url=e.uploadUrl||null,this._parallelUploadUrls=e.parallelUploadUrls||null,this._urlStorageKey=e.urlStorageKey}},{key:`start`,value:function(){var e=this,t=this.file;if(!t){this._emitError(Error(`tus: no file or stream to upload provided`));return}if(![tD,nD,rD].includes(this.options.protocol)){this._emitError(Error(`tus: unsupported protocol ${this.options.protocol}`));return}if(!this.options.endpoint&&!this.options.uploadUrl&&!this.url){this._emitError(Error(`tus: neither an endpoint or an upload URL is provided`));return}var n=this.options.retryDelays;if(n!=null&&Object.prototype.toString.call(n)!==`[object Array]`){this._emitError(Error("tus: the `retryDelays` option must either be an array or null"));return}if(this.options.parallelUploads>1)for(var r=0,i=[`uploadUrl`,`uploadSize`,`uploadLengthDeferred`];r<i.length;r++){var a=i[r];if(this.options[a]){this._emitError(Error(`tus: cannot use the ${a} option when parallelUploads is enabled`));return}}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1){this._emitError(Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));return}if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length){this._emitError(Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"));return}}this.options.fingerprint(t,this.options).then(function(n){return n==null||`${n}`,e._fingerprint=n,e._source?e._source:e.options.fileReader.openFile(t,e.options.chunkSize)}).then(function(t){if(e._source=t,e.options.uploadLengthDeferred)e._size=null;else if(e.options.uploadSize!=null){if(e._size=Number(e.options.uploadSize),Number.isNaN(e._size)){e._emitError(Error("tus: cannot convert `uploadSize` option into a number"));return}}else if(e._size=e._source.size,e._size==null){e._emitError(Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));return}e.options.parallelUploads>1||e._parallelUploadUrls!=null?e._startParallelUpload():e._startSingleUpload()}).catch(function(t){e._emitError(t)})}},{key:`_startParallelUpload`,value:function(){var t=this,n=this._size,r=0;this._parallelUploads=[];var i=this._parallelUploadUrls==null?this.options.parallelUploads:this._parallelUploadUrls.length,a=this.options.parallelUploadBoundaries??hD(this._source.size,i);this._parallelUploadUrls&&a.forEach(function(e,n){e.uploadUrl=t._parallelUploadUrls[n]||null}),this._parallelUploadUrls=Array(a.length);var o=a.map(function(i,o){var s=0;return t._source.slice(i.start,i.end).then(function(c){var l=c.value;return new Promise(function(c,u){var d=new e(l,JE(JE({},t.options),{},{uploadUrl:i.uploadUrl||null,storeFingerprintForResuming:!1,removeFingerprintOnSuccess:!1,parallelUploads:1,parallelUploadBoundaries:null,metadata:t.options.metadataForPartialUploads,headers:JE(JE({},t.options.headers),{},{"Upload-Concat":`partial`}),onSuccess:c,onError:u,onProgress:function(e){r=r-s+e,s=e,t._emitProgress(r,n)},onUploadUrlAvailable:function(){t._parallelUploadUrls[o]=d.url,t._parallelUploadUrls.filter(function(e){return!!e}).length===a.length&&t._saveUploadInUrlStorage()}}));d.start(),t._parallelUploads.push(d)})})}),s;Promise.all(o).then(function(){s=t._openRequest(`POST`,t.options.endpoint),s.setHeader(`Upload-Concat`,`final;${t._parallelUploadUrls.join(` `)}`);var e=oD(t.options.metadata);return e!==``&&s.setHeader(`Upload-Metadata`,e),t._sendRequest(s,null)}).then(function(e){if(!sD(e.getStatus(),200)){t._emitHttpError(s,e,`tus: unexpected response while creating upload`);return}var n=e.getHeader(`Location`);if(n==null){t._emitHttpError(s,e,`tus: invalid or missing Location header`);return}t.url=mD(t.options.endpoint,n),`${t.url}`,t._emitSuccess(e)}).catch(function(e){t._emitError(e)})}},{key:`_startSingleUpload`,value:function(){if(this._aborted=!1,this.url!=null){`${this.url}`,this._resumeUpload();return}if(this.options.uploadUrl!=null){`${this.options.uploadUrl}`,this.url=this.options.uploadUrl,this._resumeUpload();return}this._createUpload()}},{key:`abort`,value:function(t){var n=this;if(this._parallelUploads!=null){var r=WE(this._parallelUploads),i;try{for(r.s();!(i=r.n()).done;)i.value.abort(t)}catch(e){r.e(e)}finally{r.f()}}return this._req!==null&&this._req.abort(),this._aborted=!0,this._retryTimeout!=null&&(clearTimeout(this._retryTimeout),this._retryTimeout=null),!t||this.url==null?Promise.resolve():e.terminate(this.url,this.options).then(function(){return n._removeFromUrlStorage()})}},{key:`_emitHttpError`,value:function(e,t,n,r){this._emitError(new VT(n,r,e,t))}},{key:`_emitError`,value:function(e){var t=this;if(!this._aborted){if(this.options.retryDelays!=null&&(this._offset!=null&&this._offset>this._offsetBeforeRetry&&(this._retryAttempt=0),fD(e,this._retryAttempt,this.options))){var n=this.options.retryDelays[this._retryAttempt++];this._offsetBeforeRetry=this._offset,this._retryTimeout=setTimeout(function(){t.start()},n);return}if(typeof this.options.onError==`function`)this.options.onError(e);else throw e}}},{key:`_emitSuccess`,value:function(e){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),typeof this.options.onSuccess==`function`&&this.options.onSuccess({lastResponse:e})}},{key:`_emitProgress`,value:function(e,t){typeof this.options.onProgress==`function`&&this.options.onProgress(e,t)}},{key:`_emitChunkComplete`,value:function(e,t,n){typeof this.options.onChunkComplete==`function`&&this.options.onChunkComplete(e,t,n)}},{key:`_createUpload`,value:function(){var e=this;if(!this.options.endpoint){this._emitError(Error(`tus: unable to create upload because no endpoint is provided`));return}var t=this._openRequest(`POST`,this.options.endpoint);this.options.uploadLengthDeferred?t.setHeader(`Upload-Defer-Length`,`1`):t.setHeader(`Upload-Length`,`${this._size}`);var n=oD(this.options.metadata);n!==``&&t.setHeader(`Upload-Metadata`,n);var r;this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,r=this._addChunkToRequest(t)):((this.options.protocol===nD||this.options.protocol===rD)&&t.setHeader(`Upload-Complete`,`?0`),r=this._sendRequest(t,null)),r.then(function(n){if(!sD(n.getStatus(),200)){e._emitHttpError(t,n,`tus: unexpected response while creating upload`);return}var r=n.getHeader(`Location`);if(r==null){e._emitHttpError(t,n,`tus: invalid or missing Location header`);return}if(e.url=mD(e.options.endpoint,r),`${e.url}`,typeof e.options.onUploadUrlAvailable==`function`&&e.options.onUploadUrlAvailable(),e._size===0){e._emitSuccess(n),e._source.close();return}e._saveUploadInUrlStorage().then(function(){e.options.uploadDataDuringCreation?e._handleUploadResponse(t,n):(e._offset=0,e._performUpload())})}).catch(function(n){e._emitHttpError(t,null,`tus: failed to create upload`,n)})}},{key:`_resumeUpload`,value:function(){var e=this,t=this._openRequest(`HEAD`,this.url);this._sendRequest(t,null).then(function(n){var r=n.getStatus();if(!sD(r,200)){if(r===423){e._emitHttpError(t,n,`tus: upload is currently locked; retry later`);return}if(sD(r,400)&&e._removeFromUrlStorage(),!e.options.endpoint){e._emitHttpError(t,n,`tus: unable to resume upload (new upload cannot be created without an endpoint)`);return}e.url=null,e._createUpload();return}var i=Number.parseInt(n.getHeader(`Upload-Offset`),10);if(Number.isNaN(i)){e._emitHttpError(t,n,`tus: invalid or missing offset value`);return}var a=Number.parseInt(n.getHeader(`Upload-Length`),10);if(Number.isNaN(a)&&!e.options.uploadLengthDeferred&&e.options.protocol===tD){e._emitHttpError(t,n,`tus: invalid or missing length value`);return}typeof e.options.onUploadUrlAvailable==`function`&&e.options.onUploadUrlAvailable(),e._saveUploadInUrlStorage().then(function(){if(i===a){e._emitProgress(a,a),e._emitSuccess(n);return}e._offset=i,e._performUpload()})}).catch(function(n){e._emitHttpError(t,null,`tus: failed to resume upload`,n)})}},{key:`_performUpload`,value:function(){var e=this;if(!this._aborted){var t;this.options.overridePatchMethod?(t=this._openRequest(`POST`,this.url),t.setHeader(`X-HTTP-Method-Override`,`PATCH`)):t=this._openRequest(`PATCH`,this.url),t.setHeader(`Upload-Offset`,`${this._offset}`),this._addChunkToRequest(t).then(function(n){if(!sD(n.getStatus(),200)){e._emitHttpError(t,n,`tus: unexpected response while uploading chunk`);return}e._handleUploadResponse(t,n)}).catch(function(n){e._aborted||e._emitHttpError(t,null,`tus: failed to upload chunk at offset ${e._offset}`,n)})}}},{key:`_addChunkToRequest`,value:function(e){var t=this,n=this._offset,r=this._offset+this.options.chunkSize;return e.setProgressHandler(function(e){t._emitProgress(n+e,t._size)}),this.options.protocol===tD?e.setHeader(`Content-Type`,`application/offset+octet-stream`):this.options.protocol===rD&&e.setHeader(`Content-Type`,`application/partial-upload`),(r===1/0||r>this._size)&&!this.options.uploadLengthDeferred&&(r=this._size),this._source.slice(n,r).then(function(n){var r=n.value,i=n.done,a=r!=null&&r.size?r.size:0;t.options.uploadLengthDeferred&&i&&(t._size=t._offset+a,e.setHeader(`Upload-Length`,`${t._size}`));var o=t._offset+a;return!t.options.uploadLengthDeferred&&i&&o!==t._size?Promise.reject(Error(`upload was configured with a size of ${t._size} bytes, but the source is done after ${o} bytes`)):r===null?t._sendRequest(e):((t.options.protocol===nD||t.options.protocol===rD)&&e.setHeader(`Upload-Complete`,i?`?1`:`?0`),t._emitProgress(t._offset,t._size),t._sendRequest(e,r))})}},{key:`_handleUploadResponse`,value:function(e,t){var n=Number.parseInt(t.getHeader(`Upload-Offset`),10);if(Number.isNaN(n)){this._emitHttpError(e,t,`tus: invalid or missing offset value`);return}if(this._emitProgress(n,this._size),this._emitChunkComplete(n-this._offset,n,this._size),this._offset=n,n===this._size){this._emitSuccess(t),this._source.close();return}this._performUpload()}},{key:`_openRequest`,value:function(e,t){var n=cD(e,t,this.options);return this._req=n,n}},{key:`_removeFromUrlStorage`,value:function(){var e=this;this._urlStorageKey&&=(this._urlStorage.removeUpload(this._urlStorageKey).catch(function(t){e._emitError(t)}),null)}},{key:`_saveUploadInUrlStorage`,value:function(){var e=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||this._urlStorageKey!==null)return Promise.resolve();var t={size:this._size,metadata:this.options.metadata,creationTime:new Date().toString()};return this._parallelUploads?t.parallelUploadUrls=this._parallelUploadUrls:t.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,t).then(function(t){e._urlStorageKey=t})}},{key:`_sendRequest`,value:function(e){return lD(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:null,this.options)}}],[{key:`terminate`,value:function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=cD(`DELETE`,t,n);return lD(r,null,n).then(function(e){if(e.getStatus()!==204)throw new VT(`tus: unexpected response while terminating upload`,null,r,e)}).catch(function(i){if(i instanceof VT||(i=new VT(`tus: failed to terminate upload`,i,r,null)),!fD(i,0,n))throw i;var a=n.retryDelays[0],o=n.retryDelays.slice(1),s=JE(JE({},n),{},{retryDelays:o});return new Promise(function(e){return setTimeout(e,a)}).then(function(){return e.terminate(t,s)})})}}])}();function oD(e){return Object.entries(e).map(function(e){var t=zE(e,2),n=t[0],r=t[1];return`${n} ${AE.encode(String(r))}`}).join(`,`)}function sD(e,t){return e>=t&&e<t+100}function cD(e,t,n){var r=n.httpStack.createRequest(e,t);n.protocol===nD?r.setHeader(`Upload-Draft-Interop-Version`,`5`):n.protocol===rD?r.setHeader(`Upload-Draft-Interop-Version`,`6`):r.setHeader(`Tus-Resumable`,`1.0.0`);for(var i=n.headers||{},a=0,o=Object.entries(i);a<o.length;a++){var s=zE(o[a],2),c=s[0],l=s[1];r.setHeader(c,l)}if(n.addRequestId){var u=PE();r.setHeader(`X-Request-ID`,u)}return r}function lD(e,t,n){return uD.apply(this,arguments)}function uD(){return uD=RE(IE().mark(function e(t,n,r){var i;return IE().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(typeof r.onBeforeRequest!=`function`){e.next=3;break}return e.next=3,r.onBeforeRequest(t);case 3:return e.next=5,t.send(n);case 5:if(i=e.sent,typeof r.onAfterResponse!=`function`){e.next=9;break}return e.next=9,r.onAfterResponse(t,i);case 9:return e.abrupt(`return`,i);case 10:case`end`:return e.stop()}},e)})),uD.apply(this,arguments)}function dD(){var e=!0;return typeof navigator<`u`&&navigator.onLine===!1&&(e=!1),e}function fD(e,t,n){return n.retryDelays==null||t>=n.retryDelays.length||e.originalRequest==null?!1:n&&typeof n.onShouldRetry==`function`?n.onShouldRetry(e,t,n):pD(e)}function pD(e){var t=e.originalResponse?e.originalResponse.getStatus():0;return(!sD(t,400)||t===409||t===423)&&dD()}function mD(e,t){return new FE.default(t,e).toString()}function hD(e,t){for(var n=Math.floor(e/t),r=[],i=0;i<t;i++)r.push({start:n*i,end:n*(i+1)});return r[t-1].end=e,r}aD.defaultOptions=iD;var gD=function(){return typeof navigator<`u`&&typeof navigator.product==`string`&&navigator.product.toLowerCase()===`reactnative`};function _D(e){return new Promise(function(t,n){var r=new XMLHttpRequest;r.responseType=`blob`,r.onload=function(){var e=r.response;t(e)},r.onerror=function(e){n(e)},r.open(`GET`,e),r.send()})}var vD=function(){return typeof window<`u`&&(window.PhoneGap!==void 0||window.Cordova!==void 0||window.cordova!==void 0)};function yD(e){return new Promise(function(t,n){var r=new FileReader;r.onload=function(){t({value:new Uint8Array(r.result)})},r.onerror=function(e){n(e)},r.readAsArrayBuffer(e)})}function bD(e){"@babel/helpers - typeof";return bD=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},bD(e)}function xD(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function SD(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,wD(r.key),r)}}function CD(e,t,n){return t&&SD(e.prototype,t),n&&SD(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function wD(e){var t=TD(e,`string`);return bD(t)==`symbol`?t:t+``}function TD(e,t){if(bD(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(bD(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var ED=function(){function e(t){xD(this,e),this._file=t,this.size=t.size}return CD(e,[{key:`slice`,value:function(e,t){if(vD())return yD(this._file.slice(e,t));var n=this._file.slice(e,t),r=t>=this.size;return Promise.resolve({value:n,done:r})}},{key:`close`,value:function(){}}])}();function DD(e){"@babel/helpers - typeof";return DD=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},DD(e)}function OD(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function kD(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,jD(r.key),r)}}function AD(e,t,n){return t&&kD(e.prototype,t),n&&kD(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function jD(e){var t=MD(e,`string`);return DD(t)==`symbol`?t:t+``}function MD(e,t){if(DD(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(DD(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ND(e){return e===void 0?0:e.size===void 0?e.length:e.size}function PD(e,t){if(e.concat)return e.concat(t);if(e instanceof Blob)return new Blob([e,t],{type:e.type});if(e.set){var n=new e.constructor(e.length+t.length);return n.set(e),n.set(t,e.length),n}throw Error(`Unknown data type`)}var FD=function(){function e(t){OD(this,e),this._buffer=void 0,this._bufferOffset=0,this._reader=t,this._done=!1}return AD(e,[{key:`slice`,value:function(e,t){return e<this._bufferOffset?Promise.reject(Error(`Requested data is before the reader's current offset`)):this._readUntilEnoughDataOrDone(e,t)}},{key:`_readUntilEnoughDataOrDone`,value:function(e,t){var n=this,r=t<=this._bufferOffset+ND(this._buffer);if(this._done||r){var i=this._getDataFromBuffer(e,t),a=i==null&&this._done;return Promise.resolve({value:i,done:a})}return this._reader.read().then(function(r){var i=r.value;return r.done?n._done=!0:n._buffer=n._buffer===void 0?i:PD(n._buffer,i),n._readUntilEnoughDataOrDone(e,t)})}},{key:`_getDataFromBuffer`,value:function(e,t){e>this._bufferOffset&&(this._buffer=this._buffer.slice(e-this._bufferOffset),this._bufferOffset=e);var n=ND(this._buffer)===0;return this._done&&n?null:this._buffer.slice(0,t-e)}},{key:`close`,value:function(){this._reader.cancel&&this._reader.cancel()}}])}();function ID(e){"@babel/helpers - typeof";return ID=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},ID(e)}function LD(){LD=function(){return t};var e,t={},n=Object.prototype,r=n.hasOwnProperty,i=Object.defineProperty||function(e,t,n){e[t]=n.value},a=typeof Symbol==`function`?Symbol:{},o=a.iterator||`@@iterator`,s=a.asyncIterator||`@@asyncIterator`,c=a.toStringTag||`@@toStringTag`;function l(e,t,n){return Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{l({},``)}catch{l=function(e,t,n){return e[t]=n}}function u(e,t,n,r){var a=t&&t.prototype instanceof _?t:_,o=Object.create(a.prototype);return i(o,`_invoke`,{value:te(e,n,new T(r||[]))}),o}function d(e,t,n){try{return{type:`normal`,arg:e.call(t,n)}}catch(e){return{type:`throw`,arg:e}}}t.wrap=u;var f=`suspendedStart`,p=`suspendedYield`,m=`executing`,h=`completed`,g={};function _(){}function v(){}function y(){}var b={};l(b,o,function(){return this});var x=Object.getPrototypeOf,S=x&&x(x(ae([])));S&&S!==n&&r.call(S,o)&&(b=S);var C=y.prototype=_.prototype=Object.create(b);function ee(e){[`next`,`throw`,`return`].forEach(function(t){l(e,t,function(e){return this._invoke(t,e)})})}function w(e,t){function n(i,a,o,s){var c=d(e[i],e,a);if(c.type!==`throw`){var l=c.arg,u=l.value;return u&&ID(u)==`object`&&r.call(u,`__await`)?t.resolve(u.__await).then(function(e){n(`next`,e,o,s)},function(e){n(`throw`,e,o,s)}):t.resolve(u).then(function(e){l.value=e,o(l)},function(e){return n(`throw`,e,o,s)})}s(c.arg)}var a;i(this,`_invoke`,{value:function(e,r){function i(){return new t(function(t,i){n(e,r,t,i)})}return a=a?a.then(i,i):i()}})}function te(t,n,r){var i=f;return function(a,o){if(i===m)throw Error(`Generator is already running`);if(i===h){if(a===`throw`)throw o;return{value:e,done:!0}}for(r.method=a,r.arg=o;;){var s=r.delegate;if(s){var c=ne(s,r);if(c){if(c===g)continue;return c}}if(r.method===`next`)r.sent=r._sent=r.arg;else if(r.method===`throw`){if(i===f)throw i=h,r.arg;r.dispatchException(r.arg)}else r.method===`return`&&r.abrupt(`return`,r.arg);i=m;var l=d(t,n,r);if(l.type===`normal`){if(i=r.done?h:p,l.arg===g)continue;return{value:l.arg,done:r.done}}l.type===`throw`&&(i=h,r.method=`throw`,r.arg=l.arg)}}}function ne(t,n){var r=n.method,i=t.iterator[r];if(i===e)return n.delegate=null,r===`throw`&&t.iterator.return&&(n.method=`return`,n.arg=e,ne(t,n),n.method===`throw`)||r!==`return`&&(n.method=`throw`,n.arg=TypeError(`The iterator does not provide a '`+r+`' method`)),g;var a=d(i,t.iterator,n.arg);if(a.type===`throw`)return n.method=`throw`,n.arg=a.arg,n.delegate=null,g;var o=a.arg;return o?o.done?(n[t.resultName]=o.value,n.next=t.nextLoc,n.method!==`return`&&(n.method=`next`,n.arg=e),n.delegate=null,g):o:(n.method=`throw`,n.arg=TypeError(`iterator result is not an object`),n.delegate=null,g)}function re(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function ie(e){var t=e.completion||{};t.type=`normal`,delete t.arg,e.completion=t}function T(e){this.tryEntries=[{tryLoc:`root`}],e.forEach(re,this),this.reset(!0)}function ae(t){if(t||t===``){var n=t[o];if(n)return n.call(t);if(typeof t.next==`function`)return t;if(!isNaN(t.length)){var i=-1,a=function n(){for(;++i<t.length;)if(r.call(t,i))return n.value=t[i],n.done=!1,n;return n.value=e,n.done=!0,n};return a.next=a}}throw TypeError(ID(t)+` is not iterable`)}return v.prototype=y,i(C,`constructor`,{value:y,configurable:!0}),i(y,`constructor`,{value:v,configurable:!0}),v.displayName=l(y,c,`GeneratorFunction`),t.isGeneratorFunction=function(e){var t=typeof e==`function`&&e.constructor;return!!t&&(t===v||(t.displayName||t.name)===`GeneratorFunction`)},t.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,y):(e.__proto__=y,l(e,c,`GeneratorFunction`)),e.prototype=Object.create(C),e},t.awrap=function(e){return{__await:e}},ee(w.prototype),l(w.prototype,s,function(){return this}),t.AsyncIterator=w,t.async=function(e,n,r,i,a){a===void 0&&(a=Promise);var o=new w(u(e,n,r,i),a);return t.isGeneratorFunction(n)?o:o.next().then(function(e){return e.done?e.value:o.next()})},ee(C),l(C,c,`Generator`),l(C,o,function(){return this}),l(C,`toString`,function(){return`[object Generator]`}),t.keys=function(e){var t=Object(e),n=[];for(var r in t)n.push(r);return n.reverse(),function e(){for(;n.length;){var r=n.pop();if(r in t)return e.value=r,e.done=!1,e}return e.done=!0,e}},t.values=ae,T.prototype={constructor:T,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=e,this.done=!1,this.delegate=null,this.method=`next`,this.arg=e,this.tryEntries.forEach(ie),!t)for(var n in this)n.charAt(0)===`t`&&r.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=e)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if(e.type===`throw`)throw e.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var n=this;function i(r,i){return s.type=`throw`,s.arg=t,n.next=r,i&&(n.method=`next`,n.arg=e),!!i}for(var a=this.tryEntries.length-1;a>=0;--a){var o=this.tryEntries[a],s=o.completion;if(o.tryLoc===`root`)return i(`end`);if(o.tryLoc<=this.prev){var c=r.call(o,`catchLoc`),l=r.call(o,`finallyLoc`);if(c&&l){if(this.prev<o.catchLoc)return i(o.catchLoc,!0);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}else if(c){if(this.prev<o.catchLoc)return i(o.catchLoc,!0)}else{if(!l)throw Error(`try statement without catch or finally`);if(this.prev<o.finallyLoc)return i(o.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&r.call(i,`finallyLoc`)&&this.prev<i.finallyLoc){var a=i;break}}a&&(e===`break`||e===`continue`)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var o=a?a.completion:{};return o.type=e,o.arg=t,a?(this.method=`next`,this.next=a.finallyLoc,g):this.complete(o)},complete:function(e,t){if(e.type===`throw`)throw e.arg;return e.type===`break`||e.type===`continue`?this.next=e.arg:e.type===`return`?(this.rval=this.arg=e.arg,this.method=`return`,this.next=`end`):e.type===`normal`&&t&&(this.next=t),g},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),ie(n),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if(r.type===`throw`){var i=r.arg;ie(n)}return i}}throw Error(`illegal catch attempt`)},delegateYield:function(t,n,r){return this.delegate={iterator:ae(t),resultName:n,nextLoc:r},this.method===`next`&&(this.arg=e),g}},t}function RD(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function zD(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){RD(a,r,i,o,s,`next`,e)}function s(e){RD(a,r,i,o,s,`throw`,e)}o(void 0)})}}function BD(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function VD(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,UD(r.key),r)}}function HD(e,t,n){return t&&VD(e.prototype,t),n&&VD(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function UD(e){var t=WD(e,`string`);return ID(t)==`symbol`?t:t+``}function WD(e,t){if(ID(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ID(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var GD=function(){function e(){BD(this,e)}return HD(e,[{key:`openFile`,value:function(){var e=zD(LD().mark(function e(t,n){var r;return LD().wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!(gD()&&t&&t.uri!==void 0)){e.next=11;break}return e.prev=1,e.next=4,_D(t.uri);case 4:return r=e.sent,e.abrupt(`return`,new ED(r));case 8:throw e.prev=8,e.t0=e.catch(1),Error(`tus: cannot fetch \`file.uri\` as Blob, make sure the uri is correct and accessible. ${e.t0}`);case 11:if(typeof t.slice!=`function`||t.size===void 0){e.next=13;break}return e.abrupt(`return`,Promise.resolve(new ED(t)));case 13:if(typeof t.read!=`function`){e.next=18;break}if(n=Number(n),Number.isFinite(n)){e.next=17;break}return e.abrupt(`return`,Promise.reject(Error("cannot create source for stream without a finite value for the `chunkSize` option")));case 17:return e.abrupt(`return`,Promise.resolve(new FD(t,n)));case 18:return e.abrupt(`return`,Promise.reject(Error(`source object may only be an instance of File, Blob, or Reader in this environment`)));case 19:case`end`:return e.stop()}},e,null,[[1,8]])}));function t(t,n){return e.apply(this,arguments)}return t}()}])}();function KD(e,t){return gD()?Promise.resolve(qD(e,t)):Promise.resolve([`tus-br`,e.name,e.type,e.size,e.lastModified,t.endpoint].join(`-`))}function qD(e,t){var n=e.exif?JD(JSON.stringify(e.exif)):`noexif`;return[`tus-rn`,e.name||`noname`,e.size||`nosize`,n,t.endpoint].join(`/`)}function JD(e){var t=0;if(e.length===0)return t;for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);t=(t<<5)-t+r,t&=t}return t}function YD(e){"@babel/helpers - typeof";return YD=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},YD(e)}function XD(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function ZD(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,$D(r.key),r)}}function QD(e,t,n){return t&&ZD(e.prototype,t),n&&ZD(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function $D(e){var t=eO(e,`string`);return YD(t)==`symbol`?t:t+``}function eO(e,t){if(YD(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(YD(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var tO=function(){function e(){XD(this,e)}return QD(e,[{key:`createRequest`,value:function(e,t){return new nO(e,t)}},{key:`getName`,value:function(){return`XHRHttpStack`}}])}(),nO=function(){function e(t,n){XD(this,e),this._xhr=new XMLHttpRequest,this._xhr.open(t,n,!0),this._method=t,this._url=n,this._headers={}}return QD(e,[{key:`getMethod`,value:function(){return this._method}},{key:`getURL`,value:function(){return this._url}},{key:`setHeader`,value:function(e,t){this._xhr.setRequestHeader(e,t),this._headers[e]=t}},{key:`getHeader`,value:function(e){return this._headers[e]}},{key:`setProgressHandler`,value:function(e){`upload`in this._xhr&&(this._xhr.upload.onprogress=function(t){t.lengthComputable&&e(t.loaded)})}},{key:`send`,value:function(){var e=this,t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null;return new Promise(function(n,r){e._xhr.onload=function(){n(new rO(e._xhr))},e._xhr.onerror=function(e){r(e)},e._xhr.send(t)})}},{key:`abort`,value:function(){return this._xhr.abort(),Promise.resolve()}},{key:`getUnderlyingObject`,value:function(){return this._xhr}}])}(),rO=function(){function e(t){XD(this,e),this._xhr=t}return QD(e,[{key:`getStatus`,value:function(){return this._xhr.status}},{key:`getHeader`,value:function(e){return this._xhr.getResponseHeader(e)}},{key:`getBody`,value:function(){return this._xhr.responseText}},{key:`getUnderlyingObject`,value:function(){return this._xhr}}])}();function iO(e){"@babel/helpers - typeof";return iO=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},iO(e)}function aO(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function oO(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,cO(r.key),r)}}function sO(e,t,n){return t&&oO(e.prototype,t),n&&oO(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function cO(e){var t=lO(e,`string`);return iO(t)==`symbol`?t:t+``}function lO(e,t){if(iO(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(iO(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var uO=!1;try{uO=`localStorage`in window;var dO=`tusSupport`,fO=localStorage.getItem(dO);localStorage.setItem(dO,fO),fO===null&&localStorage.removeItem(dO)}catch(e){if(e.code===e.SECURITY_ERR||e.code===e.QUOTA_EXCEEDED_ERR)uO=!1;else throw e}var pO=uO,mO=function(){function e(){aO(this,e)}return sO(e,[{key:`findAllUploads`,value:function(){var e=this._findEntries(`tus::`);return Promise.resolve(e)}},{key:`findUploadsByFingerprint`,value:function(e){var t=this._findEntries(`tus::${e}::`);return Promise.resolve(t)}},{key:`removeUpload`,value:function(e){return localStorage.removeItem(e),Promise.resolve()}},{key:`addUpload`,value:function(e,t){var n=`tus::${e}::${Math.round(Math.random()*0xe8d4a51000)}`;return localStorage.setItem(n,JSON.stringify(t)),Promise.resolve(n)}},{key:`_findEntries`,value:function(e){for(var t=[],n=0;n<localStorage.length;n++){var r=localStorage.key(n);if(r.indexOf(e)===0)try{var i=JSON.parse(localStorage.getItem(r));i.urlStorageKey=r,t.push(i)}catch{}}return t}}])}();function hO(e){"@babel/helpers - typeof";return hO=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},hO(e)}function gO(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}function _O(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,`value`in r&&(r.writable=!0),Object.defineProperty(e,kO(r.key),r)}}function vO(e,t,n){return t&&_O(e.prototype,t),n&&_O(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function yO(e,t,n){return t=CO(t),bO(e,SO()?Reflect.construct(t,n||[],CO(e).constructor):t.apply(e,n))}function bO(e,t){if(t&&(hO(t)===`object`||typeof t==`function`))return t;if(t!==void 0)throw TypeError(`Derived constructors may only return object or undefined`);return xO(e)}function xO(e){if(e===void 0)throw ReferenceError(`this hasn't been initialised - super() hasn't been called`);return e}function SO(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(SO=function(){return!!e})()}function CO(e){return CO=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},CO(e)}function wO(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Super expression must either be null or a function`);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&TO(e,t)}function TO(e,t){return TO=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},TO(e,t)}function EO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function DO(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?EO(Object(n),!0).forEach(function(t){OO(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):EO(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function OO(e,t,n){return t=kO(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kO(e){var t=AO(e,`string`);return hO(t)==`symbol`?t:t+``}function AO(e,t){if(hO(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(hO(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var jO=DO(DO({},aD.defaultOptions),{},{httpStack:new tO,fileReader:new GD,urlStorage:pO?new mO:new JT,fingerprint:KD}),MO=function(e){function t(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:null,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return gO(this,t),n=DO(DO({},jO),n),yO(this,t,[e,n])}return wO(t,e),vO(t,null,[{key:`terminate`,value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return t=DO(DO({},jO),t),aD.terminate(e,t)}}])}(aD);typeof XMLHttpRequest==`function`&&typeof Blob==`function`&&Blob.prototype.slice;var NO=(e=>n=>t(async()=>{let{tusServerUrl:t,uploadUrl:r,uploadToken:i,mimeType:a,onProgress:o,resumePreviousUpload:s=!0}=n,c=`filename`in n?n.filename:n.data.name,l=a||(`filename`in n?void 0:n.data.type)||`application/octet-stream`;return new Promise(a=>{let u=e.createUpload(n.data,{removeFingerprintOnSuccess:!0,endpoint:t,uploadUrl:r,metadata:{filename:c,filetype:l},retryDelays:[0,300,500,700,1e3],headers:{authorization:`Bearer ${i}`},onProgress:(e,t)=>{if(o){let n=Math.round(e/t*100)/100;o({bytesSent:e,bytesTotal:t,normalized:n})}},onError:e=>{a(e)},onSuccess:()=>{a()}});if(!s){u.start();return}u.findPreviousUploads().then(e=>{let t=e.at(0);t&&u.resumeFromPreviousUpload(t),u.start()}).catch(e=>{a(e instanceof Error?e:Error(`Failed to find previous TUS uploads.`,{cause:e}))})})}))({createUpload:(e,t)=>new MO(e,t)}),PO=e.object({id:e.string().min(1),tusServerUrl:e.url(),tusUploadToken:e.string().min(1),mimeType:e.string().min(1),storageKey:e.string().min(1)}),FO=async e=>{let{client:n,file:r,onProgress:i,signal:a}=e;return t(async()=>{a?.throwIfAborted();let e=await vT(r),t=K_(n),o=await t.auth.getSessionToken(),s;try{if(s=new URL(t.buildUrl({path:`/api/v1/project/${encodeURIComponent(t.projectId)}/asset`})),s.origin!==new URL(t.baseUrl).origin)throw Error(`Feature builder asset URL must use the Gateway origin.`)}catch(e){throw Error(`Could not build feature builder asset URL.`,{cause:e})}let c=await fetch(s,{method:`POST`,headers:{Authorization:`Bearer ${o.token}`,"Content-Type":`application/json`},body:JSON.stringify({mimeType:r.type,byteSize:r.size,originalFileName:r.name||`file`,metadata:e instanceof Error?bT:e}),signal:a});if(!c.ok)throw Error(`Could not reserve upload (${c.status}).`);let l=PO.parse(await c.json());a?.throwIfAborted();let u=await Promise.race([NO({data:r,tusServerUrl:l.tusServerUrl,uploadToken:l.tusUploadToken,resumePreviousUpload:!1,onProgress:i}),...a?[new Promise(e=>{a.addEventListener(`abort`,()=>{e(Error(`Upload aborted.`))},{once:!0})})]:[]]);if(u instanceof Error)throw u;return l})},IO=u.from_html(`<button type="button" role="tab"> </button>`),LO=u.from_html(`<footer class="MobileTabBar svelte-17gs0md"><div class="tabs svelte-17gs0md" role="tablist"></div></footer>`),RO={hash:`svelte-17gs0md`,code:`.MobileTabBar.svelte-17gs0md {display:none;flex:none;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.5rem 0.75rem calc(0.5rem + env(safe-area-inset-bottom));background:var(--rough-card, white);}.tabs.svelte-17gs0md {display:grid;grid-template-columns:repeat(var(--mobile-tab-count, 3), minmax(0, 1fr));gap:0.125rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-17gs0md {appearance:none;height:2.25rem;min-width:0;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.5rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;line-height:1;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
93
107
|
box-shadow 120ms ease, color 120ms ease;}.tab.svelte-17gs0md:hover {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-17gs0md {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-17gs0md:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}
|
|
94
108
|
|
|
95
109
|
@media (max-width: 1000px) {.MobileTabBar.svelte-17gs0md {display:block;}
|
|
96
|
-
}`};function
|
|
97
|
-
box-shadow 120ms ease, opacity 120ms ease;}button.svelte-om76s9:hover:not(:disabled) {border-color:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}button.svelte-om76s9:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-om76s9:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-om76s9 {display:flex;width:100%;}.iconOnly.svelte-om76s9 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-om76s9 {justify-content:flex-start;}`};function
|
|
98
|
-
box-shadow 120ms ease, opacity 120ms ease;}button.svelte-1yyy6r1:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-secondary, oklch(0.97 0 0)) 80%, var(--rough-foreground, black));}button.svelte-1yyy6r1:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-1yyy6r1:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-1yyy6r1 {display:flex;width:100%;}.iconOnly.svelte-1yyy6r1 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-1yyy6r1 {justify-content:flex-start;}`};function yx(e,t){l.push(t,!0),l.append_styles(e,vx);let n=l.prop(t,`children`,7),r=l.prop(t,`class`,7,``),i=l.prop(t,`type`,7,`button`),a=l.prop(t,`disabled`,7,!1),o=l.prop(t,`onclick`,7),s=l.prop(t,`role`,7),c=l.prop(t,`block`,7,!1),u=l.prop(t,`iconOnly`,7,!1),d=l.prop(t,`alignStart`,7,!1),f=l.prop(t,`aria-label`,7),p=l.prop(t,`aria-haspopup`,7),m=l.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),l.flush()},get class(){return r()},set class(e=``){r(e),l.flush()},get type(){return i()},set type(e=`button`){i(e),l.flush()},get disabled(){return a()},set disabled(e=!1){a(e),l.flush()},get onclick(){return o()},set onclick(e){o(e),l.flush()},get role(){return s()},set role(e){s(e),l.flush()},get block(){return c()},set block(e=!1){c(e),l.flush()},get iconOnly(){return u()},set iconOnly(e=!1){u(e),l.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),l.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),l.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),l.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),l.flush()}},g=_x();let _;var v=l.child(g);return l.snippet(v,()=>n()??l.noop),l.reset(g),l.template_effect(()=>{l.set_attribute(g,`type`,i()),g.disabled=a(),l.set_attribute(g,`role`,s()),l.set_attribute(g,`aria-label`,f()),l.set_attribute(g,`aria-haspopup`,p()),l.set_attribute(g,`aria-expanded`,m()),_=l.set_class(g,1,l.clsx(r()),`svelte-1yyy6r1`,_,{block:c(),iconOnly:u(),alignStart:d()})}),l.delegated(`click`,g,function(...e){o()?.apply(this,e)}),l.append(e,g),l.pop(h)}l.delegate([`click`]),l.create_custom_element(yx,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var bx=e=>{let t=(e,n={})=>{let r=e?`[${e}] `:``,i=(e,t,i)=>{let a={...n,...i},o=`${r}${t}`,s=Object.keys(a).length>0;e===`info`?s?console.info(o,a):console.info(o):s?console.error(o,a):console.error(o)};return{info:(e,t)=>{i(`info`,e,t)},error:(e,t)=>{i(`error`,e,t)},child:(r,i={})=>{let a=e?`${e}:${r}`:r;return t(a,{...n,...i})}}};return t(e)},xx=`2.0.0`,Sx=`app.rough.frame.server.port`,Cx=(e,t)=>!!e&&typeof e==`object`&&`type`in e&&e.type===t&&`version`in e&&typeof e.version==`string`,wx=class{serverWindow;getClientWindow;clientOrigin;createSession;createMessageChannel;logger;session;listening=!1;constructor(e){this.serverWindow=e.serverWindow,this.getClientWindow=e.getClientWindow,this.clientOrigin=e.clientOrigin,this.createSession=e.createSession,this.createMessageChannel=e.createMessageChannel??(()=>new MessageChannel),this.logger=(e.logger??bx()).child(`channel-server`)}start(){this.listening||=(this.serverWindow.addEventListener(`message`,this.onMessage),!0)}stop(){this.listening&&(this.serverWindow.removeEventListener(`message`,this.onMessage),this.listening=!1,this.disposeSession())}onMessage=e=>{if(this.clientOrigin!==`*`&&e.origin!==this.clientOrigin){this.logger.info(`message ignored`,{reason:`unexpected origin`,origin:e.origin});return}if(!Cx(e.data,`app.rough.frame.client.ready`)){this.logger.info(`message ignored`,{reason:`unexpected type`,data:e.data});return}let t=this.getClientWindow();if(!t||e.source!==t){this.logger.info(`message ignored`,{reason:`unexpected source`});return}let n=this.createMessageChannel();this.disposeSession(),this.session=this.createSession(n.port1),t.postMessage({type:Sx,version:xx},{targetOrigin:this.clientOrigin,transfer:[n.port2]})};disposeSession(){this.session&&=(this.session[Symbol.dispose]?.(),void 0)}},Tx=[{},{}],Ex=e=>{let{store:t,iframeElement:n,onReportSize:r,getBridgeMethodDefinitions:i}=e;return{_internal:{reportSize(e){n&&(n.style.minHeight=`${e.height}px`),r?.(e)},getBridgeMethodDefinitions(){return i?.()??[]},state:{get(){return t.get()??Tx},set(e){t.set(e)},addListener(e){let n=e.dup(),r=t.addListener(n);return()=>{r(),n[Symbol.dispose]()}}}}}},Dx=class{containerElement;channelServer;iframeSrc;iframeElement;constructor(e){let{iframe:t,serverWindow:n=globalThis.window,clientOrigin:r=`*`,getTools:i,getBridgeMethodDefinitions:a,logger:o=bx(),store:s}=e,c;if(`contentWindow`in t)this.iframeElement=void 0,c=()=>t.contentWindow;else{let{containerElement:e,src:n,title:r,allow:i=[`fullscreen`,`camera`,`microphone`]}=t;this.containerElement=e,this.iframeElement=document.createElement(`iframe`),this.iframeSrc=n,this.iframeElement.width=`100%`,this.iframeElement.title=r,this.iframeElement.allow=i.join(`; `),this.iframeElement.style=`border: none;`,e.appendChild(this.iframeElement),c=()=>this.iframeElement?.contentWindow??void 0}let l=Ex({store:s,iframeElement:this.iframeElement,onReportSize:t.onReportSize,getBridgeMethodDefinitions:a});this.channelServer=new wx({getClientWindow:c,serverWindow:n,clientOrigin:r,logger:o,createSession:e=>{let t=i();return f(e,{...t,...l})}})}start(){this.channelServer.start(),this.iframeElement&&this.iframeSrc!==void 0&&(this.iframeElement.src=this.iframeSrc,this.iframeSrc=void 0)}stop(){this.channelServer.stop(),this.containerElement&&this.iframeElement&&(this.containerElement.removeChild(this.iframeElement),this.iframeElement=void 0)}},Ox=l.from_html(`<div><!></div>`);function kx(e,t){l.push(t,!0);let n=l.prop(t,`handle`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``),a,s=l.derived(()=>[n().class,i()].filter(Boolean).join(` `));o(()=>{a&&n().destroy(a)});var c={get handle(){return n()},set handle(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},u=Ox(),d=l.child(u);return l.snippet(d,()=>r()??l.noop),l.reset(u),l.bind_this(u,e=>a=e,()=>a),l.template_effect(()=>{l.set_class(u,1,l.clsx(l.get(s))),l.set_attribute(u,`role`,n().role),l.set_attribute(u,`aria-orientation`,n()[`aria-orientation`]),l.set_attribute(u,`aria-label`,n()[`aria-label`]),l.set_attribute(u,`title`,n().title)}),l.delegated(`pointerdown`,u,function(...e){n().onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,u,function(...e){n().onpointermove?.apply(this,e)}),l.delegated(`pointerup`,u,function(...e){n().onpointerup?.apply(this,e)}),l.event(`pointercancel`,u,function(...e){n().onpointercancel?.apply(this,e)}),l.delegated(`dblclick`,u,function(...e){n().ondblclick?.apply(this,e)}),l.append(e,u),l.pop(c)}l.delegate([`pointerdown`,`pointermove`,`pointerup`,`dblclick`]),l.create_custom_element(kx,{handle:{},children:{},class:{}},[],[],{mode:`open`});var Ax=e=>e.minHeight??100,jx=e=>e.maxHeight??2e3,Mx=(e,t)=>Math.min(jx(t),Math.max(Ax(t),Math.round(e))),Nx={resized:`Resizable--resized`,handle:`Resizable__resize-handle`},Px={triggerPx:60,maxSpeedPx:16},Fx=e=>{let t,n=0,r=()=>{t=void 0,!(!e.isActive()||n===0)&&(e.scrollBy(n),e.onScroll(),t=requestAnimationFrame(r))},i=e=>{n=e,t===void 0&&(t=requestAnimationFrame(r))},a=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0),n=0};return{stop:a,updateForPointer:t=>{let n=e.getViewport(),r=n.bottom-t,o=t-n.top;if(r<Px.triggerPx){let e=Math.min(1,1-r/Px.triggerPx);i(Math.max(1,Math.round(Px.maxSpeedPx*e)))}else o<=0?i(-Px.maxSpeedPx):a()}}},Ix=()=>{let e=document.documentElement,t=document.body;return Math.max(e.clientHeight,t?.offsetHeight??0,t?.scrollHeight??0)},Lx=()=>{let e,t,n=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0)};return{lock:()=>{n();let t=document.documentElement;e={previous:e?.previous??t.style.minHeight,element:t},t.style.minHeight=`${t.scrollHeight}px`},growToContent:()=>{if(!e)return;let t=e.element,n=Number.parseFloat(t.style.minHeight),r=Math.max(Number.isFinite(n)?n:0,t.scrollHeight);t.style.minHeight=`${r}px`},release:(r=!0)=>{if(n(),!e)return;let i=e,a=i.element,o=a.scrollHeight,s=Number.parseFloat(i.previous),c=Math.max(Ix(),Number.isFinite(s)?s:0);if(!r||c>=o){a.style.minHeight=i.previous,e=void 0;return}let l=performance.now(),u=n=>{let r=Math.min(1,(n-l)/180),s=1-(1-r)**3;if(a.style.minHeight=`${o+(c-o)*s}px`,r<1){t=requestAnimationFrame(u);return}a.style.minHeight=i.previous,e=void 0,t=void 0};t=requestAnimationFrame(u)}}},Rx=e=>{let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t);if((e.overflowY===`auto`||e.overflowY===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}},zx=e=>({...Nx,...e.classNames}),Bx=(e={})=>{let t,n,r,i,a=Lx(),o=n=>{if(t){if(i&&=(t.classList.remove(i),void 0),typeof n==`number`){let r=zx(e);t.style.height=`${n}px`,t.classList.add(r.resized),i=r.resized}else t.style.removeProperty(`height`)}},s=()=>{if(n?.scrollTarget){let e=n.scrollTarget.getBoundingClientRect();return{top:e.top,bottom:e.bottom}}return{top:0,bottom:window.innerHeight}},c=e=>{e!==0&&(n?.scrollTarget?n.scrollTarget.scrollTop+=e:window.scrollBy({top:e,left:0,behavior:`instant`}))},l=()=>{if(!n||!t)return;let r=t.getBoundingClientRect(),i=n.lastClientY-n.grabOffset;o(Mx(i-r.top,e)),a.growToContent()},u=Fx({getViewport:s,isActive:()=>n!==void 0,scrollBy:c,onScroll:l}),d=(e=!0)=>{n=void 0,r=void 0,u.stop(),a.release(e)},f=i=>{if(!t||i.button!==0&&i.pointerType===`mouse`)return;i.preventDefault();let s=i.currentTarget,c=t.getBoundingClientRect();n={pointerId:i.pointerId,grabOffset:i.clientY-c.bottom,lastClientY:i.clientY,scrollTarget:Rx(t)},r=s,o(Mx(c.height,e)),a.lock(),s.setPointerCapture(i.pointerId)},p=e=>{n?.pointerId===e.pointerId&&(n.lastClientY=e.clientY,l(),u.updateForPointer(e.clientY))},m=r=>{if(n?.pointerId!==r.pointerId)return;let i=r.currentTarget;if(d(),i.hasPointerCapture(r.pointerId)&&i.releasePointerCapture(r.pointerId),!t)return;let a=Number.parseFloat(t.style.height);Number.isFinite(a)&&e.heightStore?.set(a)},h=()=>{e.heightStore?.clear(),o(void 0)},g=e=>{r===e&&d(!1)},_=i=>(t=i,o(e.heightStore?.get()),()=>{u.stop(),a.release(!1),o(void 0),n=void 0,r=void 0,t=void 0});return _.handle=()=>({class:zx(e).handle,role:`separator`,"aria-orientation":`horizontal`,"aria-label":e.label??`Resize`,title:e.title??`Drag to resize, double-click to reset`,onpointerdown:f,onpointermove:p,onpointerup:m,onpointercancel:m,ondblclick:h,destroy:g}),_},Vx=()=>{let e=new Set;return{addListener(t){return e.add(t),()=>{e.delete(t)}},notify(t){for(let n of e)n(t)}}},Hx=e=>e,Ux=e=>e,Wx=e=>e,Gx=e=>({get:()=>Ux(e.get()),set:t=>{e.set(Wx(t))},addListener:t=>e.addListener(e=>{t(Hx(e))})}),Kx=()=>{let e=Vx(),t;return{get:()=>t,set:n=>{t=n,e.notify(n)},addListener:e.addListener}},qx=(e,t=globalThis.localStorage)=>{let n=Vx(),r=`app.rough.feature/sprite/${e}`;return{get:()=>{let e=t.getItem(r);return e===null?void 0:JSON.parse(e)},set:e=>{t.setItem(r,JSON.stringify(e)),n.notify(e)},addListener:n.addListener}},Jx=({datastore:e,isMock:t,spriteInstanceId:n,storage:r})=>{if(e)return Gx(e);if(t)return Kx();if(n)return qx(n,r);throw Error(`SpriteFrame is missing a spriteInstanceId.`)},Yx=l.from_html(`<div class="SpriteFrame svelte-ncf2zx"><!></div>`),Xx={hash:`svelte-ncf2zx`,code:`.SpriteFrame.svelte-ncf2zx {position:relative;flex:1;width:100%;min-height:100px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);overflow-y:auto;background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
modal. Scroll inside the frame instead. */}.SpriteFrame.svelte-ncf2zx.Resizable--resized {flex:none;overflow:hidden;}.SpriteFrame.svelte-ncf2zx.Resizable--resized iframe {height:100%;min-height:0 !important;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle {position:absolute;right:0;bottom:0;left:0;z-index:1;height:10px;cursor:ns-resize;touch-action:none;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle::after {content:'';position:absolute;bottom:3px;left:50%;width:3rem;height:3px;border-radius:999px;background:var(--rough-border, oklch(0.922 0 0));transform:translateX(-50%);transition:background-color 120ms ease, height 120ms ease;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:hover::after,
|
|
102
|
-
.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:active::after {height:4px;background:var(--rough-ring, oklch(0.708 0 0));}`};function Zx(e,t){l.push(t,!0),l.append_styles(e,Xx);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuildId`,7),i=l.prop(t,`artifactUrl`,7),a=l.prop(t,`toolList`,7),o=l.prop(t,`datastore`,7),s=l.prop(t,`isMock`,7),c=l.prop(t,`spriteInstanceId`,7),u=l.prop(t,`minHeight`,7,100),d=l.prop(t,`maxHeight`,7,2e3),f=l.derived(()=>n()?Qg(n()).store:void 0),p=l.derived(()=>l.get(f)?db(l.get(f).spriteBuild.get(r())):db.undefined),m=l.derived(()=>l.get(p)._),h=l.derived(()=>typeof i()==`string`?i():l.get(m)?.artifactUrl??void 0),g=l.state(void 0),_=l.derived(()=>Jx({datastore:o(),isMock:s(),spriteInstanceId:c()})),v=e=>{if(!e||s()){let e;return{get:()=>e,set:t=>{e=t},clear:()=>{e=void 0}}}let t=`app.rough.feature/sprite/${e}/height`;return{get:()=>{let e=localStorage.getItem(t);if(e!==null)try{let t=JSON.parse(e);return typeof t?.height==`number`?t.height:void 0}catch{return}},set:e=>{localStorage.setItem(t,JSON.stringify({height:e}))},clear:()=>{localStorage.removeItem(t)}}},y=l.derived(()=>v(c())),b=Bx({get minHeight(){return u()},get maxHeight(){return d()},get heightStore(){return l.get(y)},label:`Resize Rough feature`,title:`Drag to resize, double-click to reset`});l.user_effect(()=>{if(!l.get(h)||!l.get(g))return;let e=new Dx({iframe:{containerElement:l.get(g),src:l.get(h),title:`Sprite Frame`},getTools:()=>s()?ne(a()):te(a()),getBridgeMethodDefinitions:()=>a().map(e=>e.toJSON()),store:l.get(_)});return e.start(),()=>{e.stop()}});var ee={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuildId(){return r()},set spriteBuildId(e){r(e),l.flush()},get artifactUrl(){return i()},set artifactUrl(e){i(e),l.flush()},get toolList(){return a()},set toolList(e){a(e),l.flush()},get datastore(){return o()},set datastore(e){o(e),l.flush()},get isMock(){return s()},set isMock(e){s(e),l.flush()},get spriteInstanceId(){return c()},set spriteInstanceId(e){c(e),l.flush()},get minHeight(){return u()},set minHeight(e=100){u(e),l.flush()},get maxHeight(){return d()},set maxHeight(e=2e3){d(e),l.flush()}},x=Yx(),re=l.child(x);{let e=l.derived(()=>b.handle());kx(re,{get handle(){return l.get(e)}})}return l.reset(x),l.bind_this(x,e=>l.set(g,e),()=>l.get(g)),l.attach(x,()=>b),l.append(e,x),l.pop(ee)}l.create_custom_element(Zx,{client:{},spriteBuildId:{},artifactUrl:{},toolList:{},datastore:{},isMock:{},spriteInstanceId:{},minHeight:{},maxHeight:{}},[],[],{mode:`open`});var Qx=l.from_html(`<button type="button" role="tab"> </button>`),$x=l.from_html(`<div class="TabBar svelte-1jp57o0" role="tablist"></div>`),eS={hash:`svelte-1jp57o0`,code:`.TabBar.svelte-1jp57o0 {display:inline-flex;align-items:center;justify-content:center;gap:0.125rem;flex-shrink:0;width:fit-content;margin:0.75rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-1jp57o0 {appearance:none;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.75rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;white-space:nowrap;cursor:pointer;transition:color 120ms ease, background-color 120ms ease,
|
|
103
|
-
border-color 120ms ease, box-shadow 120ms ease;}.tab.svelte-1jp57o0:hover:not(:disabled) {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-1jp57o0 {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-1jp57o0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.tab.svelte-1jp57o0:disabled {opacity:0.5;cursor:not-allowed;}`};function tS(e,t){l.push(t,!0),l.append_styles(e,eS);let n=l.prop(t,`active`,15),r=l.prop(t,`tabs`,7),i=e=>{e.disabled||n(e.key)},a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]:not(:disabled)`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),l.flush()},get tabs(){return r()},set tabs(e){r(e),l.flush()}},s=$x();return l.each(s,21,r,e=>e.key,(e,t)=>{var r=Qx();let o;var s=l.child(r,!0);l.reset(r),l.template_effect(()=>{o=l.set_class(r,1,`tab svelte-1jp57o0`,null,o,{active:n()===l.get(t).key}),l.set_attribute(r,`aria-selected`,n()===l.get(t).key),l.set_attribute(r,`tabindex`,n()===l.get(t).key?0:-1),r.disabled=l.get(t).disabled,l.set_text(s,l.get(t).label)}),l.delegated(`click`,r,()=>i(l.get(t))),l.delegated(`keydown`,r,a),l.append(e,r)}),l.reset(s),l.append(e,s),l.pop(o)}l.delegate([`click`,`keydown`]),l.create_custom_element(tS,{active:{},tabs:{}},[],[],{mode:`open`});var nS=l.from_html(`<div role="tabpanel"><!></div>`),rS={hash:`svelte-1ermak1`,code:`.TabPanel.svelte-1ermak1 {display:none;min-width:0;min-height:0;}.TabPanel.isActive.svelte-1ermak1 {display:flex;flex:1;flex-direction:column;}`};function iS(e,t){l.push(t,!0),l.append_styles(e,rS);let n=l.prop(t,`isActive`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``);var a={get isActive(){return n()},set isActive(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},o=nS();let s;var c=l.child(o);return l.snippet(c,()=>r()??l.noop),l.reset(o),l.template_effect(()=>{s=l.set_class(o,1,`TabPanel ${i()}`,`svelte-1ermak1`,s,{isActive:n()}),l.set_attribute(o,`aria-hidden`,!n()),o.inert=!n()}),l.append(e,o),l.pop(a)}l.create_custom_element(iS,{isActive:{},children:{},class:{}},[],[],{mode:`open`});var aS=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function oS(e,t){let n=l.rest_props(t,aS),r=[[`path`,{d:`m6 9 6 6 6-6`}]];d_(e,l.spread_props({name:`chevron-down`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(oS,{},[],[],{mode:`open`});var sS=l.from_html(`<div class="preview svelte-khztz9"><!></div>`),cS=l.from_html(`<details class="Accordion svelte-khztz9"><summary class="svelte-khztz9"><header class="svelte-khztz9"><span class="heading svelte-khztz9"><!></span> <span class="chevron svelte-khztz9"><!></span></header> <!></summary> <!></details>`),lS={hash:`svelte-khztz9`,code:`.Accordion.svelte-khztz9 {display:flex;gap:0.5rem;flex-direction:column;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 0.85rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));&[open] {
|
|
110
|
+
}`};function zO(e,t){u.push(t,!0),u.append_styles(e,RO);let n=u.prop(t,`active`,15),r=u.prop(t,`tabs`,7),i=u.prop(t,`ariaLabel`,7,`Navigation`),a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),u.flush()},get tabs(){return r()},set tabs(e){r(e),u.flush()},get ariaLabel(){return i()},set ariaLabel(e=`Navigation`){i(e),u.flush()}},s=LO(),c=u.child(s);let l;return u.each(c,21,r,e=>e.key,(e,t)=>{var r=IO();let i;var o=u.only_child(r,!0);u.template_effect(()=>{i=u.set_class(r,1,`tab svelte-17gs0md`,null,i,{active:n()===u.get(t).key}),u.set_attribute(r,`aria-selected`,n()===u.get(t).key),u.set_attribute(r,`tabindex`,n()===u.get(t).key?0:-1),u.set_text(o,u.get(t).label)}),u.delegated(`click`,r,()=>n(u.get(t).key)),u.delegated(`keydown`,r,a),u.append(e,r)}),u.reset(c),u.reset(s),u.template_effect(()=>{u.set_attribute(s,`aria-label`,i()),u.set_attribute(c,`aria-label`,i()),l=u.set_style(c,``,l,{"--mobile-tab-count":r().length})}),u.append(e,s),u.pop(o)}u.delegate([`click`,`keydown`]),u.create_custom_element(zO,{active:{},tabs:{},ariaLabel:{}},[],[],{mode:`open`});var BO=u.from_html(`<button><!></button>`),VO={hash:`svelte-om76s9`,code:`button.svelte-om76s9 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid var(--rough-primary, oklch(0.205 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-primary-foreground, white);font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
111
|
+
box-shadow 120ms ease, opacity 120ms ease;}button.svelte-om76s9:hover:not(:disabled) {border-color:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}button.svelte-om76s9:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-om76s9:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-om76s9 {display:flex;width:100%;}.iconOnly.svelte-om76s9 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-om76s9 {justify-content:flex-start;}`};function HO(e,t){u.push(t,!0),u.append_styles(e,VO);let n=u.prop(t,`children`,7),r=u.prop(t,`class`,7,``),i=u.prop(t,`type`,7,`button`),a=u.prop(t,`disabled`,7,!1),o=u.prop(t,`onclick`,7),s=u.prop(t,`role`,7),c=u.prop(t,`block`,7,!1),l=u.prop(t,`iconOnly`,7,!1),d=u.prop(t,`alignStart`,7,!1),f=u.prop(t,`aria-label`,7),p=u.prop(t,`aria-haspopup`,7),m=u.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),u.flush()},get class(){return r()},set class(e=``){r(e),u.flush()},get type(){return i()},set type(e=`button`){i(e),u.flush()},get disabled(){return a()},set disabled(e=!1){a(e),u.flush()},get onclick(){return o()},set onclick(e){o(e),u.flush()},get role(){return s()},set role(e){s(e),u.flush()},get block(){return c()},set block(e=!1){c(e),u.flush()},get iconOnly(){return l()},set iconOnly(e=!1){l(e),u.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),u.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),u.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),u.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),u.flush()}},g=BO();let _;var v=u.child(g);return u.snippet(v,()=>n()??u.noop),u.reset(g),u.template_effect(()=>{u.set_attribute(g,`type`,i()),g.disabled=a(),u.set_attribute(g,`role`,s()),u.set_attribute(g,`aria-label`,f()),u.set_attribute(g,`aria-haspopup`,p()),u.set_attribute(g,`aria-expanded`,m()),_=u.set_class(g,1,u.clsx(r()),`svelte-om76s9`,_,{block:c(),iconOnly:l(),alignStart:d()})}),u.delegated(`click`,g,function(...e){o()?.apply(this,e)}),u.append(e,g),u.pop(h)}u.delegate([`click`]),u.create_custom_element(HO,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var UO=e=>t=>{let n=e??window.document.body;return n.appendChild(t),t.hidden=!1,()=>{t.parentNode===n&&n.removeChild(t)}},WO=u.from_html(`<dialog class="svelte-1phmmvx"><!></dialog>`),GO={hash:`svelte-1phmmvx`,code:`dialog.svelte-1phmmvx {position:fixed;inset:2rem;width:auto;height:auto;max-width:none;max-height:none;margin:0;border:none;padding:0;background:transparent;}dialog.svelte-1phmmvx::backdrop {background:rgb(0 0 0 / 0.5);}`};function KO(e,t){u.push(t,!0),u.append_styles(e,GO);let n=u.prop(t,`isOpen`,15,!0),r=u.prop(t,`target`,7),i=u.prop(t,`onclose`,7),a=u.prop(t,`oncancel`,7),o=u.prop(t,`children`,7),s=u.state(void 0);u.user_effect(()=>{if(u.get(s)){if(n()&&!u.get(s).open){u.get(s).showModal();return}!n()&&u.get(s).open&&u.get(s).close()}});var c={get isOpen(){return n()},set isOpen(e=!0){n(e),u.flush()},get target(){return r()},set target(e){r(e),u.flush()},get onclose(){return i()},set onclose(e){i(e),u.flush()},get oncancel(){return a()},set oncancel(e){a(e),u.flush()},get children(){return o()},set children(e){o(e),u.flush()}},l=WO(),d=u.child(l);return u.snippet(d,()=>o()??u.noop),u.reset(l),u.bind_this(l,e=>u.set(s,e),()=>u.get(s)),u.attach(l,()=>UO(r())),u.event(`close`,l,()=>{n(!1),i()?.()}),u.event(`cancel`,l,function(...e){a()?.apply(this,e)}),u.append(e,l),u.pop(c)}u.create_custom_element(KO,{isOpen:{},target:{},onclose:{},oncancel:{},children:{}},[],[],{mode:`open`});var qO=u.from_html(`<button><!></button>`),JO={hash:`svelte-1yyy6r1`,code:`button.svelte-1yyy6r1 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-secondary, oklch(0.97 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-secondary-foreground, oklch(0.205 0 0));font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
112
|
+
box-shadow 120ms ease, opacity 120ms ease;}button.svelte-1yyy6r1:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-secondary, oklch(0.97 0 0)) 80%, var(--rough-foreground, black));}button.svelte-1yyy6r1:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-1yyy6r1:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-1yyy6r1 {display:flex;width:100%;}.iconOnly.svelte-1yyy6r1 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-1yyy6r1 {justify-content:flex-start;}`};function YO(e,t){u.push(t,!0),u.append_styles(e,JO);let n=u.prop(t,`children`,7),r=u.prop(t,`class`,7,``),i=u.prop(t,`type`,7,`button`),a=u.prop(t,`disabled`,7,!1),o=u.prop(t,`onclick`,7),s=u.prop(t,`role`,7),c=u.prop(t,`block`,7,!1),l=u.prop(t,`iconOnly`,7,!1),d=u.prop(t,`alignStart`,7,!1),f=u.prop(t,`aria-label`,7),p=u.prop(t,`aria-haspopup`,7),m=u.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),u.flush()},get class(){return r()},set class(e=``){r(e),u.flush()},get type(){return i()},set type(e=`button`){i(e),u.flush()},get disabled(){return a()},set disabled(e=!1){a(e),u.flush()},get onclick(){return o()},set onclick(e){o(e),u.flush()},get role(){return s()},set role(e){s(e),u.flush()},get block(){return c()},set block(e=!1){c(e),u.flush()},get iconOnly(){return l()},set iconOnly(e=!1){l(e),u.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),u.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),u.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),u.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),u.flush()}},g=qO();let _;var v=u.child(g);return u.snippet(v,()=>n()??u.noop),u.reset(g),u.template_effect(()=>{u.set_attribute(g,`type`,i()),g.disabled=a(),u.set_attribute(g,`role`,s()),u.set_attribute(g,`aria-label`,f()),u.set_attribute(g,`aria-haspopup`,p()),u.set_attribute(g,`aria-expanded`,m()),_=u.set_class(g,1,u.clsx(r()),`svelte-1yyy6r1`,_,{block:c(),iconOnly:l(),alignStart:d()})}),u.delegated(`click`,g,function(...e){o()?.apply(this,e)}),u.append(e,g),u.pop(h)}u.delegate([`click`]),u.create_custom_element(YO,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var XO=e=>{let t=(e,n={})=>{let r=e?`[${e}] `:``,i=(e,t,i)=>{let a={...n,...i},o=`${r}${t}`,s=Object.keys(a).length>0;e===`info`?s?console.info(o,a):console.info(o):s?console.error(o,a):console.error(o)};return{info:(e,t)=>{i(`info`,e,t)},error:(e,t)=>{i(`error`,e,t)},child:(r,i={})=>{let a=e?`${e}:${r}`:r;return t(a,{...n,...i})}}};return t(e)},ZO=`2.0.0`,QO=`app.rough.frame.server.port`,$O=(e,t)=>!!e&&typeof e==`object`&&`type`in e&&e.type===t&&`version`in e&&typeof e.version==`string`,ek=class{serverWindow;getClientWindow;clientOrigin;createSession;createMessageChannel;logger;session;listening=!1;constructor(e){this.serverWindow=e.serverWindow,this.getClientWindow=e.getClientWindow,this.clientOrigin=e.clientOrigin,this.createSession=e.createSession,this.createMessageChannel=e.createMessageChannel??(()=>new MessageChannel),this.logger=(e.logger??XO()).child(`channel-server`)}start(){this.listening||=(this.serverWindow.addEventListener(`message`,this.onMessage),!0)}stop(){this.listening&&(this.serverWindow.removeEventListener(`message`,this.onMessage),this.listening=!1,this.disposeSession())}onMessage=e=>{if(this.clientOrigin!==`*`&&e.origin!==this.clientOrigin){this.logger.info(`message ignored`,{reason:`unexpected origin`,origin:e.origin});return}if(!$O(e.data,`app.rough.frame.client.ready`)){this.logger.info(`message ignored`,{reason:`unexpected type`,data:e.data});return}let t=this.getClientWindow();if(!t||e.source!==t){this.logger.info(`message ignored`,{reason:`unexpected source`});return}let n=this.createMessageChannel();this.disposeSession(),this.session=this.createSession(n.port1),t.postMessage({type:QO,version:ZO},{targetOrigin:this.clientOrigin,transfer:[n.port2]})};disposeSession(){this.session&&=(this.session[Symbol.dispose]?.(),void 0)}},tk=[{},{}],nk=e=>{let{store:t,iframeElement:n,onReportSize:r,getBridgeMethodDefinitions:i}=e;return{_internal:{reportSize(e){n&&(n.style.minHeight=`${e.height}px`),r?.(e)},getBridgeMethodDefinitions(){return i?.()??[]},state:{get(){return t.get()??tk},set(e){t.set(e)},addListener(e){let n=e.dup(),r=t.addListener(n);return()=>{r(),n[Symbol.dispose]()}}}}}},rk=class{containerElement;channelServer;iframeSrc;iframeElement;constructor(e){let{iframe:t,serverWindow:n=globalThis.window,clientOrigin:r=`*`,getTools:i,getBridgeMethodDefinitions:a,logger:o=XO(),store:s}=e,c;if(`contentWindow`in t)this.iframeElement=void 0,c=()=>t.contentWindow;else{let{containerElement:e,src:n,title:r,allow:i=[`fullscreen`,`camera`,`microphone`]}=t;this.containerElement=e,this.iframeElement=document.createElement(`iframe`),this.iframeSrc=n,this.iframeElement.width=`100%`,this.iframeElement.title=r,this.iframeElement.allow=i.join(`; `),this.iframeElement.style=`border: none;`,e.appendChild(this.iframeElement),c=()=>this.iframeElement?.contentWindow??void 0}let l=nk({store:s,iframeElement:this.iframeElement,onReportSize:t.onReportSize,getBridgeMethodDefinitions:a});this.channelServer=new ek({getClientWindow:c,serverWindow:n,clientOrigin:r,logger:o,createSession:e=>{let t=i();return p(e,{...t,...l})}})}start(){this.channelServer.start(),this.iframeElement&&this.iframeSrc!==void 0&&(this.iframeElement.src=this.iframeSrc,this.iframeSrc=void 0)}stop(){this.channelServer.stop(),this.containerElement&&this.iframeElement&&(this.containerElement.removeChild(this.iframeElement),this.iframeElement=void 0)}},ik=u.from_html(`<div><!></div>`);function ak(e,t){u.push(t,!0);let n=u.prop(t,`handle`,7),r=u.prop(t,`children`,7),i=u.prop(t,`class`,7,``),a,s=u.derived(()=>[n().class,i()].filter(Boolean).join(` `));o(()=>{a&&n().destroy(a)});var c={get handle(){return n()},set handle(e){n(e),u.flush()},get children(){return r()},set children(e){r(e),u.flush()},get class(){return i()},set class(e=``){i(e),u.flush()}},l=ik(),d=u.child(l);return u.snippet(d,()=>r()??u.noop),u.reset(l),u.bind_this(l,e=>a=e,()=>a),u.template_effect(()=>{u.set_class(l,1,u.clsx(u.get(s))),u.set_attribute(l,`role`,n().role),u.set_attribute(l,`aria-orientation`,n()[`aria-orientation`]),u.set_attribute(l,`aria-label`,n()[`aria-label`]),u.set_attribute(l,`title`,n().title)}),u.delegated(`pointerdown`,l,function(...e){n().onpointerdown?.apply(this,e)}),u.delegated(`pointermove`,l,function(...e){n().onpointermove?.apply(this,e)}),u.delegated(`pointerup`,l,function(...e){n().onpointerup?.apply(this,e)}),u.event(`pointercancel`,l,function(...e){n().onpointercancel?.apply(this,e)}),u.delegated(`dblclick`,l,function(...e){n().ondblclick?.apply(this,e)}),u.append(e,l),u.pop(c)}u.delegate([`pointerdown`,`pointermove`,`pointerup`,`dblclick`]),u.create_custom_element(ak,{handle:{},children:{},class:{}},[],[],{mode:`open`});var ok=e=>e.minHeight??100,sk=e=>e.maxHeight??2e3,ck=(e,t)=>Math.min(sk(t),Math.max(ok(t),Math.round(e))),lk={resized:`Resizable--resized`,handle:`Resizable__resize-handle`},uk={triggerPx:60,maxSpeedPx:16},dk=e=>{let t,n=0,r=()=>{t=void 0,e.isActive()&&n!==0&&(e.scrollBy(n),e.onScroll(),t=requestAnimationFrame(r))},i=e=>{n=e,t===void 0&&(t=requestAnimationFrame(r))},a=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0),n=0};return{stop:a,updateForPointer:t=>{let n=e.getViewport(),r=n.bottom-t,o=t-n.top;if(r<uk.triggerPx){let e=Math.min(1,1-r/uk.triggerPx);i(Math.max(1,Math.round(uk.maxSpeedPx*e)))}else o<=0?i(-uk.maxSpeedPx):a()}}},fk=()=>{let e=document.documentElement,t=document.body;return Math.max(e.clientHeight,t?.offsetHeight??0,t?.scrollHeight??0)},pk=()=>{let e,t,n=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0)};return{lock:()=>{n();let t=document.documentElement;e={previous:e?.previous??t.style.minHeight,element:t},t.style.minHeight=`${t.scrollHeight}px`},growToContent:()=>{if(!e)return;let t=e.element,n=Number.parseFloat(t.style.minHeight),r=Math.max(Number.isFinite(n)?n:0,t.scrollHeight);t.style.minHeight=`${r}px`},release:(r=!0)=>{if(n(),!e)return;let i=e,a=i.element,o=a.scrollHeight,s=Number.parseFloat(i.previous),c=Math.max(fk(),Number.isFinite(s)?s:0);if(!r||c>=o){a.style.minHeight=i.previous,e=void 0;return}let l=performance.now(),u=n=>{let r=Math.min(1,(n-l)/180),s=1-(1-r)**3;if(a.style.minHeight=`${o+(c-o)*s}px`,r<1){t=requestAnimationFrame(u);return}a.style.minHeight=i.previous,e=void 0,t=void 0};t=requestAnimationFrame(u)}}},mk=e=>{let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t);if((e.overflowY===`auto`||e.overflowY===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}},hk=e=>({...lk,...e.classNames}),gk=(e={})=>{let t,n,r,i,a=pk(),o=n=>{if(t){if(i&&=(t.classList.remove(i),void 0),typeof n==`number`){let r=hk(e);t.style.height=`${n}px`,t.classList.add(r.resized),i=r.resized}else t.style.removeProperty(`height`)}},s=()=>{if(n?.scrollTarget){let e=n.scrollTarget.getBoundingClientRect();return{top:e.top,bottom:e.bottom}}return{top:0,bottom:window.innerHeight}},c=e=>{e!==0&&(n?.scrollTarget?n.scrollTarget.scrollTop+=e:window.scrollBy({top:e,left:0,behavior:`instant`}))},l=()=>{if(!n||!t)return;let r=t.getBoundingClientRect(),i=n.lastClientY-n.grabOffset;o(ck(i-r.top,e)),a.growToContent()},u=dk({getViewport:s,isActive:()=>n!==void 0,scrollBy:c,onScroll:l}),d=(e=!0)=>{n=void 0,r=void 0,u.stop(),a.release(e)},f=i=>{if(!t||i.button!==0&&i.pointerType===`mouse`)return;i.preventDefault();let s=i.currentTarget,c=t.getBoundingClientRect();n={pointerId:i.pointerId,grabOffset:i.clientY-c.bottom,lastClientY:i.clientY,scrollTarget:mk(t)},r=s,o(ck(c.height,e)),a.lock(),s.setPointerCapture(i.pointerId)},p=e=>{n?.pointerId===e.pointerId&&(n.lastClientY=e.clientY,l(),u.updateForPointer(e.clientY))},m=r=>{if(n?.pointerId!==r.pointerId)return;let i=r.currentTarget;if(d(),i.hasPointerCapture(r.pointerId)&&i.releasePointerCapture(r.pointerId),!t)return;let a=Number.parseFloat(t.style.height);Number.isFinite(a)&&e.heightStore?.set(a)},h=()=>{e.heightStore?.clear(),o(void 0)},g=e=>{r===e&&d(!1)},_=i=>(t=i,o(e.heightStore?.get()),()=>{u.stop(),a.release(!1),o(void 0),n=void 0,r=void 0,t=void 0});return _.handle=()=>({class:hk(e).handle,role:`separator`,"aria-orientation":`horizontal`,"aria-label":e.label??`Resize`,title:e.title??`Drag to resize, double-click to reset`,onpointerdown:f,onpointermove:p,onpointerup:m,onpointercancel:m,ondblclick:h,destroy:g}),_},_k=()=>{let e=new Set;return{addListener(t){return e.add(t),()=>{e.delete(t)}},notify(t){for(let n of e)n(t)}}},vk=e=>e,yk=e=>e,bk=e=>e,xk=e=>({get:()=>yk(e.get()),set:t=>{e.set(bk(t))},addListener:t=>e.addListener(e=>{t(vk(e))})}),Sk=()=>{let e=_k(),t;return{get:()=>t,set:n=>{t=n,e.notify(n)},addListener:e.addListener}},Ck=(e,t=globalThis.localStorage)=>{let n=_k(),r=`app.rough.feature/sprite/${e}`;return{get:()=>{let e=t.getItem(r);return e===null?void 0:JSON.parse(e)},set:e=>{t.setItem(r,JSON.stringify(e)),n.notify(e)},addListener:n.addListener}},wk=({datastore:e,isMock:t,spriteInstanceId:n,storage:r})=>{if(e)return xk(e);if(t)return Sk();if(n)return Ck(n,r);throw Error(`SpriteFrame is missing a spriteInstanceId.`)},Tk=u.from_html(`<div class="SpriteFrame svelte-ncf2zx"><!></div>`),Ek={hash:`svelte-ncf2zx`,code:`.SpriteFrame.svelte-ncf2zx {position:relative;flex:1;width:100%;min-height:100px;overflow-y:auto;}.SpriteFrame.svelte-ncf2zx.Resizable--resized {flex:none;overflow:hidden;}.SpriteFrame.svelte-ncf2zx.Resizable--resized iframe {height:100%;min-height:0 !important;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle {position:absolute;right:0;bottom:0;left:0;z-index:1;height:10px;cursor:ns-resize;touch-action:none;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle::after {content:'';position:absolute;bottom:3px;left:50%;width:3rem;height:3px;border-radius:999px;background:var(--rough-border, oklch(0.922 0 0));transform:translateX(-50%);transition:background-color 120ms ease, height 120ms ease;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:hover::after,
|
|
113
|
+
.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:active::after {height:4px;background:var(--rough-ring, oklch(0.708 0 0));}`};function Dk(e,t){u.push(t,!0),u.append_styles(e,Ek);let n=u.prop(t,`client`,7),r=u.prop(t,`spriteBuildId`,7),i=u.prop(t,`artifactUrl`,7),a=u.prop(t,`toolList`,7),o=u.prop(t,`datastore`,7),s=u.prop(t,`isMock`,7),c=u.prop(t,`spriteInstanceId`,7),l=u.prop(t,`minHeight`,7,100),d=u.prop(t,`maxHeight`,7,2e3),f=u.derived(()=>n()?K_(n()).store:void 0),p=u.derived(()=>u.get(f)?Dx(u.get(f).spriteBuild.get(r())):Dx.undefined),m=u.derived(()=>u.get(p)._),h=u.derived(()=>typeof i()==`string`?i():u.get(m)?.artifactUrl??void 0),g=u.state(void 0),_=u.derived(()=>wk({datastore:o(),isMock:s(),spriteInstanceId:c()})),v=e=>{if(!e||s()){let e;return{get:()=>e,set:t=>{e=t},clear:()=>{e=void 0}}}let t=`app.rough.feature/sprite/${e}/height`;return{get:()=>{let e=localStorage.getItem(t);if(e!==null)try{let t=JSON.parse(e);return typeof t?.height==`number`?t.height:void 0}catch{return}},set:e=>{localStorage.setItem(t,JSON.stringify({height:e}))},clear:()=>{localStorage.removeItem(t)}}},y=u.derived(()=>v(c())),b=gk({get minHeight(){return l()},get maxHeight(){return d()},get heightStore(){return u.get(y)},label:`Resize Rough feature`,title:`Drag to resize, double-click to reset`});u.user_effect(()=>{if(!u.get(h)||!u.get(g))return;let e=new rk({iframe:{containerElement:u.get(g),src:u.get(h),title:`Sprite Frame`},getTools:()=>s()?w(a()):ee(a()),getBridgeMethodDefinitions:()=>a().map(e=>e.toJSON()),store:u.get(_)});return e.start(),()=>{e.stop()}});var x={get client(){return n()},set client(e){n(e),u.flush()},get spriteBuildId(){return r()},set spriteBuildId(e){r(e),u.flush()},get artifactUrl(){return i()},set artifactUrl(e){i(e),u.flush()},get toolList(){return a()},set toolList(e){a(e),u.flush()},get datastore(){return o()},set datastore(e){o(e),u.flush()},get isMock(){return s()},set isMock(e){s(e),u.flush()},get spriteInstanceId(){return c()},set spriteInstanceId(e){c(e),u.flush()},get minHeight(){return l()},set minHeight(e=100){l(e),u.flush()},get maxHeight(){return d()},set maxHeight(e=2e3){d(e),u.flush()}},S=Tk(),C=u.child(S);{let e=u.derived(()=>b.handle());ak(C,{get handle(){return u.get(e)}})}return u.reset(S),u.bind_this(S,e=>u.set(g,e),()=>u.get(g)),u.attach(S,()=>b),u.append(e,S),u.pop(x)}u.create_custom_element(Dk,{client:{},spriteBuildId:{},artifactUrl:{},toolList:{},datastore:{},isMock:{},spriteInstanceId:{},minHeight:{},maxHeight:{}},[],[],{mode:`open`});var Ok=u.from_html(`<button type="button" role="tab"> </button>`),kk=u.from_html(`<div class="TabBar svelte-1jp57o0" role="tablist"></div>`),Ak={hash:`svelte-1jp57o0`,code:`.TabBar.svelte-1jp57o0 {display:inline-flex;align-items:center;justify-content:center;gap:0.125rem;flex-shrink:0;width:fit-content;margin:0.75rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-1jp57o0 {appearance:none;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.75rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;white-space:nowrap;cursor:pointer;transition:color 120ms ease, background-color 120ms ease,
|
|
114
|
+
border-color 120ms ease, box-shadow 120ms ease;}.tab.svelte-1jp57o0:hover:not(:disabled) {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-1jp57o0 {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-1jp57o0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.tab.svelte-1jp57o0:disabled {opacity:0.5;cursor:not-allowed;}`};function jk(e,t){u.push(t,!0),u.append_styles(e,Ak);let n=u.prop(t,`active`,15),r=u.prop(t,`tabs`,7),i=e=>{e.disabled||n(e.key)},a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]:not(:disabled)`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),u.flush()},get tabs(){return r()},set tabs(e){r(e),u.flush()}},s=kk();return u.each(s,21,r,e=>e.key,(e,t)=>{var r=Ok();let o;var s=u.only_child(r,!0);u.template_effect(()=>{o=u.set_class(r,1,`tab svelte-1jp57o0`,null,o,{active:n()===u.get(t).key}),u.set_attribute(r,`aria-selected`,n()===u.get(t).key),u.set_attribute(r,`tabindex`,n()===u.get(t).key?0:-1),r.disabled=u.get(t).disabled,u.set_text(s,u.get(t).label)}),u.delegated(`click`,r,()=>i(u.get(t))),u.delegated(`keydown`,r,a),u.append(e,r)}),u.reset(s),u.append(e,s),u.pop(o)}u.delegate([`click`,`keydown`]),u.create_custom_element(jk,{active:{},tabs:{}},[],[],{mode:`open`});var Mk=u.from_html(`<div role="tabpanel"><!></div>`),Nk={hash:`svelte-1ermak1`,code:`.TabPanel.svelte-1ermak1 {display:none;min-width:0;min-height:0;}.TabPanel.isActive.svelte-1ermak1 {display:flex;flex:1;flex-direction:column;}`};function Pk(e,t){u.push(t,!0),u.append_styles(e,Nk);let n=u.prop(t,`isActive`,7),r=u.prop(t,`children`,7),i=u.prop(t,`class`,7,``);var a={get isActive(){return n()},set isActive(e){n(e),u.flush()},get children(){return r()},set children(e){r(e),u.flush()},get class(){return i()},set class(e=``){i(e),u.flush()}},o=Mk();let s;var c=u.child(o);return u.snippet(c,()=>r()??u.noop),u.reset(o),u.template_effect(()=>{s=u.set_class(o,1,`TabPanel ${i()}`,`svelte-1ermak1`,s,{isActive:n()}),u.set_attribute(o,`aria-hidden`,!n()),o.inert=!n()}),u.append(e,o),u.pop(a)}u.create_custom_element(Pk,{isActive:{},children:{},class:{}},[],[],{mode:`open`});var Fk=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function Ik(e,t){let n=u.rest_props(t,Fk),r=[[`path`,{d:`m6 9 6 6 6-6`}]];av(e,u.spread_props({name:`chevron-down`},()=>n,{get iconNode(){return r}}))}u.create_custom_element(Ik,{},[],[],{mode:`open`});var Lk=u.from_html(`<div class="preview svelte-khztz9"><!></div>`),Rk=u.from_html(`<details class="Accordion svelte-khztz9"><summary class="svelte-khztz9"><header class="svelte-khztz9"><span class="heading svelte-khztz9"><!></span> <span class="chevron svelte-khztz9"><!></span></header> <!></summary> <!></details>`),zk={hash:`svelte-khztz9`,code:`.Accordion.svelte-khztz9 {display:flex;gap:0.5rem;flex-direction:column;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 0.85rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));&[open] {
|
|
104
115
|
/* note: we must use strict descendant selectors here */
|
|
105
116
|
/* otherwise nested Accordions will not be displayed correctly */& > summary:where(.svelte-khztz9) > header:where(.svelte-khztz9) > .chevron:where(.svelte-khztz9) {transform:rotate(0deg);}& > summary:where(.svelte-khztz9) > .preview:where(.svelte-khztz9) {display:none;}}}summary.svelte-khztz9 {display:flex;flex-direction:column;}summary.svelte-khztz9:focus-visible {outline:none;}summary.svelte-khztz9:focus-visible header:where(.svelte-khztz9) {border-color:var(--rough-ring, oklch(0.708 0 0));box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}header.svelte-khztz9 {display:flex;align-items:center;justify-content:space-between;gap:0.5rem;width:100%;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.35rem;background:none;font:inherit;text-align:left;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
106
|
-
box-shadow 120ms ease;}header.svelte-khztz9:hover {background:var(--rough-accent, oklch(0.97 0 0));}.heading.svelte-khztz9 {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.chevron.svelte-khztz9 {flex-shrink:0;transform:rotate(-90deg);color:var(--rough-muted-foreground, oklch(0.556 0 0));transition:transform 150ms ease;}.preview.svelte-khztz9 {margin:0;padding:0 0.35rem 0.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function uS(e,t){l.push(t,!0),l.append_styles(e,lS);let n=l.prop(t,`heading`,7),r=l.prop(t,`preview`,7),i=l.prop(t,`children`,7);var a={get heading(){return n()},set heading(e){n(e),l.flush()},get preview(){return r()},set preview(e){r(e),l.flush()},get children(){return i()},set children(e){i(e),l.flush()}},o=cS(),s=l.child(o),c=l.child(s),u=l.child(c),d=l.child(u),f=e=>{var t=l.text();l.template_effect(()=>l.set_text(t,n())),l.append(e,t)},p=e=>{var t=l.comment(),r=l.first_child(t);l.snippet(r,n),l.append(e,t)};l.if(d,e=>{typeof n()==`string`?e(f):e(p,-1)}),l.reset(u);var m=l.sibling(u,2);oS(l.child(m),{size:14}),l.reset(m),l.reset(c);var h=l.sibling(c,2),g=e=>{var t=sS(),n=l.child(t);l.snippet(n,r),l.reset(t),l.append(e,t)};l.if(h,e=>{r()&&e(g)}),l.reset(s);var _=l.sibling(s,2);return l.snippet(_,()=>i()??l.noop),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(uS,{heading:{},preview:{},children:{}},[],[],{mode:`open`});var dS=l.from_html(`<div class="JsonViewer svelte-17yau2j"><andypf-json-viewer></andypf-json-viewer></div>`,2),fS={hash:`svelte-17yau2j`,code:`.JsonViewer.svelte-17yau2j {max-height:18rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem;overflow:auto;background:var(--rough-muted, oklch(0.97 0 0));}.JsonViewer.svelte-17yau2j andypf-json-viewer {display:block;max-width:100%;font-size:0.8rem;}`};function pS(e,t){l.push(t,!0),l.append_styles(e,fS);let n=l.prop(t,`value`,7);var r={get value(){return n()},set value(e){n(e),l.flush()}},i=dS(),a=l.child(i);return l.template_effect(()=>l.set_custom_element_data(a,`data`,n())),l.set_custom_element_data(a,`expanded`,2),l.set_custom_element_data(a,`indent`,2),l.set_custom_element_data(a,`theme`,`default-light`),l.set_custom_element_data(a,`showDataTypes`,!1),l.set_custom_element_data(a,`showToolbar`,!1),l.set_custom_element_data(a,`showCopy`,!1),l.set_custom_element_data(a,`showSize`,!1),l.set_custom_element_data(a,`expandIconType`,`arrow`),l.set_custom_element_data(a,`expandEmpty`,!1),l.reset(i),l.append(e,i),l.pop(r)}l.create_custom_element(pS,{value:{}},[],[],{mode:`open`});var mS=l.from_html(`<div class="tool-desc svelte-15f985v"> </div>`),hS=l.from_html(`<div class="tool-list svelte-15f985v"></div>`),gS=l.from_html(`<!> <div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`,1),_S=l.from_html(`<div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`),vS=l.from_html(`<div class="tool-card svelte-15f985v"><div class="tool-name svelte-15f985v"> </div> <!></div>`),yS=l.from_html(`<div class="tool-list svelte-15f985v"><!> <div class="tool-card tool-card-builtin svelte-15f985v"><div class="tool-name svelte-15f985v">Save feature data</div> <div class="tool-desc svelte-15f985v">Features can save their own data that persists across sessions</div></div></div>`),bS=l.from_html(`<div class="diagram svelte-15f985v"><!> <div class="feature-node svelte-15f985v"><span class="feature-node-label svelte-15f985v">This is your feature, you can build anything here</span></div> <!> <!></div>`),xS={hash:`svelte-15f985v`,code:`.diagram.svelte-15f985v {display:flex;align-items:center;gap:1.25rem;flex-direction:column;min-height:0;padding:1.5rem;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;background:var(--rough-background, white);}.feature-node.svelte-15f985v {flex-shrink:0;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.85rem 1.25rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));text-align:center;}.feature-node-label.svelte-15f985v {color:var(--rough-primary-foreground, white);font-size:0.875rem;font-weight:600;}.tool-list.svelte-15f985v {display:flex;gap:0.5rem;flex-direction:column;}.tool-card.svelte-15f985v {display:flex;gap:0.35rem;flex-direction:column;box-sizing:border-box;width:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:var(--rough-card, white);color:var(--rough-card-foreground, oklch(0.145 0 0));font:inherit;text-align:left;}.tool-card-builtin.svelte-15f985v {background:var(--rough-muted, oklch(0.97 0 0));}.tool-name.svelte-15f985v {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.tool-desc.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}.arrows.svelte-15f985v {display:flex;align-items:center;justify-content:space-evenly;width:100%;max-width:420px;}.arrow.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:1.25rem;line-height:1;}`};function SS(e,t){l.push(t,!0),l.append_styles(e,xS);let n=l.prop(t,`toolList`,7),r=l.derived(()=>n().filter(e=>e.type===`query`||e.type===`subscription`)),i=l.derived(()=>n().filter(e=>e.type===`mutation`));var a={get toolList(){return n()},set toolList(e){n(e),l.flush()}},o=bS(),s=l.child(o),c=e=>{var t=gS();uS(l.first_child(t),{heading:`Data this feature can see`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>l.get(r).map(e=>e.name).join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=hS();l.each(n,21,()=>l.get(r),e=>e.name,(e,t)=>{uS(e,{get heading(){return l.get(t).name},preview:e=>{var n=l.comment(),r=l.first_child(n),i=e=>{var n=mS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(r,e=>{l.get(t).description&&e(i)}),l.append(e,n)},children:(e,n)=>{var r=l.comment(),i=l.first_child(r),a=e=>{pS(e,{get value(){return l.get(t).outputSample}})};l.if(i,e=>{l.get(t).outputSample!=null&&e(a)}),l.append(e,r)},$$slots:{preview:!0,default:!0}})}),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.next(2),l.append(e,t)};l.if(s,e=>{l.get(r).length>0&&e(c)});var u=l.sibling(s,4),d=e=>{var t=_S();l.append(e,t)};return l.if(u,e=>{l.get(r).length>0&&e(d)}),uS(l.sibling(u,2),{heading:`Changes you can make`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>[...l.get(i).map(e=>e.name),`Save feature data`].join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=yS(),r=l.child(n);l.each(r,17,()=>l.get(i),e=>e.name,(e,t)=>{var n=vS(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var n=mS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(a,e=>{l.get(t).description&&e(o)}),l.reset(n),l.template_effect(()=>l.set_text(i,l.get(t).name)),l.append(e,n)}),l.next(2),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(SS,{toolList:{}},[],[],{mode:`open`});var CS=100,wS=e=>{let t=e.keyStepPx??CS,n=l.state(void 0),r=l.derived(()=>l.get(n)===void 0?`1fr`:`${l.get(n)}px`),i=(t,n)=>{let r=n-e.minColumnPx-e.dividerWidthPx;return Math.max(e.minColumnPx,Math.min(r,t))},a=e=>{e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault()},o=t=>{let r=e.getContainer();if(!t.currentTarget.hasPointerCapture(t.pointerId)||!r)return;let a=r.getBoundingClientRect(),o=t.clientX-a.left-e.dividerWidthPx/2;l.set(n,i(o,a.width),!0)},s=e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)};return{get column(){return l.get(r)},get widthPx(){return l.get(n)},onpointerdown:a,onpointermove:o,onpointerup:s,onpointercancel:s,onkeydown:r=>{if(r.key!==`ArrowLeft`&&r.key!==`ArrowRight`)return;let a=e.getContainer();if(!a)return;r.preventDefault();let o=a.getBoundingClientRect(),s=l.get(n)??o.width*.25,c=r.key===`ArrowLeft`?-t:t;l.set(n,i(s+c,o.width),!0)}}},TS=l.from_html(`<p class="svelte-t9dwgq">Loading…</p>`),ES=l.from_html(`<div class="error svelte-t9dwgq"> </div>`),DS=l.from_html(`<div class="system-message-detail svelte-t9dwgq"> </div>`),OS=l.from_html(`<details class="system-message-raw svelte-t9dwgq"><summary class="svelte-t9dwgq">Details</summary> <pre class="svelte-t9dwgq"> </pre></details>`),kS=l.from_html(`<div class="system-message system-message-error svelte-t9dwgq"><div class="system-message-label svelte-t9dwgq"> </div> <!> <!></div>`),AS=l.from_html(`<span class="published-tag svelte-t9dwgq">Published</span>`),jS=l.from_html(`<div class="system-message system-message-ready svelte-t9dwgq"><button type="button" class="system-message-button svelte-t9dwgq"><span class="system-message-label svelte-t9dwgq"> <!></span></button></div>`),MS=l.from_html(`<div><!> <!></div>`),NS=l.from_html(`<div class="bubble-text svelte-t9dwgq"> </div>`),PS=l.from_html(`<div class="bubble svelte-t9dwgq"><span class="author svelte-t9dwgq"> </span> <!></div>`),FS=l.from_html(`<div></div>`),IS=l.from_html(`<p class="loading svelte-t9dwgq">Loading…</p>`),LS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Your feature preview will appear here.</div>`),RS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Build logs will appear here.</div>`),zS=l.from_html(`<div class="logs-panel svelte-t9dwgq"><!></div>`),BS=l.from_html(`<button type="button" class="send-button svelte-t9dwgq"><!></button>`),VS=l.from_html(`<button type="submit" class="send-button svelte-t9dwgq" aria-label="Send message"><!></button>`),HS=l.from_html(`<!> <!> <!>`,1),US=l.from_html(`<div><div class="transcript svelte-t9dwgq"><div class="transcript-content svelte-t9dwgq"><!> <!> <!> <!></div></div> <div class="divider svelte-t9dwgq" role="slider" aria-label="Resize chat column" tabindex="0"></div> <div class="preview svelte-t9dwgq"><div class="desktop-preview-tabs svelte-t9dwgq"><!></div> <!> <!> <!> <!></div> <form class="composer svelte-t9dwgq"><div><textarea rows="1" placeholder="Describe what you want to generate" class="svelte-t9dwgq"></textarea> <!></div></form> <div class="preview-actions svelte-t9dwgq"><!></div> <!></div>`),WS=l.from_html(`<div><header class="surface-header svelte-t9dwgq"><h3 title="Option-click to toggle theme" class="svelte-t9dwgq"> </h3> <button type="button" class="close-button svelte-t9dwgq" aria-label="Close">×</button></header> <!> <!></div>`),GS={hash:`svelte-t9dwgq`,code:`.surface.svelte-t9dwgq {display:flex;flex-direction:column;box-sizing:border-box;width:100%;height:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-xl, 0.875rem);padding:0;overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.surface-header.svelte-t9dwgq {display:flex;align-items:center;justify-content:space-between;gap:1rem;flex:none;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:1rem 1.25rem;background:var(--rough-card, white);}h3.svelte-t9dwgq {margin:0;color:var(--rough-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.close-button.svelte-t9dwgq {appearance:none;display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0;background:transparent;color:var(--rough-muted-foreground, oklch(0.556 0 0));font:inherit;font-size:1.25rem;line-height:1;cursor:pointer;transition:background-color 120ms ease, color 120ms ease,
|
|
117
|
+
box-shadow 120ms ease;}header.svelte-khztz9:hover {background:var(--rough-accent, oklch(0.97 0 0));}.heading.svelte-khztz9 {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.chevron.svelte-khztz9 {flex-shrink:0;transform:rotate(-90deg);color:var(--rough-muted-foreground, oklch(0.556 0 0));transition:transform 150ms ease;}.preview.svelte-khztz9 {margin:0;padding:0 0.35rem 0.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function Bk(e,t){u.push(t,!0),u.append_styles(e,zk);let n=u.prop(t,`heading`,7),r=u.prop(t,`preview`,7),i=u.prop(t,`children`,7);var a={get heading(){return n()},set heading(e){n(e),u.flush()},get preview(){return r()},set preview(e){r(e),u.flush()},get children(){return i()},set children(e){i(e),u.flush()}},o=Rk(),s=u.child(o),c=u.child(s),l=u.child(c),d=u.child(l),f=e=>{var t=u.text();u.template_effect(()=>u.set_text(t,n())),u.append(e,t)},p=e=>{var t=u.comment(),r=u.first_child(t);u.snippet(r,n),u.append(e,t)};u.if(d,e=>{typeof n()==`string`?e(f):e(p,-1)}),u.reset(l);var m=u.sibling(l,2);Ik(u.child(m),{size:14}),u.reset(m),u.reset(c);var h=u.sibling(c,2),g=e=>{var t=Lk(),n=u.child(t);u.snippet(n,r),u.reset(t),u.append(e,t)};u.if(h,e=>{r()&&e(g)}),u.reset(s);var _=u.sibling(s,2);return u.snippet(_,()=>i()??u.noop),u.reset(o),u.append(e,o),u.pop(a)}u.create_custom_element(Bk,{heading:{},preview:{},children:{}},[],[],{mode:`open`});var Vk=u.from_html(`<div class="JsonViewer svelte-17yau2j"><andypf-json-viewer></andypf-json-viewer></div>`,2),Hk={hash:`svelte-17yau2j`,code:`.JsonViewer.svelte-17yau2j {max-height:18rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem;overflow:auto;background:var(--rough-muted, oklch(0.97 0 0));}.JsonViewer.svelte-17yau2j andypf-json-viewer {display:block;max-width:100%;font-size:0.8rem;}`};function Uk(e,t){u.push(t,!0),u.append_styles(e,Hk);let n=u.prop(t,`value`,7);var r={get value(){return n()},set value(e){n(e),u.flush()}},i=Vk(),a=u.child(i);return u.template_effect(()=>u.set_custom_element_data(a,`data`,n())),u.set_custom_element_data(a,`expanded`,2),u.set_custom_element_data(a,`indent`,2),u.set_custom_element_data(a,`theme`,`default-light`),u.set_custom_element_data(a,`showDataTypes`,!1),u.set_custom_element_data(a,`showToolbar`,!1),u.set_custom_element_data(a,`showCopy`,!1),u.set_custom_element_data(a,`showSize`,!1),u.set_custom_element_data(a,`expandIconType`,`arrow`),u.set_custom_element_data(a,`expandEmpty`,!1),u.reset(i),u.append(e,i),u.pop(r)}u.create_custom_element(Uk,{value:{}},[],[],{mode:`open`});var Wk=u.from_html(`<div class="tool-desc svelte-15f985v"> </div>`),Gk=u.from_html(`<div class="tool-list svelte-15f985v"></div>`),Kk=u.from_html(`<!> <div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`,1),qk=u.from_html(`<div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`),Jk=u.from_html(`<div class="tool-card svelte-15f985v"><div class="tool-name svelte-15f985v"> </div> <!></div>`),Yk=u.from_html(`<div class="tool-list svelte-15f985v"><!> <div class="tool-card tool-card-builtin svelte-15f985v"><div class="tool-name svelte-15f985v">Save feature data</div> <div class="tool-desc svelte-15f985v">Features can save their own data that persists across sessions</div></div></div>`),Xk=u.from_html(`<div class="diagram svelte-15f985v"><!> <div class="feature-node svelte-15f985v"><span class="feature-node-label svelte-15f985v">This is your feature, you can build anything here</span></div> <!> <!></div>`),Zk={hash:`svelte-15f985v`,code:`.diagram.svelte-15f985v {display:flex;align-items:center;gap:1.25rem;flex-direction:column;min-height:0;padding:1.5rem;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;background:var(--rough-background, white);}.feature-node.svelte-15f985v {flex-shrink:0;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.85rem 1.25rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));text-align:center;}.feature-node-label.svelte-15f985v {color:var(--rough-primary-foreground, white);font-size:0.875rem;font-weight:600;}.tool-list.svelte-15f985v {display:flex;gap:0.5rem;flex-direction:column;}.tool-card.svelte-15f985v {display:flex;gap:0.35rem;flex-direction:column;box-sizing:border-box;width:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:var(--rough-card, white);color:var(--rough-card-foreground, oklch(0.145 0 0));font:inherit;text-align:left;}.tool-card-builtin.svelte-15f985v {background:var(--rough-muted, oklch(0.97 0 0));}.tool-name.svelte-15f985v {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.tool-desc.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}.arrows.svelte-15f985v {display:flex;align-items:center;justify-content:space-evenly;width:100%;max-width:420px;}.arrow.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:1.25rem;line-height:1;}`};function Qk(e,t){u.push(t,!0),u.append_styles(e,Zk);let n=u.prop(t,`toolList`,7),r=u.derived(()=>n().filter(e=>e.type===`query`||e.type===`subscription`)),i=u.derived(()=>n().filter(e=>e.type===`mutation`));var a={get toolList(){return n()},set toolList(e){n(e),u.flush()}},o=Xk(),s=u.child(o),c=e=>{var t=Kk();Bk(u.first_child(t),{heading:`Data this feature can see`,preview:e=>{u.next();var t=u.text();u.template_effect(e=>u.set_text(t,e),[()=>u.get(r).map(e=>e.name).join(`, `)]),u.append(e,t)},children:(e,t)=>{var n=Gk();u.each(n,21,()=>u.get(r),e=>e.name,(e,t)=>{Bk(e,{get heading(){return u.get(t).name},preview:e=>{var n=u.comment(),r=u.first_child(n),i=e=>{var n=Wk(),r=u.only_child(n,!0);u.template_effect(()=>u.set_text(r,u.get(t).description)),u.append(e,n)};u.if(r,e=>{u.get(t).description&&e(i)}),u.append(e,n)},children:(e,n)=>{var r=u.comment(),i=u.first_child(r),a=e=>{Uk(e,{get value(){return u.get(t).outputSample}})};u.if(i,e=>{u.get(t).outputSample!=null&&e(a)}),u.append(e,r)},$$slots:{preview:!0,default:!0}})}),u.reset(n),u.append(e,n)},$$slots:{preview:!0,default:!0}}),u.next(2),u.append(e,t)};u.if(s,e=>{u.get(r).length>0&&e(c)});var l=u.sibling(s,4),d=e=>{var t=qk();u.append(e,t)};return u.if(l,e=>{u.get(r).length>0&&e(d)}),Bk(u.sibling(l,2),{heading:`Changes you can make`,preview:e=>{u.next();var t=u.text();u.template_effect(e=>u.set_text(t,e),[()=>[...u.get(i).map(e=>e.name),`Save feature data`].join(`, `)]),u.append(e,t)},children:(e,t)=>{var n=Yk(),r=u.child(n);u.each(r,17,()=>u.get(i),e=>e.name,(e,t)=>{var n=Jk(),r=u.child(n),i=u.only_child(r,!0),a=u.sibling(r,2),o=e=>{var n=Wk(),r=u.only_child(n,!0);u.template_effect(()=>u.set_text(r,u.get(t).description)),u.append(e,n)};u.if(a,e=>{u.get(t).description&&e(o)}),u.reset(n),u.template_effect(()=>u.set_text(i,u.get(t).name)),u.append(e,n)}),u.next(2),u.reset(n),u.append(e,n)},$$slots:{preview:!0,default:!0}}),u.reset(o),u.append(e,o),u.pop(a)}u.create_custom_element(Qk,{toolList:{}},[],[],{mode:`open`});var $k=100,eA=e=>{let t=e.keyStepPx??$k,n=u.state(void 0),r=u.derived(()=>u.get(n)===void 0?`1fr`:`${u.get(n)}px`),i=(t,n)=>{let r=n-e.minColumnPx-e.dividerWidthPx;return Math.max(e.minColumnPx,Math.min(r,t))},a=e=>{e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault()},o=t=>{let r=e.getContainer();if(!t.currentTarget.hasPointerCapture(t.pointerId)||!r)return;let a=r.getBoundingClientRect(),o=t.clientX-a.left-e.dividerWidthPx/2;u.set(n,i(o,a.width),!0)},s=e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)};return{get column(){return u.get(r)},get widthPx(){return u.get(n)},onpointerdown:a,onpointermove:o,onpointerup:s,onpointercancel:s,onkeydown:r=>{if(r.key!==`ArrowLeft`&&r.key!==`ArrowRight`)return;let a=e.getContainer();if(!a)return;r.preventDefault();let o=a.getBoundingClientRect(),s=u.get(n)??o.width*.25,c=r.key===`ArrowLeft`?-t:t;u.set(n,i(s+c,o.width),!0)}}},tA=u.from_html(`<p class="svelte-t9dwgq">Loading…</p>`),nA=u.from_html(`<div class="error svelte-t9dwgq"> </div>`),rA=u.from_html(`<div class="system-message-detail svelte-t9dwgq"> </div>`),iA=u.from_html(`<details class="system-message-raw svelte-t9dwgq"><summary class="svelte-t9dwgq">Details</summary> <pre class="svelte-t9dwgq"> </pre></details>`),aA=u.from_html(`<div class="system-message system-message-error svelte-t9dwgq"><div class="system-message-label svelte-t9dwgq"> </div> <!> <!></div>`),oA=u.from_html(`<span class="published-tag svelte-t9dwgq">Published</span>`),sA=u.from_html(`<div class="system-message system-message-ready svelte-t9dwgq"><button type="button" class="system-message-button svelte-t9dwgq"><span class="system-message-label svelte-t9dwgq"> <!></span></button></div>`),cA=u.from_html(`<div><!> <!></div>`),lA=u.from_html(`<div class="bubble-text svelte-t9dwgq"> </div>`),uA=u.from_html(`<div class="bubble svelte-t9dwgq"><span class="author svelte-t9dwgq"> </span> <!></div>`),dA=u.from_html(`<img class="chat-image svelte-t9dwgq" alt="Visual reference" loading="lazy" decoding="async"/>`),fA=u.from_html(`<div></div>`),pA=u.from_html(`<p class="loading svelte-t9dwgq">Loading…</p>`),mA=u.from_html(`<div class="preview-placeholder svelte-t9dwgq">Your feature preview will appear here.</div>`),hA=u.from_html(`<div class="preview-placeholder svelte-t9dwgq">Build logs will appear here.</div>`),gA=u.from_html(`<div class="logs-panel svelte-t9dwgq"><!></div>`),_A=u.from_html(`<button type="button" class="send-button svelte-t9dwgq"><!></button>`),vA=u.from_html(`<button type="submit" class="send-button svelte-t9dwgq" aria-label="Send message"><!></button>`),yA=u.from_html(`<button type="button" aria-label="Remove image" class="svelte-t9dwgq">×</button>`),bA=u.from_html(`<div><div class="image-preview svelte-t9dwgq"><img alt="Selected visual reference" decoding="async" class="svelte-t9dwgq"/></div> <!></div>`),xA=u.from_html(`<div class="image-list svelte-t9dwgq"></div>`),SA=u.from_html(`<!> <!> <!>`,1),CA=u.from_html(`<div><div class="transcript svelte-t9dwgq"><div class="transcript-content svelte-t9dwgq"><!> <!> <!> <!> <!></div></div> <div class="divider svelte-t9dwgq" role="slider" aria-label="Resize chat column" tabindex="0"></div> <div class="preview svelte-t9dwgq"><div class="desktop-preview-tabs svelte-t9dwgq"><!></div> <!> <!> <!> <!></div> <form class="composer svelte-t9dwgq"><input class="image-file-input svelte-t9dwgq" type="file" multiple="" accept="image/gif,image/jpeg,image/png,image/webp"/> <div><textarea rows="1" placeholder="Describe what you want to generate" class="svelte-t9dwgq"></textarea> <button type="button" class="asset-button svelte-t9dwgq" aria-label="Upload image"><!></button> <!> <!></div></form> <div class="preview-actions svelte-t9dwgq"><!></div> <!></div>`),wA=u.from_html(`<div><header class="surface-header svelte-t9dwgq"><h3 title="Option-click to toggle theme" class="svelte-t9dwgq"> </h3> <button type="button" class="close-button svelte-t9dwgq" aria-label="Close">×</button></header> <!> <!></div>`),TA={hash:`svelte-t9dwgq`,code:`.surface.svelte-t9dwgq {display:flex;flex-direction:column;box-sizing:border-box;width:100%;height:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-xl, 0.875rem);padding:0;overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.surface-header.svelte-t9dwgq {display:flex;align-items:center;justify-content:space-between;gap:1rem;flex:none;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:1rem 1.25rem;background:var(--rough-card, white);}h3.svelte-t9dwgq {margin:0;color:var(--rough-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.close-button.svelte-t9dwgq {appearance:none;display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0;background:transparent;color:var(--rough-muted-foreground, oklch(0.556 0 0));font:inherit;font-size:1.25rem;line-height:1;cursor:pointer;transition:background-color 120ms ease, color 120ms ease,
|
|
107
118
|
border-color 120ms ease, box-shadow 120ms ease;}.close-button.svelte-t9dwgq:hover {background:var(--rough-accent, oklch(0.97 0 0));color:var(--rough-accent-foreground, oklch(0.205 0 0));}.close-button.svelte-t9dwgq:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.feature-builder.svelte-t9dwgq {display:grid;grid-template-columns:var(--chat-column, 1fr) 12px 3fr;grid-template-rows:1fr auto;column-gap:0;row-gap:0.75rem;flex:1;min-height:0;padding:1rem 1.25rem;background:var(--rough-background, white);}.error.svelte-t9dwgq {flex:1;padding:1rem 1.25rem;color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.transcript.svelte-t9dwgq {grid-column:1;grid-row:1;min-height:0;overflow-y:auto;}
|
|
108
119
|
|
|
109
120
|
/* Inner wrapper so the ResizeObserver can watch content growth separately
|
|
@@ -117,8 +128,13 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
|
|
|
117
128
|
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h5,
|
|
118
129
|
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h6 {margin:0.75rem 0 0.35rem;font-size:1em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h1 {font-size:1.25em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h2 {font-size:1.15em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) ul,
|
|
119
130
|
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) ol {margin:0.5rem 0;padding-left:1.25rem;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) a {color:var(--rough-primary, oklch(0.205 0 0));text-decoration:underline;text-underline-offset:0.15em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) blockquote {margin:0.5rem 0;border-left:3px solid var(--rough-border, oklch(0.922 0 0));padding-left:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) table {width:100%;margin:0.5rem 0;border-collapse:collapse;font-size:0.8125rem;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) th,
|
|
120
|
-
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) td {border:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.3rem 0.45rem;text-align:left;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) th {background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) code {border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1em 0.25em;background:var(--rough-background, white);font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;font-size:0.85em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre {margin:0.5rem 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;overflow-x:auto;background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre code {padding:0;background:transparent;}.system-message.svelte-t9dwgq {display:flex;gap:0.4rem;flex-direction:column;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.system-message-button.svelte-t9dwgq {appearance:none;width:100%;border:none;padding:0;background:transparent;font:inherit;text-align:left;cursor:pointer;}.system-message-button.svelte-t9dwgq:focus-visible {border-radius:var(--rough-radius-md, 0.375rem);outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.system-message-label.svelte-t9dwgq {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.system-message-ready.svelte-t9dwgq {border-color:var(--rough-success-border, color-mix(in srgb, #15803d 45%, var(--rough-border, oklch(0.922 0 0))));background:var(--rough-success-background, color-mix(in srgb, #15803d 12%, var(--rough-card, white)));}.system-message-ready.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-success, #15803d);}.system-message-error.svelte-t9dwgq {border-color:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 35%, var(--rough-border, oklch(0.922 0 0)));background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 8%, var(--rough-card, white));}.system-message-error.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.system-message-detail.svelte-t9dwgq {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.system-message-raw.svelte-t9dwgq {font-size:0.85rem;}.system-message-raw.svelte-t9dwgq summary:where(.svelte-t9dwgq) {color:var(--rough-muted-foreground, oklch(0.556 0 0));cursor:pointer;}.system-message-raw.svelte-t9dwgq pre:where(.svelte-t9dwgq) {margin:0.4rem 0 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 0.65rem;overflow-x:auto;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.8rem;white-space:pre-wrap;word-break:break-word;}.
|
|
121
|
-
|
|
131
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) td {border:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.3rem 0.45rem;text-align:left;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) th {background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) code {border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1em 0.25em;background:var(--rough-background, white);font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;font-size:0.85em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre {margin:0.5rem 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;overflow-x:auto;background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre code {padding:0;background:transparent;}.system-message.svelte-t9dwgq {display:flex;gap:0.4rem;flex-direction:column;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.system-message-button.svelte-t9dwgq {appearance:none;width:100%;border:none;padding:0;background:transparent;font:inherit;text-align:left;cursor:pointer;}.system-message-button.svelte-t9dwgq:focus-visible {border-radius:var(--rough-radius-md, 0.375rem);outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.system-message-label.svelte-t9dwgq {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.system-message-ready.svelte-t9dwgq {border-color:var(--rough-success-border, color-mix(in srgb, #15803d 45%, var(--rough-border, oklch(0.922 0 0))));background:var(--rough-success-background, color-mix(in srgb, #15803d 12%, var(--rough-card, white)));}.system-message-ready.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-success, #15803d);}.system-message-error.svelte-t9dwgq {border-color:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 35%, var(--rough-border, oklch(0.922 0 0)));background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 8%, var(--rough-card, white));}.system-message-error.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.system-message-detail.svelte-t9dwgq {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.system-message-raw.svelte-t9dwgq {font-size:0.85rem;}.system-message-raw.svelte-t9dwgq summary:where(.svelte-t9dwgq) {color:var(--rough-muted-foreground, oklch(0.556 0 0));cursor:pointer;}.system-message-raw.svelte-t9dwgq pre:where(.svelte-t9dwgq) {margin:0.4rem 0 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 0.65rem;overflow-x:auto;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.8rem;white-space:pre-wrap;word-break:break-word;}.chat-image.svelte-t9dwgq {display:block;max-width:min(100%, 24rem);max-height:20rem;border-radius:var(--rough-radius-md, 0.375rem);}.chat-message-user.svelte-t9dwgq .chat-image:where(.svelte-t9dwgq) {align-self:flex-end;}.image-file-input.svelte-t9dwgq {display:none;}.image-asset.svelte-t9dwgq {position:relative;align-self:flex-start;flex:none;}.image-preview.svelte-t9dwgq {width:2.5rem;height:2.5rem;overflow:hidden;border-radius:var(--rough-radius-sm, 0.25rem);}.image-asset.svelte-t9dwgq img:where(.svelte-t9dwgq) {display:block;width:100%;height:100%;object-fit:cover;}.image-asset.is-uploading.svelte-t9dwgq img:where(.svelte-t9dwgq) {filter:blur(4px);}.image-asset.svelte-t9dwgq button:where(.svelte-t9dwgq) {position:absolute;top:-0.25rem;right:-0.25rem;width:1rem;height:1rem;border:none;border-radius:999px;padding:0;background:var(--rough-foreground, oklch(0.145 0 0));color:var(--rough-background, white);cursor:pointer;opacity:0;line-height:1;transition:opacity 120ms ease;}.image-asset.svelte-t9dwgq:hover button:where(.svelte-t9dwgq),
|
|
132
|
+
.image-asset.svelte-t9dwgq:focus-within button:where(.svelte-t9dwgq) {opacity:1;}.composer-input.svelte-t9dwgq {display:flex;align-items:flex-end;flex-wrap:wrap;gap:0.5rem;border:1px solid var(--rough-input, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.5rem 0.5rem 0.5rem 0.85rem;background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));transition:border-color 120ms ease, box-shadow 120ms ease;}.image-list.svelte-t9dwgq {display:flex;flex-basis:100%;align-items:flex-start;gap:0.5rem;}.composer-input.svelte-t9dwgq:focus-within {border-color:var(--rough-ring, oklch(0.708 0 0));box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.composer-input.isBuilding.svelte-t9dwgq textarea:where(.svelte-t9dwgq) {opacity:0.75;}textarea.svelte-t9dwgq {flex:1;min-width:0;min-height:1.5rem;max-height:12rem;border:none;outline:none;padding:0.35rem 0;overflow-y:auto;background:transparent;color:var(--rough-foreground, oklch(0.145 0 0));font:inherit;font-size:0.875rem;line-height:1.45;resize:none;}textarea.svelte-t9dwgq::placeholder {color:var(--rough-muted-foreground, oklch(0.556 0 0));}.asset-button.svelte-t9dwgq,
|
|
133
|
+
.send-button.svelte-t9dwgq {display:inline-flex;align-items:center;justify-content:center;flex:none;width:2.25rem;height:2.25rem;border:1px solid var(--rough-primary, oklch(0.205 0 0));border-radius:999px;padding:0;background:var(--rough-primary, oklch(0.205 0 0));color:var(--rough-primary-foreground, white);cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
134
|
+
box-shadow 120ms ease, transform 120ms ease, opacity 120ms ease;}.asset-button.svelte-t9dwgq:hover:not(:disabled),
|
|
135
|
+
.send-button.svelte-t9dwgq:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}.asset-button.svelte-t9dwgq:active:not(:disabled),
|
|
136
|
+
.send-button.svelte-t9dwgq:active:not(:disabled) {transform:scale(0.95);}.asset-button.svelte-t9dwgq:focus-visible,
|
|
137
|
+
.send-button.svelte-t9dwgq:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.asset-button.svelte-t9dwgq:disabled {cursor:not-allowed;}.send-button.svelte-t9dwgq:disabled {opacity:0.5;cursor:not-allowed;}.loading.svelte-t9dwgq {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;}.surface.svelte-t9dwgq > p:where(.svelte-t9dwgq) {flex:1;margin:0;padding:1rem 1.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}
|
|
122
138
|
|
|
123
139
|
@media (max-width: 1000px) {.feature-builder.svelte-t9dwgq {grid-template-columns:1fr;}.desktop-preview-tabs.svelte-t9dwgq,
|
|
124
140
|
.divider.svelte-t9dwgq,
|
|
@@ -130,6 +146,6 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
|
|
|
130
146
|
.feature-builder.tab-logs.svelte-t9dwgq .preview:where(.svelte-t9dwgq) {display:flex;grid-column:1;grid-row:1;}.feature-builder.tab-preview.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq),
|
|
131
147
|
.feature-builder.tab-capabilities.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq),
|
|
132
148
|
.feature-builder.tab-logs.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq) {display:flex;grid-column:1;grid-row:2;}
|
|
133
|
-
}`};function KS(e,t){l.push(t,!0),l.append_styles(e,GS);let n=e=>Uy(e,{allowHtml:!1,extensions:[qv()],frontmatter:!1,headingIds:!1}),r=e=>e.type===`create`?`create:${e.surfaceId}`:`edit:${e.spriteId}`,i=l.prop(t,`client`,7),a=l.prop(t,`surface`,7),o=l.prop(t,`portalTarget`,7),c=l.prop(t,`onclose`,7),f=l.prop(t,`action`,7),p=xt(),m=l.derived(()=>f().type===`edit`?f().spriteId:p),h=l.derived(()=>Qg(i())),g=l.derived(()=>l.get(h).store),_=l.derived(()=>a().tools),v=l.state(!0),y=l.state(void 0),b,ee=!1,x=!1,te,ne=async()=>{if(f().type!==`create`||x)return;let e=te;if(e)return e;let t=f(),n=(async()=>{let e=await l.get(h).getReplicache();ee||=(await e.mutate.sprite_create_v2({spriteId:p,surfaceId:t.surfaceId,name:``,context:{actionedAt:Date.now()}}),!0),await e.push({now:!0}),x=!0})();te=n;try{await n}finally{te===n&&(te=void 0)}};s(()=>{l.set(y,r(f()),!0)}),l.user_effect(()=>{let e=l.get(y);if(!e)return;let t=r(f());if(t===e){b=void 0;return}t!==b&&(b=t,console.error(`[Rough] FeatureBuilder does not support changing action after mount.`,{initialActionKey:e,currentActionKey:t}))});let re=l.derived(()=>db(l.get(g).meta.get(Qe))),ie=l.derived(()=>l.get(re)._),ae=l.derived(()=>l.get(ie)?.state===`READY`),oe=l.derived(()=>db(l.get(g).sprite.get(l.get(m)))),se=l.derived(()=>l.get(oe)._),ce=l.derived(()=>db(l.get(g).spriteBuild.filter(`FeatureBuilder:spriteBuildList:${l.get(m)}`,e=>e.spriteId===l.get(m)))),le=l.derived(()=>l.get(ce)._),S=l.derived(()=>db(l.get(g).spriteBuildEvent.filter(`FeatureBuilder:spriteBuildEventList:${l.get(m)}`,e=>l.get(le).some(t=>t.id===e.spriteBuildId)))),C=l.derived(()=>l.get(S)._),w=l.derived(()=>{if(l.get(se))return n_({sprite:l.get(se),spriteBuildList:l.get(le)})}),ue=l.derived(()=>f().type===`edit`&&!l.get(ae)),de=l.derived(()=>{if(!(f().type!==`edit`||!l.get(ae)||l.get(se)))return Error(`Sprite "${f().spriteId}" not found`)}),fe=l.state(!1),T=l.state(void 0),pe=l.state(void 0),me=l.state(void 0),he=l.derived(()=>l.get(fe)||l.get(T)!=null&&l.get(T).status!==`READY`&&l.get(T).status!==`ERROR`&&l.get(T).status!==`CANCELED`&&!l.get(me)),ge=e=>{l.set(T,e,!0),l.set(pe,e.id,!0),$e.add(e.id)},_e=l.derived(()=>l.get(pe)?db(l.get(g).spriteBuild.get(l.get(pe))):db.undefined),ve=l.derived(()=>l.get(_e)._);l.user_effect(()=>{let e=l.get(ve);e&&(e.id===l.get(pe)&&JSON.stringify(l.get(T))!==JSON.stringify(e)&&l.set(T,e,!0),(e.status===`READY`||e.status===`ERROR`||e.status===`CANCELED`)&&l.set(pe,void 0))});let ye=[{key:`preview`,label:`Preview`},{key:`capabilities`,label:`Capabilities`},{key:`logs`,label:`Logs`}],be=[{key:`chat`,label:`Chat`},...ye],E=l.state(`chat`),xe=l.state(`capabilities`),Se=l.derived(()=>l.get(E)===`chat`),Ce=l.derived(()=>l.get(E)===`capabilities`),we=l.derived(()=>l.get(E)===`preview`),Te=l.derived(()=>l.get(E)===`logs`),D=l.derived(()=>l.get(xe)===`capabilities`),Ee=l.derived(()=>l.get(xe)===`preview`),De=l.derived(()=>l.get(xe)===`logs`),Oe=l.state(``),ke=l.state(void 0),Ae=l.state(l.proxy([])),je=l.state(!1),Me=l.state(void 0),Ne=l.derived(()=>l.get(je)&&!l.get(he)),Pe=l.state(void 0),Fe=l.state(void 0),Ie=l.state(void 0),Le=l.state(void 0),Re=l.state(void 0),ze=wS({getContainer:()=>l.get(Re),minColumnPx:280,dividerWidthPx:12}),Be=l.derived(()=>{if(ze.widthPx===void 0||!l.get(Re))return;let e=l.get(Re).getBoundingClientRect().width;if(e)return Math.round(ze.widthPx/e*100)}),Ve=l.derived(()=>{let e=new u;for(let t of l.get(le))e.set(t.id,t);return l.get(T)&&e.set(l.get(T).id,l.get(T)),[...e.values()].sort((e,t)=>e.id.localeCompare(t.id))}),He=!1,Ue=e=>{l.set(Fe,e,!0),He=!0,l.set(xe,`preview`),l.set(E,`preview`)},We=l.derived(()=>l.get(Ve).findLast(e=>e.status===`READY`&&e.artifactUrl)),Ge=l.derived(()=>{if(l.get(Fe)){let e=l.get(Ve).find(e=>e.id===l.get(Fe));if(e)return e}return l.get(We)??l.get(Ve).at(-1)}),Ke=l.derived(()=>l.get(Ve).at(-1)),qe=l.derived(()=>l.get(Ge)?.status===`READY`&&l.get(Ge).artifactUrl?l.get(Ge):void 0),Je=l.derived(()=>l.get(qe)??l.get(We)),Ye=!1;l.user_effect(()=>{!Ye&&l.get(We)&&(l.set(E,`preview`),l.set(xe,`preview`),Ye=!0)}),l.user_effect(()=>{if(l.get(Ve).length===0){l.set(Fe,void 0),He=!1;return}(!He||!l.get(Fe)||!l.get(Ve).some(e=>e.id===l.get(Fe)))&&(l.set(Fe,l.get(We)?.id??l.get(Ve).at(-1)?.id,!0),He=!1)});let Xe=l.derived(()=>l.get(We)?.id),Ze=l.derived(()=>t_(l.get(le))),$e=new d,et=l.state(void 0),tt=l.derived(()=>l.get(et)??l.get(Ze)?.id??void 0),nt=l.derived(()=>!l.get(he)&&l.get(Je)!=null&&l.get(Je).id!==l.get(tt)),rt=l.derived(()=>l.get(tt)!==l.get(Xe)),it=l.state(!1),at=l.state(void 0),ot=l.state(!1),st=l.state(!1),ct=async()=>{if(!(!l.get(w)||!l.get(Je)||l.get(it))){l.set(it,!0),l.set(at,void 0);try{let e=await ab({replicache:await l.get(h).getReplicache(),spriteId:l.get(w).id,spriteBuildId:l.get(Je).id});if(e instanceof Error){l.set(at,e,!0);return}l.set(et,e.spriteBuildId,!0),l.set(ot,!1)}finally{l.set(it,!1)}}},lt=()=>{l.set(v,!1)},ut=()=>{l.get(rt)?l.set(ot,!0):lt()},dt=()=>{l.set(ot,!1),lt()},ft=()=>{l.set(ot,!1)},pt=e=>{if(e){if(typeof e.message==`string`)return e.message;if(typeof e.error==`string`)return e.error}},mt=e=>{let t=Lm.outputSchema.safeParse(e);return t.success?t.data:void 0},ht=l.derived(()=>l.get(T)?.cancelRequestedAt!=null),gt=l.derived(()=>!l.get(ht)&&(l.get(T)?.status===`PENDING`||l.get(T)?.status===`IN_PROGRESS`)),_t=async()=>{!l.get(w)||!l.get(T)||!l.get(gt)||await(await l.get(h).getReplicache()).mutate.spriteBuild_cancel_v1({spriteBuildId:l.get(T).id})},vt=async(e,t)=>{l.set(me,void 0),l.set(fe,!0);try{let n=e.trim();if(!n)throw Error(`Missing build prompt`);let r=Vm({messageList:Yp(t)});if(r instanceof Error)throw r;console.table([{"Frontend build plan (inactive)":n,"Backend build plan (active)":r}]);let i=await l.get(h).getReplicache(),a=xt();await i.mutate.spriteBuild_create_v2({spriteBuildId:a,spriteId:l.get(m),parentSpriteBuildId:l.get(Xe),prompt:r});let o=l.get(g).spriteBuild.get(a).value;return o?ge(o):l.set(pe,a,!0),{spriteBuildId:a}}finally{l.set(fe,!1)}};l.user_effect(()=>{if(l.get(ue)||l.get(de))return;let e=ax({client:i(),spriteId:l.get(m),toolList:l.get(_),getSpriteBuildEventList:e=>l.get(C).filter(t=>t.spriteBuildId===e),onStartBuild:({prompt:e},t)=>vt(e,t),onMessagesChange:e=>{l.set(Ae,e,!0)},onLoadingChange:e=>{l.set(je,e,!0)},onErrorChange:e=>{l.set(Me,e,!0)}});return l.set(ke,e,!0),e.attach(),l.set(Ae,e.getMessages(),!0),l.set(je,e.getIsLoading(),!0),l.set(Me,e.getError(),!0),()=>{e.dispose(),l.get(ke)===e&&l.set(ke,void 0)}});let yt=l.derived(()=>l.get(ke)!=null&&!l.get(he)&&!l.get(je)&&l.get(Oe).trim().length>0),bt=async e=>{e.preventDefault();let t=l.get(Oe).trim();if(!(!t||l.get(he)||l.get(je))){if(l.set(me,void 0),l.set(Me,void 0),!l.get(ke)){l.set(me,Error(`Feature builder chat is not ready`),!0);return}try{await ne(),l.set(Oe,``),await l.get(ke).sendMessage(t)}catch(e){l.set(me,e instanceof Error?e:Error(String(e)),!0)}}},St=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),bt(e))};return l.user_effect(()=>{l.get(E)!==`chat`&&l.set(xe,l.get(E),!0)}),l.user_effect(()=>{let e=l.get(Pe);e&&(l.get(Oe),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}),l.user_effect(()=>{let e=l.get(Le),t=l.get(Ie);if(!e||!t)return;let n=new ResizeObserver(()=>{t.scrollTop=t.scrollHeight});return n.observe(e),()=>n.disconnect()}),gx(e,{get target(){return o()},oncancel:ut,get onclose(){return c()},get isOpen(){return l.get(v)},set isOpen(e){l.set(v,e,!0)},children:(e,t)=>{var r=WS();let a;var o=l.child(r),s=l.child(o),c=l.child(s,!0);l.reset(s);var u=l.sibling(s,2);l.reset(o);var d=l.sibling(o,2),f=e=>{var t=TS();l.append(e,t)},p=e=>{var t=ES(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(de).message)),l.append(e,t)},m=e=>{var t=US();let r,a;{let e=(e,t=l.noop,n=l.noop,r=l.noop)=>{var i=kS(),a=l.child(i),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=DS(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n())),l.append(e,t)};l.if(s,e=>{n()&&e(c)});var u=l.sibling(s,2),d=e=>{var t=OS(),n=l.sibling(l.child(t),2),i=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(e=>l.set_text(i,e),[()=>JSON.stringify(r(),null,2)]),l.append(e,t)};l.if(u,e=>{r()&&e(d)}),l.reset(i),l.template_effect(()=>l.set_text(o,t())),l.append(e,i)},r=(t,n=l.noop)=>{let r=l.derived(()=>n().id===l.get(tt)),a=l.derived(()=>l.get(Ve).indexOf(n())+1);var o=MS();let s;var c=l.child(o),u=e=>{Nb(e,{get client(){return i()},get spriteBuild(){return n()}})};l.if(c,e=>{n().status!==`READY`&&n().status!==`ERROR`&&e(u)});var d=l.sibling(c,2),f=e=>{var t=jS(),i=l.child(t),o=l.child(i),s=l.child(o),c=l.sibling(s),u=e=>{var t=AS();l.append(e,t)};l.if(c,e=>{l.get(r)&&e(u)}),l.reset(o),l.reset(i),l.reset(t),l.template_effect(()=>l.set_text(s,`Version ${l.get(a)??``} ready `)),l.delegated(`click`,i,()=>Ue(n().id)),l.append(e,t)},p=t=>{{let r=l.derived(()=>pt(n().error));e(t,()=>`Version ${l.get(a)} failed`,()=>l.get(r),()=>n().error)}};l.if(d,e=>{n().status===`READY`?e(f):n().status===`ERROR`&&e(p,1)}),l.reset(o),l.template_effect(()=>s=l.set_class(o,1,`turn svelte-t9dwgq`,null,s,{"turn-published":l.get(r)})),l.append(t,o)};var o=l.child(t),s=l.child(o),c=l.child(s);l.each(c,17,()=>l.get(Ae),e=>e.id,(e,t)=>{var i=FS();let a;l.each(i,23,()=>l.get(t).parts,(e,n)=>`${l.get(t).id}-${n}`,(e,i)=>{var a=l.comment(),o=l.first_child(a),s=e=>{var r=PS(),a=l.child(r),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=l.comment(),r=l.first_child(t);l.html(r,()=>n(l.get(i).content)),l.append(e,t)},u=e=>{var t=NS(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(i).content)),l.append(e,t)};l.if(s,e=>{l.get(t).role===`assistant`?e(c):e(u,-1)}),l.reset(r),l.template_effect(()=>l.set_text(o,l.get(t).role===`user`?`You`:`Rough`)),l.append(e,r)},c=e=>{let t=l.derived(()=>mt(l.get(i).output)),n=l.derived(()=>l.get(t)?l.get(Ve).find(e=>e.id===l.get(t).spriteBuildId):void 0);var a=l.comment(),o=l.first_child(a),s=e=>{r(e,()=>l.get(n))};l.if(o,e=>{l.get(n)&&e(s)}),l.append(e,a)};l.if(o,e=>{l.get(i).type===`text`?e(s):l.get(i).type===`tool-call`&&l.get(i).name===`startBuild`&&e(c,1)}),l.append(e,a)}),l.reset(i),l.template_effect(()=>a=l.set_class(i,1,`chat-message svelte-t9dwgq`,null,a,{"chat-message-user":l.get(t).role===`user`,"chat-message-assistant":l.get(t).role===`assistant`})),l.append(e,i)});var u=l.sibling(c,2),d=e=>{var t=IS();l.append(e,t)};l.if(u,e=>{l.get(Ne)&&e(d)});var f=l.sibling(u,2),p=t=>{e(t,()=>`Couldn't chat`,()=>l.get(Me).message)};l.if(f,e=>{l.get(Me)&&e(p)});var m=l.sibling(f,2),h=t=>{e(t,()=>`Couldn't send message`,()=>l.get(me).message)};l.if(m,e=>{l.get(me)&&e(h)}),l.reset(s),l.bind_this(s,e=>l.set(Le,e),()=>l.get(Le)),l.reset(o),l.bind_this(o,e=>l.set(Ie,e),()=>l.get(Ie));var g=l.sibling(o,2);l.set_attribute(g,`aria-valuemin`,0),l.set_attribute(g,`aria-valuemax`,100);var v=l.sibling(g,2),y=l.child(v);tS(l.child(y),{get tabs(){return ye},get active(){return l.get(xe)},set active(e){l.set(xe,e,!0)}}),l.reset(y);var b=l.sibling(y,2),ee=t=>{e(t,()=>`Couldn't publish version`,()=>l.get(at).message)};l.if(b,e=>{l.get(at)&&e(ee)});var x=l.sibling(b,2);iS(x,{get isActive(){return l.get(D)},children:(e,t)=>{SS(e,{get toolList(){return l.get(_)}})},$$slots:{default:!0}});var te=l.sibling(x,2);iS(te,{get isActive(){return l.get(Ee)},children:(e,t)=>{var n=l.comment(),r=l.first_child(n),i=e=>{{let t=l.derived(()=>l.get(Ge).artifactUrl??void 0);Zx(e,{get toolList(){return l.get(_)},get spriteId(){return l.get(w).id},get spriteBuildId(){return l.get(Ge).id},get artifactUrl(){return l.get(t)},spriteInstanceId:void 0,isMock:!0})}},a=e=>{var t=LS();l.append(e,t)};l.if(r,e=>{l.get(w)&&l.get(Ge)?.status===`READY`&&l.get(Ge).artifactUrl?e(i):e(a,-1)}),l.append(e,n)},$$slots:{default:!0}}),iS(l.sibling(te,2),{get isActive(){return l.get(De)},children:(e,t)=>{var n=zS(),r=l.child(n),a=e=>{$b(e,{get client(){return i()},get spriteBuild(){return l.get(Ke)}})},o=e=>{var t=RS();l.append(e,t)};l.if(r,e=>{l.get(Ke)?e(a):e(o,-1)}),l.reset(n),l.append(e,n)},$$slots:{default:!0}}),l.reset(v);var ne=l.sibling(v,2),re=l.child(ne);let a;var ie=l.child(re);l.remove_textarea_child(ie),l.bind_this(ie,e=>l.set(Pe,e),()=>l.get(Pe));var ae=l.sibling(ie,2),oe=e=>{var t=BS(),n=l.child(t),r=e=>{ub(e,{})},i=e=>{h_(e,{size:12,fill:`currentColor`,"aria-hidden":`true`})};l.if(n,e=>{l.get(ht)?e(r):e(i,-1)}),l.reset(t),l.template_effect(()=>{t.disabled=!l.get(gt),l.set_attribute(t,`aria-label`,l.get(ht)?`Stopping build`:`Stop build`)}),l.delegated(`click`,t,()=>void _t()),l.append(e,t)},se=e=>{var t=VS();p_(l.child(t),{size:16,"aria-hidden":`true`}),l.reset(t),l.template_effect(()=>t.disabled=!l.get(yt)),l.append(e,t)};l.if(ae,e=>{l.get(he)?e(oe):e(se,-1)}),l.reset(re),l.reset(ne);var ce=l.sibling(ne,2),le=l.child(ce);{let e=l.derived(()=>!l.get(nt)||l.get(it));fx(le,{get disabled(){return l.get(e)},onclick:()=>void ct(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(it)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.reset(ce);var S=l.sibling(ce,2),C=e=>{ix(e,{title:`Publish before closing?`,detail:`You have iterations from this session that aren't published yet.`,get error(){return l.get(at)},actions:e=>{var t=HS(),n=l.first_child(t);yx(n,{onclick:ft,children:(e,t)=>{l.next();var n=l.text(`Keep editing`);l.append(e,n)},$$slots:{default:!0}});var r=l.sibling(n,2);yx(r,{onclick:dt,children:(e,t)=>{l.next();var n=l.text(`Close anyway`);l.append(e,n)},$$slots:{default:!0}});var i=l.sibling(r,2);{let e=l.derived(()=>!l.get(nt)||l.get(it));fx(i,{get disabled(){return l.get(e)},onclick:()=>void ct(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(it)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.append(e,t)},$$slots:{actions:!0}})};l.if(S,e=>{l.get(ot)&&e(C)}),l.reset(t),l.bind_this(t,e=>l.set(Re,e),()=>l.get(Re)),l.template_effect(()=>{l.set_attribute(g,`aria-valuenow`,l.get(Be)),a=l.set_class(re,1,`composer-input svelte-t9dwgq`,null,a,{isBuilding:l.get(he)})}),l.delegated(`pointerdown`,g,function(...e){ze.onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,g,function(...e){ze.onpointermove?.apply(this,e)}),l.delegated(`pointerup`,g,function(...e){ze.onpointerup?.apply(this,e)}),l.event(`pointercancel`,g,function(...e){ze.onpointercancel?.apply(this,e)}),l.delegated(`keydown`,g,function(...e){ze.onkeydown?.apply(this,e)}),l.event(`submit`,ne,bt),l.delegated(`keydown`,ie,St),l.bind_value(ie,()=>l.get(Oe),e=>l.set(Oe,e))}l.template_effect(()=>{r=l.set_class(t,1,`feature-builder svelte-t9dwgq`,null,r,{"tab-chat":l.get(Se),"tab-preview":l.get(we),"tab-capabilities":l.get(Ce),"tab-logs":l.get(Te)}),a=l.set_style(t,``,a,{"--chat-column":ze.column})}),l.append(e,t)};l.if(d,e=>{l.get(ue)?e(f):l.get(de)?e(p,1):e(m,-1)}),lx(l.sibling(d,2),{get tabs(){return be},ariaLabel:`Feature builder sections`,get active(){return l.get(E)},set active(e){l.set(E,e,!0)}}),l.reset(r),l.template_effect(()=>{a=l.set_class(r,1,`surface svelte-t9dwgq`,null,a,{"rough-dark":l.get(st)}),l.set_text(c,`⌥ ${l.get(w)?.name??`Rough`}`)}),l.delegated(`pointerup`,s,e=>{e.altKey&&l.set(st,!l.get(st))}),l.delegated(`click`,u,ut),l.append(e,r)},$$slots:{default:!0}}),l.pop({get client(){return i()},set client(e){i(e),l.flush()},get surface(){return a()},set surface(e){a(e),l.flush()},get portalTarget(){return o()},set portalTarget(e){o(e),l.flush()},get onclose(){return c()},set onclose(e){c(e),l.flush()},get action(){return f()},set action(e){f(e),l.flush()}})}l.delegate([`pointerup`,`click`,`pointerdown`,`pointermove`,`keydown`]),l.create_custom_element(KS,{client:{},surface:{},portalTarget:{},onclose:{},action:{}},[],[],{mode:`open`});function qS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`surfaceId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get surfaceId(){return i()},set surfaceId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`create`,surfaceId:i()}));KS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-create-modal`,l.create_custom_element(qS,{client:{},surface:{},surfaceId:{},portalTarget:{},onclose:{}},[],[]));var JS=async e=>{let{client:t,signal:n}=e,r=Qg(t);r.assertUsable();let i=Lt(e.surface),o=e.target??document.body,s=r.surfaces.acquire({surface:i}),l=new AbortController,u,d,f,p,m=()=>(p??=(async()=>{l.abort(new wt(`Modal closed`));let e=u;u=void 0,e&&await c(e),d?.remove(),d=void 0,s.release(),f?.(),f=void 0})(),p);if(f=r.operations.register({label:`openRoughCreate(${i.key})`,close:m}),n){if(n.aborted)throw await m(),new wt(`Modal opening was aborted`);n.addEventListener(`abort`,()=>void m(),{once:!0})}try{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Mt(l.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||l.signal.aborted)throw new wt(`The Rough client was destroyed before the create modal could open`);r.assertUsable(),d=document.createElement(`div`),o.appendChild(d),u=a(qS,{target:d,props:{client:t,surface:i,surfaceId:e.resolution.id,onclose:()=>{m()}}})}catch(e){throw await m(),e}return{close:m}};function YS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`edit`,spriteId:i()}));KS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-edit-modal`,l.create_custom_element(YS,{client:{},surface:{},spriteId:{},portalTarget:{},onclose:{}},[],[]));var XS=l.from_html(`<!> <!>`,1);function ZS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`label`,7,`Edit Rough Feature`),o=l.state(!1),s=()=>{l.set(o,!0)},c=()=>{l.set(o,!1)};var u={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get label(){return a()},set label(e=`Edit Rough Feature`){a(e),l.flush()}},d=XS(),f=l.first_child(d);fx(f,{onclick:s,children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,`⌥ ${a()??``}`)),l.append(e,n)},$$slots:{default:!0}});var p=l.sibling(f,2),m=e=>{YS(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return l.if(p,e=>{l.get(o)&&e(m)}),l.append(e,d),l.pop(u)}customElements.define(`rough-edit-button`,l.create_custom_element(ZS,{client:{},surface:{},spriteId:{},label:{}},[],[]));var QS=`data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='17441%2015570%20441%20441'%20fill='none'%20stroke='currentColor'%20stroke-linecap='square'%20stroke-linejoin='miter'%20%3e%3ctitle%3eRough%20logo%3c/title%3e%3cdefs%3e%3cclipPath%20id='rough-logo'%3e%3crect%20x='17501'%20y='15630'%20width='321'%20height='321'%20/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23rough-logo)'%3e%3cg%20transform='matrix(1,0,0,1,17606.5311,15766.3152)'%3e%3cpolygon%20fill='currentColor'%20stroke='none'%20points='17.41,-136.32%20173.47,179.78%20173.47,184.68%2088.38,184.68%20-63.53,-122.94%20-63.53,-136.32'%20/%3e%3c/g%3e%3cpath%20stroke-width='78.5'%20d='M%2017473%2015669.25%20L%2017543%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015669.25%20L%2017750%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015911.75%20L%2017850%2015911.75'%20/%3e%3c/g%3e%3c/svg%3e`,$S=l.from_html(`<div class="chrome svelte-1aurlo0"><button class="badge svelte-1aurlo0" aria-label="Edit Rough Feature"><img alt="Rough Logo"/></button> <!></div> <!>`,1),eC={hash:`svelte-1aurlo0`,code:`.chrome.svelte-1aurlo0 {position:relative;isolation:isolate;}.badge.svelte-1aurlo0 {position:absolute;top:8px;right:8px;z-index:10;display:flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-brand, #cb4b16);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));opacity:0;cursor:pointer;pointer-events:none;transition:opacity 150ms ease, box-shadow 120ms ease;}.badge.svelte-1aurlo0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.chrome.svelte-1aurlo0:hover .badge:where(.svelte-1aurlo0),
|
|
149
|
+
}`};function EA(e,t){u.push(t,!0),u.append_styles(e,TA);let n=e=>ax(e,{allowHtml:!1,extensions:[lb()],frontmatter:!1,headingIds:!1}),r=e=>e.type===`create`?`create:${e.surfaceId}`:`edit:${e.spriteId}`,i=u.prop(t,`client`,7),a=u.prop(t,`surface`,7),o=u.prop(t,`portalTarget`,7),l=u.prop(t,`onclose`,7),p=u.prop(t,`action`,7),m=u.derived(()=>K_(i()).mediaBaseUrl),h=(e,t,n)=>gv(e,{mediaBaseUrl:u.get(m),format:`auto`,quality:75,width:t,height:n,fit:`scale-down`}),g=_t(),_=u.derived(()=>p().type===`edit`?p().spriteId:g),v=u.derived(()=>K_(i())),y=u.derived(()=>u.get(v).store),b=u.derived(()=>a().tools),x=u.state(!0),S=u.state(void 0),C,ee=!1,w=!1,te,ne=async()=>{if(p().type!==`create`||w)return;let e=te;if(e)return e;let t=p(),n=(async()=>{let e=await u.get(v).getReplicache();ee||=(await e.mutate.sprite_create_v2({spriteId:g,surfaceId:t.surfaceId,name:``,context:{actionedAt:Date.now()}}),!0),await e.push({now:!0}),w=!0})();te=n;try{await n}finally{te===n&&(te=void 0)}};s(()=>{u.set(S,r(p()),!0)}),u.user_effect(()=>{let e=u.get(S);if(!e)return;let t=r(p());if(t===e){C=void 0;return}t!==C&&(C=t,console.error(`[Rough] FeatureBuilder does not support changing action after mount.`,{initialActionKey:e,currentActionKey:t}))});let re=u.derived(()=>Dx(u.get(y).meta.get(Je))),ie=u.derived(()=>u.get(re)._),T=u.derived(()=>u.get(ie)?.state===`READY`),ae=u.derived(()=>Dx(u.get(y).sprite.get(u.get(_)))),E=u.derived(()=>u.get(ae)._),D=u.derived(()=>Dx(u.get(y).spriteBuild.filter(`FeatureBuilder:spriteBuildList:${u.get(_)}`,e=>e.spriteId===u.get(_)))),O=u.derived(()=>u.get(D)._),k=u.derived(()=>Dx(u.get(y).spriteBuildEvent.filter(`FeatureBuilder:spriteBuildEventList:${u.get(_)}`,e=>u.get(O).some(t=>t.id===e.spriteBuildId)))),oe=u.derived(()=>u.get(k)._),A=u.derived(()=>{if(u.get(E))return X_({sprite:u.get(E),spriteBuildList:u.get(O)})}),se=u.derived(()=>p().type===`edit`&&!u.get(T)),ce=u.derived(()=>{if(p().type===`edit`&&u.get(T)&&!u.get(E))return Error(`Sprite "${p().spriteId}" not found`)}),le=u.state(!1),j=u.state(void 0),ue=u.state(void 0),de=u.state(void 0),fe=u.derived(()=>u.get(le)||u.get(j)!=null&&u.get(j).status!==`READY`&&u.get(j).status!==`ERROR`&&u.get(j).status!==`CANCELED`&&!u.get(de)),pe=e=>{u.set(j,e,!0),u.set(ue,e.id,!0),tt.add(e.id)},me=u.derived(()=>u.get(ue)?Dx(u.get(y).spriteBuild.get(u.get(ue))):Dx.undefined),he=u.derived(()=>u.get(me)._);u.user_effect(()=>{let e=u.get(he);e&&(e.id===u.get(ue)&&JSON.stringify(u.get(j))!==JSON.stringify(e)&&u.set(j,e,!0),(e.status===`READY`||e.status===`ERROR`||e.status===`CANCELED`)&&u.set(ue,void 0))});let M=[{key:`preview`,label:`Preview`},{key:`capabilities`,label:`Capabilities`},{key:`logs`,label:`Logs`}],ge=[{key:`chat`,label:`Chat`},...M],_e=u.state(`chat`),ve=u.state(`capabilities`),ye=u.derived(()=>u.get(_e)===`chat`),be=u.derived(()=>u.get(_e)===`capabilities`),xe=u.derived(()=>u.get(_e)===`preview`),Se=u.derived(()=>u.get(_e)===`logs`),Ce=u.derived(()=>u.get(ve)===`capabilities`),we=u.derived(()=>u.get(ve)===`preview`),Te=u.derived(()=>u.get(ve)===`logs`),Ee=u.state(``),De=u.state(u.proxy([])),Oe=u.state(void 0),ke=u.state(void 0),Ae=u.state(void 0),je=u.state(u.proxy([])),Me=u.state(!1),Ne=u.state(void 0),Pe=u.derived(()=>u.get(Me)&&!u.get(fe)),Fe=u.derived(()=>u.get(De).some(e=>e.asset===void 0)),Ie=u.state(void 0),Le=u.state(void 0),Re=u.state(void 0),ze=u.state(void 0),Be=u.state(void 0),Ve=eA({getContainer:()=>u.get(Be),minColumnPx:280,dividerWidthPx:12}),He=u.derived(()=>{if(Ve.widthPx===void 0||!u.get(Be))return;let e=u.get(Be).getBoundingClientRect().width;if(e)return Math.round(Ve.widthPx/e*100)}),Ue=u.derived(()=>{let e=new d;for(let t of u.get(O))e.set(t.id,t);return u.get(j)&&e.set(u.get(j).id,u.get(j)),[...e.values()].sort((e,t)=>e.id.localeCompare(t.id))}),We=!1,Ge=e=>{u.set(Le,e,!0),We=!0,u.set(ve,`preview`),u.set(_e,`preview`)},Ke=u.derived(()=>u.get(Ue).findLast(e=>e.status===`READY`&&e.artifactUrl)),qe=u.derived(()=>{if(u.get(Le)){let e=u.get(Ue).find(e=>e.id===u.get(Le));if(e)return e}return u.get(Ke)??u.get(Ue).at(-1)}),Ye=u.derived(()=>u.get(Ue).at(-1)),Xe=u.derived(()=>u.get(qe)?.status===`READY`&&u.get(qe).artifactUrl?u.get(qe):void 0),Ze=u.derived(()=>u.get(Xe)??u.get(Ke)),Qe=!1;u.user_effect(()=>{!Qe&&u.get(Ke)&&(u.set(_e,`preview`),u.set(ve,`preview`),Qe=!0)}),u.user_effect(()=>{if(u.get(Ue).length===0){u.set(Le,void 0),We=!1;return}(!We||!u.get(Le)||!u.get(Ue).some(e=>e.id===u.get(Le)))&&(u.set(Le,u.get(Ke)?.id??u.get(Ue).at(-1)?.id,!0),We=!1)});let $e=u.derived(()=>u.get(Ke)?.id),et=u.derived(()=>Y_(u.get(O))),tt=new f,nt=u.state(void 0),rt=u.derived(()=>u.get(nt)??u.get(et)?.id??void 0),it=u.derived(()=>!u.get(fe)&&u.get(Ze)!=null&&u.get(Ze).id!==u.get(rt)),at=u.derived(()=>u.get(rt)!==u.get($e)),ot=u.state(!1),st=u.state(void 0),ct=u.state(!1),lt=u.state(!1),ut=async()=>{if(u.get(A)&&u.get(Ze)&&!u.get(ot)){u.set(ot,!0),u.set(st,void 0);try{let e=await xx({replicache:await u.get(v).getReplicache(),spriteId:u.get(A).id,spriteBuildId:u.get(Ze).id});if(e instanceof Error){u.set(st,e,!0);return}u.set(nt,e.spriteBuildId,!0),u.set(ct,!1)}finally{u.set(ot,!1)}}},dt=()=>{u.set(x,!1)},ft=()=>{u.get(at)?u.set(ct,!0):dt()},pt=()=>{u.set(ct,!1),dt()},mt=()=>{u.set(ct,!1)},ht=e=>{if(e){if(typeof e.message==`string`)return e.message;if(typeof e.error==`string`)return e.error}},gt=e=>{let t=Oh.outputSchema.safeParse(e);return t.success?t.data:void 0},vt=u.derived(()=>u.get(j)?.cancelRequestedAt!=null),yt=u.derived(()=>!u.get(vt)&&(u.get(j)?.status===`PENDING`||u.get(j)?.status===`IN_PROGRESS`)),bt=async()=>{u.get(A)&&u.get(j)&&u.get(yt)&&await(await u.get(v).getReplicache()).mutate.spriteBuild_cancel_v1({spriteBuildId:u.get(j).id})},xt=async e=>{u.set(de,void 0),u.set(le,!0);try{let t=Mh({messageList:pm(e)});if(t instanceof Error)throw t;let n=await u.get(v).getReplicache(),r=_t();await n.mutate.spriteBuild_create_v2({spriteBuildId:r,spriteId:u.get(_),parentSpriteBuildId:u.get($e),prompt:t});let i=u.get(y).spriteBuild.get(r).value;return i?pe(i):u.set(ue,r,!0),{spriteBuildId:r}}finally{u.set(le,!1)}};u.user_effect(()=>{if(u.get(se)||u.get(ce))return;let e=xS({client:i(),spriteId:u.get(_),toolList:u.get(b),getSpriteBuildEventList:e=>u.get(oe).filter(t=>t.spriteBuildId===e),onStartBuild:e=>xt(e),onMessagesChange:e=>{u.set(je,e,!0)},onLoadingChange:e=>{u.set(Me,e,!0)},onErrorChange:e=>{u.set(Ne,e,!0)}});return u.set(Ae,e,!0),e.attach(),u.set(je,e.getMessages(),!0),u.set(Me,e.getIsLoading(),!0),u.set(Ne,e.getError(),!0),()=>{e.dispose(),u.get(Ae)===e&&u.set(Ae,void 0)}});let St=u.derived(()=>u.get(Ae)!=null&&!u.get(fe)&&!u.get(Me)&&!u.get(Fe)&&u.get(Ee).trim().length>0),Ct=async e=>{e.preventDefault();let t=u.get(Ee).trim();if(!t||u.get(fe)||u.get(Me)||u.get(Fe))return;if(u.set(de,void 0),u.set(Ne,void 0),!u.get(Ae)){u.set(de,Error(`Feature builder chat is not ready`),!0);return}let n=u.get(De);u.set(Ee,``),u.set(De,[],!0);try{await ne(),await u.get(Ae).sendMessage(n.length>0?{content:[{type:`text`,content:t},...n.flatMap(e=>e.asset?[{type:`image`,source:{type:`url`,value:fv(e.asset,{mediaBaseUrl:u.get(m)}),mimeType:e.asset.mimeType},metadata:{assetId:e.asset.id}}]:[])]}:t)}catch(e){u.set(De,n,!0),u.set(de,e instanceof Error?e:Error(String(e)),!0)}},wt=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Ct(e))};u.user_effect(()=>{u.get(_e)!==`chat`&&u.set(ve,u.get(_e),!0)}),u.user_effect(()=>{let e=u.get(Ie);e&&(u.get(Ee),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}),u.user_effect(()=>{let e=u.get(ze),t=u.get(Re);if(!e||!t)return;let n=new ResizeObserver(()=>{t.scrollTop=t.scrollHeight});return n.observe(e),()=>n.disconnect()});let Tt=async e=>{let t=3-u.get(De).length;if(t<=0){u.set(Oe,Error(`You can add up to 3 images.`),!0);return}let n=e.slice(0,t),r=n.length<e.length?Error(`You can add up to 3 images.`):void 0;u.set(Oe,void 0);let a=n.map(e=>({file:e,previewUrl:URL.createObjectURL(e)}));u.set(De,[...u.get(De),...a],!0);let o=await Promise.all(a.map(({file:e})=>FO({client:i(),file:e})));u.set(De,u.get(De).flatMap(e=>{let t=a.findIndex(t=>t.previewUrl===e.previewUrl);if(t===-1)return[e];let n=o[t];return n instanceof Error?[]:[{...e,asset:n}]}),!0),u.set(Oe,o.find(e=>e instanceof Error)??r,!0),await c();for(let e of a)URL.revokeObjectURL(e.previewUrl)},Et=e=>{let t=e.currentTarget,n=Array.from(t.files??[]);t.value=``,n.length>0&&Tt(n)},Dt=e=>{e.stopPropagation()},Ot=e=>{let t=Array.from(e.clipboardData?.files??[]).filter(e=>e.type.startsWith(`image/`));t.length===0||u.get(Fe)||(e.preventDefault(),Tt(t))},kt=e=>{u.set(De,u.get(De).filter(t=>t!==e),!0),u.set(Oe,void 0)};return KO(e,{get target(){return o()},oncancel:ft,get onclose(){return l()},get isOpen(){return u.get(x)},set isOpen(e){u.set(x,e,!0)},children:(e,t)=>{var r=wA();let a;var o=u.child(r),s=u.child(o),c=u.only_child(s,!0),l=u.sibling(s,2);u.reset(o);var d=u.sibling(o,2),f=e=>{var t=tA();u.append(e,t)},p=e=>{var t=nA(),n=u.only_child(t,!0);u.template_effect(()=>u.set_text(n,u.get(ce).message)),u.append(e,t)},m=e=>{var t=CA();let r,a;{let e=(e,t=u.noop,n=u.noop,r=u.noop)=>{var i=aA(),a=u.child(i),o=u.only_child(a,!0),s=u.sibling(a,2),c=e=>{var t=rA(),r=u.only_child(t,!0);u.template_effect(()=>u.set_text(r,n())),u.append(e,t)};u.if(s,e=>{n()&&e(c)});var l=u.sibling(s,2),d=e=>{var t=iA(),n=u.sibling(u.child(t),2),i=u.only_child(n,!0);u.reset(t),u.template_effect(e=>u.set_text(i,e),[()=>JSON.stringify(r(),null,2)]),u.append(e,t)};u.if(l,e=>{r()&&e(d)}),u.reset(i),u.template_effect(()=>u.set_text(o,t())),u.append(e,i)},r=(t,n=u.noop)=>{let r=u.derived(()=>n().id===u.get(rt)),a=u.derived(()=>u.get(Ue).indexOf(n())+1);var o=cA();let s;var c=u.child(o),l=e=>{Yx(e,{get client(){return i()},get spriteBuild(){return n()}})};u.if(c,e=>{n().status!==`READY`&&n().status!==`ERROR`&&e(l)});var d=u.sibling(c,2),f=e=>{var t=sA(),i=u.child(t),o=u.child(i),s=u.child(o),c=u.sibling(s),l=e=>{var t=oA();u.append(e,t)};u.if(c,e=>{u.get(r)&&e(l)}),u.reset(o),u.reset(i),u.reset(t),u.template_effect(()=>u.set_text(s,`Version ${u.get(a)??``} ready `)),u.delegated(`click`,i,()=>Ge(n().id)),u.append(e,t)},p=t=>{{let r=u.derived(()=>ht(n().error));e(t,()=>`Version ${u.get(a)} failed`,()=>u.get(r),()=>n().error)}};u.if(d,e=>{n().status===`READY`?e(f):n().status===`ERROR`&&e(p,1)}),u.reset(o),u.template_effect(()=>s=u.set_class(o,1,`turn svelte-t9dwgq`,null,s,{"turn-published":u.get(r)})),u.append(t,o)};var o=u.child(t),s=u.child(o),c=u.child(s);u.each(c,17,()=>u.get(je),e=>e.id,(e,t)=>{var i=fA();let a;u.each(i,23,()=>u.get(t).parts,(e,n)=>`${u.get(t).id}-${n}`,(e,i)=>{var a=u.comment(),o=u.first_child(a),s=e=>{var r=uA(),a=u.child(r),o=u.only_child(a,!0),s=u.sibling(a,2),c=e=>{var t=u.comment(),r=u.first_child(t);u.html(r,()=>n(u.get(i).content)),u.append(e,t)},l=e=>{var t=lA(),n=u.only_child(t,!0);u.template_effect(()=>u.set_text(n,u.get(i).content)),u.append(e,t)};u.if(s,e=>{u.get(t).role===`assistant`?e(c):e(l,-1)}),u.reset(r),u.template_effect(()=>u.set_text(o,u.get(t).role===`user`?`You`:`Rough`)),u.append(e,r)},c=e=>{var t=dA();u.template_effect(e=>u.set_attribute(t,`src`,e),[()=>h(u.get(i).source.value,768,640)]),u.append(e,t)},l=e=>{let t=u.derived(()=>gt(u.get(i).output)),n=u.derived(()=>u.get(t)?u.get(Ue).find(e=>e.id===u.get(t).spriteBuildId):void 0);var a=u.comment(),o=u.first_child(a),s=e=>{r(e,()=>u.get(n))};u.if(o,e=>{u.get(n)&&e(s)}),u.append(e,a)};u.if(o,e=>{u.get(i).type===`text`?e(s):u.get(i).type===`image`?e(c,1):u.get(i).type===`tool-call`&&u.get(i).name===`startBuild`&&e(l,2)}),u.append(e,a)}),u.reset(i),u.template_effect(()=>a=u.set_class(i,1,`chat-message svelte-t9dwgq`,null,a,{"chat-message-user":u.get(t).role===`user`,"chat-message-assistant":u.get(t).role===`assistant`})),u.append(e,i)});var l=u.sibling(c,2),d=e=>{var t=pA();u.append(e,t)};u.if(l,e=>{u.get(Pe)&&e(d)});var f=u.sibling(l,2),p=t=>{e(t,()=>`Couldn't chat`,()=>u.get(Ne).message)};u.if(f,e=>{u.get(Ne)&&e(p)});var m=u.sibling(f,2),g=t=>{e(t,()=>`Couldn't upload image`,()=>u.get(Oe).message)};u.if(m,e=>{u.get(Oe)&&e(g)});var _=u.sibling(m,2),v=t=>{e(t,()=>`Couldn't send message`,()=>u.get(de).message)};u.if(_,e=>{u.get(de)&&e(v)}),u.reset(s),u.bind_this(s,e=>u.set(ze,e),()=>u.get(ze)),u.reset(o),u.bind_this(o,e=>u.set(Re,e),()=>u.get(Re));var y=u.sibling(o,2);u.set_attribute(y,`aria-valuemin`,0),u.set_attribute(y,`aria-valuemax`,100);var x=u.sibling(y,2),S=u.child(x);jk(u.child(S),{get tabs(){return M},get active(){return u.get(ve)},set active(e){u.set(ve,e,!0)}}),u.reset(S);var C=u.sibling(S,2),ee=t=>{e(t,()=>`Couldn't publish version`,()=>u.get(st).message)};u.if(C,e=>{u.get(st)&&e(ee)});var w=u.sibling(C,2);Pk(w,{get isActive(){return u.get(Ce)},children:(e,t)=>{Qk(e,{get toolList(){return u.get(b)}})},$$slots:{default:!0}});var te=u.sibling(w,2);Pk(te,{get isActive(){return u.get(we)},children:(e,t)=>{var n=u.comment(),r=u.first_child(n),i=e=>{{let t=u.derived(()=>u.get(qe).artifactUrl??void 0);Dk(e,{get toolList(){return u.get(b)},get spriteId(){return u.get(A).id},get spriteBuildId(){return u.get(qe).id},get artifactUrl(){return u.get(t)},spriteInstanceId:void 0,isMock:!0})}},a=e=>{var t=mA();u.append(e,t)};u.if(r,e=>{u.get(A)&&u.get(qe)?.status===`READY`&&u.get(qe).artifactUrl?e(i):e(a,-1)}),u.append(e,n)},$$slots:{default:!0}}),Pk(u.sibling(te,2),{get isActive(){return u.get(Te)},children:(e,t)=>{var n=gA(),r=u.child(n),a=e=>{hS(e,{get client(){return i()},get spriteBuild(){return u.get(Ye)}})},o=e=>{var t=hA();u.append(e,t)};u.if(r,e=>{u.get(Ye)?e(a):e(o,-1)}),u.reset(n),u.append(e,n)},$$slots:{default:!0}}),u.reset(x);var ne=u.sibling(x,2),re=u.child(ne);u.bind_this(re,e=>u.set(ke,e),()=>u.get(ke));var ie=u.sibling(re,2);let a;var T=u.child(ie);u.remove_textarea_child(T),u.bind_this(T,e=>u.set(Ie,e),()=>u.get(Ie));var ae=u.sibling(T,2);lv(u.child(ae),{size:16,"aria-hidden":`true`}),u.reset(ae);var E=u.sibling(ae,2),D=e=>{var t=_A(),n=u.child(t),r=e=>{Ex(e,{})},i=e=>{dv(e,{size:12,fill:`currentColor`,"aria-hidden":`true`})};u.if(n,e=>{u.get(vt)?e(r):e(i,-1)}),u.reset(t),u.template_effect(()=>{t.disabled=!u.get(yt),u.set_attribute(t,`aria-label`,u.get(vt)?`Stopping build`:`Stop build`)}),u.delegated(`click`,t,()=>void bt()),u.append(e,t)},O=e=>{var t=vA();sv(u.child(t),{size:16,"aria-hidden":`true`}),u.reset(t),u.template_effect(()=>t.disabled=!u.get(St)),u.append(e,t)};u.if(E,e=>{u.get(fe)?e(D):e(O,-1)});var k=u.sibling(E,2),oe=e=>{var t=xA();u.each(t,21,()=>u.get(De),e=>e.previewUrl,(e,t)=>{var n=bA();let r;var i=u.child(n),a=u.only_child(i),o=u.sibling(i,2),s=e=>{var n=yA();u.delegated(`click`,n,()=>kt(u.get(t))),u.append(e,n)};u.if(o,e=>{u.get(t).asset&&e(s)}),u.reset(n),u.template_effect(e=>{r=u.set_class(n,1,`image-asset svelte-t9dwgq`,null,r,{"is-uploading":!u.get(t).asset}),u.set_attribute(a,`src`,e)},[()=>u.get(t).asset?h(u.get(t).asset.storageKey,80,80):u.get(t).previewUrl]),u.append(e,n)}),u.reset(t),u.append(e,t)};u.if(k,e=>{u.get(De).length>0&&e(oe)}),u.reset(ie),u.reset(ne);var se=u.sibling(ne,2),ce=u.child(se);{let e=u.derived(()=>!u.get(it)||u.get(ot));HO(ce,{get disabled(){return u.get(e)},onclick:()=>void ut(),children:(e,t)=>{u.next();var n=u.text();u.template_effect(()=>u.set_text(n,u.get(ot)?`Publishing…`:`Publish`)),u.append(e,n)},$$slots:{default:!0}})}u.reset(se);var le=u.sibling(se,2),j=e=>{bS(e,{title:`Publish before closing?`,detail:`You have iterations from this session that aren't published yet.`,get error(){return u.get(st)},actions:e=>{var t=SA(),n=u.first_child(t);YO(n,{onclick:mt,children:(e,t)=>{u.next();var n=u.text(`Keep editing`);u.append(e,n)},$$slots:{default:!0}});var r=u.sibling(n,2);YO(r,{onclick:pt,children:(e,t)=>{u.next();var n=u.text(`Close anyway`);u.append(e,n)},$$slots:{default:!0}});var i=u.sibling(r,2);{let e=u.derived(()=>!u.get(it)||u.get(ot));HO(i,{get disabled(){return u.get(e)},onclick:()=>void ut(),children:(e,t)=>{u.next();var n=u.text();u.template_effect(()=>u.set_text(n,u.get(ot)?`Publishing…`:`Publish`)),u.append(e,n)},$$slots:{default:!0}})}u.append(e,t)},$$slots:{actions:!0}})};u.if(le,e=>{u.get(ct)&&e(j)}),u.reset(t),u.bind_this(t,e=>u.set(Be,e),()=>u.get(Be)),u.template_effect(()=>{u.set_attribute(y,`aria-valuenow`,u.get(He)),a=u.set_class(ie,1,`composer-input svelte-t9dwgq`,null,a,{isBuilding:u.get(fe)}),ae.disabled=u.get(Fe)||u.get(De).length>=3}),u.delegated(`pointerdown`,y,function(...e){Ve.onpointerdown?.apply(this,e)}),u.delegated(`pointermove`,y,function(...e){Ve.onpointermove?.apply(this,e)}),u.delegated(`pointerup`,y,function(...e){Ve.onpointerup?.apply(this,e)}),u.event(`pointercancel`,y,function(...e){Ve.onpointercancel?.apply(this,e)}),u.delegated(`keydown`,y,function(...e){Ve.onkeydown?.apply(this,e)}),u.event(`submit`,ne,Ct),u.delegated(`change`,re,Et),u.event(`cancel`,re,Dt),u.delegated(`keydown`,T,wt),u.event(`paste`,T,Ot),u.bind_value(T,()=>u.get(Ee),e=>u.set(Ee,e)),u.delegated(`click`,ae,()=>u.get(ke)?.click())}u.template_effect(()=>{r=u.set_class(t,1,`feature-builder svelte-t9dwgq`,null,r,{"tab-chat":u.get(ye),"tab-preview":u.get(xe),"tab-capabilities":u.get(be),"tab-logs":u.get(Se)}),a=u.set_style(t,``,a,{"--chat-column":Ve.column})}),u.append(e,t)};u.if(d,e=>{u.get(se)?e(f):u.get(ce)?e(p,1):e(m,-1)}),zO(u.sibling(d,2),{get tabs(){return ge},ariaLabel:`Feature builder sections`,get active(){return u.get(_e)},set active(e){u.set(_e,e,!0)}}),u.reset(r),u.template_effect(()=>{a=u.set_class(r,1,`surface svelte-t9dwgq`,null,a,{"rough-dark":u.get(lt)}),u.set_text(c,`⌥ ${u.get(A)?.name??`Rough`}`)}),u.delegated(`pointerup`,s,e=>{e.altKey&&u.set(lt,!u.get(lt))}),u.delegated(`click`,l,ft),u.append(e,r)},$$slots:{default:!0}}),u.pop({get client(){return i()},set client(e){i(e),u.flush()},get surface(){return a()},set surface(e){a(e),u.flush()},get portalTarget(){return o()},set portalTarget(e){o(e),u.flush()},get onclose(){return l()},set onclose(e){l(e),u.flush()},get action(){return p()},set action(e){p(e),u.flush()}})}u.delegate([`pointerup`,`click`,`pointerdown`,`pointermove`,`keydown`,`change`]),u.create_custom_element(EA,{client:{},surface:{},portalTarget:{},onclose:{},action:{}},[],[],{mode:`open`});function DA(e,t){u.push(t,!0);let n=u.prop(t,`client`,7),r=u.prop(t,`surface`,7),i=u.prop(t,`surfaceId`,7),a=u.prop(t,`portalTarget`,7),o=u.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),u.flush()},get surface(){return r()},set surface(e){r(e),u.flush()},get surfaceId(){return i()},set surfaceId(e){i(e),u.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),u.flush()},get onclose(){return o()},set onclose(e){o(e),u.flush()}};{let t=u.derived(()=>({type:`create`,surfaceId:i()}));EA(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return u.get(t)},get onclose(){return o()}})}return u.pop(s)}customElements.define(`rough-create-modal`,u.create_custom_element(DA,{client:{},surface:{},surfaceId:{},portalTarget:{},onclose:{}},[],[]));var OA=async e=>{let{client:t,signal:n}=e,r=K_(t);r.assertUsable();let i=Nt(e.surface),o=e.target??document.body,s=r.surfaces.acquire({surface:i}),c=new AbortController,u,d,f,p,m=()=>(p??=(async()=>{c.abort(new bt(`Modal closed`));let e=u;u=void 0,e&&await l(e),d?.remove(),d=void 0,s.release(),f?.(),f=void 0})(),p);if(f=r.operations.register({label:`openRoughCreate(${i.key})`,close:m}),n){if(n.aborted)throw await m(),new bt(`Modal opening was aborted`);n.addEventListener(`abort`,()=>void m(),{once:!0})}try{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Ot(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)throw new bt(`The Rough client was destroyed before the create modal could open`);r.assertUsable(),d=document.createElement(`div`),o.appendChild(d),u=a(DA,{target:d,props:{client:t,surface:i,surfaceId:e.resolution.id,onclose:()=>{m()}}})}catch(e){throw await m(),e}return{close:m}};function kA(e,t){u.push(t,!0);let n=u.prop(t,`client`,7),r=u.prop(t,`surface`,7),i=u.prop(t,`spriteId`,7),a=u.prop(t,`portalTarget`,7),o=u.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),u.flush()},get surface(){return r()},set surface(e){r(e),u.flush()},get spriteId(){return i()},set spriteId(e){i(e),u.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),u.flush()},get onclose(){return o()},set onclose(e){o(e),u.flush()}};{let t=u.derived(()=>({type:`edit`,spriteId:i()}));EA(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return u.get(t)},get onclose(){return o()}})}return u.pop(s)}customElements.define(`rough-edit-modal`,u.create_custom_element(kA,{client:{},surface:{},spriteId:{},portalTarget:{},onclose:{}},[],[]));var AA=u.from_html(`<!> <!>`,1);function jA(e,t){u.push(t,!0);let n=u.prop(t,`client`,7),r=u.prop(t,`surface`,7),i=u.prop(t,`spriteId`,7),a=u.prop(t,`label`,7,`Edit Rough Feature`),o=u.state(!1),s=()=>{u.set(o,!0)},c=()=>{u.set(o,!1)};var l={get client(){return n()},set client(e){n(e),u.flush()},get surface(){return r()},set surface(e){r(e),u.flush()},get spriteId(){return i()},set spriteId(e){i(e),u.flush()},get label(){return a()},set label(e=`Edit Rough Feature`){a(e),u.flush()}},d=AA(),f=u.first_child(d);HO(f,{onclick:s,children:(e,t)=>{u.next();var n=u.text();u.template_effect(()=>u.set_text(n,`⌥ ${a()??``}`)),u.append(e,n)},$$slots:{default:!0}});var p=u.sibling(f,2),m=e=>{kA(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return u.if(p,e=>{u.get(o)&&e(m)}),u.append(e,d),u.pop(l)}customElements.define(`rough-edit-button`,u.create_custom_element(jA,{client:{},surface:{},spriteId:{},label:{}},[],[]));var MA=`data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='17441%2015570%20441%20441'%20fill='none'%20stroke='currentColor'%20stroke-linecap='square'%20stroke-linejoin='miter'%20%3e%3ctitle%3eRough%20logo%3c/title%3e%3cdefs%3e%3cclipPath%20id='rough-logo'%3e%3crect%20x='17501'%20y='15630'%20width='321'%20height='321'%20/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23rough-logo)'%3e%3cg%20transform='matrix(1,0,0,1,17606.5311,15766.3152)'%3e%3cpolygon%20fill='currentColor'%20stroke='none'%20points='17.41,-136.32%20173.47,179.78%20173.47,184.68%2088.38,184.68%20-63.53,-122.94%20-63.53,-136.32'%20/%3e%3c/g%3e%3cpath%20stroke-width='78.5'%20d='M%2017473%2015669.25%20L%2017543%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015669.25%20L%2017750%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015911.75%20L%2017850%2015911.75'%20/%3e%3c/g%3e%3c/svg%3e`,NA=u.from_html(`<button class="badge svelte-1aurlo0" aria-label="Edit Rough Feature"><img alt="Rough Logo"/></button>`),PA=u.from_html(`<div class="chrome svelte-1aurlo0"><!> <!></div> <!>`,1),FA={hash:`svelte-1aurlo0`,code:`.chrome.svelte-1aurlo0 {position:relative;isolation:isolate;}.badge.svelte-1aurlo0 {position:absolute;top:8px;right:8px;z-index:10;display:flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-brand, #cb4b16);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));opacity:0;cursor:pointer;pointer-events:none;transition:opacity 150ms ease, box-shadow 120ms ease;}.badge.svelte-1aurlo0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.chrome.svelte-1aurlo0:hover .badge:where(.svelte-1aurlo0),
|
|
134
150
|
.chrome.svelte-1aurlo0:focus-within .badge:where(.svelte-1aurlo0),
|
|
135
|
-
.chrome.svelte-1aurlo0:active .badge:where(.svelte-1aurlo0) {opacity:1;pointer-events:auto;}`};function
|
|
151
|
+
.chrome.svelte-1aurlo0:active .badge:where(.svelte-1aurlo0) {opacity:1;pointer-events:auto;}`};function IA(e,t){u.push(t,!0),u.append_styles(e,FA);let n=u.prop(t,`client`,7),r=u.prop(t,`surface`,7),i=u.prop(t,`spriteId`,7),a=u.prop(t,`children`,7),o=u.prop(t,`isEditable`,7,!0),s=u.state(!1),c=()=>{u.set(s,!0)},l=()=>{u.set(s,!1)};var d={get client(){return n()},set client(e){n(e),u.flush()},get surface(){return r()},set surface(e){r(e),u.flush()},get spriteId(){return i()},set spriteId(e){i(e),u.flush()},get children(){return a()},set children(e){a(e),u.flush()},get isEditable(){return o()},set isEditable(e=!0){o(e),u.flush()}},f=PA(),p=u.first_child(f),m=u.child(p),h=e=>{var t=NA(),n=u.only_child(t);u.template_effect(()=>u.set_attribute(n,`src`,MA)),u.delegated(`click`,t,c),u.append(e,t)};u.if(m,e=>{o()&&e(h)});var g=u.sibling(m,2);u.snippet(g,a),u.reset(p);var _=u.sibling(p,2),v=e=>{kA(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:l})};return u.if(_,e=>{o()&&u.get(s)&&e(v)}),u.append(e,f),u.pop(d)}u.delegate([`click`]),u.create_custom_element(IA,{client:{},surface:{},spriteId:{},children:{},isEditable:{}},[],[],{mode:`open`});function LA(e,t){u.push(t,!0);let n=u.prop(t,`client`,7),r=u.prop(t,`surface`,7),i=u.prop(t,`featureId`,7),a=u.prop(t,`buildId`,7),o=u.prop(t,`datastore`,7),s=u.prop(t,`isEditable`,7,!0);return IA(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},get isEditable(){return s()},children:(e,t)=>{Dk(e,{get client(){return n()},get spriteId(){return i()},get spriteBuildId(){return a()},get spriteInstanceId(){return i()},get toolList(){return r().tools},get datastore(){return o()}})},$$slots:{default:!0}}),u.pop({get client(){return n()},set client(e){n(e),u.flush()},get surface(){return r()},set surface(e){r(e),u.flush()},get featureId(){return i()},set featureId(e){i(e),u.flush()},get buildId(){return a()},set buildId(e){a(e),u.flush()},get datastore(){return o()},set datastore(e){o(e),u.flush()},get isEditable(){return s()},set isEditable(e=!0){s(e),u.flush()}})}customElements.define(`rough-feature`,u.create_custom_element(LA,{client:{},surface:{},featureId:{},buildId:{},datastore:{},isEditable:{}},[],[]));var RA=u.from_html(`<div class="SpriteBuildMenuItem svelte-1uvsqdj" role="none"><div class="copy svelte-1uvsqdj"><h3 class="svelte-1uvsqdj"> </h3> <p class="svelte-1uvsqdj"> </p></div> <!></div>`),zA={hash:`svelte-1uvsqdj`,code:`.SpriteBuildMenuItem.svelte-1uvsqdj {display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;border-radius:var(--rough-radius-sm, 0.25rem);padding:0.75rem;background:transparent;color:var(--rough-popover-foreground, oklch(0.145 0 0));}.SpriteBuildMenuItem.svelte-1uvsqdj:hover {background:var(--rough-accent, oklch(0.97 0 0));color:var(--rough-accent-foreground, oklch(0.205 0 0));}.copy.svelte-1uvsqdj {min-width:0;}.copy.svelte-1uvsqdj h3:where(.svelte-1uvsqdj) {margin:0;font-size:0.875rem;font-weight:600;}.copy.svelte-1uvsqdj p:where(.svelte-1uvsqdj) {margin:0.25rem 0 0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function BA(e,t){u.push(t,!0),u.append_styles(e,zA);let n=u.prop(t,`sprite`,7),r=u.prop(t,`spriteBuild`,7),i=u.prop(t,`onselect`,7),a=async()=>{i()?.(n(),r())};var o={get sprite(){return n()},set sprite(e){n(e),u.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),u.flush()},get onselect(){return i()},set onselect(e){i(e),u.flush()}},s=RA(),c=u.child(s),l=u.child(c),d=u.only_child(l,!0),f=u.sibling(l,2),p=u.only_child(f,!0);return u.reset(c),HO(u.sibling(c,2),{onclick:a,role:`menuitem`,children:(e,t)=>{u.next();var n=u.text(`Insert`);u.append(e,n)},$$slots:{default:!0}}),u.reset(s),u.template_effect(()=>{u.set_text(d,n().name),u.set_text(p,r().prompt)}),u.append(e,s),u.pop(o)}u.create_custom_element(BA,{sprite:{},spriteBuild:{},onselect:{}},[],[],{mode:`open`});var VA=u.from_html(`<!> Insert Existing Rough Feature`,1),HA=u.from_html(`<p class="svelte-17o42e2">Loading…</p>`),UA=u.from_html(`<div class="menu svelte-17o42e2" role="menu"><!></div>`),WA=u.from_html(`<div class="SpriteBuildMenu svelte-17o42e2"><!> <!></div>`),GA={hash:`svelte-17o42e2`,code:`.SpriteBuildMenu.svelte-17o42e2 {position:relative;}.menu.svelte-17o42e2 {position:absolute;top:calc(100% + 0.5rem);left:0;z-index:10;display:grid;gap:0.25rem;min-width:22rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-popover, white);box-shadow:var(--rough-shadow-md, 0 4px 6px -1px rgb(0 0 0 / 0.1));color:var(--rough-popover-foreground, oklch(0.145 0 0));}.menu.svelte-17o42e2 p:where(.svelte-17o42e2) {margin:0;padding:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;}`};function KA(e,t){u.push(t,!0),u.append_styles(e,GA);let n=u.prop(t,`client`,7),r=u.prop(t,`surfaceId`,7),i=u.prop(t,`onselect`,7),a=u.derived(()=>K_(n()).store),o=u.derived(()=>Dx(u.get(a).meta.get(Je))),s=u.derived(()=>u.get(o)._),c=u.derived(()=>Dx(u.get(a).sprite.filter(`sprite-build-menu:${r()}`,e=>e.surfaceId===r()))),l=u.derived(()=>u.get(c)._),d=u.derived(()=>Dx(u.get(a).spriteBuild.asList)),f=u.derived(()=>u.get(d)._),p=u.derived(()=>u.get(s)?.state===`READY`),m=u.derived(()=>u.get(l).flatMap(e=>{let t=Y_(u.get(f).filter(t=>t.spriteId===e.id));return t?[{sprite:{id:e.id,name:e.name,ownedByPersonId:e.ownedByPersonId,publishedSpriteBuildId:t.id},spriteBuild:t}]:[]})),h=u.state(!1),g=()=>{u.set(h,!u.get(h))},_=(e,t)=>{u.set(h,!1),i()?.(e,t)};var v={get client(){return n()},set client(e){n(e),u.flush()},get surfaceId(){return r()},set surfaceId(e){r(e),u.flush()},get onselect(){return i()},set onselect(e){i(e),u.flush()}},y=WA(),b=u.child(y);YO(b,{onclick:g,"aria-haspopup":`menu`,get"aria-expanded"(){return u.get(h)},children:(e,t)=>{var n=VA();Ik(u.first_child(n),{size:20}),u.next(),u.append(e,n)},$$slots:{default:!0}});var x=u.sibling(b,2),S=e=>{var t=UA(),n=u.child(t),r=e=>{var t=HA();u.append(e,t)},i=e=>{var t=u.comment(),n=u.first_child(t);u.each(n,17,()=>u.get(m),e=>e.sprite.id,(e,t)=>{BA(e,{get sprite(){return u.get(t).sprite},get spriteBuild(){return u.get(t).spriteBuild},onselect:_})}),u.append(e,t)};u.if(n,e=>{u.get(p)?e(i,-1):e(r)}),u.reset(t),u.append(e,t)};return u.if(x,e=>{u.get(h)&&e(S)}),u.reset(y),u.append(e,y),u.pop(v)}u.create_custom_element(KA,{client:{},surfaceId:{},onselect:{}},[],[],{mode:`open`});export{ne as Mutation,HO as PrimaryButton,re as Query,ak as ResizeHandle,Ct as RoughClientDestroyError,bt as RoughClientDestroyedError,DA as RoughCreateModal,jA as RoughEditButton,LA as RoughFeature,wt as RoughInvalidClientError,xt as RoughReplicacheIdentityConflictError,St as RoughSurfaceContractConflictError,YO as SecondaryButton,KA as SpriteBuildMenu,Dk as SpriteFrame,ie as Subscription,q_ as createRoughClient,jt as defineRoughSurface,Q_ as getRoughFeatures,OA as openRoughCreate,J_ as whenRoughClientReady};
|