UNPKG

agent-device

Version:

Open source device layer for AI coding agents: a CLI, MCP server, and typed Node.js API to control mobile, web, TV, and desktop apps on devices and simulators, locally or in the cloud.

7 lines (6 loc) • 42.2 kB
import{a as e}from"./rolldown-runtime.js";import{_ as t,a as n,c as r,d as i,f as a,g as o,h as s,l as c,m as l,p as u,s as d,v as f}from"./destination-tunnel-dialer.js";import{EventEmitter as p,once as m}from"events";import h from"fs";import*as g from"zlib";import{Readable as _}from"stream";import*as v from"net";import y from"os";import b from"path";import*as x from"crypto";import S from"crypto";import{pipeline as C}from"stream/promises";function w(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const T=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var E=class extends Error{},D=class e extends E{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new k({message:r,cause:T(n)});let a=n;return t===400?new j(t,a,r,i):t===401?new M(t,a,r,i):t===403?new N(t,a,r,i):t===404?new P(t,a,r,i):t===409?new F(t,a,r,i):t===422?new I(t,a,r,i):t===429?new L(t,a,r,i):t>=500?new R(t,a,r,i):new e(t,a,r,i)}},O=class extends D{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},k=class extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},A=class extends k{constructor({message:e}={}){super({message:e??`Request timed out.`})}},j=class extends D{},M=class extends D{},N=class extends D{},P=class extends D{},F=class extends D{},I=class extends D{},L=class extends D{},R=class extends D{};async function ee(e,t,n,r){for(let i=0;i<=3;i++){let a=await f.fetch(e,{method:`GET`,headers:{Authorization:`Bearer ${t}`}});if(!a.ok){let e=await a.text();if(a.status>=500&&a.status<600&&i<3)continue;throw Error(`Download failed: ${a.status} ${e}`)}if(!a.body)throw Error(`Download failed: response body is missing`);await h.promises.mkdir(b.dirname(n),{recursive:!0});let o=_.fromWeb(a.body);if(r){let e=Number(a.headers.get(`content-length`)??0),t=0;o.on(`data`,n=>{t+=n.length,r(t,e)})}await C(o,h.createWriteStream(n));return}}function z(e,t){return async(n,r)=>{try{return await e(n,r)}catch(e){throw t(e),e}}}function B(e,t,n,r){let i=`${e} failed: ${t}${n?` ${n}`:``}`;return t===404?new P(404,{message:i},void 0,r):Object.assign(Error(i),{status:t,body:n})}function te(e,t){return e instanceof Error&&e.status===t}const V={healthyConnectionMs:15e3,giveUpAfterMs:3e5};var H=class extends Error{},U=class extends Error{},W=class{constructor(){this.dataListeners=[],this.closeListeners=[],this.closed=!1}on(e,t){return e===`data`?this.dataListeners.push(t):e===`close`&&this.closeListeners.push(t),this}emit(e,t){if(e===`data`&&typeof t==`string`)for(let e of this.dataListeners)e(t);else if(e===`close`&&!this.closed){this.closed=!0;for(let e of this.closeListeners)e()}}};function G(e){let n=null,{eventsUrl:r,signal:i}=e,a=new Promise((a,o)=>{if(i?.aborted){o(e.abortError());return}let s=!1,c=-1,l=0,u=null,d=0,p=0,m=0,h=!1,g=!1,_,v=()=>{u?.close(),i?.removeEventListener(`abort`,x)},y=e=>{s||(s=!0,v(),a(e))},b=e=>{s||(s=!0,v(),o(e))},x=()=>b(e.abortError());u=t({url:r,fetch:z(async(t,n)=>{let i=await f.fetch(t,n);return i.status===204?b(new U(`event stream to ${r} was closed by the server (HTTP 204)`)):e.failOnClientError&&i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?b(B(`GET exec logs`,i.status,await i.text(),i.headers)):i.ok||(_=Error(`server answered HTTP ${i.status}`)),g=i.ok,i},e=>{_=e instanceof Error?e:Error(String(e))}),headers:{Authorization:`Bearer ${e.token}`},onConnect:()=>{d=Date.now()},onComment:()=>{h=!0},onScheduleReconnect:()=>{if(s||i?.aborted)return;let t=Date.now(),n=performance.now(),a=d>0?t-d:0;d=0,l>0&&p>0&&t-p-(n-m)>3e4&&(l=t,e.onStreamDeadSince?.(l)),p=t,m=n;let o=h||g&&a>=V.healthyConnectionMs;if(h=!1,g=!1,o){l=0,e.onStreamDeadSince?.(0),_=void 0;return}if(l===0){l=t,e.onStreamDeadSince?.(l),e.log?.(`warn`,`SSE disconnected; reconnecting`);return}if(t-l>=V.giveUpAfterMs){let e=Math.round((t-l)/1e3),n=_?`; last error: ${_.message}`:``;b(new H(`event stream to ${r} kept failing for ${e}s without delivering events${n}; the execution may no longer exist (instance deleted or record expired)`))}},onMessage:t=>{if(s)return;l=0,e.onStreamDeadSince?.(0),h=!0,_=void 0;let n=t.id===void 0?NaN:Number.parseInt(t.id,10);if(!Number.isNaN(n)){if(n<=c)return;c=n}try{let n={...t.id!==void 0&&{id:t.id},type:t.event||`message`,data:typeof t.data==`string`?t.data:String(t.data??``)};if(e.onEvent(n),n.type===`exitCode`){let t=ie(n.data);e.log?.(`debug`,`Execution completed via SSE: exitCode=${t}`),y(t)}}catch(e){b(e)}}}),n=u,s?u.close():i?.addEventListener(`abort`,x,{once:!0})});return{connection:n,result:a}}var ne=class{constructor(e,t){this.command=new W,this.stdout=new W,this.stderr=new W,this.exitListeners=[],this.abortController=new AbortController,this.sseConnection=null,this.killed=!1,this.streamDeadSince=0,this.detached=!1,this.appStoreEvent=null,this.playstoreEvent=null,this.xctestCases=[],this.xctestSummary=null,this.options=t,this.log=t.log??(()=>{}),this.startedPromise=new Promise((e,t)=>{this.resolveStarted=e,this.rejectStarted=t}),this.startedPromise.catch(()=>{}),this.resultPromise=e instanceof Promise?e.then(e=>this.run(e)):this.run(e),this.resultPromise.catch(e=>this.rejectStarted(e))}then(e,t){return this.resultPromise.then(e,t)}catch(e){return this.resultPromise.catch(e)}finally(e){return this.resultPromise.finally(e)}on(e,t){return e===`exit`&&this.exitListeners.push(t),this}detach(){return this.detached=!0,this.resultPromise.catch(()=>{}),this.startedPromise}async kill(){if(this.killed=!0,this.abortController.abort(),this.sseConnection&&=(this.sseConnection.close(),null),!this.execId){this.log(`warn`,`Failed to cancel execution: execId is not set`);return}try{await f.fetch(`${this.options.apiUrl}/exec/${this.execId}/cancel`,{method:`POST`,headers:{Authorization:`Bearer ${this.options.token}`}}),this.log(`info`,`Execution cancelled`)}catch(e){this.log(`warn`,`Failed to cancel execution: ${e}`)}}async run(e){let{log:t}=this,{apiUrl:n,token:r}=this.options,i={...e};`additionalMetadata`in i&&delete i.additionalMetadata;let a;try{a=await f.fetch(`${n}/exec`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify(i),signal:this.abortController.signal})}catch(e){if(this.killed){this.rejectStarted(Error(`Execution cancelled before it started`)),this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`);for(let e of this.exitListeners)e(-1);return{exitCode:-1,execId:``,status:`CANCELLED`}}throw e}if(!a.ok){let e=await a.text(),t=e;try{t=JSON.parse(e).message||e}catch{}throw Error(`exec failed: ${a.status} ${t}`)}let o=await a.json();if(this.execId=o.execId,t(`debug`,`Execution started: ${this.execId}`),this.resolveStarted(this.execId),this.detached)return this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`),new Promise(()=>{});let s=`${n}/exec/${this.execId}/events`,c=36e5;e.command===`xcodebuild`&&e.testflight&&(c+=(Math.max(0,e.testflight.waitTimeoutSeconds??0)+900)*1e3),e.command===`xcodebuild`&&e.xcodebuild?.action===`build-for-testing`&&(c+=72e5),e.command===`run`&&(c=(Math.max(1,e.timeoutSeconds??3600)+60)*1e3);let l,u=!1,d,p;try{l=await Promise.race([this.connectSSE(s),new Promise((e,t)=>{p=setTimeout(()=>t(Error(`SSE completion timeout`)),c)})])}catch(e){if(this.killed)t(`debug`,`Execution killed`),l=-1;else{let n=e instanceof Error?e.message:String(e),r=this.streamDeadSince>0?Date.now()-this.streamDeadSince:0,i=e instanceof U?`stream-closed`:e instanceof H?`stream-lost`:`timeout`;i===`timeout`&&r>0&&(i=`stream-lost`,n=`the completion budget expired while the event stream had already been failing for ${Math.round(r/1e3)}s; the execution may no longer exist (instance deleted or record expired)`),d={reason:i,message:n},t(`warn`,n),l=1,u=!0}}finally{clearTimeout(p),this.sseConnection&&=(this.sseConnection.close(),null)}this.command.emit(`close`),this.stdout.emit(`close`),this.stderr.emit(`close`);for(let e of this.exitListeners)e(l);let m=l===0?`SUCCEEDED`:l===-1?`CANCELLED`:`FAILED`,h={exitCode:l,execId:this.execId,status:m,...`additionalMetadata`in e?e.additionalMetadata??{}:{},...this.appStoreEvent?{appstore:this.appStoreEvent}:{},...this.playstoreEvent?{playstore:this.playstoreEvent}:{},...this.xctestCases.length>0||this.xctestSummary?{xctest:{cases:this.xctestCases,...this.xctestSummary?{summary:this.xctestSummary}:{}}}:{},...u?{timedOut:u}:{},...d?{incomplete:d}:{}};return this.log(`debug`,`Execution finished: ${h.status} (exit ${h.exitCode})`),h}connectSSE(e){let t=G({eventsUrl:e,token:this.options.token,signal:this.abortController.signal,abortError:()=>Error(`killed`),log:this.log,onStreamDeadSince:e=>{this.streamDeadSince=e},onEvent:({type:e,data:t})=>{if(e===`command`)this.command.emit(`data`,t);else if(e===`stdout`)this.stdout.emit(`data`,t);else if(e===`stderr`)this.stderr.emit(`data`,t);else if(e===`testflight`)try{this.appStoreEvent=JSON.parse(t)}catch{this.appStoreEvent={state:`unknown`},this.log(`warn`,`SSE testflight event has invalid data: ${t}`)}else if(e===`playstore`)try{this.playstoreEvent=JSON.parse(t)}catch{this.playstoreEvent={state:`unknown`},this.log(`warn`,`SSE playstore event has invalid data: ${t}`)}else if(e===`xctest`){let e;try{let n=JSON.parse(t);n?.type===`case`?(this.xctestCases.push(n),e=n):n?.type===`summary`?(this.xctestSummary=n,e=n):this.log(`debug`,`SSE xctest event of unknown type ignored: ${t}`)}catch{this.log(`warn`,`SSE xctest event has invalid data: ${t}`)}if(e)try{this.options.onXctestEvent?.(e)}catch(e){this.log(`warn`,`onXctestEvent callback threw: ${String(e)}`)}}}});return this.sseConnection=t.connection,t.result}};async function K(e,t){if(!e.trim())throw Error(`execId must not be empty`);let n=t.follow??!1;if(n&&(e===`active`||e===`latest`)){let n=[],r=await K(e,{...t,follow:!1,onEvent:e=>n.push(e)});if(r.status!==`RUNNING`){for(let e of n)t.onEvent?.(e);return r}if(r.execId===e)throw Error(`The server did not resolve the ${e} build alias.`);return K(r.execId,t)}let r=t.apiUrl.length;for(;t.apiUrl[r-1]===`/`;)r--;let i=new URL(`${t.apiUrl.slice(0,r)}/exec/${encodeURIComponent(e)}/events`);if(i.searchParams.set(`follow`,String(n)),!n){let n=await f.fetch(i,{method:`GET`,headers:{Authorization:`Bearer ${t.token}`},...t.signal&&{signal:t.signal}});if(!n.ok){let e=await n.text();throw B(`GET exec logs`,n.status,e,n.headers)}let r=re(await n.text()),a,o=e;for(let e of r)o=ae(e,o),t.onEvent?.(e),e.type===`exitCode`&&(a=ie(e.data));return oe(o,a)}let a=e,o=await G({eventsUrl:i.toString(),token:t.token,...t.signal&&{signal:t.signal},failOnClientError:!0,log:t.log,abortError:()=>Error(`exec log stream for ${e} was aborted`),onEvent:e=>{a=ae(e,a),t.onEvent?.(e)}}).result;return oe(a,o)}function re(e){let t=e.replace(/\r\n/g,` `).replace(/\r/g,` `),n=[];for(let e of t.split(` `)){if(!e.trim())continue;let t,r=`message`,i=[];for(let n of e.split(` `))n.startsWith(`id:`)?t=n.slice(3).trimStart():n.startsWith(`event:`)?r=n.slice(6).trimStart():n.startsWith(`data:`)&&i.push(n.slice(5).replace(/^ /,``));(i.length>0||r!==`message`||t!==void 0)&&n.push({...t!==void 0&&{id:t},type:r,data:i.join(` `)})}return n}function ie(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw Error(`invalid exec exit code: ${e}`);return t}function ae(e,t){if(e.type!==`meta`)return t;try{let n=JSON.parse(e.data);return typeof n.id==`string`&&n.id?n.id:t}catch{return t}}function oe(e,t){return t===void 0?{execId:e,status:`RUNNING`}:{execId:e,exitCode:t,status:t===0?`SUCCEEDED`:t===-1?`CANCELLED`:`FAILED`}}function se(e,t){return new ne(e,t)}const ce=(e,t)=>{};async function le(e){let t=e.log??ce,n=e.rootPath;if(!h.existsSync(n))throw Error(`watchFolderTree root does not exist: ${n}`);let r=h.watch(n,{recursive:!0},(t,n)=>{if(!n)return;let r=n.split(b.sep).join(`/`);e.ignoreFn(r)||e.onChange(r?`change:${r}`:`change`)});return t(`debug`,`watchFolderTree(recursive): ${n}`),{close:()=>r.close()}}const ue=67108864,de=(e,t)=>{};function q(){return Date.now()}function J(e){return e<1e3?`${e.toFixed(0)}ms`:`${(e/1e3).toFixed(2)}s`}function Y(e){if(e<1024)return`${e}B`;let t=e/1024;if(t<1024)return`${t.toFixed(1)}KiB`;let n=t/1024;return n<1024?`${n.toFixed(1)}MiB`:`${(n/1024).toFixed(2)}GiB`}function fe(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function pe(e){let t=e;return t?.code===`ENOENT`||t?.cause?.code===`ENOENT`}function me(){let e=y.cpus()?.length??1;return Math.min(4,Math.max(1,e-1))}async function he(e,t,n){let r=Array(e.length),i=0,a=Array(Math.min(t,e.length)).fill(0).map(async()=>{for(;;){let t=i++;if(t>=e.length)return;let a=e[t];r[t]=await n(a)}});return await Promise.all(a),r}function ge(e){return`${e}/sync`}function _e(e){let t=Buffer.allocUnsafe(4);return t.writeUInt32BE(e>>>0,0),t}async function ve(e,t,n,r){let i=ge(e.apiUrl),a={"Content-Type":`application/octet-stream`,Authorization:`Bearer ${e.token}`},o=Buffer.from(JSON.stringify(t),`utf-8`),s=Buffer.concat([_e(o.length),o]);async function*c(){yield s;for(let e of n){let t=await h.promises.open(e.filePath,`r`);try{let e=await t.stat(),n=0;for(;n<e.size;){let r=Math.min(262144,e.size-n),i=Buffer.allocUnsafe(r),{bytesRead:a}=await t.read(i,0,r,n);if(a<=0)break;n+=a,yield i.subarray(0,a)}}finally{await t.close()}}}let l=_.from(c()),u;if(r===`zstd`){let e=g.createZstdCompress;if(!e)throw Error(`zstd compression not available in this Node.js version`);u=l.pipe(e({level:3})),a[`Content-Encoding`]=`zstd`}else if(r===`gzip`){let e=g.createGzip;if(!e)throw Error(`gzip compression not available in this Node.js version`);u=l.pipe(e({level:6})),a[`Content-Encoding`]=`gzip`}else u=l;let d=new AbortController,p,m=e=>{p=e,d.abort()};l.on(`error`,m),u.on(`error`,m);let v=await f.fetch(i,{method:`POST`,headers:a,body:u,duplex:`half`,signal:d.signal}).catch(e=>{throw p||e}),y=await v.text();if(!v.ok)throw B(`folder-sync http`,v.status,y,v.headers);return JSON.parse(y)}async function X(e){return await new Promise((t,n)=>{let r=S.createHash(`sha256`),i=h.createReadStream(e);i.on(`data`,e=>r.update(e)),i.on(`error`,n),i.on(`end`,()=>t(r.digest(`hex`)))})}function ye(e,t){if(t.includes(`\\`))throw Error(`symlink ${e} -> ${t} target contains a backslash, which the daemon rejects; remove the link or pass --ignore to skip it`);let n=b.posix.normalize(b.posix.join(b.posix.dirname(e),t));if(n===`.`||n===`..`||n.startsWith(`../`))throw Error(`symlink ${e} -> ${t} points outside the sync root; run the sync from the repo root that contains the target, remove the link, or pass --ignore to skip it`)}async function be(e,t,n,r){let i=b.resolve(e),a=await h.promises.stat(i);if(a.isFile()){let e=b.basename(i);return t(e)?[]:[{path:e,size:a.size,sha256:await X(i),absPath:i,mode:a.mode&4095}]}let o=[],s=[i];for(;s.length;){let e=s.pop(),a=await h.promises.readdir(e,{withFileTypes:!0});for(let c of a){let a=b.join(e,c.name),l=b.relative(i,a).split(b.sep).join(`/`);if(c.isDirectory()){if(t(l+`/`))continue;s.push(a);continue}if(c.isSymbolicLink()){if(!n||t(l)||t(l+`/`))continue;let e=(await h.promises.readlink(a)).split(b.sep).join(`/`);if(b.posix.isAbsolute(e)||b.win32.isAbsolute(e)){r?.(`warn`,`skipping symlink ${l} -> ${e}: absolute targets cannot resolve remotely`);continue}ye(l,e);let i=S.createHash(`sha256`).update(e).digest(`hex`);o.push({path:l,size:Buffer.byteLength(e),sha256:i,absPath:a,mode:0,linkTarget:e});continue}if(!c.isFile()||t(l))continue;let u=await h.promises.stat(a),d=await X(a),f=u.mode&4095;o.push({path:l,size:u.size,sha256:d,absPath:a,mode:f})}}return o.sort((e,t)=>e.path.localeCompare(t.path)),o}async function xe(e){if(!e||e.length===0)return[];let t=[];for(let n of e){let e=b.posix.normalize(n.remotePath),r=b.resolve(n.localPath),i=await h.promises.stat(r);if(!i.isFile())throw Error(`additional file localPath must be a file: ${n.localPath}`);let a=await X(r);t.push({path:e,size:i.size,sha256:a,absPath:r,mode:i.mode&4095})}return t.sort((e,t)=>e.path.localeCompare(t.path)),t}let Z=null;async function Se(){return Z||=(async()=>await import(`./dist.js`).then(t=>e(t.default,1)))().catch(e=>{throw Z=null,e}),await Z}async function*Ce(e){for await(let t of h.createReadStream(e,{highWaterMark:1048576}))t instanceof Uint8Array?yield t:yield Buffer.from(t)}function we(e){return Math.max(0,Math.ceil(e*.9)-1)}async function Te(e,t,n,r){let i=await Se(),a=await h.promises.open(e,`r`),o=(await a.stat()).size,s=h.createWriteStream(n),c=0,l=!1,u={size:o,read:async(e,t)=>{let{bytesRead:n}=await a.read(t,0,t.byteLength,e);return n}};try{for await(let e of i.encode(Ce(t),u)){if(c+=e.byteLength,c>r){l=!0;break}s.write(e)||await m(s,`drain`)}s.end(),await m(s,`finish`)}catch(e){throw s.destroy(),await h.promises.rm(n,{force:!0}),e}finally{await a.close()}return l?(await h.promises.rm(n,{force:!0}),-1):c}async function Ee(e,t,n,r,i){let a=t.split(`/`),o=b.join(e,a.join(b.sep));if(i){let t=e;for(let e=0;e<a.length-1;e++){if(t=b.join(t,a[e]),i.has(t))continue;let n=await h.promises.lstat(t).catch(()=>null);n&&!n.isDirectory()?await h.promises.rm(t,{recursive:!0,force:!0}):n&&i.add(t)}}await h.promises.mkdir(b.dirname(o),{recursive:!0});let s=await h.promises.lstat(o).catch(()=>null);if(s&&(s.isSymbolicLink()||s.isDirectory()||r!==void 0)&&await h.promises.rm(o,{recursive:!0,force:!0}),r!==void 0){await h.promises.symlink(r,o);return}await h.promises.copyFile(n,o)}function De(e,t){return b.join(e,t.split(`/`).join(b.sep))}async function Oe(e,t){let n=(e,n)=>{(t.log??de)(e,`syncFolder: ${n}`)};n(`debug`,`setup ${e} watch=${t.watch} basisCacheDir=${t.basisCacheDir}`);let r=async n=>{let r=q(),i=await ke(e,t,n);return t.onSyncComplete?.({bytesSent:i.bytesSent??0,durationMs:q()-r,...i.installedAppPath===void 0?{}:{installedAppPath:i.installedAppPath},...i.installedBundleId===void 0?{}:{installedBundleId:i.installedBundleId}}),i};if(!t.watch)return await r();let i=await r(`startup`),a=!1,o=!1,s=!1,c,l,u=async e=>{a=!0;try{await r(e)}finally{a=!1,o&&!s&&(o=!1,d(`queued-changes`))}},d=e=>{if(s)return;if(a){o=!0;return}let t=u(e).catch(e=>{n(`error`,`syncFolder: watch sync failed: ${e instanceof Error?e.message:String(e)}`)});l=t,t.finally(()=>{l===t&&(l=void 0)})},f=e=>{s||(c&&clearTimeout(c),c=setTimeout(()=>{c=void 0,d(e)},500))},p=await h.promises.stat(e),m;if(p.isFile()){let t=b.basename(e),n=b.dirname(e),r=h.watch(n,(e,n)=>{!n||n.toString()!==t||f(`change:${t}`)});m={close:()=>r.close()}}else m=await le({rootPath:e,log:n,ignoreFn:t.ignoreFn,onChange:e=>{f(e)}});return{...i,stopWatching:async()=>{s=!0,o=!1,c&&=(clearTimeout(c),void 0),m.close(),await l}}}async function ke(e,t,n,r=0){let i=q(),a=t.log??de,o=(e,t)=>a(e,`syncFolder: ${t}`),s=await be(e,t.ignoreFn,t.syncSymlinks??!1,o),c=await xe(t.additionalFiles),l=[...s,...c].sort((e,t)=>e.path.localeCompare(t.path)),u=new Map(l.map(e=>[e.path,e])),d=fe(`sync`),f=b.basename(b.resolve(e)),p=t.compression??(g.createZstdCompress?`zstd`:`gzip`);await h.promises.mkdir(t.basisCacheDir,{recursive:!0});let m=0,_=0,v=0,x=0,S=me(),C=[];for(let e of l){let n=De(t.basisCacheDir,e.path),r=await h.promises.lstat(n).catch(()=>null);if(!r){C.push(e);continue}if(e.linkTarget!==void 0){if(!r.isSymbolicLink()){C.push(e);continue}(await h.promises.readlink(n)).split(b.sep).join(`/`)!==e.linkTarget&&C.push(e);continue}if(!r.isFile()){C.push(e);continue}await X(n)!==e.sha256.toLowerCase()&&C.push(e)}let w=C.filter(e=>e.linkTarget===void 0),T=new Set(C.map(e=>e.path)),E=await he(w,S,async e=>{let n=De(t.basisCacheDir,e.path);if((e.size>=65536?await h.promises.lstat(n).catch(()=>null):null)?.isFile()){let t=await X(n),r=await h.promises.mkdtemp(b.join(y.tmpdir(),`limulator-xdelta3-`)),i=b.join(r,`patch.xdelta3`),a=q(),s=await Te(n,e.absPath,i,we(e.size)),c=q()-a;if(x+=c,s>=0)return o(`debug`,`delta(file): ${b.posix.basename(e.path)} patchSize=${s} encode=${J(c)}`),_+=s,{payload:{kind:`delta`,path:e.path,basisSha256:t.toLowerCase(),targetSha256:e.sha256.toLowerCase(),length:s},filePath:i,cleanupDir:r};try{await h.promises.rm(r,{recursive:!0,force:!0})}catch{}}return o(`debug`,`full(file): ${e.path} size=${e.size}`),e.size>=ue&&o(`debug`,`uploading large file ${e.path} (${Y(e.size)})`),m+=e.size,{payload:{kind:`full`,path:e.path,targetSha256:e.sha256.toLowerCase(),length:e.size},filePath:e.absPath}}),D={id:d,rootName:f,install:t.install,...t.launchMode?{launchMode:t.launchMode}:{},files:l.map(e=>({path:e.path,size:e.size,sha256:e.sha256.toLowerCase(),...e.linkTarget===void 0?{mode:e.mode}:{link:e.linkTarget}})),payloads:E.map(e=>e.payload)},O=E.some(e=>e.payload.kind===`delta`),k=t.compression??(O?`identity`:p);o(`debug`,`sync started files=${l.length}${n?` reason=${n}`:``} compression=${k}`);let A=q(),j;try{j=await ve(t,D,E.map(e=>({filePath:e.filePath})),k)}catch(i){if(r<1&&pe(i))return o(`warn`,`sync retrying after missing file during upload (ENOENT)`),await ke(e,t,n,r+1);throw i}if(v+=q()-A,!j.ok&&j.needFull&&j.needFull.length>0){let e=new Set(j.needFull),n=[...e].filter(e=>u.get(e)?.linkTarget!==void 0);if(n.length>0)throw Error(`this instance's build daemon does not support symlinks yet (needs an updated limbuild); recreate the instance or retry later. Paths: ${n.join(`, `)}`);let r=[];for(let t of e){let e=u.get(t);e&&(e.size>=ue&&o(`debug`,`uploading large file ${e.path} (${Y(e.size)})`),m+=e.size,T.add(e.path),r.push({payload:{kind:`full`,path:e.path,targetSha256:e.sha256.toLowerCase(),length:e.size},filePath:e.absPath}))}if(r.length>0){o(`debug`,`daemon requested a full upload for ${r.length} files (no matching basis); retrying once`);let e={...D,id:fe(`sync`),payloads:r.map(e=>e.payload)},n=q();j=await ve(t,e,r.map(e=>({filePath:e.filePath})),t.compression??p),v+=q()-n}}await Promise.all(E.map(async e=>{if(e.cleanupDir)try{await h.promises.rm(e.cleanupDir,{recursive:!0,force:!0})}catch{}}));let M=q()-i;if(!j.ok)throw Error(j.error??`sync failed`);let N=q()-i,P=m+_;o(`debug`,`sync complete: files=${l.length} changed=${T.size} sent=${Y(P)} in ${J(N)}`),o(`debug`,`sync timing syncWork=${J(M)} total=${J(N)}`);let F={bytesSent:P};j.installedAppPath&&(F.installedAppPath=j.installedAppPath),j.bundleId&&(F.installedBundleId=j.bundleId);let I=t.syncSymlinks?new Set:void 0;for(let e of l)await Ee(t.basisCacheDir,e.path,e.absPath,e.linkTarget,I);return F}async function Ae(e,t,n,r,i){return(i?.mode??`singleton`)===`multiplexed`?Ne(e,t,n,r,i):Me(e,t,n,r,i)}async function je(e,t,n){Fe(n.localPort,`localPort`,1,65535);let r=n.localHost??`127.0.0.1`,i=n.localPort,a=n.logLevel??`info`,s=n.maxConnections??64,c=n.maxPendingBytesPerConnection??16777216,l=n.maxBufferedBytes??4194304,u=l/4,d=n.connectTimeoutMs??1e4,p={debug:(...e)=>{a===`debug`&&console.log(`[ReverseTunnel]`,...e)},info:(...e)=>{(a===`info`||a===`debug`)&&console.log(`[ReverseTunnel]`,...e)},warn:(...e)=>{(a===`warn`||a===`info`||a===`debug`)&&console.warn(`[ReverseTunnel]`,...e)},error:(...e)=>{a!==`none`&&console.error(`[ReverseTunnel]`,...e)}};return new Promise((n,a)=>{let m=new Map,h=new Set,g=new Map,_=new Map,y=new Map,b=new Map,x=new Set,S,C,w=!1,T=`connecting`,E=!1,D,O=!1,k=e=>{T!==e&&(T=e,p.debug(`Connection state changed to: ${e}`),x.forEach(t=>{try{t(e)}catch(e){p.error(`Error in connection state callback:`,e)}}))},A=e=>{S&&S.readyState===o.default.OPEN&&S.send($(e),()=>M())},j=()=>{if(!O){O=!0,p.debug(`WebSocket send buffer full, pausing local reads`);for(let e of m.values())e.destroyed||e.pause()}},M=()=>{if(O&&!(!S||S.bufferedAmount>=u)){O=!1,p.debug(`WebSocket send buffer drained, resuming local reads`);for(let e of m.values())e.destroyed||e.resume()}},N=e=>{let t=b.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{b.delete(e)},3e4);n.unref(),b.set(e,n)},P=(e,t,n=!1)=>{let r=m.get(e),i=y.get(e);m.delete(e),h.delete(e),g.delete(e),_.delete(e),y.delete(e),N(e),i&&clearTimeout(i),t&&A(e),r&&!r.destroyed&&(n?(r.end(),setTimeout(()=>{r.destroyed||r.destroy()},1e3).unref()):r.destroy())},F=()=>{for(let e of Array.from(m.keys()))P(e,!1);O=!1,m.clear(),h.clear(),g.clear(),_.clear();for(let e of b.values())clearTimeout(e);b.clear()},I=()=>{C&&=(clearInterval(C),void 0),S&&=(S.removeAllListeners(),(S.readyState===o.default.OPEN||S.readyState===o.default.CONNECTING)&&S.close(1e3,`close`),void 0)},L=()=>{w=!0,I(),F(),k(`disconnected`)},R=()=>T,ee=e=>(x.add(e),()=>{x.delete(e)}),z=e=>{D=e,E=!0,n({remoteAddress:D,close:L,getConnectionState:R,onConnectionStateChange:ee})},B=e=>{E?p.error(e.message):(I(),F(),k(`disconnected`),a(e))},te=(e,t)=>{let n=y.get(e);n&&(clearTimeout(n),y.delete(e));let r=g.get(e)??[];g.delete(e),_.delete(e),h.delete(e);for(let e of r)t.write(e)},V=(e,t)=>{if(b.has(e)){p.debug(`Ignoring payload for closed conn=${e}`);return}if(m.size>=s){p.warn(`Rejecting reverse tunnel conn=${e}: max connections reached`),A(e),N(e);return}if(t.length>c){p.warn(`Rejecting reverse tunnel conn=${e}: initial payload exceeds pending byte limit`),A(e),N(e);return}g.set(e,[t]),_.set(e,t.length),h.add(e);let n=v.createConnection({host:r,port:i});M(),O&&n.pause(),m.set(e,n);let a=setTimeout(()=>{p.error(`Local TCP connect timed out conn=${e} after ${d}ms`),m.has(e)&&P(e,!0)},d);a.unref(),y.set(e,a),n.on(`connect`,()=>{p.debug(`Connected conn=${e} to ${r}:${i}`),te(e,n)});let u=$(e),f=t=>{t&&p.error(`Failed to send conn=${e} data: ${t.message}`),M()};n.on(`data`,e=>{if(S&&S.readyState===o.default.OPEN){let t=Buffer.allocUnsafe(4+e.length);u.copy(t,0),e.copy(t,4),S.send(t,f),!O&&S.bufferedAmount>l&&j()}}),n.on(`close`,()=>{p.debug(`Local TCP connection closed conn=${e}`),m.has(e)&&P(e,!0)}),n.on(`error`,t=>{p.error(`Local TCP connection error conn=${e}: ${t.message}`),m.has(e)&&P(e,!0)})},H=e=>{if(e.length<4){p.error(`Received binary frame shorter than 4 bytes; dropping`);return}let t=Ie(e),n=e.subarray(4);if(n.length===0){p.debug(`Received remote close for conn=${t}`),P(t,!1,!0);return}if(b.has(t)){p.debug(`Ignoring payload for closed conn=${t}`);return}let r=m.get(t);if(!r){V(t,n);return}if(h.has(t)){let e=g.get(t)??[],r=(_.get(t)??0)+n.length;if(r>c){p.warn(`Closing reverse tunnel conn=${t}: pending byte limit exceeded`),P(t,!0);return}e.push(n),g.set(t,e),_.set(t,r);return}r.write(n)},U=e=>{let t;try{t=JSON.parse(e.toString())}catch{B(Error(`Malformed reverse tunnel control message: ${e.toString()}`));return}if(t.type===`ready`){if(typeof t.remoteHost!=`string`||typeof t.remotePort!=`number`){B(Error(`Malformed reverse tunnel ready message: ${e.toString()}`));return}p.info(`Reverse tunnel ready: ${t.remoteHost}:${t.remotePort}`),k(`connected`),z({address:t.remoteHost,port:t.remotePort});return}if(t.type===`error`){B(Error(t.message||`Reverse tunnel failed to start`));return}B(Error(`Unexpected reverse tunnel control message type: ${t.type}`))},W=new URL(e),G=f.getWebSocketAgent(W.toString());S=new o.default(W.toString(),{headers:{Authorization:`Bearer ${t}`},...G?{agent:G}:{},perMessageDeflate:!1}),S.on(`error`,e=>{p.error(`WebSocket error:`,e.message),B(e)}),S.on(`close`,(e,t)=>{C&&=(clearInterval(C),void 0),p.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),F(),k(`disconnected`),!w&&!E&&B(Error(`Reverse tunnel WebSocket closed before ready: ${e} ${t.toString()}`))}),S.on(`open`,()=>{let e=S;p.debug(`Connected WebSocket to ${W.toString()}`),C=setInterval(()=>{e.readyState===o.default.OPEN&&e.ping()},3e4)}),S.on(`message`,(e,t)=>{if(!E){if(t){B(Error(`Received reverse tunnel binary frame before ready control message`));return}U(e);return}if(!t){p.warn(`Ignoring unexpected reverse tunnel text message: ${e.toString()}`);return}H(Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e))})})}async function Me(e,t,n,r,i){let a=i?.maxReconnectAttempts??6,s=i?.reconnectDelay??1e3,c=i?.maxReconnectDelay??3e4,l=i?.logLevel??`info`,u={debug:(...e)=>{l===`debug`&&console.log(`[Tunnel]`,...e)},info:(...e)=>{(l===`info`||l===`debug`)&&console.log(`[Tunnel]`,...e)},warn:(...e)=>{(l===`warn`||l===`info`||l===`debug`)&&console.warn(`[Tunnel]`,...e)},error:(...e)=>{l!==`none`&&console.error(`[Tunnel]`,...e)}};return new Promise((i,l)=>{let d=v.createServer(),p,m,h,g=0,_=!1,y,b=`connecting`,S,C,w=new Set,T=e=>{b!==e&&(b=e,u.debug(`Connection state changed to: ${e}`),w.forEach(t=>{try{t(e)}catch(e){u.error(`Error in connection state callback:`,e)}}))},E=()=>{h&&=(clearTimeout(h),void 0),m&&=(clearInterval(m),void 0),p&&=(p.removeAllListeners(),(p.readyState===o.default.OPEN||p.readyState===o.default.CONNECTING)&&p.close(1e3,`close`),void 0)},D=()=>{_=!0,E(),T(`disconnected`),y&&!y.destroyed&&y.destroy(),d.listening&&d.close()},O=()=>{if(_){u.debug(`Skipping reconnection (intentional disconnect)`);return}if(Q(C??``)){u.error(`Skipping reconnection (non-retryable error): ${C}`);return}if(!y||y.destroyed){u.debug(`Skipping reconnection (TCP socket closed)`);return}if(g>=a){u.error(`Max reconnection attempts (${a}) reached. Closing tunnel.`,C?`Last error: ${C}`:``),D();return}let e=Math.min(s*2**g,c);g++,u.debug(`Scheduling reconnection attempt ${g} in ${e}ms...`),T(`reconnecting`),h=setTimeout(()=>{u.debug(`Attempting to reconnect (attempt ${g})...`),k()},e)},k=()=>{if(!y||y.destroyed){u.error(`Cannot setup WebSocket: TCP socket is closed`);return}E(),T(`connecting`);let n=new URL(e);S&&n.searchParams.set(`sessionId`,S);let r=f.getWebSocketAgent(n.toString());p=new o.default(n.toString(),{headers:{Authorization:`Bearer ${t}`},...r?{agent:r}:{},perMessageDeflate:!1}),p.on(`error`,e=>{let t=e.message||String(e);C=t,u.debug(`WebSocket error:`,t)}),p.on(`close`,(e,t)=>{m&&=(clearInterval(m),void 0);let n=!_&&!Q(C??``)&&b!==`disconnected`;T(`disconnected`),u.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),y&&!y.destroyed&&!y.isPaused()&&(u.debug(`Pausing TCP socket (applying backpressure)`),y.pause()),n&&y&&!y.destroyed?O():Q(C??``)&&(u.error(`Closing tunnel due to non-retryable error: ${C}`),D())}),p.on(`open`,()=>{let e=p;u.debug(`WebSocket connected`),g=0,C=void 0,T(`connected`),m=setInterval(()=>{e.readyState===o.default.OPEN&&e.ping()},3e4),y&&y.isPaused()&&(u.debug(`Resuming TCP socket (releasing backpressure)`),y.resume());let t=t=>{e.readyState===o.default.OPEN&&e.send(t)};y.removeListener(`data`,t),y.on(`data`,t),e.on(`message`,e=>{y&&!y.destroyed&&y.write(e)})})};d.once(`error`,e=>{D(),l(Error(`TCP server error: ${e.message}`))});let A=()=>b,j=e=>(w.add(e),()=>{w.delete(e)});d.once(`listening`,()=>{let e=d.address();if(!e||typeof e==`string`)return D(),l(Error(`Failed to obtain listening address`));i({address:e,close:D,getConnectionState:A,onConnectionStateChange:j})});let M=()=>{E(),T(`disconnected`),y&&!y.destroyed&&(y.destroy(),y=void 0),g=0,_=!1,S=void 0,C=void 0,u.debug(`Connection cleaned up, ready for new TCP connection`)};d.on(`connection`,e=>{if(y&&!y.destroyed){u.debug(`Rejecting new TCP connection - already have an active connection`),e.destroy();return}S=x.randomUUID(),u.debug(`TCP client connected`,`sessionId`,S),y=e,y.on(`close`,()=>{u.debug(`TCP socket closed by client`),M()}),y.on(`error`,e=>{u.error(`TCP socket error:`,e),M()}),k()}),d.listen(r,n)})}async function Ne(e,t,n,r,i){let a=i?.logLevel??`info`,s={debug:(...e)=>{a===`debug`&&console.log(`[Tunnel:Mux]`,...e)},info:(...e)=>{(a===`info`||a===`debug`)&&console.log(`[Tunnel:Mux]`,...e)},warn:(...e)=>{(a===`warn`||a===`info`||a===`debug`)&&console.warn(`[Tunnel:Mux]`,...e)},error:(...e)=>{a!==`none`&&console.error(`[Tunnel:Mux]`,...e)}};return new Promise((a,c)=>{let l=v.createServer(),u=new Map,d=1,p,m,h=!1,g=!1,_=`connecting`,y=i?.maxReconnectAttempts??6,b=i?.reconnectDelay??1e3,x=i?.maxReconnectDelay??3e4,S=0,C,w,T=new Set,E=e=>{_!==e&&(_=e,s.debug(`Connection state changed to: ${e}`),T.forEach(t=>{try{t(e)}catch(e){s.error(`Error in connection state callback:`,e)}}))},D=()=>{m&&=(clearInterval(m),void 0),p&&=(p.removeAllListeners(),(p.readyState===o.default.OPEN||p.readyState===o.default.CONNECTING)&&p.close(1e3,`close`),void 0)},O=()=>{for(let[e,t]of u)s.debug(`Closing TCP connection ${e}`),t.destroyed||t.destroy();u.clear()},k=()=>{h=!0,C&&=(clearTimeout(C),void 0),D(),O(),E(`disconnected`),l.listening&&l.close()},A=()=>{if(h||C)return;if(Q(w??``)){s.error(`Closing multiplexed tunnel (non-retryable error): ${w}`),k();return}if(S>=y){s.error(`Max reconnection attempts (${y}) reached. Closing tunnel.`),k();return}let e=Math.min(b*2**S,x);S++,E(`reconnecting`),s.debug(`Scheduling reconnection attempt ${S} in ${e}ms...`),C=setTimeout(()=>{C=void 0,N().catch(()=>{})},e)},j=e=>{if(p&&p.readyState===o.default.OPEN){let t=$(e);p.send(t),s.debug(`Sent close signal for connection ${e}`)}},M=e=>{let t=u.get(e);t&&(t.destroyed||t.destroy(),u.delete(e),s.debug(`Removed connection ${e}`))},N=()=>new Promise((n,r)=>{D(),E(`connecting`);let i=new URL(e);i.searchParams.set(`mode`,`multiplexed`),s.debug(`Connecting WebSocket to: ${i.toString()}`);let a=f.getWebSocketAgent(i.toString());p=new o.default(i.toString(),{headers:{Authorization:`Bearer ${t}`},...a?{agent:a}:{},perMessageDeflate:!1}),p.on(`error`,e=>{let t=e.message||String(e);w=t,s.error(`WebSocket error:`,t,e.code||``),r(e)}),p.on(`close`,(e,t)=>{if(m&&=(clearInterval(m),void 0),s.debug(`WebSocket disconnected (code=${e}, reason=${t.toString()})`),O(),!g||h){E(`disconnected`);return}A()}),p.on(`open`,()=>{let e=p;s.debug(`WebSocket connected`),S=0,w=void 0,E(`connected`),m=setInterval(()=>{e.readyState===o.default.OPEN&&e.ping()},3e4),e.on(`message`,e=>{let t=e;if(s.debug(`WS→TCP raw message: ${t.length} bytes`),t.length<4){s.error(`Received binary frame shorter than 4 bytes; dropping`);return}let n=Ie(t),r=t.subarray(4);if(r.length===0){s.debug(`Received close signal for connection ${n}`),M(n);return}s.debug(`WS→TCP [conn=${n}] ${r.length} bytes: ${r.subarray(0,Math.min(200,r.length)).toString(`utf8`).replace(/[\x00-\x1f]/g,`.`)}`);let i=u.get(n);i&&!i.destroyed?i.write(r):s.debug(`Received data for unknown/closed connection ${n}`)}),n()})});l.once(`error`,e=>{k(),c(Error(`TCP server error: ${e.message}`))});let P=()=>_,F=e=>(T.add(e),()=>{T.delete(e)});l.once(`listening`,async()=>{let e=l.address();if(!e||typeof e==`string`)return k(),c(Error(`Failed to obtain listening address`));s.debug(`Multiplexed tunnel listening on ${e.address}:${e.port}`);try{await N(),g=!0,s.debug(`WebSocket ready, tunnel fully initialized`),a({address:e,close:k,getConnectionState:P,onConnectionStateChange:F})}catch(e){k(),c(Error(`Failed to establish WebSocket connection: ${e}`))}}),l.on(`connection`,e=>{if(!p||p.readyState!==o.default.OPEN){e.destroy();return}let t=d++;d>4294967295&&(d=1),u.set(t,e),s.debug(`New TCP connection ${t} from ${e.remoteAddress}:${e.remotePort}, WS state=${p?.readyState}, total connections=${u.size}`),e.on(`data`,n=>{if(p&&p.readyState===o.default.OPEN){let e=$(t),r=Buffer.concat([e,n]);s.debug(`TCP→WS [conn=${t}] ${n.length} bytes: ${n.subarray(0,Math.min(200,n.length)).toString(`utf8`).replace(/[\x00-\x1f]/g,`.`)}`),p.send(r,e=>{e&&s.error(`TCP→WS [conn=${t}] send error: ${e.message}`)})}else s.debug(`TCP→WS [conn=${t}] WS not open (state=${p?.readyState}), closing connection`),e.destroy()}),e.on(`close`,()=>{s.debug(`TCP connection ${t} closed by client`),j(t),u.delete(t)}),e.on(`error`,e=>{s.error(`TCP connection ${t} error:`,e),j(t),u.delete(t)})}),l.listen(r,n)})}function Pe(e){let t=e.match(/Unexpected server response: (\d+)/);return t?.[1]?parseInt(t[1],10):void 0}const Q=e=>{let t=Pe(e);return t!==void 0&&t>=400&&t<500};function Fe(e,t,n,r){if(!Number.isInteger(e)||e<n||e>r)throw Error(`${t} must be an integer between ${n} and ${r}`)}function $(e){let t=Buffer.alloc(4);return t.writeUInt32BE(e,0),t}function Ie(e){if(e.length<4)throw Error(`Header must be at least 4 bytes`);return e.readUInt32BE(0)}const Le=1e4;async function Re(e,t){let n=await f.fetch(r(e).toString(),{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Le)});if(!n.ok)throw Error(`getTunnelStatus failed: ${n.status} ${await n.text()}`);return Be(await n.json())}async function ze(e,t,n){if(!n.trim())throw Error(`tunnelId must not be empty`);let r=await f.fetch(c(e,n).toString(),{method:`DELETE`,headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(Le)});if(!r.ok)throw Error(`stopTunnel failed: ${r.status} ${await r.text()}`)}function Be(e){let t=l(e,`tunnel status`),n={};return t.active!==void 0&&(n.active=Ve(t.active)),t.lastFailure!==void 0&&(n.lastFailure=Ge(t.lastFailure)),t.lastDialFailure!==void 0&&(n.lastDialFailure=Ke(t.lastDialFailure)),n}function Ve(e){let t=l(e,`active tunnel`),n=s(t,`state`);if(n!==`starting`&&n!==`ready`&&n!==`stopping`)throw Error(`invalid tunnel state ${n}`);return{tunnelId:a(t,`tunnelId`),...u(t,`name`),state:n,selectors:i(t,`selectors`).map((e,t)=>Ue(e,`selector-${t+1}`)),inspection:He(t)}}function He(e){let t=l(e.inspection,`inspection`),r=t.enabled,i=t.captureBodies,a=t.persist;if(typeof r!=`boolean`||typeof i!=`boolean`||typeof a!=`boolean`)throw Error(`inspection enabled, captureBodies, and persist must be booleans`);let o=t.maxBodyBytes,s=t.ttlSeconds;if(typeof o!=`number`||typeof s!=`number`)throw Error(`inspection maxBodyBytes and ttlSeconds must be numbers`);return n({enabled:r,captureBodies:i,maxBodyBytes:o,persist:a,ttlSeconds:s})}function Ue(e,t){let n=l(e,`tunnel selector`),r=a(n,`id`);if(r!==t)throw Error(`invalid tunnel selector id ${r}`);let o=s(n,`kind`);if(o!==`route`&&o!==`domain`)throw Error(`invalid tunnel selector kind ${o}`);return{id:r,kind:o,value:a(n,`value`),...n.binds===void 0?{}:{binds:i(n,`binds`).map(We)}}}function We(e){let t=l(e,`tunnel bind report`),n=s(t,`status`);if(n!==`ok`&&n!==`conflict`&&n!==`error`)throw Error(`invalid tunnel bind status ${n}`);let r=t.osCode;if(r!==void 0&&typeof r!=`string`)throw Error(`tunnel bind osCode must be a string`);return{address:a(t,`address`),status:n,...r===void 0?{}:{osCode:r}}}function Ge(e){let t=l(e,`tunnel failure`);return{tunnelId:a(t,`tunnelId`),code:a(t,`code`)}}function Ke(e){let t=l(e,`tunnel dial failure`),n=t.connectionId;if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>4294967295)throw Error(`tunnel dial failure connectionId must be an unsigned 32-bit integer`);let r=t.osCode;if(r!==void 0&&typeof r!=`string`)throw Error(`tunnel dial failure osCode must be a string`);return{tunnelId:a(t,`tunnelId`),connectionId:n,selectorId:a(t,`selectorId`),reason:a(t,`reason`),...r===void 0?{}:{osCode:r}}}async function qe(e,t,n){return Je(d(e,`trusted-cas`).toString(),t,n)}async function Je(e,t,n){let r=await f.fetch(e,{method:`POST`,headers:{"Content-Type":`application/x-pem-file`,Authorization:`Bearer ${t}`},body:n});if(!r.ok){let e=(await r.text()).trim(),t=e;try{let n=JSON.parse(e);t=n.message||n.reason||e}catch{}throw Error(`Adding the CA certificate failed (${r.status}): ${t||r.statusText}`)}return await r.json()}function Ye(e){if(!e)return{};if(e===!0)return{persist:!0};if(e.ttlSeconds!==void 0&&(!Number.isInteger(e.ttlSeconds)||e.ttlSeconds<=0))throw Error(`ttlSeconds must be a positive integer`);return{persist:!0,...e.ttlSeconds!==void 0&&{ttlSeconds:e.ttlSeconds}}}var Xe=class extends Error{};function Ze(e){let n=!1,r=0,i=0,a=0,o=0,s=!1,c=!1,l,u=t=>{n||(n=!0,d.close(),e.onError?.(t))},d=t({url:e.url,fetch:z(async(e,t)=>{let n=await f.fetch(e,t);return n.ok||(l=Error(`server answered HTTP ${n.status}`)),c=n.ok,n},e=>{l=e instanceof Error?e:Error(String(e))}),headers:{Authorization:`Bearer ${e.token}`},onConnect:()=>{r=Date.now()},onComment:()=>{s=!0},onScheduleReconnect:()=>{if(n)return;let t=Date.now(),d=performance.now(),f=r>0?t-r:0;r=0,i>0&&a>0&&t-a-(d-o)>3e4&&(i=t),a=t,o=d;let p=s||c&&f>=V.healthyConnectionMs;if(s=!1,c=!1,p){i=0,l=void 0;return}if(i===0){i=t;return}if(t-i>=V.giveUpAfterMs){let n=Math.round((t-i)/1e3),r=l?`; last error: ${l.message}`:``;u(new Xe(`session stream to ${e.url} kept failing for ${n}s without delivering entries${r}; the instance may no longer exist`))}},onMessage:t=>{i=0,s=!0,l=void 0;let n=typeof t.data==`string`?t.data:String(t.data??``),r;try{r=JSON.parse(n)}catch{return}typeof r?.ts==`number`&&e.onEntry(r)}});return()=>{n||(n=!0,d.close())}}var Qe=class extends p{constructor(e,t,n,r){super(),this.wsUrl=e,this.subscribeMessage=t,this.ws=null,this.stopped=!1,this.terminateMessageType=n,this.subscriptionId=r,this._connect()}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}off(e,t){return super.off(e,t)}stop(){if(!this.stopped){if(this.stopped=!0,this.ws&&this.ws.readyState===o.default.OPEN){let e={type:this.terminateMessageType,id:this.subscriptionId};try{this.ws.send(JSON.stringify(e))}catch{}this.ws.close()}this.ws=null,this.emit(`close`)}}_connect(){let e=f.getWebSocketAgent(this.wsUrl);this.ws=new o.default(this.wsUrl,e?{agent:e}:{}),this.ws.on(`open`,()=>{if(this.stopped){this.ws?.close();return}this.ws?.send(JSON.stringify(this.subscribeMessage),e=>{e&&(this.emit(`error`,e),this.stop())})}),this.ws.on(`message`,e=>{if(!this.stopped)try{let t=JSON.parse(e.toString());if(t.error){this.emit(`error`,Error(t.error));return}if(t.lines&&t.lines.length>0){this.emit(`lines`,t.lines);for(let e of t.lines)this.emit(`line`,e)}}catch{}}),this.ws.on(`error`,e=>{this.stopped||this.emit(`error`,e)}),this.ws.on(`close`,()=>{this.stopped||(this.stopped=!0,this.emit(`close`)),this.ws=null})}};export{L as A,M as C,E as D,R as E,T as M,w as N,P as O,O as S,F as T,z as _,Je as a,A as b,Fe as c,Ae as d,Oe as f,te as g,B as h,qe as i,I as j,N as k,Q as l,K as m,Ze as n,Re as o,se as p,Ye as r,ze as s,Qe as t,je as u,ee as v,j as w,D as x,k as y};