@runappsai/sdk 0.7.0 → 0.7.1
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 +3 -1
- package/dist/realtime.d.ts +9 -2
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +6 -1
- package/dist/realtime.js.map +1 -1
- package/dist/sdk.umd.js +3 -3
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/realtime.ts +14 -3
package/dist/sdk.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/* @runappsai/sdk 0.7.
|
|
2
|
-
"use strict";var RunApps=(()=>{var ce=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.prototype.hasOwnProperty;var nn=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var rn=(n,e)=>{for(var t in e)ce(n,t,{get:e[t],enumerable:!0})},sn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of en(e))!tn.call(n,s)&&s!==t&&ce(n,s,{get:()=>e[s],enumerable:!(r=Zt(e,s))||r.enumerable});return n};var on=n=>sn(ce({},"__esModule",{value:!0}),n);var u=(n,e,t)=>nn(n,typeof e!="symbol"?e+"":e,t);var tr={};rn(tr,{APIError:()=>C,ActivityTracker:()=>M,BrowserAuth:()=>L,Client:()=>K,FilesRemote:()=>R,RealtimeSession:()=>Y,RunApps:()=>K,RunJobs:()=>K,SDKEvents:()=>O,ServerTools:()=>tt,SyncEngine:()=>P,acceptsField:()=>Vt,acceptsModality:()=>pt,allowedValuesFor:()=>Ht,assistantMessage:()=>st,audioPart:()=>ut,base64ToBytes:()=>At,bytesToBase64:()=>Oe,decodeMediaUrl:()=>z,defaultVoice:()=>mt,encodeImageUrl:()=>bt,float32FromPCM16:()=>kt,getOptionsSchema:()=>re,hasCapabilityTag:()=>dt,imagePart:()=>ct,installIndexedDBHook:()=>te,newRequestId:()=>I,pcm16FromFloat32:()=>xt,requiresField:()=>Gt,supportsInstructText:()=>gt,supportsVoiceClone:()=>ht,systemMessage:()=>rt,textPart:()=>at,toolResultMessage:()=>ot,userMessage:()=>nt,userMessageParts:()=>it,validateRequest:()=>zt,videoPart:()=>lt});var C=class extends Error{constructor(t,r,s){super(`runapps: ${t} ${r}: ${s}`);u(this,"statusCode");u(this,"type");this.name="APIError",this.statusCode=t,this.type=r}};var le=class{constructor(e){u(this,"baseURL");u(this,"apiKey");u(this,"apiKeyResolver");u(this,"onUnauthorized");u(this,"fetchImpl");if(!e.apiKey&&!e.apiKeyResolver)throw new Error("RunApps: pass either `apiKey` or `apiKeyResolver` when constructing the client");this.baseURL=e.baseURL.replace(/\/+$/,""),this.apiKey=e.apiKey,this.apiKeyResolver=e.apiKeyResolver,this.onUnauthorized=e.onUnauthorized,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis)}async resolveToken(){return this.apiKeyResolver?await this.apiKeyResolver():this.apiKey??""}bearerToken(){return this.resolveToken()}async fetchWithAuthRetry(e,t){let r=this.baseURL+e,s=await this.fetchImpl(r,await this.buildInit(t));if(s.status!==401||!this.onUnauthorized)return s;try{await this.onUnauthorized()}catch{return s}return s=await this.fetchImpl(r,await this.buildInit(t)),s}async buildInit(e){let t=await e();return t.cache?t:{...t,cache:"no-store"}}async postJSON(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.jsonHeaders(),body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async getJSON(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);return await r.json()}async getPublicJSON(e,t){let r=await this.fetchImpl(this.baseURL+e,{method:"GET",cache:"no-store",...t?.signal?{signal:t.signal}:{}});if(!r.ok)throw await this.parseError(r);return await r.json()}async getRaw(e,t){let r=await this.fetchWithAuthRetry(e,async()=>{let l=await this.authHeaders();return t?.ifNoneMatch&&(l["If-None-Match"]=`"${W(t.ifNoneMatch)}"`),{method:"GET",headers:l,signal:t?.signal}}),s=an(r.headers.get("date"));if(r.status===304){let l=W(r.headers.get("etag"))||t?.ifNoneMatch;return{data:new Uint8Array(0),contentType:"",etag:l,notModified:!0,serverTime:s}}if(!r.ok)throw await this.parseError(r);let o=new Uint8Array(await r.arrayBuffer()),i=r.headers.get("content-type")??"",a=W(r.headers.get("etag"))||void 0;return{data:o,contentType:i,etag:a,serverTime:s}}async postMultipart(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.authHeaders(),body:t,signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async postJSONStream(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:{...await this.jsonHeaders(),"Accept-Encoding":"identity"},body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return s}async putBytes(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>{let o={...await this.authHeaders(),"Content-Type":r?.contentType??"application/octet-stream"};return r?.headers&&Object.assign(o,r.headers),{method:"PUT",headers:o,body:t,signal:r?.signal}});if(!s.ok)throw await this.parseError(s);if(r?.parse!=="none")return await s.json()}async deletePath(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"DELETE",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);if(t?.parse!=="none")return await r.json()}async head(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"HEAD",headers:await this.authHeaders(),signal:t?.signal}));return{status:r.status,headers:r.headers}}async jsonHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${await this.resolveToken()}`}}async authHeaders(){return{Authorization:`Bearer ${await this.resolveToken()}`}}async parseError(e){let t=await e.text(),r="error",s=t||e.statusText;try{let o=JSON.parse(t);o.type&&(r=o.type),o.message&&(s=o.message)}catch{}return new C(e.status,r,s)}};function W(n){return(n??"").trim().replace(/^W\//i,"").replace(/"/g,"")}function an(n){if(!n)return;let e=Date.parse(n);return Number.isNaN(e)?void 0:e}var O=class{constructor(){u(this,"handlers",new Map)}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r));let s=t;return r.add(s),()=>{this.handlers.get(e)?.delete(s)}}emit(e,t){let r=this.handlers.get(e);if(!(!r||r.size===0))for(let s of r)try{s(t)}catch(o){console.error("[runapps sdk] event listener for",e,"threw:",o)}}clear(){this.handlers.clear()}};function I(){return"req_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}async function
|
|
3
|
-
`))!==-1;){let a=r.slice(0,i).replace(/\r$/,"");if(r=r.slice(i+1),!a.startsWith("data: "))continue;let l=a.slice(6).trim();if(l==="[DONE]")return;if(!l)continue;let c;try{c=JSON.parse(l)}catch(p){throw new Error(`runapps: decode stream chunk: ${p.message}`)}let d=c.error;if(d)throw new C(d.code??0,d.type??"upstream_error",d.message??l);yield c}}}finally{t.releaseLock()}}var dt=(n,e)=>Array.isArray(n.capability_tags)&&n.capability_tags.some(t=>t.id===e),pt=(n,e)=>Array.isArray(n.input_modalities)&&n.input_modalities.includes(e);function ft(n,e){let t=n.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var ht=n=>ft(n,"supports_voice_clone"),gt=n=>ft(n,"supports_instruct_text"),mt=n=>{let e=n.options?.default_voice;return typeof e=="string"?e:null},de=class{constructor(e){u(this,"transport",e)}async list(e={},t){let r="/v1/models";return e.capability&&(r+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getPublicJSON(r,t)).data}};var pe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},r),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,r){let s=r?.pollIntervalMs??2e3,o=r?.signal;return y(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:o});for(;a.status!=="succeeded"&&a.status!=="failed";)await un(s,o),a=await this.getAsyncStatus(a.id,{signal:o});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},i=>({costUSD:i.usage?.total_cost}))}async submitGenerate(e,t,r){return y(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},r))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,r){let s=dn(e,t);return y(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,r),o=>({costUSD:o.usage?.total_cost}))}};function un(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}function dn(n,e){let t=new FormData;return t.set("model",n),t.set("prompt",typeof e.prompt=="string"?e.prompt:JSON.stringify(e.prompt)),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",yt(e.image),e.image.filename),e.mask&&t.set("mask",yt(e.mask),e.mask.filename),t}function yt(n){let e=n.contentType??pn(n.filename);return n.data instanceof Blob?n.data.type===e?n.data:new Blob([n.data],{type:e}):typeof n.data=="string"?new Blob([n.data],{type:e}):new Blob([n.data],{type:e})}function pn(n){switch(n.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function bt(n){if(n instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=n instanceof Uint8Array?n:new Uint8Array(n),t=hn(e),r=32768,s="";for(let i=0;i<e.length;i+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(i,i+r)));let o=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${o}`}async function z(n){if(n.startsWith("data:")){let e=n.slice(5),t=e.indexOf(";"),r=e.indexOf(",");if(t===-1||r===-1||r<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),o=e.slice(r+1);return{bytes:fn(o),contentType:s}}if(n.startsWith("http://")||n.startsWith("https://")){let e=await fetch(n);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${n.slice(0,32)}`)}function fn(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function hn(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=6&&n[0]===71&&n[1]===73&&n[2]===70&&n[3]===56?"image/gif":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":"application/octet-stream"}var fe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async speech(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",wt(e,t),r),{bytes:o,contentType:i}=await z(s.audio_url);return{data:o,contentType:i,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,r){return y(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",wt(e,t),r);if(!s.id)throw new Error("runapps: speech submit response missing job id");return gn(this.transport,s.id,r)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,r){let s=vt(e,t);return y(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,r),o=>({costUSD:o.usage?.total_cost}))}async transcribeAsync(e,t,r){return y(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=vt(e,t),o=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,r);if(!o.id)throw new Error("runapps: transcribe submit response missing job id");return mn(this.transport,o.id,r)},s=>({costUSD:s.usage?.total_cost}))}};async function gn(n,e,t){let r=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await he(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await n.getJSON(r,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:l,contentType:c}=await z(a.audio_url);return{data:l,contentType:c,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await he(s,t?.signal)}}async function mn(n,e,t){let r=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await he(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let i=await n.getJSON(r,t);switch(i.status){case"succeeded":return yn(i);case"failed":throw new Error(i.error||"runapps: transcribe job failed");case"queued":case"running":await he(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(i.status)}`)}}}function yn(n){let e={text:n.text??"",usage:n.usage??{total_cost:0}},t={};for(let[r,s]of Object.entries(n))r==="text"||r==="usage"||r==="id"||r==="status"||(t[r]=s);return Object.keys(t).length>0&&(e.raw=t),e}function he(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",o,{once:!0})})}function wt(n,e){let{extra:t,...r}=e,s={model:n,...r};if(t)for(let[o,i]of Object.entries(t))o in s||(s[o]=i);return s}function vt(n,e){let t=new FormData;if(t.set("model",n),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let o of e.timestamp_granularities)t.append("timestamp_granularities[]",o);if(e.user&&t.set("user",e.user),!e.file){if(!e.url)throw new Error("runapps: transcribe needs `file` or `url`");return t.set("url",e.url),t}let r=e.file.contentType??bn(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:r});return t.set("file",s,e.file.filename),t}function bn(n){switch(n.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var St=1,wn=1e4,Y=class{constructor(e){u(this,"ws",e);u(this,"sessionId","");u(this,"closed");u(this,"handlers",new Map);u(this,"usage",null);u(this,"resolveClosed");u(this,"isClosed",!1);u(this,"queue",[]);u(this,"waiters",[]);u(this,"iterating",!1);this.closed=new Promise(t=>{this.resolveClosed=t}),e.addEventListener("message",t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{return}if(!(!r||typeof r.type!="string")){if(r.type==="session.created"){let s=r.session?.id;typeof s=="string"&&(this.sessionId=s)}else r.type==="gateway.usage"&&(this.usage=r.usage??null);this.dispatch(r)}}),e.addEventListener("close",t=>{if(!this.isClosed){this.isClosed=!0;for(let r of this.waiters.splice(0))r({value:void 0,done:!0});this.resolveClosed({code:t.code??1006,reason:t.reason??"",usage:this.usage})}})}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r.delete(t)}send(e){if(this.ws.readyState!==St)throw new Error("runapps: realtime session is closed");this.ws.send(JSON.stringify(e))}appendAudio(e){this.send({type:"input_audio_buffer.append",audio:Oe(xn(e))})}commitAudio(){this.send({type:"input_audio_buffer.commit"})}mute(){this.send({type:"input_audio_mute.commit"})}unmute(){this.send({type:"input_audio_unmute.commit"})}say(e){this.send({type:"speech_text_buffer.commit",text:e})}cancelResponse(){this.send({type:"response.cancel"})}update(e){this.send({type:"session.update",session:e})}sendFunctionResult(e,t){this.send({type:"conversation.item.create",items:[{call_id:e,role:"tool",content:[{type:"input_text",text:t}]}]})}async close(){if(!this.isClosed&&this.ws.readyState===St){try{this.send({type:"session.close"})}catch{}let e=setTimeout(()=>this.ws.close(1e3,"client timeout"),wn);try{return await this.closed}finally{clearTimeout(e)}}return this.isClosed||this.ws.close(1e3),this.closed}[Symbol.asyncIterator](){return this.iterating=!0,{next:()=>{let e=this.queue.shift();return e?Promise.resolve({value:e,done:!1}):this.isClosed?Promise.resolve({value:void 0,done:!0}):new Promise(t=>this.waiters.push(t))},return:()=>(this.iterating=!1,this.queue=[],Promise.resolve({value:void 0,done:!0}))}}dispatch(e){for(let t of[e.type,"*"]){let r=this.handlers.get(t);if(r)for(let s of[...r])try{s(e)}catch(o){setTimeout(()=>{throw o})}}if(this.iterating){let t=this.waiters.shift();t?t({value:e,done:!1}):this.queue.push(e)}}},ge=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async connect(e={}){let t=e.WebSocket??globalThis.WebSocket;if(!t)throw new Error("runapps: no WebSocket available \u2014 pass `WebSocket` (e.g. from the `ws` package) on Node < 22");let r=await this.transport.bearerToken(),s=new t(Sn(this.transport.baseURL,e),["realtime","runapps-key."+r]),o=new Y(s),i=e.model??"",a=I(),l=Date.now();this.events.emit("request:start",{id:a,model:i,capability:"realtime",startedAt:l,streaming:!0});try{await new Promise((c,d)=>{let p=setTimeout(()=>{g(new Error("runapps: realtime session did not open in time")),s.close(1e3,"open timeout")},e.timeoutMs??15e3),h=()=>{g(new Error("runapps: realtime connect aborted")),s.close(1e3,"aborted")};e.signal?.addEventListener("abort",h,{once:!0});let f=!1;function g(S){f||(f=!0,clearTimeout(p),e.signal?.removeEventListener("abort",h),d(S))}let b=o.on("session.created",()=>{f||(f=!0,clearTimeout(p),e.signal?.removeEventListener("abort",h),b(),x(),c())}),x=o.on("error",S=>{let v=S.error??{};g(new Error(`runapps: realtime error: ${v.message??JSON.stringify(S)}`))});s.addEventListener("open",()=>{s.send(JSON.stringify(vn(e)))}),o.closed.then(S=>{g(new Error(`runapps: realtime connection closed (${S.code}${S.reason?" "+S.reason:""})`))})})}catch(c){try{s.close(1e3,"connect failed")}catch{}throw this.events.emit("request:error",{id:a,model:i,capability:"realtime",latencyMs:Date.now()-l,error:c}),c}return o.closed.then(c=>{this.events.emit("request:end",{id:a,model:i,capability:"realtime",latencyMs:Date.now()-l,totalTokens:c.usage?.output_tokens??0,...c.usage?.total_cost!==void 0&&{costUSD:c.usage.total_cost}})}),o}};function vn(n){let e={type:"session.create",session:n.session??{}};return n.extension&&(e.extension=n.extension),e}function Sn(n,e){let t=new URL(n.replace(/\/+$/,"")+"/v1/realtime");t.protocol=t.protocol==="http:"?"ws:":"wss:";for(let[r,s]of Object.entries(e.query??{}))t.searchParams.set(r,s);return e.model&&t.searchParams.set("model",e.model),t.toString()}function xt(n,e,t=16e3){let r=e/t,s=r===1?n.length:Math.floor(n.length/r),o=new Int16Array(s);for(let i=0;i<s;i++){let a;if(r===1)a=n[i];else{let l=i*r,c=Math.floor(l),d=l-c,p=n[c],h=n[Math.min(c+1,n.length-1)];a=p+(h-p)*d}a=Math.max(-1,Math.min(1,a)),o[i]=a<0?a*32768:a*32767}return o}function kt(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float32Array(n.byteLength>>1);for(let r=0;r<t.length;r++)t[r]=e.getInt16(r*2,!0)/32768;return t}function Oe(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function At(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function xn(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}var me=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return y(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},r))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let r=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await kn(r,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function kn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}var ye=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async step(e,t,r){return y(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},r),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function X(n,e){let t=e.replace(/^\/+/,"");return n+"/"+t.split("/").map(encodeURIComponent).join("/")}var Q=class{constructor(e,t,r){u(this,"transport",e);u(this,"events",r);u(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}run(e,t){return this.events?y(this.events,{model:e,capability:"files"},t):t()}async put(e,t,r){let s={};return r?.ifNoneMatch&&(s["If-None-Match"]="*"),r?.ifMatch&&(s["If-Match"]=`"${W(r.ifMatch)}"`),this.run("files.put",()=>this.transport.putBytes(X(this.base,e),t,{contentType:r?.contentType,headers:Object.keys(s).length?s:void 0,signal:r?.signal}))}async putString(e,t,r){return this.put(e,t,{...r,contentType:r?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){return this.run("files.read",()=>this.readRaw(e,t))}async readRaw(e,t){let{data:r,contentType:s,etag:o,notModified:i}=await this.transport.getRaw(X(this.base,e),t);return{blob:new Blob([new Uint8Array(r)],{type:s||"application/octet-stream"}),contentType:s,etag:o,...i?{notModified:!0}:{}}}async readJSON(e,t){let r;try{r=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return r.notModified?{value:void 0,etag:r.etag,notModified:!0}:{value:JSON.parse(await r.blob.text()),etag:r.etag}}async stat(e,t){let{status:r,headers:s}=await this.run("files.stat",()=>this.transport.head(X(this.base,e),t));if(r===404)throw Object.assign(new Error("not found"),{status:404});if(r>=400)throw Object.assign(new Error("stat failed"),{status:r});let o=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:o,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:r}=await this.run("files.exists",()=>this.transport.head(X(this.base,e),t));return r>=200&&r<400}async del(e,t){await this.run("files.del",()=>this.transport.deletePath(X(this.base,e),t))}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let r=t.toString();return this.run("files.list",()=>this.transport.getJSON(this.base+(r?"?"+r:""),e?.signal?{signal:e.signal}:void 0))}async deleteMany(e,t){return this.run("files.deleteMany",()=>this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t))}async move(e,t,r){return this.run("files.move",()=>this.transport.postJSON(this.base+"/move",{from:e,to:t},r))}async copy(e,t,r){return this.run("files.copy",()=>this.transport.postJSON(this.base+"/copy",{from:e,to:t},r))}async putFromURL(e,t,r){return this.run("files.putFromURL",()=>this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:r?.contentType,if_none_match:r?.ifNoneMatch,if_match:r?.ifMatch},r?.signal?{signal:r.signal}:void 0))}async batch(e,t){return e.length===0?[]:this.run("files.batch",()=>this.batchRaw(e,t))}async batchRaw(e,t){if(e.length<=30)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let o=0;o<e.length;o+=30){let i=e.slice(o,o+30),a=await this.transport.postJSON(this.base+"/batch",{ops:i},t);s.push(...a.results)}return s}};var be=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t,r){return y(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},r),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var M=class{constructor(){u(this,"active",new Map);u(this,"recent",[]);u(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});u(this,"lastErrorAt",0);u(this,"changeListeners",new Set);u(this,"sync")}attach(e){let t=[e.on("request:start",r=>{this.onStart(r),this.notify()}),e.on("request:streamDelta",r=>{this.onDelta(r),this.notify()}),e.on("request:end",r=>{this.onEnd(r),this.notify()}),e.on("request:error",r=>{this.onError(r),this.notify()}),e.on("sync:state",r=>{this.sync={...r},this.notify()})];return()=>{for(let r of t)r()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},...this.sync?{sync:{...this.sync}}:{},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let r=Date.now();t.rateSamples.push({t:r,tokens:e.deltaTokens});let s=r-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let o=t.rateSamples.reduce((a,l)=>a+l.tokens,0),i=r-t.rateSamples[0].t;t.tokensPerSec=i>0?o*1e3/i:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),e.capability!=="files"&&(this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD))}onError(e){let t=this.active.get(e.id);if(this.active.delete(e.id),e.capability==="files"){e.statusCode!==404&&(this.lastErrorAt=Date.now());return}this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var _t={ArrayBuffer:n=>n,Uint8Array:n=>new Uint8Array(n),Int8Array:n=>new Int8Array(n),Uint8ClampedArray:n=>new Uint8ClampedArray(n),Int16Array:n=>new Int16Array(n),Uint16Array:n=>new Uint16Array(n),Int32Array:n=>new Int32Array(n),Uint32Array:n=>new Uint32Array(n),Float32Array:n=>new Float32Array(n),Float64Array:n=>new Float64Array(n),BigInt64Array:n=>new BigInt64Array(n),BigUint64Array:n=>new BigUint64Array(n),DataView:n=>new DataView(n)};function ve(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function Tt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Me(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}async function A(n,e){if(n===void 0)return{$rt:"undef"};if(n===null)return null;switch(typeof n){case"string":case"boolean":return n;case"number":return Number.isNaN(n)?{$rt:"num",v:"NaN"}:n===1/0?{$rt:"num",v:"Infinity"}:n===-1/0?{$rt:"num",v:"-Infinity"}:Object.is(n,-0)?{$rt:"num",v:"-0"}:n;case"bigint":return{$rt:"bigint",v:n.toString()};case"function":case"symbol":throw new TypeError(`runapps sync: ${typeof n} values cannot be stored`)}if(n instanceof Date){let r=n.getTime();return{$rt:"date",v:Number.isNaN(r)?"invalid":r}}if(n instanceof RegExp)return{$rt:"re",s:n.source,f:n.flags};if(typeof Blob<"u"&&n instanceof Blob){if(!e)throw new TypeError("runapps sync: Blob values need a blob sink");let r=await e(n),s={$rt:"blob",r:r.ref,t:r.type,s:r.size},o=n;return typeof File<"u"&&n instanceof File&&(s.n=o.name,s.m=o.lastModified),s}if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n))};if(ArrayBuffer.isView(n)){let r=n.constructor.name;if(!(r in _t))throw new TypeError(`runapps sync: unsupported binary type ${r}`);let s=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return{$rt:"bin",c:r,v:ve(s)}}if(n instanceof Map){let r=[];for(let[s,o]of n)r.push([await A(s,e),await A(o,e)]);return{$rt:"map",v:r}}if(n instanceof Set){let r=[];for(let s of n)r.push(await A(s,e));return{$rt:"set",v:r}}if(Array.isArray(n)){let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=await A(n[s],e);return r}if(Me(n)){let r=Object.prototype.hasOwnProperty.call(n,"$rt"),s={};for(let o of Object.keys(n))s[o]=await A(n[o],e);return r?{$rt:"obj",v:s}:s}let t={};for(let r of Object.keys(n))t[r]=await A(n[r],e);return t}async function _(n,e){if(n===null||typeof n!="object")return n;if(Array.isArray(n)){let o=new Array(n.length);for(let i=0;i<n.length;i++)o[i]=await _(n[i],e);return o}let t=n;if(typeof t.$rt=="string"){let o=t;switch(o.$rt){case"undef":return;case"date":return o.v==="invalid"?new Date(NaN):new Date(o.v);case"num":return o.v==="NaN"?NaN:o.v==="Infinity"?1/0:o.v==="-Infinity"?-1/0:-0;case"bigint":return BigInt(o.v);case"re":return new RegExp(o.s,o.f);case"bin":{let i=Tt(o.v),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);let l=_t[o.c];if(!l)throw new TypeError(`runapps sync: unsupported binary type ${o.c}`);return l(a)}case"map":{let i=new Map;for(let a of o.v)i.set(await _(a[0],e),await _(a[1],e));return i}case"set":{let i=new Set;for(let a of o.v)i.add(await _(a,e));return i}case"blob":{if(!e)throw new TypeError("runapps sync: Blob values need a blob source");let i=await e({ref:o.r,type:o.t,size:o.s});return o.n!==void 0&&typeof File<"u"?new File([i],o.n,{type:o.t,lastModified:o.m??Date.now()}):i}case"obj":return _(o.v,e)}}let s={};for(let o of Object.keys(t))s[o]=await _(t[o],e);return s}function j(n){if(typeof n=="number"){if(Number.isNaN(n))throw new TypeError("runapps sync: NaN is not a valid key");return n}if(typeof n=="string")return n;if(n instanceof Date)return{$rt:"date",v:n.getTime()};if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n))};if(ArrayBuffer.isView(n))return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))};if(Array.isArray(n))return n.map(e=>j(e));throw new TypeError("runapps sync: invalid IndexedDB key")}function Z(n){if(typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(Z);if(n&&typeof n=="object"){let e=n;if(e.$rt==="date")return new Date(e.v);if(e.$rt==="bin"){let t=Tt(e.v),r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),r}}throw new TypeError("runapps sync: invalid encoded key")}function Se(n){return JSON.stringify(j(n))}function xe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function we(n,e){if(Object.is(n,e))return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Object.is(n.getTime(),e.getTime());if(typeof Blob<"u"&&(n instanceof Blob||e instanceof Blob))return!1;if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof ArrayBuffer){let s=a=>a instanceof ArrayBuffer?new Uint8Array(a):ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):null,o=s(n),i=s(e);if(!o||!i||o.length!==i.length||n.constructor!==e.constructor)return!1;for(let a=0;a<o.length;a++)if(o[a]!==i[a])return!1;return!0}if(n instanceof Map||e instanceof Map){if(!(n instanceof Map&&e instanceof Map)||n.size!==e.size)return!1;for(let[s,o]of n)if(!e.has(s)||!we(o,e.get(s)))return!1;return!0}if(n instanceof Set||e instanceof Set){if(!(n instanceof Set&&e instanceof Set)||n.size!==e.size)return!1;for(let s of n)if(!e.has(s))return!1;return!0}if(Array.isArray(n)||Array.isArray(e)){if(!(Array.isArray(n)&&Array.isArray(e))||n.length!==e.length)return!1;for(let s=0;s<n.length;s++)if(!we(n[s],e[s]))return!1;return!0}let t=Object.keys(n),r=Object.keys(e);if(t.length!==r.length)return!1;for(let s of t)if(!Object.prototype.hasOwnProperty.call(e,s)||!we(n[s],e[s]))return!1;return!0}function Et(n,e){if(!Me(n)||!Me(e))return;let t=[];for(let r of new Set([...Object.keys(n),...Object.keys(e)])){let s=Object.prototype.hasOwnProperty.call(n,r),o=Object.prototype.hasOwnProperty.call(e,r);(s!==o||!we(n[r],e[r]))&&t.push(r)}return t}function Ct(n,e){if(e==null)return;let t=s=>{let o=n;if(s==="")return o;for(let i of s.split(".")){if(o===null||typeof o!="object")return;o=o[i]}return o};if(Array.isArray(e)){let s=e.map(t);return s.some(o=>o===void 0)?void 0:s}let r=t(e);return r===void 0?void 0:r}var It=60,Dt="__runapps_auth_v1__",Pt="__runjobs_auth_v1__",Rt="__runapps_signed_out_v1__",Bt="__runjobs_signed_out_v1__";function ee(n){return n?`${Dt}:${n}`:Dt}function ke(n){return n?`${Rt}:${n}`:Rt}function je(n){return n?`${Pt}:${n}`:Pt}function Ot(n){return n?`${Bt}:${n}`:Bt}var L=class{constructor(e={}){u(this,"origin");u(this,"hideBadge");u(this,"project");u(this,"events");u(this,"tracker");u(this,"badgePosition");u(this,"token",null);u(this,"expiresAt",0);u(this,"userInfo",null);u(this,"listeners",[]);u(this,"parentHandshake",null);u(this,"signingIn",!1);u(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new M,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}ownerId(){return this.tokenIsFresh()?this.userInfo?.id?this.userInfo.id:"t"+xe(this.token).toString(36):null}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:ee(this.project),signedOut:ke(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-It}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,r){this.token=e,this.expiresAt=t||this.nowSec()+3600,r&&(this.userInfo=r,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(o){console.warn("[runapps] onTokenChange handler threw",o)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem(ee(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem(ee(this.project));if(!e){if(e=localStorage.getItem(je(this.project)),!e)return;localStorage.setItem(ee(this.project),e),localStorage.removeItem(je(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-It){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ee(this.project)),localStorage.removeItem(je(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ke(this.project))==="1"||localStorage.getItem(Ot(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(ke(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ke(this.project)),localStorage.removeItem(Ot(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let o=s.indexOf("=");o>=0&&(e[decodeURIComponent(s.slice(0,o))]=decodeURIComponent(s.slice(o+1).replace(/\+/g," ")))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let r;if(e.user)try{r=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,r);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let r=!1,s=[],o=()=>{r=!0,window.removeEventListener("message",i);for(let l of s)clearTimeout(l)},i=l=>{if(l.origin!==this.origin)return;let c=l.data;c&&(c.type==="runapps:token"||c.type==="runjobs:token")&&c.token&&(this.setToken(c.token,c.expires_at??0,c.user),o(),e())};window.addEventListener("message",i);let a=()=>{if(!r)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(l){o(),t(l)}};a();for(let l of[250,750,1500,3e3])s.push(setTimeout(a,l));s.push(setTimeout(()=>{r||(o(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=Dn({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function An(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let n=document.createElement("style");n.id="__runapps_kf__",n.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}@keyframes __runapps_sync_ping__ { 0% { transform: scale(1); opacity: 0.9; } 100% { transform: scale(2.1); opacity: 0; }}",(document.head??document.documentElement).appendChild(n)}function _n(n){let e=n.startsWith("top")?"top":"bottom",t=n.endsWith("right")?"right":"left",r=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${r};${s}`}}var Ut="__runapps_badge_pos__",Tn="__runjobs_badge_pos__",Mt=5,U=8;function En(){if(typeof document>"u")return null;let n=document.cookie.split(";").map(c=>c.trim()),e=Ut,t=n.find(c=>c.startsWith(e+"="));if(t||(e=Tn,t=n.find(c=>c.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),o=s[0],i=s[1];if(s.length!==2||o===void 0||i===void 0)return null;let a=Number.parseInt(o,10),l=Number.parseInt(i,10);return!Number.isFinite(a)||!Number.isFinite(l)?null:{x:a,y:l}}function Cn(n,e){if(typeof document>"u")return;let t=3600*24*365,r=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Ut}=${encodeURIComponent(`${Math.round(n)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${r}`}function jt(n,e,t,r){let s=typeof window<"u"?window.innerWidth:1024,o=typeof window<"u"?window.innerHeight:768,i=Math.max(U,s-t-U),a=Math.max(U,o-r-U);return{x:Math.min(Math.max(U,n),i),y:Math.min(Math.max(U,e),a)}}function In(n){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,r=n.left+n.width/2,o=n.top+n.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",i=r<e/2?"left:0;right:auto":"right:0;left:auto";return`${o};${i}`}function Dn(n){let{id:e,user:t,dashboardUrl:r,tracker:s,position:o,onSignOut:i}=n,a=_n(o),l=a.popover;An();let c=document.createElement("button");c.id=e,c.type="button",c.setAttribute("aria-label","RunApps activity status"),c.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:5px","border-radius:50%","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","-webkit-user-select:none","touch-action:none","-webkit-touch-callout:none","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),c.addEventListener("mouseenter",()=>{c.style.backgroundColor="rgba(30,30,40,0.7)",c.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="rgba(15,15,20,0.55)",c.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let p="http://www.w3.org/2000/svg",h=document.createElementNS(p,"svg");h.setAttribute("viewBox","0 0 26 26"),h.setAttribute("width","26"),h.setAttribute("height","26"),h.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let f=document.createElementNS(p,"circle");f.setAttribute("cx","13"),f.setAttribute("cy","13"),f.setAttribute("r","12"),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(255,255,255,0.08)"),f.setAttribute("stroke-width","1.5");let g=document.createElementNS(p,"circle");g.setAttribute("cx","13"),g.setAttribute("cy","13"),g.setAttribute("r","12"),g.setAttribute("fill","none"),g.setAttribute("stroke","#3b82f6"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("transform","rotate(-90 13 13)");let b=2*Math.PI*12;g.setAttribute("stroke-dasharray",String(b)),g.setAttribute("stroke-dashoffset",String(b)),h.appendChild(f),h.appendChild(g);let x=document.createElement("div");x.textContent=(t.name||"?").charAt(0).toUpperCase(),x.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let S=document.createElement("span");S.style.cssText=["position:absolute","bottom:-1px;right:-1px","width:7px;height:7px;border-radius:50%","background:rgba(255,255,255,0.2)","border:1.5px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","opacity:0","transition:background-color 150ms ease-out, box-shadow 200ms ease-out, opacity 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(h),d.appendChild(x),d.appendChild(S),c.appendChild(d);let v=null,k=!1,B=null,se=null,oe=null,De=()=>{se!==null&&(window.clearTimeout(se),se=null)},$=()=>{oe!==null&&(window.clearTimeout(oe),oe=null)},qe=()=>{$(),oe=window.setTimeout(()=>{B==="hover"&&q()},300)},Ve=m=>{if(De(),$(),k){m==="click"&&(B="click");return}v||(v=On(t,r,l,()=>{q(),i()}),v.addEventListener("mouseenter",$),v.addEventListener("mouseleave",()=>{B==="hover"&&qe()})),c.appendChild(v),k=!0,B=m,ae()},q=()=>{$(),k&&(v?.remove(),k=!1,B=null)};c.addEventListener("click",m=>{m.stopPropagation(),k?q():Ve("click")}),c.addEventListener("mouseenter",()=>{$(),De(),se=window.setTimeout(()=>{k||Ve("hover")},400)}),c.addEventListener("mouseleave",()=>{De(),B==="hover"&&qe()}),document.addEventListener("click",m=>{k&&!c.contains(m.target)&&q()});let Ge=0,He=0,Je=0,We=0,ie=!1,V=!1,Pe=!1,Re=(m,w)=>{c.style.left=`${m}px`,c.style.top=`${w}px`,c.style.right="auto",c.style.bottom="auto"},ze=()=>{let m=c.getBoundingClientRect();if(l=In({left:m.left,top:m.top,width:m.width,height:m.height}),v){v.style.top="",v.style.bottom="",v.style.left="",v.style.right="";for(let w of l.split(";")){let[E,J]=w.split(":");E&&J&&v.style.setProperty(E.trim(),J.trim())}}};c.addEventListener("pointerdown",m=>{if(m.button!==0)return;ie=!0,V=!1,Ge=m.clientX,He=m.clientY;let w=c.getBoundingClientRect();Je=w.left,We=w.top}),c.addEventListener("pointermove",m=>{if(!ie)return;let w=m.clientX-Ge,E=m.clientY-He;if(!V){if(Math.abs(w)<Mt&&Math.abs(E)<Mt)return;V=!0;try{c.setPointerCapture(m.pointerId)}catch{}c.style.cursor="grabbing",k&&q()}let J=c.getBoundingClientRect(),Ze=jt(Je+w,We+E,J.width,J.height);Re(Ze.x,Ze.y)});let Ye=m=>{if(!ie||(ie=!1,!V))return;V=!1,c.style.cursor="pointer";try{c.hasPointerCapture(m.pointerId)&&c.releasePointerCapture(m.pointerId)}catch{}let w=c.getBoundingClientRect();Cn(w.left,w.top),ze(),Pe=!0};c.addEventListener("pointerup",Ye),c.addEventListener("pointercancel",Ye),c.addEventListener("click",m=>{Pe&&(Pe=!1,m.stopPropagation(),m.preventDefault())},!0);let G=En();G&&(Re(G.x,G.y),requestAnimationFrame(()=>{let m=c.getBoundingClientRect(),w=jt(G.x,G.y,m.width,m.height);Re(w.x,w.y),ze()}));let Be=!1,H=null,Xe,Qe=()=>{if(Be=!1,!s){h.style.opacity="0",S.style.background="rgba(255,255,255,0.2)",S.style.opacity="0";return}let m=s.snapshot(),w=m.sync?.lastChangeAt;w&&w!==Xe&&(Xe=w,Rn(d,S)),Pn(h,g,b,m),Bn(S,m),k&&v&&Mn(v,m);let E=m.status!=="idle"||k;E&&H===null?H=window.setInterval(ae,160):!E&&H!==null&&(window.clearInterval(H),H=null)};function ae(){Be||(Be=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(Qe):setTimeout(Qe,0))}return s&&s.onChange(ae),ae(),c}function Pn(n,e,t,r){if(r.active.length===0){n.style.opacity="0";return}n.style.opacity="1";let s=r.active.reduce((o,i)=>i.tokensPerSec>o.tokensPerSec?i:o,r.active[0]);if(s.streaming&&s.tokensPerSec>0){let o=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-o))),e.setAttribute("stroke","#3b82f6")}else r.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}var Ue=0;function Rn(n,e){let t=document.createElement("span");t.style.cssText=["position:absolute;inset:0","border-radius:50%","border:2px solid #10b981","pointer-events:none","animation:__runapps_sync_ping__ 700ms ease-out forwards"].join(";"),t.addEventListener("animationend",()=>t.remove()),n.appendChild(t),setTimeout(()=>t.remove(),1e3),Ue=Date.now()+1200,e.style.opacity="1",e.style.background="#10b981",e.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",e.style.animation="",setTimeout(()=>{Date.now()>=Ue&&(e.style.background="rgba(255,255,255,0.2)",e.style.opacity="0",e.style.boxShadow="0 0 0 0 transparent")},1250)}function Bn(n,e){switch(n.style.opacity="1",e.status){case"idle":{let t=e.sync;Date.now()<Ue?(n.style.background="#10b981",n.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",n.style.animation=""):t&&t.state==="syncing"?(n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite"):t&&(t.state==="offline"||t.state==="error")?(n.style.background="#f59e0b",n.style.boxShadow="0 0 0 2px rgba(245,158,11,0.3)",n.style.animation=""):(n.style.background="rgba(255,255,255,0.2)",n.style.opacity="0",n.style.boxShadow="0 0 0 0 transparent",n.style.animation="");break}case"active":n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":n.style.background="#ef4444",n.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",n.style.animation="";break}}function On(n,e,t,r){let s=document.createElement("div");s.style.cssText=["position:absolute",t,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),s.setAttribute("data-runapps-popover","1"),s.addEventListener("click",g=>g.stopPropagation());let o=document.createElement("div");o.style.cssText=["display:flex;align-items:center;gap:8px","margin-bottom:10px;padding-bottom:8px","border-bottom:1px solid rgba(255,255,255,0.08)"].join(";");let i=document.createElement("div");i.textContent=(n.name||"?").charAt(0).toUpperCase(),i.style.cssText=["width:24px;height:24px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff"].join(";");let a=document.createElement("div");a.textContent=n.name||"Signed in",a.title=n.name||"",a.style.cssText="font-size:12px;font-weight:500;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";let l=document.createElement("div");l.textContent="Signed in with RunApps",l.style.cssText="font-size:10px;color:rgba(255,255,255,0.5)";let c=document.createElement("div");c.style.cssText="min-width:0",c.appendChild(a),c.appendChild(l),o.appendChild(i),o.appendChild(c),s.appendChild(o);let d=document.createElement("div");d.setAttribute("data-runapps-popover-content","1"),s.appendChild(d);let p=document.createElement("div");p.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let h=document.createElement("a");h.textContent="Open dashboard \u2192",h.href=e,h.target="_blank",h.rel="noopener noreferrer",h.style.cssText="color:#a78bfa;text-decoration:none",p.appendChild(h);let f=document.createElement("button");return f.type="button",f.textContent="Sign out",f.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),f.addEventListener("mouseenter",()=>{f.style.color="#f87171"}),f.addEventListener("mouseleave",()=>{f.style.color="rgba(255,255,255,0.55)"}),f.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),r()}),p.appendChild(f),s.appendChild(p),s}function Mn(n,e){let t=n.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let r=Date.now();t.appendChild(Un(e,r)),t.appendChild(Ln(e,r)),e.sync&&t.appendChild(jn(e.sync,r)),t.appendChild(Nn(e.session,r))}function jn(n,e){let t=document.createElement("div");t.style.marginBottom="10px";let r=n.lastSyncedAt?`synced ${Le(e-n.lastSyncedAt)}`:"\u2014";t.appendChild(Ae("Sync",r));let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0;font-size:10px";let o=document.createElement("span"),i=document.createElement("span");i.textContent="\u25CF ";let a={off:["Not signed in","rgba(255,255,255,0.4)"],idle:["Up to date","#10b981"],syncing:["Syncing\u2026","#3b82f6"],offline:["Offline","#f59e0b"],error:["Retrying","#f59e0b"]},[l,c]=a[n.state]??["","#fff"];i.style.color=c,o.style.color="#fff",o.appendChild(i),o.appendChild(document.createTextNode(l));let d=document.createElement("span");return d.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums",d.textContent=n.pending>0?`${n.pending} pending`:"",d.title=n.error??"",s.appendChild(o),s.appendChild(d),t.appendChild(s),t}function Un(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Ae("Active",n.active.length>0?`${n.active.length} in flight`:"\u2014")),n.active.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="No calls in flight.",t.appendChild(r),t}for(let r of n.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",o.textContent=r.model;let i=document.createElement("span");i.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-r.startedAt)/1e3).toFixed(1),l=r.tokensPerSec>0?` \xB7 ${Math.round(r.tokensPerSec)} tok/s`:"";i.textContent=`${a}s${l}`,s.appendChild(o),s.appendChild(i),t.appendChild(s)}return t}function Ln(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Ae("Recent",n.recent.length>0?`last ${Math.min(n.recent.length,5)}`:"\u2014")),n.recent.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="Nothing yet this session.",t.appendChild(r),t}for(let r of n.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let i=document.createElement("span");i.textContent=r.ok?"\u2713 ":"\u2717 ",i.style.color=r.ok?"#10b981":"#ef4444",o.appendChild(i),o.appendChild(document.createTextNode(r.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let l=`${(r.latencyMs/1e3).toFixed(1)}s`,c=r.costUSD!==void 0?` \xB7 $${r.costUSD.toFixed(4)}`:"",d=` \xB7 ${Le(e-r.endedAt)}`;a.textContent=`${l}${c}${d}`,s.appendChild(o),s.appendChild(a),t.appendChild(s)}return t}function Nn(n,e){let t=document.createElement("div");t.appendChild(Ae("Session",Le(e-n.startedAt)));let r=document.createElement("div");r.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${n.totalCalls} call${n.totalCalls===1?"":"s"}`;let o=document.createElement("span");o.textContent=`$${n.totalCostUSD.toFixed(4)}`;let i=document.createElement("span");return i.textContent=n.errorCount>0?`${n.errorCount} error${n.errorCount===1?"":"s"}`:"0 errors",n.errorCount>0&&(i.style.color="#ef4444"),r.appendChild(s),r.appendChild(o),r.appendChild(i),t.appendChild(r),t}function Ae(n,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let r=document.createElement("span");r.textContent=n;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(r),t.appendChild(s),t}function Le(n){return n<1500?"just now":n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}var Lt=new WeakMap,Ne=new WeakMap,Ee=new Set,N=null;function _e(n){try{return typeof structuredClone=="function"?structuredClone(n):n}catch{return n}}function Fn(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Te(n,e,t){let r;if(e&&typeof IDBVersionChangeEvent=="function"?r=new IDBVersionChangeEvent(n,{oldVersion:e.oldVersion,newVersion:e.newVersion??null}):(r=new Event(n,{bubbles:!1,cancelable:n==="error"}),e&&Object.assign(r,e)),t)for(let s of["target","currentTarget","srcElement"])try{Object.defineProperty(r,s,{value:t,configurable:!0})}catch{}return r}var Ce=class{constructor(e,t,r){u(this,"readyState","pending");u(this,"result");u(this,"error",null);u(this,"transaction",null);u(this,"source",null);u(this,"listeners",new Map);u(this,"handlers",{success:null,error:null,blocked:null,upgradeneeded:null});e.addEventListener("upgradeneeded",s=>{let o=s;this.result=e.result,this.transaction=e.transaction,Ne.set(e.result,{name:t,subs:r}),this.dispatch(Te("upgradeneeded",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("blocked",s=>{let o=s;this.dispatch(Te("blocked",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("error",()=>{this.error=e.error,this.readyState="done",this.transaction=null,this.dispatch(Te("error",void 0,this))}),e.addEventListener("success",()=>{let s=e.result;Ne.set(s,{name:t,subs:r}),this.transaction=null;let o=!1,i=()=>{o||(o=!0,this.result=s,this.readyState="done",this.dispatch(Te("success",void 0,this)))},a=[],l=0;for(let d of r)try{let p=d.opts.onOpen(s,t);p&&typeof p.then=="function"&&(a.push(p.catch(()=>{})),l=Math.max(l,d.opts.openTimeoutMs))}catch{}if(a.length===0){i();return}let c=setTimeout(i,l);Promise.all(a).then(()=>{clearTimeout(c),i()})})}addEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:o=>t.handleEvent(o),s=this.listeners.get(e);s||this.listeners.set(e,s=new Set),s.add(r),t.__rtFn=r}removeEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:t.__rtFn;r&&this.listeners.get(e)?.delete(r)}dispatchEvent(e){return this.dispatch(e),!e.defaultPrevented}dispatch(e){let t=this.handlers[e.type];if(t)try{t.call(this,e)}catch(r){Fe(r)}for(let r of this.listeners.get(e.type)??[])try{r.call(this,e)}catch(s){Fe(s)}}get onsuccess(){return this.handlers.success??null}set onsuccess(e){this.handlers.success=e}get onerror(){return this.handlers.error??null}set onerror(e){this.handlers.error=e}get onblocked(){return this.handlers.blocked??null}set onblocked(e){this.handlers.blocked=e}get onupgradeneeded(){return this.handlers.upgradeneeded??null}set onupgradeneeded(e){this.handlers.upgradeneeded=e}};function Fe(n){setTimeout(()=>{throw n},0)}typeof IDBOpenDBRequest=="function"&&Object.setPrototypeOf(Ce.prototype,IDBOpenDBRequest.prototype);function Nt(n){let e=n.source;return typeof IDBIndex=="function"&&e instanceof IDBIndex?e.objectStore:e}function Ft(n,e){if(e.startsWith("__runapps"))return[];let t=[];for(let r of Ee)(r.factory===null||r.factory===n)&&r.opts.include(e)&&t.push(r);return t}function Kn(){let n=IDBFactory.prototype,e=IDBDatabase.prototype,t=IDBObjectStore.prototype,r=IDBCursor.prototype,s=N={open:n.open,deleteDatabase:n.deleteDatabase,transaction:e.transaction,put:t.put,add:t.add,get:t.get,delete:t.delete,clear:t.clear,getAllKeys:t.getAllKeys,cursorUpdate:r.update,cursorDelete:r.delete},o=i=>Lt.get(i.transaction)??null;n.open=function(i,a){let l=a===void 0?s.open.call(this,i):s.open.call(this,i,a),c=Ft(this,i);return c.length===0?l:new Ce(l,i,c)},n.deleteDatabase=function(i){for(let a of Ft(this,i))try{a.opts.onDeleteDatabase(i)}catch{}return s.deleteDatabase.call(this,i)},e.transaction=function(i,a,l){let c=l!==void 0?s.transaction.call(this,i,a,l):a!==void 0?s.transaction.call(this,i,a):s.transaction.call(this,i),d=Ne.get(this);if(d&&c.mode==="readwrite"){let p={db:d.name,subs:d.subs,ops:[]};Lt.set(c,p),c.addEventListener("complete",()=>{if(p.ops.length===0)return;let h=p.ops;p.ops=[];for(let f of p.subs){let g=h.filter(b=>!f.opts.excludeStore(p.db,b.store));if(g.length!==0)try{f.opts.onCommit(p.db,g)}catch(b){Fe(b)}}})}return c},t.put=function(i,a){let l=o(this),c=null;if(l&&Fn(i)){let p=a!==void 0?a:Ct(i,this.keyPath);if(p!==void 0)try{let h=s.get.call(this,p),f=c={value:void 0};h.addEventListener("success",()=>{f.value=h.result})}catch{c=null}}let d=a===void 0?s.put.call(this,i):s.put.call(this,i,a);if(l){let p=this.name,h=_e(i),f=c;d.addEventListener("success",()=>{l.ops.push({store:p,kind:"put",key:d.result,value:h,prior:f?.value})})}return d},t.add=function(i,a){let l=a===void 0?s.add.call(this,i):s.add.call(this,i,a),c=o(this);if(c){let d=this.name,p=_e(i);l.addEventListener("success",()=>{c.ops.push({store:d,kind:"put",key:l.result,value:p})})}return l},t.delete=function(i){let a=o(this);if(a){let l=this.name;if(typeof IDBKeyRange=="function"&&i instanceof IDBKeyRange){let c=s.getAllKeys.call(this,i);c.addEventListener("success",()=>{for(let d of c.result)a.ops.push({store:l,kind:"del",key:d})})}else a.ops.push({store:l,kind:"del",key:i})}return s.delete.call(this,i)},t.clear=function(){let i=o(this),a=s.clear.call(this);if(i){let l=this.name;a.addEventListener("success",()=>{i.ops.push({store:l,kind:"clear"})})}return a},r.update=function(i){let a=Nt(this),l=o(a),c=l?_e(this.value):void 0,d=s.cursorUpdate.call(this,i);if(l){let p=a.name,h=_e(i),f=this.primaryKey;d.addEventListener("success",()=>{l.ops.push({store:p,kind:"put",key:f,value:h,prior:c})})}return d},r.delete=function(){let i=Nt(this),a=o(i);return a&&a.ops.push({store:i.name,kind:"del",key:this.primaryKey}),s.cursorDelete.call(this)}}function $n(){if(!N)return;let n=N;IDBFactory.prototype.open=n.open,IDBFactory.prototype.deleteDatabase=n.deleteDatabase,IDBDatabase.prototype.transaction=n.transaction,IDBObjectStore.prototype.put=n.put,IDBObjectStore.prototype.add=n.add,IDBObjectStore.prototype.delete=n.delete,IDBObjectStore.prototype.clear=n.clear,IDBCursor.prototype.update=n.cursorUpdate,IDBCursor.prototype.delete=n.cursorDelete,N=null}function te(n){if(typeof indexedDB>"u"||typeof IDBFactory!="function"||typeof IDBDatabase!="function"||typeof IDBObjectStore!="function"||typeof IDBCursor!="function")return null;N||Kn();let e=N,t={opts:n,factory:n.factory??indexedDB};Ee.add(t);let r=t.factory;return{originalOpen:(s,o)=>o===void 0?e.open.call(r,s):e.open.call(r,s,o),uninstall(){Ee.delete(t),Ee.size===0&&$n()}}}var Kt="__runapps_sync__";function F(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB request failed"))})}function D(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onabort=()=>t(n.error??new Error("IndexedDB transaction aborted")),n.onerror=()=>t(n.error??new Error("IndexedDB transaction failed"))})}var ne=class{constructor(e){u(this,"open",e);u(this,"dbPromise",null)}db(){return this.dbPromise||(this.dbPromise=new Promise((e,t)=>{let r=this.open(Kt,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains("ops")||s.createObjectStore("ops",{keyPath:"id",autoIncrement:!0}).createIndex("store",["db","store"],{unique:!1}),s.objectStoreNames.contains("meta")||s.createObjectStore("meta")},r.onsuccess=()=>{let s=r.result;s.onversionchange=()=>{s.close(),this.dbPromise=null},e(s)},r.onerror=()=>t(r.error??new Error("cannot open sync log")),r.onblocked=()=>t(new Error("sync log open blocked"))}),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}async append(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.add(o);await D(r)}async pending(){let t=(await this.db()).transaction("ops","readonly");return await F(t.objectStore("ops").getAll())}async pendingCount(){let t=(await this.db()).transaction("ops","readonly");return F(t.objectStore("ops").count())}async remove(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.delete(o);await D(r)}async clearOps(){let t=(await this.db()).transaction("ops","readwrite");t.objectStore("ops").clear(),await D(t)}async getMeta(e){let r=(await this.db()).transaction("meta","readonly");return await F(r.objectStore("meta").get(e))}async setMeta(e){let r=(await this.db()).transaction("meta","readwrite"),s=r.objectStore("meta");for(let o of Object.keys(e))e[o]===void 0?s.delete(o):s.put(e[o],o);await D(r)}async metaWithPrefix(e){let s=(await this.db()).transaction("meta","readonly").objectStore("meta"),o=IDBKeyRange.bound(e,e+"\uFFFF"),i=await F(s.getAllKeys(o)),a=await F(s.getAll(o)),l=new Map;return i.forEach((c,d)=>l.set(c,a[d])),l}async clearAll(){let t=(await this.db()).transaction(["ops","meta"],"readwrite");t.objectStore("ops").clear(),t.objectStore("meta").clear(),await D(t)}close(){this.dbPromise?.then(e=>e.close()).catch(()=>{}),this.dbPromise=null}};function $t(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!("$rt"in n)}function qn(n,e){return JSON.stringify(n)===JSON.stringify(e)}function Vn(n,e,t){if(!n)return e;if(e.d||n.d||!$t(n.v)||!$t(e.v))return e.t>=n.t?e:n;let r=n.f??{},s=t?new Set(t):null,o={},i={},a=new Set([...Object.keys(n.v),...Object.keys(e.v)]);for(let l of a){let c=l in n.v,d=l in e.v,p=r[l]??n.t;if(s?!s.has(l):c&&d&&qn(n.v[l],e.v[l])){c&&(o[l]=n.v[l],r[l]!==void 0&&(i[l]=r[l]));continue}e.t>=p?d&&(o[l]=e.v[l],i[l]=e.t):c&&(o[l]=n.v[l],i[l]=p)}return{k:e.k,v:o,t:Math.max(n.t,e.t),f:i}}var Gn=720*3600*1e3,Hn=1e4,Jn=5e3,Wn=5*6e4,$e=class{constructor(){u(this,"last",0);u(this,"offset",0)}now(){let e=Date.now()+this.offset;return this.last=e>this.last?e:this.last+1,this.last}observe(e,t,r){let s=(t+r)/2,o=e-s;Math.abs(o-this.offset)>2e3&&(this.offset=o)}};function Ke(n){return encodeURIComponent(n).replace(/%2F/gi,"%2F")}var P=class{constructor(e,t={}){u(this,"deps",e);u(this,"options");u(this,"log");u(this,"hook");u(this,"clock",new $e);u(this,"schemas",new Map);u(this,"etags",new Map);u(this,"conns",new Map);u(this,"state",{state:"off",pending:0});u(this,"paused",!1);u(this,"disposed",!1);u(this,"leader",!0);u(this,"pushTimer",null);u(this,"pushDeadline",0);u(this,"pullTimer",null);u(this,"backoffMs",0);u(this,"backoffUntil",0);u(this,"chain",Promise.resolve());u(this,"cleanup",[]);u(this,"channel",null);u(this,"metaLoaded",null);u(this,"logChain",Promise.resolve());u(this,"moved",!1);this.options={databases:t.databases??[],exclude:t.exclude??[],shards:Math.max(1,Math.min(64,t.shards??8)),pushDelayMs:t.pushDelayMs??2500,pullIntervalMs:t.pullIntervalMs??6e4,openTimeoutMs:t.openTimeoutMs??5e3,prefix:(t.prefix??"db").replace(/^\/+|\/+$/g,"")};let r=new Set(this.options.exclude.filter(i=>!i.includes("/"))),s=new Set(this.options.exclude.filter(i=>i.includes("/"))),o=new Set(this.options.databases);this.hook=te({include:i=>(o.size===0||o.has(i))&&!r.has(i),excludeStore:(i,a)=>s.has(i+"/"+a),onCommit:(i,a)=>this.onCommit(i,a),onOpen:(i,a)=>this.onOpen(i,a),onDeleteDatabase:i=>this.onDeleteDatabase(i),openTimeoutMs:this.options.openTimeoutMs,factory:e.factory}),this.log=new ne((i,a)=>this.hook?this.hook.originalOpen(i,a):indexedDB.open(i,a)),typeof window<"u"&&this.attachBrowserTriggers(),this.cleanup.push(e.onAuthChange(()=>this.schedule("auth"))),this.refreshPending(),this.schedule("start")}status(){return{...this.state}}now(){return this.leader?this.enqueue(()=>this.sync()):(this.post({type:"sync:request"}),Promise.resolve())}post(e){try{this.channel?.postMessage(e)}catch{}}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule("resume")}dispose(){this.disposed=!0;for(let e of this.cleanup)e();this.pushTimer&&clearTimeout(this.pushTimer),this.pullTimer&&clearInterval(this.pullTimer),this.channel?.close();for(let e of this.conns.values())e.then(t=>t.close()).catch(()=>{});this.conns.clear(),this.log.close(),this.hook?.uninstall()}onCommit(e,t){let r=[];for(let o of t){let i=this.clock.now();o.kind==="clear"?r.push({db:e,store:o.store,kind:"clear",kid:"",ts:i}):o.kind==="del"?r.push({db:e,store:o.store,kind:"del",kid:Se(o.key),key:j(o.key),ts:i}):r.push({db:e,store:o.store,kind:"put",kid:Se(o.key),key:j(o.key),value:o.value,changed:o.prior===void 0?void 0:Et(o.prior,o.value),ts:i})}this.enqueueLog(r);let s=new Map;for(let o of t){let i=s.get(o.store);i||s.set(o.store,i={keys:[],cleared:!1}),o.kind==="clear"?(i.cleared=!0,i.keys=[]):i.cleared||i.keys.push(o.key)}for(let[o,i]of s){let a={db:e,store:o,keys:i.keys,cleared:i.cleared,source:"tab"};this.post({type:"db:change",change:a})}}enqueueLog(e){this.logChain=this.logChain.then(()=>this.log.append(e)).then(()=>this.refreshPending()).then(()=>{this.leader||this.post({type:"sync:request"})}).catch(t=>this.fail(t)),this.schedulePush()}async onOpen(e,t){let r=new Map,s=Array.from(e.objectStoreNames);if(s.length>0){let o=e.transaction(s,"readonly");for(let i of s){let a=o.objectStore(i);r.set(i,{keyPath:a.keyPath,autoIncrement:a.autoIncrement}),a.autoIncrement&&typeof console<"u"&&console.warn(`[runapps sync] "${t}/${i}" uses autoIncrement keys: records created on two devices while offline can get the same key, and only one survives. Prefer client-generated ids (e.g. crypto.randomUUID()).`)}}this.schemas.set(t,r),this.log.setMeta({["schema:"+t]:Object.fromEntries(r)}).catch(()=>{}),!(!this.deps.userId()||this.paused||!this.leader)&&await this.enqueue(()=>this.pullDatabase(t)).catch(()=>{})}onDeleteDatabase(e){let t=this.schemas.get(e),r=t?Array.from(t.keys()):[];this.schemas.delete(e),this.conns.get(e)?.then(o=>o.close()).catch(()=>{}),this.conns.delete(e);let s=this.clock.now();this.enqueueLog(r.map(o=>({db:e,store:o,kind:"clear",kid:"",ts:s})))}attachBrowserTriggers(){let e=(r,s,o)=>{r.addEventListener(s,o),this.cleanup.push(()=>r.removeEventListener(s,o))};e(window,"online",()=>{this.backoffUntil=0,this.schedule("online")}),e(window,"focus",()=>{this.schedule("focus")}),typeof document<"u"&&e(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.schedule("visible"),this.updatePullTimer()}),this.updatePullTimer(),typeof BroadcastChannel=="function"&&(this.channel=new BroadcastChannel("__runapps_db_change__"),this.channel.onmessage=r=>{let s=r.data;s&&(s.type==="db:change"?this.deps.events.emit("db:change",s.change):s.type==="sync:state"?this.leader||(this.state={...s.state},this.deps.events.emit("sync:state",{...s.state})):s.type==="sync:request"?this.leader&&(this.post({type:"sync:state",state:{...this.state}}),this.schedule("peer")):s.source==="remote"&&this.deps.events.emit("db:change",s))});let t=navigator.locks;t&&typeof t.request=="function"&&(this.leader=!1,this.post({type:"sync:request"}),t.request("__runapps_sync__",()=>(this.leader=!0,this.schedule("leader"),new Promise(()=>{}))).catch(()=>{this.leader=!0}))}updatePullTimer(){let e=typeof document>"u"||document.visibilityState!=="hidden";e&&!this.pullTimer&&this.options.pullIntervalMs>0?(this.pullTimer=setInterval(()=>{this.schedule("interval")},this.options.pullIntervalMs),this.pullTimer.unref?.()):!e&&this.pullTimer&&(clearInterval(this.pullTimer),this.pullTimer=null)}schedulePush(){if(this.disposed)return;let e=Date.now();this.pushDeadline||(this.pushDeadline=e+Hn);let t=Math.max(0,Math.min(this.options.pushDelayMs,this.pushDeadline-e));this.pushTimer&&clearTimeout(this.pushTimer),this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.pushDeadline=0,this.schedule("push")},t),this.pushTimer.unref?.()}schedule(e){return this.disposed||this.paused||!this.leader?Promise.resolve():this.deps.userId()?Date.now()<this.backoffUntil?Promise.resolve():this.enqueue(()=>this.sync()):(this.setState({state:"off"}),Promise.resolve())}enqueue(e){let t=this.chain.then(e,e);return this.chain=t.catch(()=>{}),t}setState(e){let t={...this.state,...e};e.state&&e.state!=="error"&&delete t.error;let r=t.state!==this.state.state||t.pending!==this.state.pending||t.lastSyncedAt!==this.state.lastSyncedAt||t.lastChangeAt!==this.state.lastChangeAt||t.error!==this.state.error;this.state=t,r&&(this.deps.events.emit("sync:state",{...t}),this.leader&&this.post({type:"sync:state",state:{...t}}))}async refreshPending(){try{let e=await this.log.pendingCount();this.setState({pending:e})}catch{}}fail(e){let t=typeof navigator<"u"&&navigator.onLine===!1,r=e instanceof Error?e.message:String(e);this.backoffMs=this.backoffMs?Math.min(this.backoffMs*2,Wn):Jn,this.backoffUntil=Date.now()+this.backoffMs,this.setState({state:t?"offline":"error",error:r}),!t&&typeof console<"u"&&console.warn("[runapps sync]",r)}async loadMeta(){return this.metaLoaded||(this.metaLoaded=(async()=>{for(let[e,t]of await this.log.metaWithPrefix("etag:"))this.etags.set(e.slice(5),t);for(let[e,t]of await this.log.metaWithPrefix("schema:")){let r=e.slice(7);this.schemas.has(r)||this.schemas.set(r,new Map(Object.entries(t)))}})(),this.metaLoaded.catch(()=>{this.metaLoaded=null})),this.metaLoaded}async ensureOwner(e){let t=await this.log.getMeta("owner");if(t!==e){if(t!==void 0){for(let[r,s]of this.schemas)for(let o of s.keys())this.storeExcluded(r,o)||(await this.withStore(r,o,"readwrite",i=>{i.clear()}).catch(()=>{}),this.emitChange({db:r,store:o,keys:[],cleared:!0,source:"remote"}));await this.log.clearAll(),this.etags.clear(),this.metaLoaded=null,await this.loadMeta()}await this.log.setMeta({owner:e})}}async sync(){if(this.disposed||this.paused||!this.leader)return;let e=this.deps.userId();if(!e){this.setState({state:"off"});return}this.setState({state:"syncing"}),this.moved=!1;try{await this.loadMeta(),await this.ensureOwner(e),await this.logChain,await this.push(),await this.pull(),this.backoffMs=0,this.backoffUntil=0,await this.refreshPending();let t=Date.now();this.setState({state:"idle",lastSyncedAt:t,...this.moved?{lastChangeAt:t}:{}})}catch(t){await this.refreshPending(),this.fail(t)}}storeExcluded(e,t){return this.options.exclude.includes(e+"/"+t)||this.options.exclude.includes(e)}shardPath(e,t,r){return`${this.options.prefix}/${Ke(e)}/${Ke(t)}/${r}.json`}shardOf(e){return xe(e)%this.options.shards}async readShard(e){let t=Date.now(),r=await this.deps.remote.getJSON(e);if(r.status==="ok"){r.serverTime&&this.clock.observe(r.serverTime,t,Date.now());let s=r.value,o={v:1,cleared:s?.cleared??0,r:s?.r??{}};return this.etags.set(e,r.etag),{shard:o,etag:r.etag}}return this.etags.delete(e),{shard:{v:1,cleared:0,r:{}}}}async push(){let e=await this.log.pending();if(e.length===0)return;let t=new Map;for(let o of e){let i=o.db+"\0"+o.store,a=t.get(i);a||t.set(i,a=[]),a.push(o)}let r=[],s={};for(let[,o]of t){let i=o[0].db,a=o[0].store;if(this.storeExcluded(i,a)){for(let f of o)f.id!==void 0&&r.push(f.id);continue}let l=0,c=-1;o.forEach((f,g)=>{f.kind==="clear"&&(l=Math.max(l,f.ts),c=g)});let d=o.slice(c+1),p=new Map;for(let f of d){let g=this.shardOf(f.kid),b=p.get(g);b||p.set(g,b=[]),b.push(f)}let h=l>0?Array.from({length:this.options.shards},(f,g)=>g):Array.from(p.keys());for(let f of h){let g=this.shardPath(i,a,f),b=p.get(f)??[],x=await Promise.all(b.map(v=>this.encodeOp(v))),S=await this.writeShard(g,l,x);s["etag:"+g]=S}for(let f of o)f.id!==void 0&&r.push(f.id)}await this.log.setMeta(s),await this.log.remove(r),r.length>0&&(this.moved=!0),await this.refreshPending()}async encodeOp(e){if(e.kind==="del")return{kid:e.kid,rec:{k:e.key,v:null,t:e.ts,d:1}};let t=await A(e.value,r=>this.storeBlob(r));return{kid:e.kid,rec:{k:e.key,v:t,t:e.ts},changed:e.changed}}async writeShard(e,t,r){for(let s=0;s<5;s++){let{shard:o,etag:i}=await this.readShard(e),a=this.clock.now();if(t>o.cleared){o.cleared=t;for(let d of Object.keys(o.r))o.r[d].t<=t&&delete o.r[d]}for(let{kid:d,rec:p,changed:h}of r)p.t<=o.cleared||(o.r[d]=Vn(o.r[d],p,h));for(let d of Object.keys(o.r)){let p=o.r[d];p.d&&a-p.t>Gn&&delete o.r[d]}let l=Date.now(),c=await this.deps.remote.putJSON(e,o,i?{ifMatch:i}:{ifNoneMatch:!0});if(c.status==="ok")return c.serverTime&&this.clock.observe(c.serverTime,l,Date.now()),this.etags.set(e,c.etag),c.etag;this.etags.delete(e)}throw new Error(`could not write ${e}: too many concurrent writers`)}async storeBlob(e){let t=new Uint8Array(await e.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",t),s=Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join(""),o=`${this.options.prefix}/_blobs/${s}`;return await this.deps.remote.putBlob(o,e),{ref:o,type:e.type,size:e.size}}async pull(){let e=await this.deps.remote.list(this.options.prefix+"/");await this.applyListing(e)}async pullDatabase(e){if(!this.deps.userId())return;await this.loadMeta();let t=await this.deps.remote.list(`${this.options.prefix}/${Ke(e)}/`);await this.applyListing(t)}async applyListing(e){let t=new RegExp("^"+this.options.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/([^/]+)/([^/]+)/(\\d+)\\.json$"),r=await this.log.pending(),s={};for(let o of e){let i=t.exec(o.path);if(!i)continue;let a=decodeURIComponent(i[1]),l=decodeURIComponent(i[2]);if(this.etags.get(o.path)===o.etag||this.storeExcluded(a,l))continue;let c=this.schemas.get(a);if(!c||!c.has(l))continue;let d=await this.deps.remote.getJSON(o.path,this.etags.get(o.path));if(d.status==="unchanged")continue;if(d.status==="missing"){this.etags.delete(o.path),s["etag:"+o.path]=void 0;continue}let p=d.value,h={v:1,cleared:p?.cleared??0,r:p?.r??{}};await this.applyShard(a,l,h,r),this.etags.set(o.path,d.etag),s["etag:"+o.path]=d.etag}Object.keys(s).length&&await this.log.setMeta(s)}async applyShard(e,t,r,s){let o=new Map,i=0;for(let h of s)h.db!==e||h.store!==t||(h.kind==="clear"?i=Math.max(i,h.ts):o.set(h.kid,Math.max(o.get(h.kid)??0,h.ts)));let a=`cleared:${e}/${t}`,l=await this.log.getMeta(a)??0,c=this.schemas.get(e)?.get(t),d=[],p=!1;await this.withStore(e,t,"readwrite",h=>{r.cleared>l&&r.cleared>i&&(h.clear(),p=!0);for(let f of Object.keys(r.r)){let g=r.r[f];if((o.get(f)??0)>=g.t||g.t<=i)continue;let b=Z(g.k);if(d.push(b),g.d)h.delete(b);else{let x=g._decoded;c&&c.keyPath!==null?h.put(x):h.put(x,b)}}if(p)for(let f of s)f.db!==e||f.store!==t||f.kind!=="put"||f.ts<=r.cleared||(c&&c.keyPath!==null?h.put(f.value):h.put(f.value,Z(f.key)))},async()=>{for(let h of Object.keys(r.r)){let f=r.r[h];f.d||(o.get(h)??0)>=f.t||f.t<=i||(f._decoded=await _(f.v,g=>this.deps.remote.getBlob(g.ref)))}}),r.cleared>l&&await this.log.setMeta({[a]:r.cleared}),(d.length>0||p)&&this.emitChange({db:e,store:t,keys:d,cleared:p,source:"remote"})}emitChange(e){this.moved=!0,this.deps.events.emit("db:change",e);try{this.post(e)}catch{}}conn(e){let t=this.conns.get(e);return t||(t=new Promise((r,s)=>{let i=(this.hook?this.hook.originalOpen:a=>indexedDB.open(a))(e);i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>{a.close(),this.conns.delete(e)},r(a)},i.onerror=()=>s(i.error??new Error(`cannot open ${e}`)),i.onblocked=()=>s(new Error(`open of ${e} blocked`))}),this.conns.set(e,t),t.catch(()=>this.conns.delete(e))),t}async withStore(e,t,r,s,o){o&&await o();let i=await this.conn(e);if(!i.objectStoreNames.contains(t))return;let a=i.transaction(t,r);s(a.objectStore(t)),await D(a)}};var R=class{constructor(e){u(this,"files",e)}async list(e){let t=[],r;do{let s=await this.files.list({prefix:e,limit:1e3,...r?{cursor:r}:{}});for(let o of s.files)o.etag&&t.push({path:o.path,etag:o.etag});r=s.next_cursor}while(r);return t}async getJSON(e,t){let r=await this.files.readJSON(e,t?{ifNoneMatch:t}:void 0);return r.notModified?{status:"unchanged"}:r.value===void 0?{status:"missing"}:{status:"ok",value:r.value,etag:r.etag??""}}async putJSON(e,t,r){try{let s=await this.files.put(e,JSON.stringify(t),{contentType:"application/json",...r.ifMatch?{ifMatch:r.ifMatch}:{},...r.ifNoneMatch?{ifNoneMatch:!0}:{}});return{status:"ok",etag:s.etag??"",serverTime:s.last_modified?Date.parse(s.last_modified):void 0}}catch(s){let o=s.statusCode;if(o===412||o===409)return{status:"conflict"};throw s}}async putBlob(e,t){try{await this.files.put(e,t,{contentType:t.type||"application/octet-stream",ifNoneMatch:!0})}catch(r){if(r.statusCode!==409)throw r}}getBlob(e){return this.files.get(e)}};var zn="https://www.runapps.ai",K=class{constructor(e={}){u(this,"chat");u(this,"models");u(this,"image");u(this,"audio");u(this,"video");u(this,"computer");u(this,"files");u(this,"embeddings");u(this,"realtime");u(this,"auth",null);u(this,"sync",null);u(this,"events",new O);let t=e.authProvider??(!e.apiKey&&!e.apiKeyResolver&&typeof window<"u"?"runapps":"static"),r=e.apiKeyResolver,s=e.baseURL,o;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let l=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,c=new L({origin:s,hideBadge:!l,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=c,r=c.getToken,o=()=>c.invalidate()}if(!e.apiKey&&!r)throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");let i=new le({baseURL:s??zn,...e.apiKey!==void 0&&{apiKey:e.apiKey},...r!==void 0&&{apiKeyResolver:r},...o!==void 0&&{onUnauthorized:o},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new ue(i,this.events),this.models=new de(i),this.image=new pe(i,this.events),this.audio=new fe(i,this.events),this.video=new me(i,this.events),this.computer=new ye(i,this.events),this.files=new Q(i,e.project,this.events),this.embeddings=new be(i,this.events),this.realtime=new ge(i,this.events);let a=e.sync??this.auth!==null;if(a&&typeof indexedDB<"u"&&this.auth){let l=this.auth,c=new P({remote:new R(new Q(i,e.project)),events:this.events,userId:()=>l.ownerId(),onAuthChange:d=>l.onTokenChange(()=>d())},typeof a=="object"?a:{});this.sync=c}}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function qt(n){return n?n.map(e=>Array.isArray(e)?{fields:e}:e):[]}function re(n){let e=n.options;return!e||typeof e!="object"?null:e}function Vt(n,e){let r=re(n)?.inputs?.[e];return r?r.presence!=="forbidden":!1}function Gt(n,e){return re(n)?.inputs?.[e]?.presence==="required"}function Ht(n,e){return re(n)?.inputs?.[e]?.enum??null}function zt(n,e={}){if(!n)return[];let t=[];if(n.inputs)for(let[r,s]of Object.entries(n.inputs)){let o=r in e,i=e[r];o&&!T(i)?t.push(...Yt(r,s,i)):o&&s.min_items!==void 0&&Array.isArray(i)&&i.length<s.min_items&&t.push({field:r,reason:`at least ${s.min_items} items`}),t.push(...Xt(r,s,i,o))}for(let r of n.constraints??[])t.push(...Yn(r,e));return t}function Yt(n,e,t){let r=[];if(!Xn(e.type,t))return r.push({field:n,reason:`expected type ${e.type}, got ${Ie(t)}`}),r;if(e.enum&&e.enum.length>0&&!Qn(t,e.enum)&&r.push({field:n,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=Qt(t);s!==null&&(e.min!==void 0&&s<e.min&&r.push({field:n,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&r.push({field:n,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&r.push({field:n,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&r.push({field:n,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,o)=>{if(typeof s!="object"||s===null||Array.isArray(s)){r.push({field:`${n}[${o}]`,reason:`expected object, got ${Ie(s)}`});return}r.push(...Jt(`${n}[${o}]`,e.fields,s))}):r.push({field:n,reason:`expected array of objects, got ${Ie(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?r.push({field:n,reason:`expected object, got ${Ie(t)}`}):r.push(...Jt(n,e.fields,t))),r}function Jt(n,e,t){let r=[];for(let[s,o]of Object.entries(e)){let i=`${n}.${s}`,a=t[s],l=s in t;l&&!T(a)&&r.push(...Yt(i,o,a)),r.push(...Xt(i,o,a,l))}return r}function Xt(n,e,t,r){let s=e.presence??"optional";return s==="required"&&(!r||T(t))?[{field:n,reason:"required"}]:s==="forbidden"&&r&&!T(t)?[{field:n,reason:"must not be set for this model"}]:[]}function Yn(n,e){switch(n.kind){case"any_of_required":{let t=n.fields??[];return t.some(s=>s in e&&!T(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=n.fields??[],r=t.filter(s=>s in e&&!T(e[s]));return r.length>1?[{field:r.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${r.join(", ")})`}]:[]}case"group_mutex":{let t=qt(n.groups),r=[],s=[];for(let o of t){let i=o.fields.filter(a=>a in e&&!T(e[a]));i.length>0&&(r.push(o),s.push(...i))}if(r.length>1){let o=t.map(i=>`[${i.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${o} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=n.when;if(!t)return[];if(!(t in e&&!T(e[t])))return[];let s=(n.then??[]).filter(o=>!(o in e)||T(e[o]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=n.fields?.[0];if(!t)return[];let r=e[t];if(typeof r!="string"||r==="")return[];let s=er(r);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${r}"`}];let[o,i]=s,a=o*i,l=[];return n.min!==void 0&&a<n.min&&l.push({field:t,reason:`image too small: ${o}x${i} = ${a} pixels, minimum ${n.min}`}),n.max!==void 0&&a>n.max&&l.push({field:t,reason:`image too large: ${o}x${i} = ${a} pixels, maximum ${n.max}`}),l}}return[]}function Xn(n,e){switch(n){case"string":return typeof e=="string";case"int":case"float":return Qt(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&Wt(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&Wt(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function Ie(n){return n===null?"null":Array.isArray(n)?"array":typeof n}function Qt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Wt(n){return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")}function T(n){return n==null?!0:typeof n=="string"?n==="":Array.isArray(n)?n.length===0:!1}function Qn(n,e){for(let t of e)if(Zn(n,t))return!0;return!1}function Zn(n,e){return n===e}function er(n){for(let e of["x","X","*","\xD7"]){let t=n.indexOf(e);if(t<=0)continue;let r=parseInt(n.slice(0,t).trim(),10),s=parseInt(n.slice(t+e.length).trim(),10);if(Number.isFinite(r)&&Number.isFinite(s)&&r>0&&s>0)return[r,s]}return null}return on(tr);})();
|
|
1
|
+
/* @runappsai/sdk 0.7.1 */
|
|
2
|
+
"use strict";var RunApps=(()=>{var ce=Object.defineProperty;var Zt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.prototype.hasOwnProperty;var nn=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var rn=(n,e)=>{for(var t in e)ce(n,t,{get:e[t],enumerable:!0})},sn=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of en(e))!tn.call(n,s)&&s!==t&&ce(n,s,{get:()=>e[s],enumerable:!(r=Zt(e,s))||r.enumerable});return n};var on=n=>sn(ce({},"__esModule",{value:!0}),n);var u=(n,e,t)=>nn(n,typeof e!="symbol"?e+"":e,t);var tr={};rn(tr,{APIError:()=>C,ActivityTracker:()=>M,BrowserAuth:()=>L,Client:()=>K,FilesRemote:()=>R,RealtimeSession:()=>Y,RunApps:()=>K,RunJobs:()=>K,SDKEvents:()=>O,ServerTools:()=>tt,SyncEngine:()=>P,acceptsField:()=>Vt,acceptsModality:()=>pt,allowedValuesFor:()=>Ht,assistantMessage:()=>st,audioPart:()=>ut,base64ToBytes:()=>At,bytesToBase64:()=>Oe,decodeMediaUrl:()=>z,defaultVoice:()=>mt,encodeImageUrl:()=>bt,float32FromPCM16:()=>kt,getOptionsSchema:()=>re,hasCapabilityTag:()=>dt,imagePart:()=>ct,installIndexedDBHook:()=>te,newRequestId:()=>I,pcm16FromFloat32:()=>xt,requiresField:()=>Gt,supportsInstructText:()=>gt,supportsVoiceClone:()=>ht,systemMessage:()=>rt,textPart:()=>at,toolResultMessage:()=>ot,userMessage:()=>nt,userMessageParts:()=>it,validateRequest:()=>zt,videoPart:()=>lt});var C=class extends Error{constructor(t,r,s){super(`runapps: ${t} ${r}: ${s}`);u(this,"statusCode");u(this,"type");this.name="APIError",this.statusCode=t,this.type=r}};var le=class{constructor(e){u(this,"baseURL");u(this,"apiKey");u(this,"apiKeyResolver");u(this,"onUnauthorized");u(this,"fetchImpl");if(!e.apiKey&&!e.apiKeyResolver)throw new Error("RunApps: pass either `apiKey` or `apiKeyResolver` when constructing the client");this.baseURL=e.baseURL.replace(/\/+$/,""),this.apiKey=e.apiKey,this.apiKeyResolver=e.apiKeyResolver,this.onUnauthorized=e.onUnauthorized,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis)}async resolveToken(){return this.apiKeyResolver?await this.apiKeyResolver():this.apiKey??""}bearerToken(){return this.resolveToken()}async fetchWithAuthRetry(e,t){let r=this.baseURL+e,s=await this.fetchImpl(r,await this.buildInit(t));if(s.status!==401||!this.onUnauthorized)return s;try{await this.onUnauthorized()}catch{return s}return s=await this.fetchImpl(r,await this.buildInit(t)),s}async buildInit(e){let t=await e();return t.cache?t:{...t,cache:"no-store"}}async postJSON(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.jsonHeaders(),body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async getJSON(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);return await r.json()}async getPublicJSON(e,t){let r=await this.fetchImpl(this.baseURL+e,{method:"GET",cache:"no-store",...t?.signal?{signal:t.signal}:{}});if(!r.ok)throw await this.parseError(r);return await r.json()}async getRaw(e,t){let r=await this.fetchWithAuthRetry(e,async()=>{let l=await this.authHeaders();return t?.ifNoneMatch&&(l["If-None-Match"]=`"${W(t.ifNoneMatch)}"`),{method:"GET",headers:l,signal:t?.signal}}),s=an(r.headers.get("date"));if(r.status===304){let l=W(r.headers.get("etag"))||t?.ifNoneMatch;return{data:new Uint8Array(0),contentType:"",etag:l,notModified:!0,serverTime:s}}if(!r.ok)throw await this.parseError(r);let o=new Uint8Array(await r.arrayBuffer()),i=r.headers.get("content-type")??"",a=W(r.headers.get("etag"))||void 0;return{data:o,contentType:i,etag:a,serverTime:s}}async postMultipart(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.authHeaders(),body:t,signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async postJSONStream(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:{...await this.jsonHeaders(),"Accept-Encoding":"identity"},body:JSON.stringify(t),signal:r?.signal}));if(!s.ok)throw await this.parseError(s);return s}async putBytes(e,t,r){let s=await this.fetchWithAuthRetry(e,async()=>{let o={...await this.authHeaders(),"Content-Type":r?.contentType??"application/octet-stream"};return r?.headers&&Object.assign(o,r.headers),{method:"PUT",headers:o,body:t,signal:r?.signal}});if(!s.ok)throw await this.parseError(s);if(r?.parse!=="none")return await s.json()}async deletePath(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"DELETE",headers:await this.authHeaders(),signal:t?.signal}));if(!r.ok)throw await this.parseError(r);if(t?.parse!=="none")return await r.json()}async head(e,t){let r=await this.fetchWithAuthRetry(e,async()=>({method:"HEAD",headers:await this.authHeaders(),signal:t?.signal}));return{status:r.status,headers:r.headers}}async jsonHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${await this.resolveToken()}`}}async authHeaders(){return{Authorization:`Bearer ${await this.resolveToken()}`}}async parseError(e){let t=await e.text(),r="error",s=t||e.statusText;try{let o=JSON.parse(t);o.type&&(r=o.type),o.message&&(s=o.message)}catch{}return new C(e.status,r,s)}};function W(n){return(n??"").trim().replace(/^W\//i,"").replace(/"/g,"")}function an(n){if(!n)return;let e=Date.parse(n);return Number.isNaN(e)?void 0:e}var O=class{constructor(){u(this,"handlers",new Map)}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r));let s=t;return r.add(s),()=>{this.handlers.get(e)?.delete(s)}}emit(e,t){let r=this.handlers.get(e);if(!(!r||r.size===0))for(let s of r)try{s(t)}catch(o){console.error("[runapps sdk] event listener for",e,"threw:",o)}}clear(){this.handlers.clear()}};function I(){return"req_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}async function b(n,e,t,r){let s=I(),o=Date.now();n.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:o,streaming:!1});try{let i=await t(),a=r?r(i):{};return n.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,totalTokens:a.totalTokens??0,...a.costUSD!==void 0&&{costUSD:a.costUSD},...a.finishReason!==void 0&&{finishReason:a.finishReason}}),i}catch(i){let a=i;throw n.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,error:a,...typeof a.statusCode=="number"&&{statusCode:a.statusCode}}),i}}function cn(n){return n?Math.max(1,Math.round(n.length/4)):0}async function*et(n,e,t,r){let s=I(),o=Date.now();n.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:o,streaming:!0});let i=0,a,l,c;try{for await(let d of t()){let p=r(d);if(p.deltaText){let h=cn(p.deltaText);i+=h,n.emit("request:streamDelta",{id:s,deltaTokens:h,totalTokens:i})}p.completionTokens!==void 0&&(a=p.completionTokens),p.costUSD!==void 0&&(l=p.costUSD),p.finishReason!==void 0&&(c=p.finishReason),yield d}n.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,totalTokens:a??i,...l!==void 0&&{costUSD:l},...c!==void 0&&{finishReason:c}})}catch(d){let p=d;throw n.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-o,error:p,...typeof p.statusCode=="number"&&{statusCode:p.statusCode}}),d}}var tt={WebSearch:"web_search",WebFetch:"web_fetch",TwitterSearch:"twitter_search"},nt=n=>({role:"user",content:n}),rt=n=>({role:"system",content:n}),st=n=>({role:"assistant",content:n}),ot=(n,e)=>({role:"tool",tool_call_id:n,content:e}),it=(...n)=>({role:"user",content:n}),at=n=>({type:"text",text:n}),ct=(n,e)=>({type:"image_url",image_url:e?{url:n,detail:e}:{url:n}}),lt=n=>({type:"video_url",video_url:{url:n}}),ut=n=>({type:"audio_url",audio_url:{url:n}}),ue=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t){let r={...e,stream:!1};return b(this.events,{model:e.model,capability:"text"},()=>this.transport.postJSON("/v1/chat/completions",r,t),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost,finishReason:s.choices?.[0]?.finish_reason}))}async*stream(e,t){let r={...e,stream:!0,stream_options:e.stream_options??{include_usage:!0}},s=async function*(){let o=await this.transport.postJSONStream("/v1/chat/completions",r,t);if(!o.body)throw new Error("runapps: streaming response had no body");yield*ln(o.body)}.bind(this);yield*et(this.events,{model:e.model,capability:"text"},s,o=>({deltaText:o.choices?.[0]?.delta?.content??"",completionTokens:o.usage?.completion_tokens,costUSD:o.usage?.total_cost,finishReason:o.choices?.[0]?.finish_reason??void 0}))}};async function*ln(n){let e=new TextDecoder,t=n.getReader(),r="";try{for(;;){let{value:s,done:o}=await t.read();if(o)break;r+=e.decode(s,{stream:!0});let i;for(;(i=r.indexOf(`
|
|
3
|
+
`))!==-1;){let a=r.slice(0,i).replace(/\r$/,"");if(r=r.slice(i+1),!a.startsWith("data: "))continue;let l=a.slice(6).trim();if(l==="[DONE]")return;if(!l)continue;let c;try{c=JSON.parse(l)}catch(p){throw new Error(`runapps: decode stream chunk: ${p.message}`)}let d=c.error;if(d)throw new C(d.code??0,d.type??"upstream_error",d.message??l);yield c}}}finally{t.releaseLock()}}var dt=(n,e)=>Array.isArray(n.capability_tags)&&n.capability_tags.some(t=>t.id===e),pt=(n,e)=>Array.isArray(n.input_modalities)&&n.input_modalities.includes(e);function ft(n,e){let t=n.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var ht=n=>ft(n,"supports_voice_clone"),gt=n=>ft(n,"supports_instruct_text"),mt=n=>{let e=n.options?.default_voice;return typeof e=="string"?e:null},de=class{constructor(e){u(this,"transport",e)}async list(e={},t){let r="/v1/models";return e.capability&&(r+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getPublicJSON(r,t)).data}};var pe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return b(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},r),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,r){let s=r?.pollIntervalMs??2e3,o=r?.signal;return b(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:o});for(;a.status!=="succeeded"&&a.status!=="failed";)await un(s,o),a=await this.getAsyncStatus(a.id,{signal:o});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},i=>({costUSD:i.usage?.total_cost}))}async submitGenerate(e,t,r){return b(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},r))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,r){let s=dn(e,t);return b(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,r),o=>({costUSD:o.usage?.total_cost}))}};function un(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}function dn(n,e){let t=new FormData;return t.set("model",n),t.set("prompt",typeof e.prompt=="string"?e.prompt:JSON.stringify(e.prompt)),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",yt(e.image),e.image.filename),e.mask&&t.set("mask",yt(e.mask),e.mask.filename),t}function yt(n){let e=n.contentType??pn(n.filename);return n.data instanceof Blob?n.data.type===e?n.data:new Blob([n.data],{type:e}):typeof n.data=="string"?new Blob([n.data],{type:e}):new Blob([n.data],{type:e})}function pn(n){switch(n.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function bt(n){if(n instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=n instanceof Uint8Array?n:new Uint8Array(n),t=hn(e),r=32768,s="";for(let i=0;i<e.length;i+=r)s+=String.fromCharCode.apply(null,Array.from(e.subarray(i,i+r)));let o=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${o}`}async function z(n){if(n.startsWith("data:")){let e=n.slice(5),t=e.indexOf(";"),r=e.indexOf(",");if(t===-1||r===-1||r<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),o=e.slice(r+1);return{bytes:fn(o),contentType:s}}if(n.startsWith("http://")||n.startsWith("https://")){let e=await fetch(n);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${n.slice(0,32)}`)}function fn(n){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(n,"base64"));let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function hn(n){return n.length>=8&&n[0]===137&&n[1]===80&&n[2]===78&&n[3]===71?"image/png":n.length>=3&&n[0]===255&&n[1]===216&&n[2]===255?"image/jpeg":n.length>=6&&n[0]===71&&n[1]===73&&n[2]===70&&n[3]===56?"image/gif":n.length>=12&&n[0]===82&&n[1]===73&&n[2]===70&&n[3]===70&&n[8]===87&&n[9]===69&&n[10]===66&&n[11]===80?"image/webp":"application/octet-stream"}var fe=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async speech(e,t,r){return b(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",wt(e,t),r),{bytes:o,contentType:i}=await z(s.audio_url);return{data:o,contentType:i,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,r){return b(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",wt(e,t),r);if(!s.id)throw new Error("runapps: speech submit response missing job id");return gn(this.transport,s.id,r)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,r){let s=vt(e,t);return b(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,r),o=>({costUSD:o.usage?.total_cost}))}async transcribeAsync(e,t,r){return b(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=vt(e,t),o=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,r);if(!o.id)throw new Error("runapps: transcribe submit response missing job id");return mn(this.transport,o.id,r)},s=>({costUSD:s.usage?.total_cost}))}};async function gn(n,e,t){let r=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await he(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await n.getJSON(r,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:l,contentType:c}=await z(a.audio_url);return{data:l,contentType:c,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await he(s,t?.signal)}}async function mn(n,e,t){let r=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await he(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let i=await n.getJSON(r,t);switch(i.status){case"succeeded":return yn(i);case"failed":throw new Error(i.error||"runapps: transcribe job failed");case"queued":case"running":await he(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(i.status)}`)}}}function yn(n){let e={text:n.text??"",usage:n.usage??{total_cost:0}},t={};for(let[r,s]of Object.entries(n))r==="text"||r==="usage"||r==="id"||r==="status"||(t[r]=s);return Object.keys(t).length>0&&(e.raw=t),e}function he(n,e){return new Promise((t,r)=>{if(e?.aborted){r(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",o,{once:!0})})}function wt(n,e){let{extra:t,...r}=e,s={model:n,...r};if(t)for(let[o,i]of Object.entries(t))o in s||(s[o]=i);return s}function vt(n,e){let t=new FormData;if(t.set("model",n),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let o of e.timestamp_granularities)t.append("timestamp_granularities[]",o);if(e.user&&t.set("user",e.user),!e.file){if(!e.url)throw new Error("runapps: transcribe needs `file` or `url`");return t.set("url",e.url),t}let r=e.file.contentType??bn(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:r});return t.set("file",s,e.file.filename),t}function bn(n){switch(n.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var St=1,wn=1e4,Y=class{constructor(e){u(this,"ws",e);u(this,"sessionId","");u(this,"closed");u(this,"handlers",new Map);u(this,"usage",null);u(this,"resolveClosed");u(this,"isClosed",!1);u(this,"queue",[]);u(this,"waiters",[]);u(this,"iterating",!1);this.closed=new Promise(t=>{this.resolveClosed=t}),e.addEventListener("message",t=>{if(typeof t.data!="string")return;let r;try{r=JSON.parse(t.data)}catch{return}if(!(!r||typeof r.type!="string")){if(r.type==="session.created"){let s=r.session?.id;typeof s=="string"&&(this.sessionId=s)}else r.type==="gateway.usage"&&(this.usage=r.usage??null);this.dispatch(r)}}),e.addEventListener("close",t=>{if(!this.isClosed){this.isClosed=!0;for(let r of this.waiters.splice(0))r({value:void 0,done:!0});this.resolveClosed({code:t.code??1006,reason:t.reason??"",usage:this.usage})}})}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r.delete(t)}send(e){if(this.ws.readyState!==St)throw new Error("runapps: realtime session is closed");this.ws.send(JSON.stringify(e))}appendAudio(e){this.send({type:"input_audio_buffer.append",audio:Oe(xn(e))})}commitAudio(){this.send({type:"input_audio_buffer.commit"})}mute(){this.send({type:"input_audio_mute.commit"})}unmute(){this.send({type:"input_audio_unmute.commit"})}say(e){this.send({type:"speech_text_buffer.commit",text:e})}cancelResponse(){this.send({type:"response.cancel"})}update(e){this.send({type:"session.update",session:e})}sendFunctionResult(e,t){this.send({type:"conversation.item.create",items:[{call_id:e,role:"tool",content:[{type:"input_text",text:t}]}]})}async close(){if(!this.isClosed&&this.ws.readyState===St){try{this.send({type:"session.close"})}catch{}let e=setTimeout(()=>this.ws.close(1e3,"client timeout"),wn);try{return await this.closed}finally{clearTimeout(e)}}return this.isClosed||this.ws.close(1e3),this.closed}[Symbol.asyncIterator](){return this.iterating=!0,{next:()=>{let e=this.queue.shift();return e?Promise.resolve({value:e,done:!1}):this.isClosed?Promise.resolve({value:void 0,done:!0}):new Promise(t=>this.waiters.push(t))},return:()=>(this.iterating=!1,this.queue=[],Promise.resolve({value:void 0,done:!0}))}}dispatch(e){for(let t of[e.type,"*"]){let r=this.handlers.get(t);if(r)for(let s of[...r])try{s(e)}catch(o){setTimeout(()=>{throw o})}}if(this.iterating){let t=this.waiters.shift();t?t({value:e,done:!1}):this.queue.push(e)}}},ge=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async connect(e={}){let t=e.WebSocket??globalThis.WebSocket;if(!t)throw new Error("runapps: no WebSocket available \u2014 pass `WebSocket` (e.g. from the `ws` package) on Node < 22");let r=await this.transport.bearerToken(),s=new t(Sn(this.transport.baseURL,e),["realtime","runapps-key."+r]),o=new Y(s),i=e.model??"",a=I(),l=Date.now();this.events.emit("request:start",{id:a,model:i,capability:"realtime",startedAt:l,streaming:!0});try{await new Promise((c,d)=>{let p=setTimeout(()=>{g(new Error("runapps: realtime session did not open in time")),s.close(1e3,"open timeout")},e.timeoutMs??15e3),h=()=>{g(new Error("runapps: realtime connect aborted")),s.close(1e3,"aborted")};e.signal?.addEventListener("abort",h,{once:!0});let f=!1;function g(S){f||(f=!0,clearTimeout(p),e.signal?.removeEventListener("abort",h),d(S))}let w=o.on("session.created",()=>{f||(f=!0,clearTimeout(p),e.signal?.removeEventListener("abort",h),w(),x(),c())}),x=o.on("error",S=>{let y=S.error??{};g(new Error(`runapps: realtime error: ${y.message??JSON.stringify(S)}`))});s.addEventListener("open",()=>{s.send(JSON.stringify(vn(e)))}),o.closed.then(S=>{let y=S.code===1006?" \u2014 check the API key, the model name and the account balance":"";g(new Error(`runapps: realtime connection closed (${S.code}${S.reason?" "+S.reason:""})${y}`))})})}catch(c){try{s.close(1e3,"connect failed")}catch{}throw this.events.emit("request:error",{id:a,model:i,capability:"realtime",latencyMs:Date.now()-l,error:c}),c}return o.closed.then(c=>{this.events.emit("request:end",{id:a,model:i,capability:"realtime",latencyMs:Date.now()-l,totalTokens:c.usage?.output_tokens??0,...c.usage?.total_cost!==void 0&&{costUSD:c.usage.total_cost}})}),o}};function vn(n){let e={type:"session.create",session:n.session??{}};return n.extension&&(e.extension=n.extension),e}function Sn(n,e){let t=new URL(n.replace(/\/+$/,"")+"/v1/realtime");t.protocol=t.protocol==="http:"?"ws:":"wss:";for(let[r,s]of Object.entries(e.query??{}))t.searchParams.set(r,s);return e.model&&t.searchParams.set("model",e.model),e.maxCost!==void 0&&e.maxCost>0&&t.searchParams.set("max_cost",String(e.maxCost)),t.toString()}function xt(n,e,t=16e3){let r=e/t,s=r===1?n.length:Math.floor(n.length/r),o=new Int16Array(s);for(let i=0;i<s;i++){let a;if(r===1)a=n[i];else{let l=i*r,c=Math.floor(l),d=l-c,p=n[c],h=n[Math.min(c+1,n.length-1)];a=p+(h-p)*d}a=Math.max(-1,Math.min(1,a)),o[i]=a<0?a*32768:a*32767}return o}function kt(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=new Float32Array(n.byteLength>>1);for(let r=0;r<t.length;r++)t[r]=e.getInt16(r*2,!0)/32768;return t}function Oe(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function At(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function xn(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}var me=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async generate(e,t,r){return b(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},r))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let r=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await kn(r,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function kn(n,e){return new Promise((t,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(s),r(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}var ye=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async step(e,t,r){return b(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},r),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function X(n,e){let t=e.replace(/^\/+/,"");return n+"/"+t.split("/").map(encodeURIComponent).join("/")}var Q=class{constructor(e,t,r){u(this,"transport",e);u(this,"events",r);u(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}run(e,t){return this.events?b(this.events,{model:e,capability:"files"},t):t()}async put(e,t,r){let s={};return r?.ifNoneMatch&&(s["If-None-Match"]="*"),r?.ifMatch&&(s["If-Match"]=`"${W(r.ifMatch)}"`),this.run("files.put",()=>this.transport.putBytes(X(this.base,e),t,{contentType:r?.contentType,headers:Object.keys(s).length?s:void 0,signal:r?.signal}))}async putString(e,t,r){return this.put(e,t,{...r,contentType:r?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){return this.run("files.read",()=>this.readRaw(e,t))}async readRaw(e,t){let{data:r,contentType:s,etag:o,notModified:i}=await this.transport.getRaw(X(this.base,e),t);return{blob:new Blob([new Uint8Array(r)],{type:s||"application/octet-stream"}),contentType:s,etag:o,...i?{notModified:!0}:{}}}async readJSON(e,t){let r;try{r=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return r.notModified?{value:void 0,etag:r.etag,notModified:!0}:{value:JSON.parse(await r.blob.text()),etag:r.etag}}async stat(e,t){let{status:r,headers:s}=await this.run("files.stat",()=>this.transport.head(X(this.base,e),t));if(r===404)throw Object.assign(new Error("not found"),{status:404});if(r>=400)throw Object.assign(new Error("stat failed"),{status:r});let o=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:o,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:r}=await this.run("files.exists",()=>this.transport.head(X(this.base,e),t));return r>=200&&r<400}async del(e,t){await this.run("files.del",()=>this.transport.deletePath(X(this.base,e),t))}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let r=t.toString();return this.run("files.list",()=>this.transport.getJSON(this.base+(r?"?"+r:""),e?.signal?{signal:e.signal}:void 0))}async deleteMany(e,t){return this.run("files.deleteMany",()=>this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t))}async move(e,t,r){return this.run("files.move",()=>this.transport.postJSON(this.base+"/move",{from:e,to:t},r))}async copy(e,t,r){return this.run("files.copy",()=>this.transport.postJSON(this.base+"/copy",{from:e,to:t},r))}async putFromURL(e,t,r){return this.run("files.putFromURL",()=>this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:r?.contentType,if_none_match:r?.ifNoneMatch,if_match:r?.ifMatch},r?.signal?{signal:r.signal}:void 0))}async batch(e,t){return e.length===0?[]:this.run("files.batch",()=>this.batchRaw(e,t))}async batchRaw(e,t){if(e.length<=30)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let o=0;o<e.length;o+=30){let i=e.slice(o,o+30),a=await this.transport.postJSON(this.base+"/batch",{ops:i},t);s.push(...a.results)}return s}};var be=class{constructor(e,t){u(this,"transport",e);u(this,"events",t)}async create(e,t,r){return b(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},r),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var M=class{constructor(){u(this,"active",new Map);u(this,"recent",[]);u(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});u(this,"lastErrorAt",0);u(this,"changeListeners",new Set);u(this,"sync")}attach(e){let t=[e.on("request:start",r=>{this.onStart(r),this.notify()}),e.on("request:streamDelta",r=>{this.onDelta(r),this.notify()}),e.on("request:end",r=>{this.onEnd(r),this.notify()}),e.on("request:error",r=>{this.onError(r),this.notify()}),e.on("sync:state",r=>{this.sync={...r},this.notify()})];return()=>{for(let r of t)r()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},...this.sync?{sync:{...this.sync}}:{},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let r=Date.now();t.rateSamples.push({t:r,tokens:e.deltaTokens});let s=r-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let o=t.rateSamples.reduce((a,l)=>a+l.tokens,0),i=r-t.rateSamples[0].t;t.tokensPerSec=i>0?o*1e3/i:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),e.capability!=="files"&&(this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD))}onError(e){let t=this.active.get(e.id);if(this.active.delete(e.id),e.capability==="files"){e.statusCode!==404&&(this.lastErrorAt=Date.now());return}this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var _t={ArrayBuffer:n=>n,Uint8Array:n=>new Uint8Array(n),Int8Array:n=>new Int8Array(n),Uint8ClampedArray:n=>new Uint8ClampedArray(n),Int16Array:n=>new Int16Array(n),Uint16Array:n=>new Uint16Array(n),Int32Array:n=>new Int32Array(n),Uint32Array:n=>new Uint32Array(n),Float32Array:n=>new Float32Array(n),Float64Array:n=>new Float64Array(n),BigInt64Array:n=>new BigInt64Array(n),BigUint64Array:n=>new BigUint64Array(n),DataView:n=>new DataView(n)};function ve(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}function Tt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Me(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}async function A(n,e){if(n===void 0)return{$rt:"undef"};if(n===null)return null;switch(typeof n){case"string":case"boolean":return n;case"number":return Number.isNaN(n)?{$rt:"num",v:"NaN"}:n===1/0?{$rt:"num",v:"Infinity"}:n===-1/0?{$rt:"num",v:"-Infinity"}:Object.is(n,-0)?{$rt:"num",v:"-0"}:n;case"bigint":return{$rt:"bigint",v:n.toString()};case"function":case"symbol":throw new TypeError(`runapps sync: ${typeof n} values cannot be stored`)}if(n instanceof Date){let r=n.getTime();return{$rt:"date",v:Number.isNaN(r)?"invalid":r}}if(n instanceof RegExp)return{$rt:"re",s:n.source,f:n.flags};if(typeof Blob<"u"&&n instanceof Blob){if(!e)throw new TypeError("runapps sync: Blob values need a blob sink");let r=await e(n),s={$rt:"blob",r:r.ref,t:r.type,s:r.size},o=n;return typeof File<"u"&&n instanceof File&&(s.n=o.name,s.m=o.lastModified),s}if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n))};if(ArrayBuffer.isView(n)){let r=n.constructor.name;if(!(r in _t))throw new TypeError(`runapps sync: unsupported binary type ${r}`);let s=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return{$rt:"bin",c:r,v:ve(s)}}if(n instanceof Map){let r=[];for(let[s,o]of n)r.push([await A(s,e),await A(o,e)]);return{$rt:"map",v:r}}if(n instanceof Set){let r=[];for(let s of n)r.push(await A(s,e));return{$rt:"set",v:r}}if(Array.isArray(n)){let r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=await A(n[s],e);return r}if(Me(n)){let r=Object.prototype.hasOwnProperty.call(n,"$rt"),s={};for(let o of Object.keys(n))s[o]=await A(n[o],e);return r?{$rt:"obj",v:s}:s}let t={};for(let r of Object.keys(n))t[r]=await A(n[r],e);return t}async function _(n,e){if(n===null||typeof n!="object")return n;if(Array.isArray(n)){let o=new Array(n.length);for(let i=0;i<n.length;i++)o[i]=await _(n[i],e);return o}let t=n;if(typeof t.$rt=="string"){let o=t;switch(o.$rt){case"undef":return;case"date":return o.v==="invalid"?new Date(NaN):new Date(o.v);case"num":return o.v==="NaN"?NaN:o.v==="Infinity"?1/0:o.v==="-Infinity"?-1/0:-0;case"bigint":return BigInt(o.v);case"re":return new RegExp(o.s,o.f);case"bin":{let i=Tt(o.v),a=new ArrayBuffer(i.byteLength);new Uint8Array(a).set(i);let l=_t[o.c];if(!l)throw new TypeError(`runapps sync: unsupported binary type ${o.c}`);return l(a)}case"map":{let i=new Map;for(let a of o.v)i.set(await _(a[0],e),await _(a[1],e));return i}case"set":{let i=new Set;for(let a of o.v)i.add(await _(a,e));return i}case"blob":{if(!e)throw new TypeError("runapps sync: Blob values need a blob source");let i=await e({ref:o.r,type:o.t,size:o.s});return o.n!==void 0&&typeof File<"u"?new File([i],o.n,{type:o.t,lastModified:o.m??Date.now()}):i}case"obj":return _(o.v,e)}}let s={};for(let o of Object.keys(t))s[o]=await _(t[o],e);return s}function j(n){if(typeof n=="number"){if(Number.isNaN(n))throw new TypeError("runapps sync: NaN is not a valid key");return n}if(typeof n=="string")return n;if(n instanceof Date)return{$rt:"date",v:n.getTime()};if(n instanceof ArrayBuffer)return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n))};if(ArrayBuffer.isView(n))return{$rt:"bin",c:"ArrayBuffer",v:ve(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))};if(Array.isArray(n))return n.map(e=>j(e));throw new TypeError("runapps sync: invalid IndexedDB key")}function Z(n){if(typeof n=="number"||typeof n=="string")return n;if(Array.isArray(n))return n.map(Z);if(n&&typeof n=="object"){let e=n;if(e.$rt==="date")return new Date(e.v);if(e.$rt==="bin"){let t=Tt(e.v),r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),r}}throw new TypeError("runapps sync: invalid encoded key")}function Se(n){return JSON.stringify(j(n))}function xe(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function we(n,e){if(Object.is(n,e))return!0;if(n===null||e===null||typeof n!="object"||typeof e!="object")return!1;if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Object.is(n.getTime(),e.getTime());if(typeof Blob<"u"&&(n instanceof Blob||e instanceof Blob))return!1;if(ArrayBuffer.isView(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(e)||e instanceof ArrayBuffer){let s=a=>a instanceof ArrayBuffer?new Uint8Array(a):ArrayBuffer.isView(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):null,o=s(n),i=s(e);if(!o||!i||o.length!==i.length||n.constructor!==e.constructor)return!1;for(let a=0;a<o.length;a++)if(o[a]!==i[a])return!1;return!0}if(n instanceof Map||e instanceof Map){if(!(n instanceof Map&&e instanceof Map)||n.size!==e.size)return!1;for(let[s,o]of n)if(!e.has(s)||!we(o,e.get(s)))return!1;return!0}if(n instanceof Set||e instanceof Set){if(!(n instanceof Set&&e instanceof Set)||n.size!==e.size)return!1;for(let s of n)if(!e.has(s))return!1;return!0}if(Array.isArray(n)||Array.isArray(e)){if(!(Array.isArray(n)&&Array.isArray(e))||n.length!==e.length)return!1;for(let s=0;s<n.length;s++)if(!we(n[s],e[s]))return!1;return!0}let t=Object.keys(n),r=Object.keys(e);if(t.length!==r.length)return!1;for(let s of t)if(!Object.prototype.hasOwnProperty.call(e,s)||!we(n[s],e[s]))return!1;return!0}function Et(n,e){if(!Me(n)||!Me(e))return;let t=[];for(let r of new Set([...Object.keys(n),...Object.keys(e)])){let s=Object.prototype.hasOwnProperty.call(n,r),o=Object.prototype.hasOwnProperty.call(e,r);(s!==o||!we(n[r],e[r]))&&t.push(r)}return t}function Ct(n,e){if(e==null)return;let t=s=>{let o=n;if(s==="")return o;for(let i of s.split(".")){if(o===null||typeof o!="object")return;o=o[i]}return o};if(Array.isArray(e)){let s=e.map(t);return s.some(o=>o===void 0)?void 0:s}let r=t(e);return r===void 0?void 0:r}var It=60,Dt="__runapps_auth_v1__",Pt="__runjobs_auth_v1__",Rt="__runapps_signed_out_v1__",Bt="__runjobs_signed_out_v1__";function ee(n){return n?`${Dt}:${n}`:Dt}function ke(n){return n?`${Rt}:${n}`:Rt}function je(n){return n?`${Pt}:${n}`:Pt}function Ot(n){return n?`${Bt}:${n}`:Bt}var L=class{constructor(e={}){u(this,"origin");u(this,"hideBadge");u(this,"project");u(this,"events");u(this,"tracker");u(this,"badgePosition");u(this,"token",null);u(this,"expiresAt",0);u(this,"userInfo",null);u(this,"listeners",[]);u(this,"parentHandshake",null);u(this,"signingIn",!1);u(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new M,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}ownerId(){return this.tokenIsFresh()?this.userInfo?.id?this.userInfo.id:"t"+xe(this.token).toString(36):null}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:ee(this.project),signedOut:ke(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-It}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,r){this.token=e,this.expiresAt=t||this.nowSec()+3600,r&&(this.userInfo=r,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(o){console.warn("[runapps] onTokenChange handler threw",o)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem(ee(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem(ee(this.project));if(!e){if(e=localStorage.getItem(je(this.project)),!e)return;localStorage.setItem(ee(this.project),e),localStorage.removeItem(je(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-It){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ee(this.project)),localStorage.removeItem(je(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ke(this.project))==="1"||localStorage.getItem(Ot(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(ke(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(ke(this.project)),localStorage.removeItem(Ot(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let o=s.indexOf("=");o>=0&&(e[decodeURIComponent(s.slice(0,o))]=decodeURIComponent(s.slice(o+1).replace(/\+/g," ")))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let r;if(e.user)try{r=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,r);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let r=!1,s=[],o=()=>{r=!0,window.removeEventListener("message",i);for(let l of s)clearTimeout(l)},i=l=>{if(l.origin!==this.origin)return;let c=l.data;c&&(c.type==="runapps:token"||c.type==="runjobs:token")&&c.token&&(this.setToken(c.token,c.expires_at??0,c.user),o(),e())};window.addEventListener("message",i);let a=()=>{if(!r)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(l){o(),t(l)}};a();for(let l of[250,750,1500,3e3])s.push(setTimeout(a,l));s.push(setTimeout(()=>{r||(o(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=Dn({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function An(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let n=document.createElement("style");n.id="__runapps_kf__",n.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}@keyframes __runapps_sync_ping__ { 0% { transform: scale(1); opacity: 0.9; } 100% { transform: scale(2.1); opacity: 0; }}",(document.head??document.documentElement).appendChild(n)}function _n(n){let e=n.startsWith("top")?"top":"bottom",t=n.endsWith("right")?"right":"left",r=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${r};${s}`}}var Ut="__runapps_badge_pos__",Tn="__runjobs_badge_pos__",Mt=5,U=8;function En(){if(typeof document>"u")return null;let n=document.cookie.split(";").map(c=>c.trim()),e=Ut,t=n.find(c=>c.startsWith(e+"="));if(t||(e=Tn,t=n.find(c=>c.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),o=s[0],i=s[1];if(s.length!==2||o===void 0||i===void 0)return null;let a=Number.parseInt(o,10),l=Number.parseInt(i,10);return!Number.isFinite(a)||!Number.isFinite(l)?null:{x:a,y:l}}function Cn(n,e){if(typeof document>"u")return;let t=3600*24*365,r=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Ut}=${encodeURIComponent(`${Math.round(n)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${r}`}function jt(n,e,t,r){let s=typeof window<"u"?window.innerWidth:1024,o=typeof window<"u"?window.innerHeight:768,i=Math.max(U,s-t-U),a=Math.max(U,o-r-U);return{x:Math.min(Math.max(U,n),i),y:Math.min(Math.max(U,e),a)}}function In(n){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,r=n.left+n.width/2,o=n.top+n.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",i=r<e/2?"left:0;right:auto":"right:0;left:auto";return`${o};${i}`}function Dn(n){let{id:e,user:t,dashboardUrl:r,tracker:s,position:o,onSignOut:i}=n,a=_n(o),l=a.popover;An();let c=document.createElement("button");c.id=e,c.type="button",c.setAttribute("aria-label","RunApps activity status"),c.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:5px","border-radius:50%","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","-webkit-user-select:none","touch-action:none","-webkit-touch-callout:none","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),c.addEventListener("mouseenter",()=>{c.style.backgroundColor="rgba(30,30,40,0.7)",c.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="rgba(15,15,20,0.55)",c.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let p="http://www.w3.org/2000/svg",h=document.createElementNS(p,"svg");h.setAttribute("viewBox","0 0 26 26"),h.setAttribute("width","26"),h.setAttribute("height","26"),h.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let f=document.createElementNS(p,"circle");f.setAttribute("cx","13"),f.setAttribute("cy","13"),f.setAttribute("r","12"),f.setAttribute("fill","none"),f.setAttribute("stroke","rgba(255,255,255,0.08)"),f.setAttribute("stroke-width","1.5");let g=document.createElementNS(p,"circle");g.setAttribute("cx","13"),g.setAttribute("cy","13"),g.setAttribute("r","12"),g.setAttribute("fill","none"),g.setAttribute("stroke","#3b82f6"),g.setAttribute("stroke-width","2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("transform","rotate(-90 13 13)");let w=2*Math.PI*12;g.setAttribute("stroke-dasharray",String(w)),g.setAttribute("stroke-dashoffset",String(w)),h.appendChild(f),h.appendChild(g);let x=document.createElement("div");x.textContent=(t.name||"?").charAt(0).toUpperCase(),x.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let S=document.createElement("span");S.style.cssText=["position:absolute","bottom:-1px;right:-1px","width:7px;height:7px;border-radius:50%","background:rgba(255,255,255,0.2)","border:1.5px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","opacity:0","transition:background-color 150ms ease-out, box-shadow 200ms ease-out, opacity 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(h),d.appendChild(x),d.appendChild(S),c.appendChild(d);let y=null,k=!1,B=null,se=null,oe=null,De=()=>{se!==null&&(window.clearTimeout(se),se=null)},$=()=>{oe!==null&&(window.clearTimeout(oe),oe=null)},qe=()=>{$(),oe=window.setTimeout(()=>{B==="hover"&&q()},300)},Ve=m=>{if(De(),$(),k){m==="click"&&(B="click");return}y||(y=On(t,r,l,()=>{q(),i()}),y.addEventListener("mouseenter",$),y.addEventListener("mouseleave",()=>{B==="hover"&&qe()})),c.appendChild(y),k=!0,B=m,ae()},q=()=>{$(),k&&(y?.remove(),k=!1,B=null)};c.addEventListener("click",m=>{m.stopPropagation(),k?q():Ve("click")}),c.addEventListener("mouseenter",()=>{$(),De(),se=window.setTimeout(()=>{k||Ve("hover")},400)}),c.addEventListener("mouseleave",()=>{De(),B==="hover"&&qe()}),document.addEventListener("click",m=>{k&&!c.contains(m.target)&&q()});let Ge=0,He=0,Je=0,We=0,ie=!1,V=!1,Pe=!1,Re=(m,v)=>{c.style.left=`${m}px`,c.style.top=`${v}px`,c.style.right="auto",c.style.bottom="auto"},ze=()=>{let m=c.getBoundingClientRect();if(l=In({left:m.left,top:m.top,width:m.width,height:m.height}),y){y.style.top="",y.style.bottom="",y.style.left="",y.style.right="";for(let v of l.split(";")){let[E,J]=v.split(":");E&&J&&y.style.setProperty(E.trim(),J.trim())}}};c.addEventListener("pointerdown",m=>{if(m.button!==0)return;ie=!0,V=!1,Ge=m.clientX,He=m.clientY;let v=c.getBoundingClientRect();Je=v.left,We=v.top}),c.addEventListener("pointermove",m=>{if(!ie)return;let v=m.clientX-Ge,E=m.clientY-He;if(!V){if(Math.abs(v)<Mt&&Math.abs(E)<Mt)return;V=!0;try{c.setPointerCapture(m.pointerId)}catch{}c.style.cursor="grabbing",k&&q()}let J=c.getBoundingClientRect(),Ze=jt(Je+v,We+E,J.width,J.height);Re(Ze.x,Ze.y)});let Ye=m=>{if(!ie||(ie=!1,!V))return;V=!1,c.style.cursor="pointer";try{c.hasPointerCapture(m.pointerId)&&c.releasePointerCapture(m.pointerId)}catch{}let v=c.getBoundingClientRect();Cn(v.left,v.top),ze(),Pe=!0};c.addEventListener("pointerup",Ye),c.addEventListener("pointercancel",Ye),c.addEventListener("click",m=>{Pe&&(Pe=!1,m.stopPropagation(),m.preventDefault())},!0);let G=En();G&&(Re(G.x,G.y),requestAnimationFrame(()=>{let m=c.getBoundingClientRect(),v=jt(G.x,G.y,m.width,m.height);Re(v.x,v.y),ze()}));let Be=!1,H=null,Xe,Qe=()=>{if(Be=!1,!s){h.style.opacity="0",S.style.background="rgba(255,255,255,0.2)",S.style.opacity="0";return}let m=s.snapshot(),v=m.sync?.lastChangeAt;v&&v!==Xe&&(Xe=v,Rn(d,S)),Pn(h,g,w,m),Bn(S,m),k&&y&&Mn(y,m);let E=m.status!=="idle"||k;E&&H===null?H=window.setInterval(ae,160):!E&&H!==null&&(window.clearInterval(H),H=null)};function ae(){Be||(Be=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(Qe):setTimeout(Qe,0))}return s&&s.onChange(ae),ae(),c}function Pn(n,e,t,r){if(r.active.length===0){n.style.opacity="0";return}n.style.opacity="1";let s=r.active.reduce((o,i)=>i.tokensPerSec>o.tokensPerSec?i:o,r.active[0]);if(s.streaming&&s.tokensPerSec>0){let o=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-o))),e.setAttribute("stroke","#3b82f6")}else r.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}var Ue=0;function Rn(n,e){let t=document.createElement("span");t.style.cssText=["position:absolute;inset:0","border-radius:50%","border:2px solid #10b981","pointer-events:none","animation:__runapps_sync_ping__ 700ms ease-out forwards"].join(";"),t.addEventListener("animationend",()=>t.remove()),n.appendChild(t),setTimeout(()=>t.remove(),1e3),Ue=Date.now()+1200,e.style.opacity="1",e.style.background="#10b981",e.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",e.style.animation="",setTimeout(()=>{Date.now()>=Ue&&(e.style.background="rgba(255,255,255,0.2)",e.style.opacity="0",e.style.boxShadow="0 0 0 0 transparent")},1250)}function Bn(n,e){switch(n.style.opacity="1",e.status){case"idle":{let t=e.sync;Date.now()<Ue?(n.style.background="#10b981",n.style.boxShadow="0 0 0 2px rgba(16,185,129,0.35)",n.style.animation=""):t&&t.state==="syncing"?(n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite"):t&&(t.state==="offline"||t.state==="error")?(n.style.background="#f59e0b",n.style.boxShadow="0 0 0 2px rgba(245,158,11,0.3)",n.style.animation=""):(n.style.background="rgba(255,255,255,0.2)",n.style.opacity="0",n.style.boxShadow="0 0 0 0 transparent",n.style.animation="");break}case"active":n.style.background="#3b82f6",n.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",n.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":n.style.background="#ef4444",n.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",n.style.animation="";break}}function On(n,e,t,r){let s=document.createElement("div");s.style.cssText=["position:absolute",t,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),s.setAttribute("data-runapps-popover","1"),s.addEventListener("click",g=>g.stopPropagation());let o=document.createElement("div");o.style.cssText=["display:flex;align-items:center;gap:8px","margin-bottom:10px;padding-bottom:8px","border-bottom:1px solid rgba(255,255,255,0.08)"].join(";");let i=document.createElement("div");i.textContent=(n.name||"?").charAt(0).toUpperCase(),i.style.cssText=["width:24px;height:24px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff"].join(";");let a=document.createElement("div");a.textContent=n.name||"Signed in",a.title=n.name||"",a.style.cssText="font-size:12px;font-weight:500;color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";let l=document.createElement("div");l.textContent="Signed in with RunApps",l.style.cssText="font-size:10px;color:rgba(255,255,255,0.5)";let c=document.createElement("div");c.style.cssText="min-width:0",c.appendChild(a),c.appendChild(l),o.appendChild(i),o.appendChild(c),s.appendChild(o);let d=document.createElement("div");d.setAttribute("data-runapps-popover-content","1"),s.appendChild(d);let p=document.createElement("div");p.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let h=document.createElement("a");h.textContent="Open dashboard \u2192",h.href=e,h.target="_blank",h.rel="noopener noreferrer",h.style.cssText="color:#a78bfa;text-decoration:none",p.appendChild(h);let f=document.createElement("button");return f.type="button",f.textContent="Sign out",f.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),f.addEventListener("mouseenter",()=>{f.style.color="#f87171"}),f.addEventListener("mouseleave",()=>{f.style.color="rgba(255,255,255,0.55)"}),f.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),r()}),p.appendChild(f),s.appendChild(p),s}function Mn(n,e){let t=n.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let r=Date.now();t.appendChild(Un(e,r)),t.appendChild(Ln(e,r)),e.sync&&t.appendChild(jn(e.sync,r)),t.appendChild(Nn(e.session,r))}function jn(n,e){let t=document.createElement("div");t.style.marginBottom="10px";let r=n.lastSyncedAt?`synced ${Le(e-n.lastSyncedAt)}`:"\u2014";t.appendChild(Ae("Sync",r));let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0;font-size:10px";let o=document.createElement("span"),i=document.createElement("span");i.textContent="\u25CF ";let a={off:["Not signed in","rgba(255,255,255,0.4)"],idle:["Up to date","#10b981"],syncing:["Syncing\u2026","#3b82f6"],offline:["Offline","#f59e0b"],error:["Retrying","#f59e0b"]},[l,c]=a[n.state]??["","#fff"];i.style.color=c,o.style.color="#fff",o.appendChild(i),o.appendChild(document.createTextNode(l));let d=document.createElement("span");return d.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums",d.textContent=n.pending>0?`${n.pending} pending`:"",d.title=n.error??"",s.appendChild(o),s.appendChild(d),t.appendChild(s),t}function Un(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Ae("Active",n.active.length>0?`${n.active.length} in flight`:"\u2014")),n.active.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="No calls in flight.",t.appendChild(r),t}for(let r of n.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",o.textContent=r.model;let i=document.createElement("span");i.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-r.startedAt)/1e3).toFixed(1),l=r.tokensPerSec>0?` \xB7 ${Math.round(r.tokensPerSec)} tok/s`:"";i.textContent=`${a}s${l}`,s.appendChild(o),s.appendChild(i),t.appendChild(s)}return t}function Ln(n,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(Ae("Recent",n.recent.length>0?`last ${Math.min(n.recent.length,5)}`:"\u2014")),n.recent.length===0){let r=document.createElement("div");return r.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",r.textContent="Nothing yet this session.",t.appendChild(r),t}for(let r of n.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let i=document.createElement("span");i.textContent=r.ok?"\u2713 ":"\u2717 ",i.style.color=r.ok?"#10b981":"#ef4444",o.appendChild(i),o.appendChild(document.createTextNode(r.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let l=`${(r.latencyMs/1e3).toFixed(1)}s`,c=r.costUSD!==void 0?` \xB7 $${r.costUSD.toFixed(4)}`:"",d=` \xB7 ${Le(e-r.endedAt)}`;a.textContent=`${l}${c}${d}`,s.appendChild(o),s.appendChild(a),t.appendChild(s)}return t}function Nn(n,e){let t=document.createElement("div");t.appendChild(Ae("Session",Le(e-n.startedAt)));let r=document.createElement("div");r.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${n.totalCalls} call${n.totalCalls===1?"":"s"}`;let o=document.createElement("span");o.textContent=`$${n.totalCostUSD.toFixed(4)}`;let i=document.createElement("span");return i.textContent=n.errorCount>0?`${n.errorCount} error${n.errorCount===1?"":"s"}`:"0 errors",n.errorCount>0&&(i.style.color="#ef4444"),r.appendChild(s),r.appendChild(o),r.appendChild(i),t.appendChild(r),t}function Ae(n,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let r=document.createElement("span");r.textContent=n;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(r),t.appendChild(s),t}function Le(n){return n<1500?"just now":n<6e4?`${Math.round(n/1e3)}s ago`:n<36e5?`${Math.round(n/6e4)}m ago`:`${Math.round(n/36e5)}h ago`}var Lt=new WeakMap,Ne=new WeakMap,Ee=new Set,N=null;function _e(n){try{return typeof structuredClone=="function"?structuredClone(n):n}catch{return n}}function Fn(n){if(n===null||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Te(n,e,t){let r;if(e&&typeof IDBVersionChangeEvent=="function"?r=new IDBVersionChangeEvent(n,{oldVersion:e.oldVersion,newVersion:e.newVersion??null}):(r=new Event(n,{bubbles:!1,cancelable:n==="error"}),e&&Object.assign(r,e)),t)for(let s of["target","currentTarget","srcElement"])try{Object.defineProperty(r,s,{value:t,configurable:!0})}catch{}return r}var Ce=class{constructor(e,t,r){u(this,"readyState","pending");u(this,"result");u(this,"error",null);u(this,"transaction",null);u(this,"source",null);u(this,"listeners",new Map);u(this,"handlers",{success:null,error:null,blocked:null,upgradeneeded:null});e.addEventListener("upgradeneeded",s=>{let o=s;this.result=e.result,this.transaction=e.transaction,Ne.set(e.result,{name:t,subs:r}),this.dispatch(Te("upgradeneeded",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("blocked",s=>{let o=s;this.dispatch(Te("blocked",{oldVersion:o.oldVersion,newVersion:o.newVersion},this))}),e.addEventListener("error",()=>{this.error=e.error,this.readyState="done",this.transaction=null,this.dispatch(Te("error",void 0,this))}),e.addEventListener("success",()=>{let s=e.result;Ne.set(s,{name:t,subs:r}),this.transaction=null;let o=!1,i=()=>{o||(o=!0,this.result=s,this.readyState="done",this.dispatch(Te("success",void 0,this)))},a=[],l=0;for(let d of r)try{let p=d.opts.onOpen(s,t);p&&typeof p.then=="function"&&(a.push(p.catch(()=>{})),l=Math.max(l,d.opts.openTimeoutMs))}catch{}if(a.length===0){i();return}let c=setTimeout(i,l);Promise.all(a).then(()=>{clearTimeout(c),i()})})}addEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:o=>t.handleEvent(o),s=this.listeners.get(e);s||this.listeners.set(e,s=new Set),s.add(r),t.__rtFn=r}removeEventListener(e,t){if(!t)return;let r=typeof t=="function"?t:t.__rtFn;r&&this.listeners.get(e)?.delete(r)}dispatchEvent(e){return this.dispatch(e),!e.defaultPrevented}dispatch(e){let t=this.handlers[e.type];if(t)try{t.call(this,e)}catch(r){Fe(r)}for(let r of this.listeners.get(e.type)??[])try{r.call(this,e)}catch(s){Fe(s)}}get onsuccess(){return this.handlers.success??null}set onsuccess(e){this.handlers.success=e}get onerror(){return this.handlers.error??null}set onerror(e){this.handlers.error=e}get onblocked(){return this.handlers.blocked??null}set onblocked(e){this.handlers.blocked=e}get onupgradeneeded(){return this.handlers.upgradeneeded??null}set onupgradeneeded(e){this.handlers.upgradeneeded=e}};function Fe(n){setTimeout(()=>{throw n},0)}typeof IDBOpenDBRequest=="function"&&Object.setPrototypeOf(Ce.prototype,IDBOpenDBRequest.prototype);function Nt(n){let e=n.source;return typeof IDBIndex=="function"&&e instanceof IDBIndex?e.objectStore:e}function Ft(n,e){if(e.startsWith("__runapps"))return[];let t=[];for(let r of Ee)(r.factory===null||r.factory===n)&&r.opts.include(e)&&t.push(r);return t}function Kn(){let n=IDBFactory.prototype,e=IDBDatabase.prototype,t=IDBObjectStore.prototype,r=IDBCursor.prototype,s=N={open:n.open,deleteDatabase:n.deleteDatabase,transaction:e.transaction,put:t.put,add:t.add,get:t.get,delete:t.delete,clear:t.clear,getAllKeys:t.getAllKeys,cursorUpdate:r.update,cursorDelete:r.delete},o=i=>Lt.get(i.transaction)??null;n.open=function(i,a){let l=a===void 0?s.open.call(this,i):s.open.call(this,i,a),c=Ft(this,i);return c.length===0?l:new Ce(l,i,c)},n.deleteDatabase=function(i){for(let a of Ft(this,i))try{a.opts.onDeleteDatabase(i)}catch{}return s.deleteDatabase.call(this,i)},e.transaction=function(i,a,l){let c=l!==void 0?s.transaction.call(this,i,a,l):a!==void 0?s.transaction.call(this,i,a):s.transaction.call(this,i),d=Ne.get(this);if(d&&c.mode==="readwrite"){let p={db:d.name,subs:d.subs,ops:[]};Lt.set(c,p),c.addEventListener("complete",()=>{if(p.ops.length===0)return;let h=p.ops;p.ops=[];for(let f of p.subs){let g=h.filter(w=>!f.opts.excludeStore(p.db,w.store));if(g.length!==0)try{f.opts.onCommit(p.db,g)}catch(w){Fe(w)}}})}return c},t.put=function(i,a){let l=o(this),c=null;if(l&&Fn(i)){let p=a!==void 0?a:Ct(i,this.keyPath);if(p!==void 0)try{let h=s.get.call(this,p),f=c={value:void 0};h.addEventListener("success",()=>{f.value=h.result})}catch{c=null}}let d=a===void 0?s.put.call(this,i):s.put.call(this,i,a);if(l){let p=this.name,h=_e(i),f=c;d.addEventListener("success",()=>{l.ops.push({store:p,kind:"put",key:d.result,value:h,prior:f?.value})})}return d},t.add=function(i,a){let l=a===void 0?s.add.call(this,i):s.add.call(this,i,a),c=o(this);if(c){let d=this.name,p=_e(i);l.addEventListener("success",()=>{c.ops.push({store:d,kind:"put",key:l.result,value:p})})}return l},t.delete=function(i){let a=o(this);if(a){let l=this.name;if(typeof IDBKeyRange=="function"&&i instanceof IDBKeyRange){let c=s.getAllKeys.call(this,i);c.addEventListener("success",()=>{for(let d of c.result)a.ops.push({store:l,kind:"del",key:d})})}else a.ops.push({store:l,kind:"del",key:i})}return s.delete.call(this,i)},t.clear=function(){let i=o(this),a=s.clear.call(this);if(i){let l=this.name;a.addEventListener("success",()=>{i.ops.push({store:l,kind:"clear"})})}return a},r.update=function(i){let a=Nt(this),l=o(a),c=l?_e(this.value):void 0,d=s.cursorUpdate.call(this,i);if(l){let p=a.name,h=_e(i),f=this.primaryKey;d.addEventListener("success",()=>{l.ops.push({store:p,kind:"put",key:f,value:h,prior:c})})}return d},r.delete=function(){let i=Nt(this),a=o(i);return a&&a.ops.push({store:i.name,kind:"del",key:this.primaryKey}),s.cursorDelete.call(this)}}function $n(){if(!N)return;let n=N;IDBFactory.prototype.open=n.open,IDBFactory.prototype.deleteDatabase=n.deleteDatabase,IDBDatabase.prototype.transaction=n.transaction,IDBObjectStore.prototype.put=n.put,IDBObjectStore.prototype.add=n.add,IDBObjectStore.prototype.delete=n.delete,IDBObjectStore.prototype.clear=n.clear,IDBCursor.prototype.update=n.cursorUpdate,IDBCursor.prototype.delete=n.cursorDelete,N=null}function te(n){if(typeof indexedDB>"u"||typeof IDBFactory!="function"||typeof IDBDatabase!="function"||typeof IDBObjectStore!="function"||typeof IDBCursor!="function")return null;N||Kn();let e=N,t={opts:n,factory:n.factory??indexedDB};Ee.add(t);let r=t.factory;return{originalOpen:(s,o)=>o===void 0?e.open.call(r,s):e.open.call(r,s,o),uninstall(){Ee.delete(t),Ee.size===0&&$n()}}}var Kt="__runapps_sync__";function F(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error??new Error("IndexedDB request failed"))})}function D(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onabort=()=>t(n.error??new Error("IndexedDB transaction aborted")),n.onerror=()=>t(n.error??new Error("IndexedDB transaction failed"))})}var ne=class{constructor(e){u(this,"open",e);u(this,"dbPromise",null)}db(){return this.dbPromise||(this.dbPromise=new Promise((e,t)=>{let r=this.open(Kt,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains("ops")||s.createObjectStore("ops",{keyPath:"id",autoIncrement:!0}).createIndex("store",["db","store"],{unique:!1}),s.objectStoreNames.contains("meta")||s.createObjectStore("meta")},r.onsuccess=()=>{let s=r.result;s.onversionchange=()=>{s.close(),this.dbPromise=null},e(s)},r.onerror=()=>t(r.error??new Error("cannot open sync log")),r.onblocked=()=>t(new Error("sync log open blocked"))}),this.dbPromise.catch(()=>{this.dbPromise=null})),this.dbPromise}async append(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.add(o);await D(r)}async pending(){let t=(await this.db()).transaction("ops","readonly");return await F(t.objectStore("ops").getAll())}async pendingCount(){let t=(await this.db()).transaction("ops","readonly");return F(t.objectStore("ops").count())}async remove(e){if(e.length===0)return;let r=(await this.db()).transaction("ops","readwrite"),s=r.objectStore("ops");for(let o of e)s.delete(o);await D(r)}async clearOps(){let t=(await this.db()).transaction("ops","readwrite");t.objectStore("ops").clear(),await D(t)}async getMeta(e){let r=(await this.db()).transaction("meta","readonly");return await F(r.objectStore("meta").get(e))}async setMeta(e){let r=(await this.db()).transaction("meta","readwrite"),s=r.objectStore("meta");for(let o of Object.keys(e))e[o]===void 0?s.delete(o):s.put(e[o],o);await D(r)}async metaWithPrefix(e){let s=(await this.db()).transaction("meta","readonly").objectStore("meta"),o=IDBKeyRange.bound(e,e+"\uFFFF"),i=await F(s.getAllKeys(o)),a=await F(s.getAll(o)),l=new Map;return i.forEach((c,d)=>l.set(c,a[d])),l}async clearAll(){let t=(await this.db()).transaction(["ops","meta"],"readwrite");t.objectStore("ops").clear(),t.objectStore("meta").clear(),await D(t)}close(){this.dbPromise?.then(e=>e.close()).catch(()=>{}),this.dbPromise=null}};function $t(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&!("$rt"in n)}function qn(n,e){return JSON.stringify(n)===JSON.stringify(e)}function Vn(n,e,t){if(!n)return e;if(e.d||n.d||!$t(n.v)||!$t(e.v))return e.t>=n.t?e:n;let r=n.f??{},s=t?new Set(t):null,o={},i={},a=new Set([...Object.keys(n.v),...Object.keys(e.v)]);for(let l of a){let c=l in n.v,d=l in e.v,p=r[l]??n.t;if(s?!s.has(l):c&&d&&qn(n.v[l],e.v[l])){c&&(o[l]=n.v[l],r[l]!==void 0&&(i[l]=r[l]));continue}e.t>=p?d&&(o[l]=e.v[l],i[l]=e.t):c&&(o[l]=n.v[l],i[l]=p)}return{k:e.k,v:o,t:Math.max(n.t,e.t),f:i}}var Gn=720*3600*1e3,Hn=1e4,Jn=5e3,Wn=5*6e4,$e=class{constructor(){u(this,"last",0);u(this,"offset",0)}now(){let e=Date.now()+this.offset;return this.last=e>this.last?e:this.last+1,this.last}observe(e,t,r){let s=(t+r)/2,o=e-s;Math.abs(o-this.offset)>2e3&&(this.offset=o)}};function Ke(n){return encodeURIComponent(n).replace(/%2F/gi,"%2F")}var P=class{constructor(e,t={}){u(this,"deps",e);u(this,"options");u(this,"log");u(this,"hook");u(this,"clock",new $e);u(this,"schemas",new Map);u(this,"etags",new Map);u(this,"conns",new Map);u(this,"state",{state:"off",pending:0});u(this,"paused",!1);u(this,"disposed",!1);u(this,"leader",!0);u(this,"pushTimer",null);u(this,"pushDeadline",0);u(this,"pullTimer",null);u(this,"backoffMs",0);u(this,"backoffUntil",0);u(this,"chain",Promise.resolve());u(this,"cleanup",[]);u(this,"channel",null);u(this,"metaLoaded",null);u(this,"logChain",Promise.resolve());u(this,"moved",!1);this.options={databases:t.databases??[],exclude:t.exclude??[],shards:Math.max(1,Math.min(64,t.shards??8)),pushDelayMs:t.pushDelayMs??2500,pullIntervalMs:t.pullIntervalMs??6e4,openTimeoutMs:t.openTimeoutMs??5e3,prefix:(t.prefix??"db").replace(/^\/+|\/+$/g,"")};let r=new Set(this.options.exclude.filter(i=>!i.includes("/"))),s=new Set(this.options.exclude.filter(i=>i.includes("/"))),o=new Set(this.options.databases);this.hook=te({include:i=>(o.size===0||o.has(i))&&!r.has(i),excludeStore:(i,a)=>s.has(i+"/"+a),onCommit:(i,a)=>this.onCommit(i,a),onOpen:(i,a)=>this.onOpen(i,a),onDeleteDatabase:i=>this.onDeleteDatabase(i),openTimeoutMs:this.options.openTimeoutMs,factory:e.factory}),this.log=new ne((i,a)=>this.hook?this.hook.originalOpen(i,a):indexedDB.open(i,a)),typeof window<"u"&&this.attachBrowserTriggers(),this.cleanup.push(e.onAuthChange(()=>this.schedule("auth"))),this.refreshPending(),this.schedule("start")}status(){return{...this.state}}now(){return this.leader?this.enqueue(()=>this.sync()):(this.post({type:"sync:request"}),Promise.resolve())}post(e){try{this.channel?.postMessage(e)}catch{}}pause(){this.paused=!0}resume(){this.paused=!1,this.schedule("resume")}dispose(){this.disposed=!0;for(let e of this.cleanup)e();this.pushTimer&&clearTimeout(this.pushTimer),this.pullTimer&&clearInterval(this.pullTimer),this.channel?.close();for(let e of this.conns.values())e.then(t=>t.close()).catch(()=>{});this.conns.clear(),this.log.close(),this.hook?.uninstall()}onCommit(e,t){let r=[];for(let o of t){let i=this.clock.now();o.kind==="clear"?r.push({db:e,store:o.store,kind:"clear",kid:"",ts:i}):o.kind==="del"?r.push({db:e,store:o.store,kind:"del",kid:Se(o.key),key:j(o.key),ts:i}):r.push({db:e,store:o.store,kind:"put",kid:Se(o.key),key:j(o.key),value:o.value,changed:o.prior===void 0?void 0:Et(o.prior,o.value),ts:i})}this.enqueueLog(r);let s=new Map;for(let o of t){let i=s.get(o.store);i||s.set(o.store,i={keys:[],cleared:!1}),o.kind==="clear"?(i.cleared=!0,i.keys=[]):i.cleared||i.keys.push(o.key)}for(let[o,i]of s){let a={db:e,store:o,keys:i.keys,cleared:i.cleared,source:"tab"};this.post({type:"db:change",change:a})}}enqueueLog(e){this.logChain=this.logChain.then(()=>this.log.append(e)).then(()=>this.refreshPending()).then(()=>{this.leader||this.post({type:"sync:request"})}).catch(t=>this.fail(t)),this.schedulePush()}async onOpen(e,t){let r=new Map,s=Array.from(e.objectStoreNames);if(s.length>0){let o=e.transaction(s,"readonly");for(let i of s){let a=o.objectStore(i);r.set(i,{keyPath:a.keyPath,autoIncrement:a.autoIncrement}),a.autoIncrement&&typeof console<"u"&&console.warn(`[runapps sync] "${t}/${i}" uses autoIncrement keys: records created on two devices while offline can get the same key, and only one survives. Prefer client-generated ids (e.g. crypto.randomUUID()).`)}}this.schemas.set(t,r),this.log.setMeta({["schema:"+t]:Object.fromEntries(r)}).catch(()=>{}),!(!this.deps.userId()||this.paused||!this.leader)&&await this.enqueue(()=>this.pullDatabase(t)).catch(()=>{})}onDeleteDatabase(e){let t=this.schemas.get(e),r=t?Array.from(t.keys()):[];this.schemas.delete(e),this.conns.get(e)?.then(o=>o.close()).catch(()=>{}),this.conns.delete(e);let s=this.clock.now();this.enqueueLog(r.map(o=>({db:e,store:o,kind:"clear",kid:"",ts:s})))}attachBrowserTriggers(){let e=(r,s,o)=>{r.addEventListener(s,o),this.cleanup.push(()=>r.removeEventListener(s,o))};e(window,"online",()=>{this.backoffUntil=0,this.schedule("online")}),e(window,"focus",()=>{this.schedule("focus")}),typeof document<"u"&&e(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.schedule("visible"),this.updatePullTimer()}),this.updatePullTimer(),typeof BroadcastChannel=="function"&&(this.channel=new BroadcastChannel("__runapps_db_change__"),this.channel.onmessage=r=>{let s=r.data;s&&(s.type==="db:change"?this.deps.events.emit("db:change",s.change):s.type==="sync:state"?this.leader||(this.state={...s.state},this.deps.events.emit("sync:state",{...s.state})):s.type==="sync:request"?this.leader&&(this.post({type:"sync:state",state:{...this.state}}),this.schedule("peer")):s.source==="remote"&&this.deps.events.emit("db:change",s))});let t=navigator.locks;t&&typeof t.request=="function"&&(this.leader=!1,this.post({type:"sync:request"}),t.request("__runapps_sync__",()=>(this.leader=!0,this.schedule("leader"),new Promise(()=>{}))).catch(()=>{this.leader=!0}))}updatePullTimer(){let e=typeof document>"u"||document.visibilityState!=="hidden";e&&!this.pullTimer&&this.options.pullIntervalMs>0?(this.pullTimer=setInterval(()=>{this.schedule("interval")},this.options.pullIntervalMs),this.pullTimer.unref?.()):!e&&this.pullTimer&&(clearInterval(this.pullTimer),this.pullTimer=null)}schedulePush(){if(this.disposed)return;let e=Date.now();this.pushDeadline||(this.pushDeadline=e+Hn);let t=Math.max(0,Math.min(this.options.pushDelayMs,this.pushDeadline-e));this.pushTimer&&clearTimeout(this.pushTimer),this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.pushDeadline=0,this.schedule("push")},t),this.pushTimer.unref?.()}schedule(e){return this.disposed||this.paused||!this.leader?Promise.resolve():this.deps.userId()?Date.now()<this.backoffUntil?Promise.resolve():this.enqueue(()=>this.sync()):(this.setState({state:"off"}),Promise.resolve())}enqueue(e){let t=this.chain.then(e,e);return this.chain=t.catch(()=>{}),t}setState(e){let t={...this.state,...e};e.state&&e.state!=="error"&&delete t.error;let r=t.state!==this.state.state||t.pending!==this.state.pending||t.lastSyncedAt!==this.state.lastSyncedAt||t.lastChangeAt!==this.state.lastChangeAt||t.error!==this.state.error;this.state=t,r&&(this.deps.events.emit("sync:state",{...t}),this.leader&&this.post({type:"sync:state",state:{...t}}))}async refreshPending(){try{let e=await this.log.pendingCount();this.setState({pending:e})}catch{}}fail(e){let t=typeof navigator<"u"&&navigator.onLine===!1,r=e instanceof Error?e.message:String(e);this.backoffMs=this.backoffMs?Math.min(this.backoffMs*2,Wn):Jn,this.backoffUntil=Date.now()+this.backoffMs,this.setState({state:t?"offline":"error",error:r}),!t&&typeof console<"u"&&console.warn("[runapps sync]",r)}async loadMeta(){return this.metaLoaded||(this.metaLoaded=(async()=>{for(let[e,t]of await this.log.metaWithPrefix("etag:"))this.etags.set(e.slice(5),t);for(let[e,t]of await this.log.metaWithPrefix("schema:")){let r=e.slice(7);this.schemas.has(r)||this.schemas.set(r,new Map(Object.entries(t)))}})(),this.metaLoaded.catch(()=>{this.metaLoaded=null})),this.metaLoaded}async ensureOwner(e){let t=await this.log.getMeta("owner");if(t!==e){if(t!==void 0){for(let[r,s]of this.schemas)for(let o of s.keys())this.storeExcluded(r,o)||(await this.withStore(r,o,"readwrite",i=>{i.clear()}).catch(()=>{}),this.emitChange({db:r,store:o,keys:[],cleared:!0,source:"remote"}));await this.log.clearAll(),this.etags.clear(),this.metaLoaded=null,await this.loadMeta()}await this.log.setMeta({owner:e})}}async sync(){if(this.disposed||this.paused||!this.leader)return;let e=this.deps.userId();if(!e){this.setState({state:"off"});return}this.setState({state:"syncing"}),this.moved=!1;try{await this.loadMeta(),await this.ensureOwner(e),await this.logChain,await this.push(),await this.pull(),this.backoffMs=0,this.backoffUntil=0,await this.refreshPending();let t=Date.now();this.setState({state:"idle",lastSyncedAt:t,...this.moved?{lastChangeAt:t}:{}})}catch(t){await this.refreshPending(),this.fail(t)}}storeExcluded(e,t){return this.options.exclude.includes(e+"/"+t)||this.options.exclude.includes(e)}shardPath(e,t,r){return`${this.options.prefix}/${Ke(e)}/${Ke(t)}/${r}.json`}shardOf(e){return xe(e)%this.options.shards}async readShard(e){let t=Date.now(),r=await this.deps.remote.getJSON(e);if(r.status==="ok"){r.serverTime&&this.clock.observe(r.serverTime,t,Date.now());let s=r.value,o={v:1,cleared:s?.cleared??0,r:s?.r??{}};return this.etags.set(e,r.etag),{shard:o,etag:r.etag}}return this.etags.delete(e),{shard:{v:1,cleared:0,r:{}}}}async push(){let e=await this.log.pending();if(e.length===0)return;let t=new Map;for(let o of e){let i=o.db+"\0"+o.store,a=t.get(i);a||t.set(i,a=[]),a.push(o)}let r=[],s={};for(let[,o]of t){let i=o[0].db,a=o[0].store;if(this.storeExcluded(i,a)){for(let f of o)f.id!==void 0&&r.push(f.id);continue}let l=0,c=-1;o.forEach((f,g)=>{f.kind==="clear"&&(l=Math.max(l,f.ts),c=g)});let d=o.slice(c+1),p=new Map;for(let f of d){let g=this.shardOf(f.kid),w=p.get(g);w||p.set(g,w=[]),w.push(f)}let h=l>0?Array.from({length:this.options.shards},(f,g)=>g):Array.from(p.keys());for(let f of h){let g=this.shardPath(i,a,f),w=p.get(f)??[],x=await Promise.all(w.map(y=>this.encodeOp(y))),S=await this.writeShard(g,l,x);s["etag:"+g]=S}for(let f of o)f.id!==void 0&&r.push(f.id)}await this.log.setMeta(s),await this.log.remove(r),r.length>0&&(this.moved=!0),await this.refreshPending()}async encodeOp(e){if(e.kind==="del")return{kid:e.kid,rec:{k:e.key,v:null,t:e.ts,d:1}};let t=await A(e.value,r=>this.storeBlob(r));return{kid:e.kid,rec:{k:e.key,v:t,t:e.ts},changed:e.changed}}async writeShard(e,t,r){for(let s=0;s<5;s++){let{shard:o,etag:i}=await this.readShard(e),a=this.clock.now();if(t>o.cleared){o.cleared=t;for(let d of Object.keys(o.r))o.r[d].t<=t&&delete o.r[d]}for(let{kid:d,rec:p,changed:h}of r)p.t<=o.cleared||(o.r[d]=Vn(o.r[d],p,h));for(let d of Object.keys(o.r)){let p=o.r[d];p.d&&a-p.t>Gn&&delete o.r[d]}let l=Date.now(),c=await this.deps.remote.putJSON(e,o,i?{ifMatch:i}:{ifNoneMatch:!0});if(c.status==="ok")return c.serverTime&&this.clock.observe(c.serverTime,l,Date.now()),this.etags.set(e,c.etag),c.etag;this.etags.delete(e)}throw new Error(`could not write ${e}: too many concurrent writers`)}async storeBlob(e){let t=new Uint8Array(await e.arrayBuffer()),r=await crypto.subtle.digest("SHA-256",t),s=Array.from(new Uint8Array(r),i=>i.toString(16).padStart(2,"0")).join(""),o=`${this.options.prefix}/_blobs/${s}`;return await this.deps.remote.putBlob(o,e),{ref:o,type:e.type,size:e.size}}async pull(){let e=await this.deps.remote.list(this.options.prefix+"/");await this.applyListing(e)}async pullDatabase(e){if(!this.deps.userId())return;await this.loadMeta();let t=await this.deps.remote.list(`${this.options.prefix}/${Ke(e)}/`);await this.applyListing(t)}async applyListing(e){let t=new RegExp("^"+this.options.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/([^/]+)/([^/]+)/(\\d+)\\.json$"),r=await this.log.pending(),s={};for(let o of e){let i=t.exec(o.path);if(!i)continue;let a=decodeURIComponent(i[1]),l=decodeURIComponent(i[2]);if(this.etags.get(o.path)===o.etag||this.storeExcluded(a,l))continue;let c=this.schemas.get(a);if(!c||!c.has(l))continue;let d=await this.deps.remote.getJSON(o.path,this.etags.get(o.path));if(d.status==="unchanged")continue;if(d.status==="missing"){this.etags.delete(o.path),s["etag:"+o.path]=void 0;continue}let p=d.value,h={v:1,cleared:p?.cleared??0,r:p?.r??{}};await this.applyShard(a,l,h,r),this.etags.set(o.path,d.etag),s["etag:"+o.path]=d.etag}Object.keys(s).length&&await this.log.setMeta(s)}async applyShard(e,t,r,s){let o=new Map,i=0;for(let h of s)h.db!==e||h.store!==t||(h.kind==="clear"?i=Math.max(i,h.ts):o.set(h.kid,Math.max(o.get(h.kid)??0,h.ts)));let a=`cleared:${e}/${t}`,l=await this.log.getMeta(a)??0,c=this.schemas.get(e)?.get(t),d=[],p=!1;await this.withStore(e,t,"readwrite",h=>{r.cleared>l&&r.cleared>i&&(h.clear(),p=!0);for(let f of Object.keys(r.r)){let g=r.r[f];if((o.get(f)??0)>=g.t||g.t<=i)continue;let w=Z(g.k);if(d.push(w),g.d)h.delete(w);else{let x=g._decoded;c&&c.keyPath!==null?h.put(x):h.put(x,w)}}if(p)for(let f of s)f.db!==e||f.store!==t||f.kind!=="put"||f.ts<=r.cleared||(c&&c.keyPath!==null?h.put(f.value):h.put(f.value,Z(f.key)))},async()=>{for(let h of Object.keys(r.r)){let f=r.r[h];f.d||(o.get(h)??0)>=f.t||f.t<=i||(f._decoded=await _(f.v,g=>this.deps.remote.getBlob(g.ref)))}}),r.cleared>l&&await this.log.setMeta({[a]:r.cleared}),(d.length>0||p)&&this.emitChange({db:e,store:t,keys:d,cleared:p,source:"remote"})}emitChange(e){this.moved=!0,this.deps.events.emit("db:change",e);try{this.post(e)}catch{}}conn(e){let t=this.conns.get(e);return t||(t=new Promise((r,s)=>{let i=(this.hook?this.hook.originalOpen:a=>indexedDB.open(a))(e);i.onsuccess=()=>{let a=i.result;a.onversionchange=()=>{a.close(),this.conns.delete(e)},r(a)},i.onerror=()=>s(i.error??new Error(`cannot open ${e}`)),i.onblocked=()=>s(new Error(`open of ${e} blocked`))}),this.conns.set(e,t),t.catch(()=>this.conns.delete(e))),t}async withStore(e,t,r,s,o){o&&await o();let i=await this.conn(e);if(!i.objectStoreNames.contains(t))return;let a=i.transaction(t,r);s(a.objectStore(t)),await D(a)}};var R=class{constructor(e){u(this,"files",e)}async list(e){let t=[],r;do{let s=await this.files.list({prefix:e,limit:1e3,...r?{cursor:r}:{}});for(let o of s.files)o.etag&&t.push({path:o.path,etag:o.etag});r=s.next_cursor}while(r);return t}async getJSON(e,t){let r=await this.files.readJSON(e,t?{ifNoneMatch:t}:void 0);return r.notModified?{status:"unchanged"}:r.value===void 0?{status:"missing"}:{status:"ok",value:r.value,etag:r.etag??""}}async putJSON(e,t,r){try{let s=await this.files.put(e,JSON.stringify(t),{contentType:"application/json",...r.ifMatch?{ifMatch:r.ifMatch}:{},...r.ifNoneMatch?{ifNoneMatch:!0}:{}});return{status:"ok",etag:s.etag??"",serverTime:s.last_modified?Date.parse(s.last_modified):void 0}}catch(s){let o=s.statusCode;if(o===412||o===409)return{status:"conflict"};throw s}}async putBlob(e,t){try{await this.files.put(e,t,{contentType:t.type||"application/octet-stream",ifNoneMatch:!0})}catch(r){if(r.statusCode!==409)throw r}}getBlob(e){return this.files.get(e)}};var zn="https://www.runapps.ai",K=class{constructor(e={}){u(this,"chat");u(this,"models");u(this,"image");u(this,"audio");u(this,"video");u(this,"computer");u(this,"files");u(this,"embeddings");u(this,"realtime");u(this,"auth",null);u(this,"sync",null);u(this,"events",new O);let t=e.authProvider??(!e.apiKey&&!e.apiKeyResolver&&typeof window<"u"?"runapps":"static"),r=e.apiKeyResolver,s=e.baseURL,o;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let l=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,c=new L({origin:s,hideBadge:!l,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=c,r=c.getToken,o=()=>c.invalidate()}if(!e.apiKey&&!r)throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");let i=new le({baseURL:s??zn,...e.apiKey!==void 0&&{apiKey:e.apiKey},...r!==void 0&&{apiKeyResolver:r},...o!==void 0&&{onUnauthorized:o},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new ue(i,this.events),this.models=new de(i),this.image=new pe(i,this.events),this.audio=new fe(i,this.events),this.video=new me(i,this.events),this.computer=new ye(i,this.events),this.files=new Q(i,e.project,this.events),this.embeddings=new be(i,this.events),this.realtime=new ge(i,this.events);let a=e.sync??this.auth!==null;if(a&&typeof indexedDB<"u"&&this.auth){let l=this.auth,c=new P({remote:new R(new Q(i,e.project)),events:this.events,userId:()=>l.ownerId(),onAuthChange:d=>l.onTokenChange(()=>d())},typeof a=="object"?a:{});this.sync=c}}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function qt(n){return n?n.map(e=>Array.isArray(e)?{fields:e}:e):[]}function re(n){let e=n.options;return!e||typeof e!="object"?null:e}function Vt(n,e){let r=re(n)?.inputs?.[e];return r?r.presence!=="forbidden":!1}function Gt(n,e){return re(n)?.inputs?.[e]?.presence==="required"}function Ht(n,e){return re(n)?.inputs?.[e]?.enum??null}function zt(n,e={}){if(!n)return[];let t=[];if(n.inputs)for(let[r,s]of Object.entries(n.inputs)){let o=r in e,i=e[r];o&&!T(i)?t.push(...Yt(r,s,i)):o&&s.min_items!==void 0&&Array.isArray(i)&&i.length<s.min_items&&t.push({field:r,reason:`at least ${s.min_items} items`}),t.push(...Xt(r,s,i,o))}for(let r of n.constraints??[])t.push(...Yn(r,e));return t}function Yt(n,e,t){let r=[];if(!Xn(e.type,t))return r.push({field:n,reason:`expected type ${e.type}, got ${Ie(t)}`}),r;if(e.enum&&e.enum.length>0&&!Qn(t,e.enum)&&r.push({field:n,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=Qt(t);s!==null&&(e.min!==void 0&&s<e.min&&r.push({field:n,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&r.push({field:n,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&r.push({field:n,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&r.push({field:n,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,o)=>{if(typeof s!="object"||s===null||Array.isArray(s)){r.push({field:`${n}[${o}]`,reason:`expected object, got ${Ie(s)}`});return}r.push(...Jt(`${n}[${o}]`,e.fields,s))}):r.push({field:n,reason:`expected array of objects, got ${Ie(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?r.push({field:n,reason:`expected object, got ${Ie(t)}`}):r.push(...Jt(n,e.fields,t))),r}function Jt(n,e,t){let r=[];for(let[s,o]of Object.entries(e)){let i=`${n}.${s}`,a=t[s],l=s in t;l&&!T(a)&&r.push(...Yt(i,o,a)),r.push(...Xt(i,o,a,l))}return r}function Xt(n,e,t,r){let s=e.presence??"optional";return s==="required"&&(!r||T(t))?[{field:n,reason:"required"}]:s==="forbidden"&&r&&!T(t)?[{field:n,reason:"must not be set for this model"}]:[]}function Yn(n,e){switch(n.kind){case"any_of_required":{let t=n.fields??[];return t.some(s=>s in e&&!T(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=n.fields??[],r=t.filter(s=>s in e&&!T(e[s]));return r.length>1?[{field:r.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${r.join(", ")})`}]:[]}case"group_mutex":{let t=qt(n.groups),r=[],s=[];for(let o of t){let i=o.fields.filter(a=>a in e&&!T(e[a]));i.length>0&&(r.push(o),s.push(...i))}if(r.length>1){let o=t.map(i=>`[${i.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${o} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=n.when;if(!t)return[];if(!(t in e&&!T(e[t])))return[];let s=(n.then??[]).filter(o=>!(o in e)||T(e[o]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=n.fields?.[0];if(!t)return[];let r=e[t];if(typeof r!="string"||r==="")return[];let s=er(r);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${r}"`}];let[o,i]=s,a=o*i,l=[];return n.min!==void 0&&a<n.min&&l.push({field:t,reason:`image too small: ${o}x${i} = ${a} pixels, minimum ${n.min}`}),n.max!==void 0&&a>n.max&&l.push({field:t,reason:`image too large: ${o}x${i} = ${a} pixels, maximum ${n.max}`}),l}}return[]}function Xn(n,e){switch(n){case"string":return typeof e=="string";case"int":case"float":return Qt(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&Wt(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&Wt(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function Ie(n){return n===null?"null":Array.isArray(n)?"array":typeof n}function Qt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Wt(n){return n.startsWith("http://")||n.startsWith("https://")||n.startsWith("data:")}function T(n){return n==null?!0:typeof n=="string"?n==="":Array.isArray(n)?n.length===0:!1}function Qn(n,e){for(let t of e)if(Zn(n,t))return!0;return!1}function Zn(n,e){return n===e}function er(n){for(let e of["x","X","*","\xD7"]){let t=n.indexOf(e);if(t<=0)continue;let r=parseInt(n.slice(0,t).trim(),10),s=parseInt(n.slice(t+e.length).trim(),10);if(Number.isFinite(r)&&Number.isFinite(s)&&r>0&&s>0)return[r,s]}return null}return on(tr);})();
|
|
4
4
|
RunApps = Object.assign(RunApps.Client, RunApps); var RunJobs = RunApps;
|
|
5
5
|
//# sourceMappingURL=sdk.umd.js.map
|