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.
3 lines • 46.4 kB
JavaScript
import{A as e,C as t,D as n,E as r,M as i,N as a,O as o,S as s,T as c,_ as l,b as u,d,f,g as p,h as m,j as h,k as g,m as _,p as v,v as ee,w as te,x as ne,y as re}from"./log-stream.js";import{i as ie,r as ae}from"./ios-client.js";import{_ as oe,v as y}from"./destination-tunnel-dialer.js";import"./instance-client.js";import b,{promises as se}from"fs";import"net";import ce from"os";import x,{basename as le}from"path";import ue,{createHash as de}from"crypto";import"child_process";function S(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function C(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var fe=class{constructor(e,t,n,r){this.endpoint=e,this.tokenFile=t,this.fetcher=n,this.fetchOptions=r}async get(){return this.cached&&this.cached.expires-Date.now()>6e4?this.cached.token:(this.pending||=this.exchange().finally(()=>{this.pending=void 0}),this.pending)}async exchange(){let{readFile:e}=await import(`node:fs/promises`),t=(await e(this.tokenFile,`utf8`)).trim(),n=await this.fetcher(`${this.endpoint.replace(/\/$/,``)}/v1/access_tokens`,{...this.fetchOptions,method:`POST`,headers:{Authorization:`Bearer ${t}`,"Content-Type":`application/json`},body:JSON.stringify({}),signal:AbortSignal.timeout(3e4),redirect:`error`});if(!n.ok)throw Error(`Workload token exchange returned HTTP ${n.status}`);let r=await n.json();if(!r.token)throw Error(`This instance has no delegated asset permissions`);let i=Date.parse(r.expiresAt);if(!Number.isFinite(i)||i<=Date.now())throw Error(`Workload token exchange returned an invalid expiration`);return this.cached={token:r.token,expires:i},r.token}};let pe=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return pe=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};const me=/^[a-z][a-z0-9+.-]*:/i,he=e=>me.test(e);let w=e=>(w=Array.isArray,w(e)),ge=w;function _e(e){return typeof e==`object`?e??{}:{}}function ve(e){if(!e)return!0;for(let t in e)return!1;return!0}function ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const be=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new n(`${e} must be an integer`);if(t<0)throw new n(`${e} must be a positive integer`);return t},xe=e=>{try{return JSON.parse(e)}catch{return}},T=`0.69.1`;function Se(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const Ce=()=>{let e=Se();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":T,"X-Stainless-OS":Ee(Deno.build.os),"X-Stainless-Arch":Te(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":T,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":T,"X-Stainless-OS":Ee(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Te(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=we();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":T,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":T,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function we(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const Te=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,Ee=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let De;const Oe=()=>De??=Ce();function ke(){if(typeof fetch<`u`)return y.fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Limrun({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ae(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function je(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ae({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function Me(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ne=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Pe(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new n(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}const E={off:0,error:200,warn:300,info:400,debug:500},Fe=(e,t,n)=>{if(e){if(ye(E,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(E))}`)}};function D(){}function O(e,t,n){return!t||E[e]>E[n]?D:t[e].bind(t)}const Ie={error:D,warn:D,info:D,debug:D};let Le=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ie;let r=Le.get(t);if(r&&r[0]===n)return r[1];let i={error:O(`error`,t,n),warn:O(`warn`,t,n),info:O(`info`,t,n),debug:O(`debug`,t,n)};return Le.set(t,[n,i]),i}const A=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Re(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var j,ze=class e extends Promise{constructor(e,t,n=Re){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,j.set(this,void 0),S(this,j,e,`f`)}_thenUnwrap(t){return new e(C(this,j,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(C(this,j,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};j=new WeakMap;var M,Be=class{constructor(e,t,n,r){M.set(this,void 0),S(this,M,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new n("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,M,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(M=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ve=class extends ze{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Re(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},N=class extends Be{constructor(e,t,n,r){super(e,t,n,r),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.getPaginatedItems();if(!(typeof this.options.query==`object`&&`endingBefore`in(this.options.query||{}))){let t=e[e.length-1]?.metadata.id;return t?{...this.options,query:{..._e(this.options.query),startingAfter:t}}:null}let t=e[0]?.metadata.id;return t?{...this.options,query:{..._e(this.options.query),endingBefore:t}}:null}};const P=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function F(e,t,n){return P(),new File(e,t??`unknown_file`,n)}function He(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Ue=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,We=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ge=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&We(e),Ke=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function qe(e,t,n){if(P(),e=await e,Ge(e))return e instanceof File?e:F([await e.arrayBuffer()],e.name);if(Ke(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),F(await I(r),t,n)}let r=await I(e);if(t||=He(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return F(r,t,n)}async function I(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(We(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ue(e))for await(let n of e)t.push(...await I(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Je(e)}`)}return t}function Je(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var L=class{constructor(e){this._client=e}};const Ye=Symbol(`brand.privateNullableHeaders`);function*Xe(e){if(!e)return;if(Ye in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ge(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ge(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const R=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Xe(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ye]:!0,values:t,nulls:n}};function Ze(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Qe=Object.freeze(Object.create(null)),z=((e=Ze)=>function(t,...r){if(t.length===1)return t[0];let i=!1,a=[],o=t.reduce((t,n,o)=>{/[?#]/.test(n)&&(i=!0);let s=r[o],c=(i?encodeURIComponent:e)(``+s);return o!==r.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Qe)??Qe)?.toString)&&(c=s+``,a.push({start:t.length+n.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+n+(o===r.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)a.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(a.sort((e,t)=>e.start-t.start),a.length>0){let e=0,t=a.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new n(`Path parameters result in path with invalid segments:\n${a.map(e=>e.error).join(`
`)}\n${o}\n${t}`)}return o})(Ze);var $e=class extends L{list(e,t={},n){return this._client.get(z`/v1/organizations/${e}/xcode_snapshots`,{query:t,...n})}get(e,t,n){return this._client.get(z`/v1/organizations/${e}/xcode_snapshots/${t}`,n)}delete(e,t,n){return this._client.delete(z`/v1/organizations/${e}/xcode_snapshots/${t}`,{...n,headers:R([{Accept:`*/*`},n?.headers])})}},et=class extends L{list(e,t={},n){return this._client.get(z`/v1/organizations/${e}/ios_snapshots`,{query:t,...n})}get(e,t,n){return this._client.get(z`/v1/organizations/${e}/ios_snapshots/${t}`,n)}delete(e,t,n){return this._client.delete(z`/v1/organizations/${e}/ios_snapshots/${t}`,{...n,headers:R([{Accept:`*/*`},n?.headers])})}},tt=class extends L{get(e,t){return this._client.get(`/v1/analytics`,{query:nt(e),...t})}getInstances(e,t){return this._client.get(`/v1/analytics/instances`,{query:nt(e),...t})}};function nt(e){let{startedAt:t,stoppedAt:n,...r}=e,i={...r};for(let[e,r]of Object.entries({startedAt:t,stoppedAt:n}))if(r!==void 0)for(let[t,n]of Object.entries(r))n!==void 0&&(i[`${e}[${t}]`]=n);return i}var B=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/gradle_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/gradle_instances`,N,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/gradle_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}update(e,t,n){let{ifMatch:r,...i}=t;return this._client.patch(z`/v1/gradle_instances/${e}`,{...n,body:i,headers:R([n?.headers,{"If-Match":r,Accept:`*/*`}])})}get(e,t){return this._client.get(z`/v1/gradle_instances/${e}`,t)}},rt=class extends L{create(e,t){return this._client.post(`/v1/scoped_tokens`,{body:e,...t})}},it=class extends L{createUploadURL(e,t){return this._client.get(z`/v1/assets/${e}/upload_urls`,t)}update(e,t,n){return this._client.patch(z`/v1/assets/${e}`,{body:t,...n,headers:R([{Accept:`*/*`},n?.headers])})}list(e={},t){return this._client.get(`/v1/assets`,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/assets/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}get(e,t={},n){return this._client.get(z`/v1/assets/${e}`,{query:t,...n})}getOrCreate(e,t){return this._client.put(`/v1/assets`,{body:e,...t})}};function at(e,t){if(!t)return{body:e};let n=0;return{body:new ReadableStream({pull(r){if(n>=e.length){r.close();return}let i=e.subarray(n,Math.min(n+262144,e.length));n+=i.length,r.enqueue(i),t(n,e.length)}}),duplex:`half`}}var ot=class extends it{async getOrUpload(e,t){let n=await this.getOrCreate({name:e.name??le(e.path),kind:e.kind??`App`,...e.platform&&{platform:e.platform},...e.ttl&&{ttl:e.ttl},...e.uploadOptions},t),r=await se.readFile(e.path),i=de(`md5`).update(r).digest(`hex`);if(n.md5&&n.md5===i)return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,kind:n.kind,...n.platform&&{platform:n.platform},md5:n.md5,...n.expiresAt&&{expiresAt:n.expiresAt}};let a=await y.fetch(n.signedUploadUrl,{headers:{...e.onUploadProgress&&{"Content-Length":r.length.toString()},"Content-Type":`application/octet-stream`},method:`PUT`,...at(r,e.onUploadProgress)});if(a.status!==200)throw Error(`Failed to upload asset: ${a.status} ${await a.text()}`);return{id:n.id,name:n.name,signedDownloadUrl:n.signedDownloadUrl,kind:n.kind,...n.platform&&{platform:n.platform},md5:i,...n.expiresAt&&{expiresAt:n.expiresAt}}}},st=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/ios_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/ios_instances`,N,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/ios_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}update(e,t,n){let{ifMatch:r,...i}=t;return this._client.patch(z`/v1/ios_instances/${e}`,{...n,body:i,headers:R([n?.headers,{"If-Match":r,Accept:`*/*`}])})}get(e,t){return this._client.get(z`/v1/ios_instances/${e}`,t)}},ct=class extends st{listSessionArtifacts(e,t,n){return this._client.get(z`/v1/ios_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}},lt=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/android_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/android_instances`,N,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/android_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}update(e,t,n){let{ifMatch:r,...i}=t;return this._client.patch(z`/v1/android_instances/${e}`,{...n,body:i,headers:R([n?.headers,{"If-Match":r,Accept:`*/*`}])})}get(e,t){return this._client.get(z`/v1/android_instances/${e}`,t)}},V=class extends lt{listSessionArtifacts(e,t,n){return this._client.get(z`/v1/android_instances/${e}/session_artifacts`,{query:t?{kind:t}:void 0,...n})}listRecordings(e,t){return this.listSessionArtifacts(e,`recording`,t)}listAppLogs(e,t){return this.listSessionArtifacts(e,`appLog`,t)}listEvents(e,t){return this.listSessionArtifacts(e,`eventLog`,t)}};async function ut(e,t,n,r){let i=x.resolve(r);await b.promises.mkdir(x.dirname(i),{recursive:!0});let a=await b.promises.mkdtemp(x.join(x.dirname(i),`.lim-download-`));try{let r=x.join(a,`download`);await ee(`${e.replace(/\/$/,``)}/files?path=${encodeURIComponent(n)}`,t,r),await b.promises.rename(r,i)}finally{await b.promises.rm(a,{recursive:!0,force:!0})}}function H(e){if([e.target,e.assetName,e.signedUploadUrl].filter(e=>e!==void 0).length!==1)throw Error(`Provide exactly one upload target or signedUploadUrl`);if(e.signedUploadUrl!==void 0){if(!e.signedUploadUrl)throw Error(`signedUploadUrl must not be empty`);return{signedUploadUrl:e.signedUploadUrl}}if(e.assetName===``)throw Error(`assetName must not be empty`);let t=e.target??`name/${e.assetName}`;if(t.startsWith(`name/`)){if(t===`name/`)throw Error(`Name targets must include an exact name after name/`)}else if(!/^asset_[0-7][0-9a-hjkmnp-tv-z]{25}$/.test(t))throw Error(`Upload target must be an asset ID or an exact name target`);if(e.token!==void 0&&!e.token.trim())throw Error(`Upload token must not be empty`);return{assetUpload:{target:t,ttl:e.ttl||`336h`,...e.token!==void 0&&{token:e.token},...e.uploadOptions!==void 0&&{uploadOptions:e.uploadOptions}}}}var dt=class extends L{create(e,t){let{reuseIfExists:n,wait:r,...i}=e;return this._client.post(`/v1/xcode_instances`,{query:{reuseIfExists:n,wait:r},body:i,...t})}list(e={},t){return this._client.getAPIList(`/v1/xcode_instances`,N,{query:e,...t})}delete(e,t){return this._client.delete(z`/v1/xcode_instances/${e}`,{...t,headers:R([{Accept:`*/*`},t?.headers])})}update(e,t,n){let{ifMatch:r,...i}=t;return this._client.patch(z`/v1/xcode_instances/${e}`,{...n,body:i,headers:R([n?.headers,{"If-Match":r,Accept:`*/*`}])})}get(e,t){return this._client.get(z`/v1/xcode_instances/${e}`,t)}};function U(e){let t=e.status.token;if(!t)throw Error(`Instance ${e.metadata.id} came back without its token: the credential used can read it but not control it.`);return t}var W=class extends Error{constructor(e){super(`Instance ${e} was gone before it reported any cache status`),this.instanceId=e,this.name=`XcodeCacheGoneError`}},G=class extends Error{constructor(e,t,n){super(`Timed out after ${Math.round(t/1e3)}s waiting for the cache ${e} to finish`+(n?` (last phase: ${n[e].phase})`:``)),this.side=e,this.timeoutMs=t,this.cache=n,this.name=`XcodeCacheTimeoutError`}};const ft={restore:12e5,save:72e4};function pt(e){return e===`disabled`||e===`unsupported`||e===`restored`||e===`skipped`||e===`failed`}function mt(e){return e===`disabled`||e===`published`||e===`skipped`||e===`failed`||e===`timed_out`}function ht(e,t){return t===`restore`?pt(e.restore.phase):mt(e.save.phase)}function gt(e,t={}){let n=t.side??`restore`,r=t.timeoutMs??ft[n],i=e.baseURL;for(;i.endsWith(`/`);)i=i.slice(0,-1);let a=`${i}/v1/xcode_instances/${encodeURIComponent(e.instanceId)}/cache`;return new Promise((i,o)=>{let s,c=``,l=!1,u=e=>{if(!l){l=!0,clearTimeout(d),t.signal?.removeEventListener(`abort`,f);try{h.close()}catch{}e()}},d=setTimeout(()=>u(()=>o(new G(n,r,s))),r),f=()=>u(()=>o(t.signal?.reason??Error(`aborted`))),p=!1,m=()=>{p||l||(p=!0,y.fetch(a,{headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`application/json`}}).then(async t=>{if(p=!1,t.status!==404){await t.text().catch(()=>void 0);return}u(()=>s?i({cache:s,gone:!0}):o(new W(e.instanceId)))}).catch(()=>{p=!1}))},h=oe({url:a,fetch:async(t,n)=>{let r=await y.fetch(t,n);return r.status===404&&u(()=>s?i({cache:s,gone:!0}):o(new W(e.instanceId))),r},onConnect:()=>t.onOpen?.(),headers:{Authorization:`Bearer ${e.apiKey}`,Accept:`text/event-stream`},onMessage:e=>{if(e.event!==`cache`&&e.event!==`gone`)return;let r;try{r=JSON.parse(typeof e.data==`string`?e.data:String(e.data))}catch(e){u(()=>o(Error(`Cache stream sent unreadable data: ${e}`)));return}if(s=r,e.event===`gone`){m();return}let a=`${r.restore.phase}/${r.restore.reason??``}|${r.save.phase}/${r.save.reason??``}`;a!==c&&(c=a,t.onUpdate?.(r)),ht(r,n)&&u(()=>i({cache:r,gone:!1}))}});if(t.signal?.aborted){f();return}t.signal?.addEventListener(`abort`,f,{once:!0})})}var _t=class extends W{constructor(e){super(e),this.name=`XcodeSnapshotGoneError`,this.message=`Instance ${e} was gone before it reported any disk snapshot status`}},vt=class extends G{constructor(e){super(e.side,e.timeoutMs,e.cache),this.name=`XcodeSnapshotTimeoutError`,this.message=e.message.replace(`the cache `,`the disk snapshot `),this.snapshot=e.cache?K(e.cache):void 0}};function K(e){let{cacheKey:t,...n}=e.save;return{...e,save:{...n,...t===void 0?{}:{snapshotKey:t}}}}async function yt(e,t={}){let{onUpdate:n,...r}=t;try{let t=await gt(e,{...r,...n?{onUpdate:e=>n(K(e))}:{}});return{snapshot:K(t.cache),gone:t.gone}}catch(e){throw e instanceof W?new _t(e.instanceId):e instanceof G?new vt(e):e}}function bt(e,t){let n=x.resolve(e),r=`limsync-cache-${x.basename(n)}-${ue.createHash(`sha1`).update(n).digest(`hex`).slice(0,8)}`;return{cacheKey:r,basisCacheDir:t??x.join(ce.tmpdir(),r)}}const xt=[`none`,`error`,`warn`,`info`,`debug`];function St(e,t){let n=xt.indexOf(t),r=e=>n>=xt.indexOf(e);return(t,n)=>{r(t)&&(t===`error`||t===`warn`?console[t](e,n):console.log(e,n))}}function Ct(e){return(t,n)=>{if(t.trim()===``)throw Error(`commandLine must not be empty`);if(n?.timeoutSeconds!==void 0&&(!Number.isInteger(n.timeoutSeconds)||n.timeoutSeconds<1||n.timeoutSeconds>21600))throw Error(`timeoutSeconds must be an integer between 1 and 21600`);let r={command:`run`,commandLine:t,cwd:n?.cwd??`.`,...n?.env?.length&&{env:n.env},...n?.timeoutSeconds!==void 0&&{timeoutSeconds:n.timeoutSeconds}};return v(r,e)}}const wt=/^[A-Z0-9_]+$/,Tt=4096,Et=65536;function Dt(e){let t=Object.entries(e);if(t.length>32)throw Error(`too many build settings: got ${t.length}, max 32`);let n=0;for(let[e,r]of t){if(!wt.test(e))throw Error(`invalid build setting key "${e}": keys must match ^[A-Z0-9_]+$`);if(typeof r!=`string`)throw Error(`invalid build setting value for "${e}": value must be a string`);let t=Buffer.byteLength(r,`utf8`);if(t>Tt)throw Error(`build setting value for "${e}" is too large: got ${t} bytes, max ${Tt} bytes`);if(n+=Buffer.byteLength(e,`utf8`)+t,n>Et)throw Error(`build settings payload is too large: max ${Et} bytes`)}}const Ot=e=>new Promise(t=>setTimeout(t,e)),kt=/failed: (?:502|503|504)\b|\bEOF\b|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed/i;function At(e){let t=e instanceof Error?e.message:String(e);return kt.test(t)}async function jt(e,t={}){let n=t.sleep??Ot,r=t.attempts??5,i=t.retryOn??At,a;for(let o=1;o<=r;o++)try{return await e()}catch(e){if(!i(e))throw e;if(a=e,o<r){let r=e instanceof Error?e.message:String(e);t.log?.(`Retrying after error (${r.trim()})...`),await n(2e3*o)}}throw a}function Mt(e){if(e===``||e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`))throw Error(`invalid sandbox home path from server: ${e}`);let t=e.split(`/`);if(t.some(e=>e===``||e===`.`||e===`..`))throw Error(`invalid sandbox home path from server: ${e}`);return t.join(`/`)}async function Nt(e,t){let n=await J(await y.fetch(`${e}/info`,{method:`GET`,headers:{Authorization:`Bearer ${t}`}}),`GET /info`);if(!n.homeDir)throw Error(`GET /info response is missing homeDir`);return{homeDir:Mt(n.homeDir),...n.xcode?{xcode:n.xcode}:{}}}function Pt(e){let t=new URL(e);if(t.protocol===`https:`)t.protocol=`wss:`;else if(t.protocol===`http:`)t.protocol=`ws:`;else throw Error(`Unsupported apiUrl protocol for rbe tunnel: ${t.protocol}`);return t.pathname=`${t.pathname.replace(/\/+$/,``)}/rbe/tunnel`,t.search=``,t.hash=``,t.toString()}var Ft=class extends n{constructor(e){super(`Remote build execution is not available on this Xcode instance (${e} returned 404). Its limbuild may predate RBE support, or you may be targeting the wrong environment (for example production instead of staging).`),this.name=`RbeUnsupportedError`}},It=class extends n{constructor(e){super(`Xcode version selection is not available on this sandbox (${e} returned 404): its daemon predates Xcode selection. Create a new sandbox, or omit the Xcode version to build with its default.`),this.name=`XcodeSelectionUnsupportedError`}};function Lt(e,t){return Rt(e,t,e=>new It(e))}function q(e,t){return Rt(e,t,e=>new Ft(e))}async function Rt(e,t,n){if(e.status===404)throw await e.text().catch(()=>void 0),n(t);return J(e,t)}async function J(e,t){let n=await e.text();if(!e.ok)throw m(t,e.status,n,e.headers);if(!n.trim())throw Error(`${t} returned an empty response`);return JSON.parse(n)}var zt=class extends dt{listBuildLogs(e,t){return this._client.get(z`/v1/xcode_instances/${e}/build_logs`,t)}listBazelBuildLogs(e,t){return this._client.get(z`/v1/xcode_instances/${e}/bazel_build_logs`,t)}create(e,t){if(e.spec?.snapshot!==void 0){let{snapshot:n,cache:r,...i}=e.spec;if(r!==void 0)throw Error(`Use either spec.snapshot or the legacy spec.cache, not both.`);return super.create({...e,spec:{...i,cache:n}},t)}return super.create(e,t)}getSnapshot(e,t){return this.getCache(e,t)._thenUnwrap(K)}bindSnapshotKey(e,t,n){return this.bindCacheKey(e,t,n)._thenUnwrap(K)}followSnapshot(e,t){let n=this._client.apiKey;if(!n)throw Error(`Following disk snapshot status needs an API key on the client`);return yt({baseURL:this._client.baseURL,apiKey:n,instanceId:e},t)}getCache(e,t){return this._client.get(z`/v1/xcode_instances/${e}/cache`,t)}bindCacheKey(e,t,n){return this._client.put(z`/v1/xcode_instances/${e}/cache`,{body:{key:t},...n})}followCache(e,t){let n=this._client.apiKey;if(!n)throw Error(`Following cache status needs an API key on the client`);return gt({baseURL:this._client.baseURL,apiKey:n,instanceId:e},t)}async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=U(e.instance)}else t=e.apiUrl,n=e.token;let r=St(`[XcodeInstance]`,e.logLevel??`info`),i=this._client,a=async e=>{let r,i;if(`status`in e){if(!e.status.apiUrl)throw Error(`Simulator instance not ready: apiUrl is not available`);r=e.status.apiUrl,i=U(e)}else r=e.apiUrl,i=e.token;return J(await y.fetch(`${t}/simulator`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({apiUrl:r,token:i})}),`POST /simulator`)},o=async e=>{try{return await i.iosInstances.delete(e),!0}catch{return!1}};return{async pullFile(e,r){await ut(t,n,e,r)},async sync(e,i){let{cacheKey:a,basisCacheDir:o}=bt(e,i?.basisCacheDir),s={apiUrl:t,token:n,udid:a,install:i?.install??!0,ignoreFn:await ae(e,{basisCacheDir:o,log:r,xcodeDefaults:!0,...i?.include?{include:i.include}:{},...i?.ignore?{additional:i.ignore}:{}}),basisCacheDir:o,watch:i?.watch??!0,launchMode:`ForegroundIfRunning`,log:r,syncSymlinks:!0,...i?.additionalFiles&&{additionalFiles:i.additionalFiles},...i?.onSyncComplete?{onSyncComplete:i.onSyncComplete}:{}},c=await f(e,s),l={};return c.bytesSent!==void 0&&(l.bytesSent=c.bytesSent),c.stopWatching&&(l.stopWatching=c.stopWatching),l},xcodebuild(e,i){if(i?.reactNative?.devServerURL&&e?.configuration===`Release`)throw Error(`reactNative.devServerURL is only supported for Debug builds`);if(e?.onlyTesting?.length&&e?.skipTesting?.length)throw Error(`onlyTesting and skipTesting are mutually exclusive; pass one`);if((e?.onlyTesting?.length||e?.skipTesting?.length)&&e?.action!==`build-for-testing`)throw Error(`onlyTesting/skipTesting require action: 'build-for-testing'`);if(e?.runTests===!1&&e?.action!==`build-for-testing`)throw Error(`runTests: false requires action: 'build-for-testing'`);if(e?.action===`build-for-testing`&&e.sdk!==void 0&&e.sdk!==`iphonesimulator`)throw Error(`action: 'build-for-testing' requires the iphonesimulator sdk`);i?.buildSettings&&Dt(i.buildSettings);let a={command:`xcodebuild`,...e&&{xcodebuild:e},...i?.xcodegen&&{xcodegen:i.xcodegen},...i?.reactNative&&{reactNative:i.reactNative},...i?.signing&&{signing:i.signing},...i?.cloudSigning&&{cloudSigning:i.cloudSigning},...i?.appstore&&{testflight:i.appstore},...i?.buildSettings&&{buildSettings:i.buildSettings},...i?.env?.length&&{env:i.env},...i?.gitInit!==void 0&&{gitInit:i.gitInit},...i?.logProcessor&&{logProcessor:i.logProcessor},...i?.webhook&&{webhook:i.webhook}},o={apiUrl:t,token:n,log:r,...i?.onXctestEvent&&{onXctestEvent:i.onXctestEvent}};return i?.upload&&Object.assign(a,H(i.upload)),v(a,o)},run:Ct({apiUrl:t,token:n,log:r}),observeBuildLogs(e,i){return _(e,{apiUrl:t,token:n,log:r,...i})},async getSimulator(){return J(await y.fetch(`${t}/simulator`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /simulator`)},attachSimulator:a,attachNewSimulator:async e=>{let t=await i.iosInstances.create({wait:!0,spec:{...e?.model&&{model:e.model},...e?.clues&&{clues:e.clues},role:{permissions:[]}}});try{await a(t)}catch(e){throw await o(t.metadata.id),e}return{iosInstanceId:t.metadata.id,simulator:t}},deleteSimulator:o,async getXcode(){return Lt(await y.fetch(`${t}/xcode`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /xcode`)},async setXcode(e){return Lt(await y.fetch(`${t}/xcode`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify({version:e})}),`POST /xcode`)},getInfo:()=>Nt(t,n),async startRbe(e){return q(await y.fetch(`${t}/rbe`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify(e??{})}),`POST /rbe`)},async getRbe(){return q(await y.fetch(`${t}/rbe`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe`)},async stopRbe(){return q(await y.fetch(`${t}/rbe`,{method:`DELETE`,headers:{Authorization:`Bearer ${n}`}}),`DELETE /rbe`)},async startRbeTunnel(r){return d(Pt(t),n,r?.host??`127.0.0.1`,r?.port??8980,{mode:`multiplexed`,logLevel:r?.logLevel??e.logLevel??`info`})},async uploadLatestRbeBuild(e){let r=H(e);return await jt(async()=>{let e=await y.fetchLongRequest(`${t}/rbe/upload`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${n}`},body:JSON.stringify(r)});if(e.status===404)throw await e.text().catch(()=>void 0),Error(`POST /rbe/upload returned 404: the instance may no longer exist, or its limbuild predates RBE upload support. Recreate the instance and retry.`);return J(e,`POST /rbe/upload`)},{retryOn:e=>At(e)||p(e,400)&&/no successful RBE app build/i.test(e.body)})},async getActiveRbeBuilds(){return q(await y.fetch(`${t}/rbe/builds/active`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe/builds/active`)},async getRecentRbeBuilds(){return q(await y.fetch(`${t}/rbe/builds/recent`,{method:`GET`,headers:{Authorization:`Bearer ${n}`}}),`GET /rbe/builds/recent`)},waitForRbeBuildEnd(e,r){return new Promise((i,a)=>{if(r?.signal?.aborted){a(Error(`waiting for build ${e} was aborted`));return}let o=!1,s=()=>{f.close(),r?.signal?.removeEventListener(`abort`,d)},c=e=>{o||(o=!0,s(),i(e))},u=e=>{o||(o=!0,s(),a(e))},d=()=>u(Error(`waiting for build ${e} was aborted`)),f=oe({url:`${t}/exec/${e}/events`,fetch:l(y.fetch,t=>u(Error(`build event stream for ${e} is unreachable: ${t instanceof Error?t.message:t}`))),headers:{Authorization:`Bearer ${n}`},onMessage:t=>{if(t.event!==`end`)return;let n;try{n=JSON.parse(t.data)}catch(t){u(Error(`invalid build end event for ${e}: ${t}`));return}c(n)},onDisconnect:()=>{u(Error(`build event stream for ${e} ended without a terminal event (the build may have finished and its live stream been removed)`))}});r?.signal?.addEventListener(`abort`,d,{once:!0})})}}}};function Bt(e){let t=e.endsWith(`/`)?e.slice(0,-1):e,n=t.split(`/`);return n[n.length-1]===`local.properties`||n.length===1&&(t===`.gradle`||t===`.kotlin`||t===`build`)}var Vt=class extends B{listBuildLogs(e,t){return this._client.get(z`/v1/gradle_instances/${e}/build_logs`,t)}async createClient(e){let t,n;if(`instance`in e){if(!e.instance.status.apiUrl)throw Error(`Instance not ready: apiUrl is not available`);t=e.instance.status.apiUrl,n=U(e.instance)}else t=e.apiUrl,n=e.token;let r=St(`[GradleInstance]`,e.logLevel??`info`);return this._client,{async pullFile(e,r){await ut(t,n,e,r)},async sync(e,i){let{cacheKey:a,basisCacheDir:o}=bt(e,i?.basisCacheDir),s=i?.ignore,c={apiUrl:t,token:n,udid:a,install:!1,ignoreFn:await ae(e,{basisCacheDir:o,log:r,xcodeDefaults:!1,nestedGitignore:!0,additional:s?e=>Bt(e)||s(e):Bt,...i?.include?{include:i.include}:{}}),basisCacheDir:o,watch:i?.watch??!1,launchMode:`ForegroundIfRunning`,log:r,syncSymlinks:!0,...i?.additionalFiles&&{additionalFiles:i.additionalFiles},...i?.onSyncComplete&&{onSyncComplete:i.onSyncComplete}},l=await f(e,c),u={};return l.bytesSent!==void 0&&(u.bytesSent=l.bytesSent),l.stopWatching&&(u.stopWatching=l.stopWatching),u},run:Ct({apiUrl:t,token:n,log:r}),gradlebuild(e){let i={command:`gradlebuild`,...e?.env?.length&&{env:e.env},...e?.tasks?.length&&{tasks:e.tasks},...e?.projectPath&&{projectPath:e.projectPath},...e?.reactNative&&{reactNative:e.reactNative},...e?.signing&&{signing:e.signing},...e?.webhook&&{webhook:e.webhook},...e?.playstore&&{playstore:e.playstore}};return e?.upload&&Object.assign(i,H(e.upload)),v(i,{apiUrl:t,token:n,log:r})},observeBuildLogs(e,i){return _(e,{apiUrl:t,token:n,log:r,...i})}}}};B.prototype.listBuildLogs=Vt.prototype.listBuildLogs,B.prototype.createClient=Vt.prototype.createClient;var Ht=class extends L{create(e,t){return this._client.post(`/v1/access_tokens`,{body:e,...t})}revoke(e,t){return this._client.delete(`/v1/access_tokens/${encodeURIComponent(e)}`,t)}};const Y=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var X,Z,Q,Ut,$=class{constructor({baseURL:e=Y(`LIMRUN_BASE_URL`),apiKey:t=Y(`LIM_API_KEY`)??null,...n}={}){X.add(this),Q.set(this,void 0),this.androidInstances=new V(this),this.assets=new ot(this),this.iosInstances=new ct(this),this.xcodeInstances=new zt(this),this.xcodeSnapshots=new $e(this),this.iosSnapshots=new et(this),this.gradleInstances=new B(this),this.analytics=new tt(this),this.accessTokens=new Ht(this),this.scopedTokens=new rt(this);let r=n.workloadTokenFile===null?void 0:n.workloadTokenFile??Y(`LIMRUN_WORKLOAD_IDENTITY_TOKEN_FILE`),i={apiKey:t,...n,baseURL:e||(!t&&r?Y(`DIRECTOR_URL`):void 0)||`https://api.limrun.com`};this.baseURL=i.baseURL,this.timeout=i.timeout??Z.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Fe(i.logLevel,`ClientOptions.logLevel`,this)??Fe(Y(`LIMRUN_LOG`),`process.env['LIMRUN_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ke(),S(this,Q,Ne,`f`);let o=Y(`LIMRUN_CUSTOM_HEADERS`);if(o){let e={};for(let t of o.split(`
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}this._options=i,this.apiKey=t,!t&&r&&(this.workloadCredentials=new fe(this.baseURL,r,this.fetch,this.fetchOptions))}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!((this.apiKey||this.workloadCredentials)&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected the apiKey to be set. Or for the "Authorization" headers to be explicitly omitted`)}async authHeaders(e){if(this.apiKey==null){let t=R([this._options.defaultHeaders,e.headers]);return t.values.has(`authorization`)||t.nulls.has(`authorization`)?void 0:this.workloadCredentials?R([{Authorization:`Bearer ${await this.workloadCredentials.get()}`}]):void 0}return R([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Pe(e)}getUserAgent(){let e=`${this.constructor.name}/JS ${T}`,t=this._options.userAgent?.trim();return t?`${t} ${e}`:e}defaultIdempotencyKey(){return`stainless-node-retry-${pe()}`}makeStatusError(e,t,n,r){return ne.generate(e,t,n,r)}buildURL(e,t,n){let r=!C(this,X,`m`,Ut).call(this)&&n||this.baseURL,i=he(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!ve(a)||!ve(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ze(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,o=r.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(r);let{req:c,url:l,timeout:d}=await this.buildRequest(r,{retryCount:o-t});await this.prepareRequest(c,{url:l,options:r});let f=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),p=n===void 0?``:`, retryOf: ${n}`,m=Date.now();if(k(this).debug(`[${f}] sending request`,A({retryOfRequestLogID:n,method:r.method,url:l,options:r,headers:c.headers})),r.signal?.aborted)throw new s;let h=new AbortController,g=await this.fetchWithTimeout(l,c,d,h).catch(i),_=Date.now();if(g instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new s;let i=a(g)||/timed? ?out/i.test(String(g)+(`cause`in g?String(g.cause):``));if(t)return k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (${e})`,A({retryOfRequestLogID:n,url:l,durationMs:_-m,message:g.message})),this.retryRequest(r,t,n??f);throw k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - error; no more retries left`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,A({retryOfRequestLogID:n,url:l,durationMs:_-m,message:g.message})),i?new u:new re({cause:g})}let v=`[${f}${p}] ${c.method} ${l} ${g.ok?`succeeded`:`failed`} with status ${g.status} in ${_-m}ms`;if(!g.ok){let e=await this.shouldRetry(g);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Me(g.body),k(this).info(`${v} - ${e}`),k(this).debug(`[${f}] response error (${e})`,A({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-m})),this.retryRequest(r,t,n??f,g.headers)}let a=e?`error; no more retries left`:`error; not retryable`;k(this).info(`${v} - ${a}`);let o=await g.text().catch(e=>i(e).message),s=xe(o),c=s?void 0:o;throw k(this).debug(`[${f}] response error (${a})`,A({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:c,durationMs:Date.now()-m})),this.makeStatusError(g.status,s,c,g.headers)}return k(this).info(v),k(this).debug(`[${f}] response start`,A({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:_-m})),{response:g,options:r,controller:h,requestLogID:f,retryOfRequestLogID:n,startTime:m}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Ve(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ie(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&be(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=R([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Oe()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?C(this,Q,`f`).call(this,{body:t,headers:R([n])}):{bodyHeaders:void 0,body:void 0};let r=R([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:je(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:C(this,Q,`f`).call(this,{body:t,headers:r})}};Z=$,Q=new WeakMap,X=new WeakSet,Ut=function(){return this.baseURL!==`https://api.limrun.com`},$.Limrun=Z,$.DEFAULT_TIMEOUT=3e5,$.LimrunError=n,$.APIError=ne,$.APIConnectionError=re,$.APIConnectionTimeoutError=u,$.APIUserAbortError=s,$.NotFoundError=o,$.ConflictError=c,$.RateLimitError=e,$.BadRequestError=te,$.AuthenticationError=t,$.InternalServerError=r,$.PermissionDeniedError=g,$.UnprocessableEntityError=h,$.toFile=qe,$.AndroidInstances=V,$.Assets=ot,$.IosInstances=ct,$.XcodeInstances=zt,$.GradleInstances=B,$.Analytics=tt,$.AccessTokens=Ht,$.ScopedTokens=rt,process.platform;export{$ as t};