evolve-sdk 0.0.55.dev1310__tar.gz → 0.0.55.dev1348__tar.gz

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.
Files changed (44) hide show
  1. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/PKG-INFO +1 -1
  2. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/bridge/dist/bridge.bundle.cjs +2 -2
  3. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/__init__.py +1 -1
  4. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve_sdk.egg-info/PKG-INFO +1 -1
  5. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/pyproject.toml +1 -1
  6. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/LICENSE +0 -0
  7. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/MANIFEST.in +0 -0
  8. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/README.md +0 -0
  9. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/bridge/__init__.py +0 -0
  10. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/_http.py +0 -0
  11. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/agent.py +0 -0
  12. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/bridge.py +0 -0
  13. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/browser_credentials.py +0 -0
  14. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/browser_profiles.py +0 -0
  15. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/config.py +0 -0
  16. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/hosted.py +0 -0
  17. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/integrations.py +0 -0
  18. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/managed_secrets.py +0 -0
  19. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/pipeline/__init__.py +0 -0
  20. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/pipeline/pipeline.py +0 -0
  21. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/pipeline/types.py +0 -0
  22. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/__init__.py +0 -0
  23. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/agent_md/judge.md +0 -0
  24. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/agent_md/reduce.md +0 -0
  25. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/agent_md/verify.md +0 -0
  26. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/user/judge.md +0 -0
  27. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/user/retry_feedback.md +0 -0
  28. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/prompts/user/verify.md +0 -0
  29. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/py.typed +0 -0
  30. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/results.py +0 -0
  31. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/retry.py +0 -0
  32. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/schema.py +0 -0
  33. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/sessions_client.py +0 -0
  34. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/storage_client.py +0 -0
  35. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/swarm/__init__.py +0 -0
  36. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/swarm/results.py +0 -0
  37. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/swarm/swarm.py +0 -0
  38. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/swarm/types.py +0 -0
  39. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve/utils.py +0 -0
  40. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve_sdk.egg-info/SOURCES.txt +0 -0
  41. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve_sdk.egg-info/dependency_links.txt +0 -0
  42. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve_sdk.egg-info/requires.txt +0 -0
  43. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/evolve_sdk.egg-info/top_level.txt +0 -0
  44. {evolve_sdk-0.0.55.dev1310 → evolve_sdk-0.0.55.dev1348}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1310
3
+ Version: 0.0.55.dev1348
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -214,7 +214,7 @@ ${e}
214
214
 
215
215
  }; __evolve_eos=$?; printf '%s' '${t}' 2>/dev/null >&9; exec 9>&-; (exit $__evolve_eos)`:e}function CPe(e,t){return e.endsWith(`${t}
216
216
  `)?e.slice(0,-(t.length+1)):e.endsWith(t)?e.slice(0,-t.length):e}function Kb(e,t){let n=qPe(e);return{stdout:CPe(n.stdout,t),stderr:n.stderr}}function yW(e,t){let n=`${e}
217
- `,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function vW(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function NPe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function o2t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!NPe(e)}function c2t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function l2t(e){return/^[^:]+:\d+$/.test(e)}function u2t(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function BT(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let t=e.allowedDestinations??[];if(t.length===0)return{networkBlockAll:!0};for(let i of t){if(i.trim()==="")throw new Kl("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(i)}). Every entry must be a hostname, *.wildcard domain, IPv4 address, or IPv4 CIDR \u2014 remove the blank entry (an empty allowlist would open the sandbox, not seal it).`,i);if(i.includes(","))throw new Kl("invalid-destination",`network.allowedDestinations entry "${i}" contains a comma. Daytona's allowlists are sent as one comma-joined string, so a comma inside an entry would smuggle extra destinations past the list caps \u2014 pass one destination per array entry.`,i)}let n=[],r=[];for(let i of t)if(NPe(i))n.push(i.includes("/")?i:`${i}/32`);else{if(o2t(i))throw new Kl("invalid-ipv4",`"${i}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,i);if(c2t(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(l2t(i))throw new Kl("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${i}" and list just the host or IP.`,i);if(i.includes("*")&&!u2t(i))throw new Kl("wildcard-hostname",`Daytona's domain allowlist supports exactly one wildcard form \u2014 a "*." prefix ("*.example.com" allows example.com and its subdomains) \u2014 and cannot express "${i}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,i);r.push(i)}if(n.length>0&&r.length>0)throw new Kl("mixed-allowlist",`Daytona's networkAllowList (IPv4 CIDRs) and domainAllowList (DNS names) are mutually exclusive \u2014 at most one may be non-empty per sandbox, and this policy names both kinds (CIDRs: ${n.join(", ")}; domains: ${r.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(r.length>0){let i=[...new Set(r)];if(i.length>lW)throw new Kl("allowlist-too-large",`Daytona allows at most ${lW} entries in its domain allowlist; this policy names ${i.length} domains (${i.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return{networkBlockAll:!1,domainAllowList:i.join(",")}}let a=[...new Set(n)];if(a.length>cW)throw new Kl("allowlist-too-large",`Daytona allows at most ${cW} entries in its network allowlist; this policy resolved to ${a.length} CIDRs (${a.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:a.join(",")}}function MPe(e){let t=BT(e);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:!1,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function DPe(e){let t=wW(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function UPe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function IW(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function BPe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function FPe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)FPe(r,t)}function d2t(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(FPe(c?.data,t),c)):o}}})}function p2t(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function mPe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function LPe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=p2t(a,o);;){let c=mPe(a,oy,0),l=mPe(a,cy,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=oy.length):l!==-1&&(u=l,d="stderr",f=cy.length),u===-1){let p=Math.max(0,a.length-(Ph-1));s(a.subarray(0,p)),a=a.slice(p);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function VPe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=LPe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function qPe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function h2t(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function GPe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>IM)return{sandboxes:r,complete:!1,pagesFetched:IM,stoppedAtLimit:!1,error:`sandbox list exceeded ${IM} sandboxes scanned`};if(t?.state){let o=BPe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(IW(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function TM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new xW({...e,apiKey:t})}var gPe,EM,bW,yPe,cW,lW,vPe,Z1t,SW,bPe,SPe,Nh,_Pe,IM,Kl,wPe,t2t,xM,IPe,xPe,n2t,EPe,dW,TPe,dPe,Iy,UT,_W,kPe,i2t,fPe,a2t,OPe,APe,f2t,$Pe,zPe,oW,xW,m2t,g2t,y2t,v2t,b2t,S2t,_2t,w2t,I2t,x2t,E2t,T2t,k2t,O2t,A2t,P2t,R2t,C2t,N2t,M2t,D2t,FT=Q(()=>{"use strict";uPe();gPe=require("crypto"),EM="c-fae503a880ec",bW={[`evolve-all-${EM}`]:`evolvingmachines/evolve-all:${EM}`,"evolve-all":"evolvingmachines/evolve-all"},yPe=10,cW=10,lW=20,vPe=18e4,Z1t=2e3,SW=6e5,bPe=5e3,SPe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Nh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),_Pe=100,IM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},wPe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images require the registry pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret; AWS ECR registrations name an IAM role Daytona assumes (no password). Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},t2t=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},xM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},IPe=class extends Error{constructor(){super("Daytona takes no create-time boot command: it never runs an image entrypoint or any argv at boot (harbor daytona/environment.py:706-708 works around exactly that, starting dockerd by hand). The boot is already inert \u2014 run the process by exec after create."),this.name="DaytonaBootCommandError"}},xPe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},n2t=new Set(["pending_build","building_snapshot","pulling_snapshot"]);EPe=class extends Error{phase;state;sandboxId;constructor(e,t,n){super(`Daytona sandbox boot abandoned during ${e} (provider state ${t??"not yet reported"}, sandbox ${n??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=e,this.state=t,this.sandboxId=n}},dW="evolve_boot",TPe=5e3,dPe=30;Iy=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};UT=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},_W=Symbol("daytona-snapshot-gone"),kPe=new Set(["pending","pulling","building","snapshotting"]),i2t=3;fPe=new Set(["error","build_failed"]),a2t=new Set(["latest","lts","stable"]);OPe=6e4,APe=2e3;f2t=class extends gy{constructor(e,t){super(e);let n=this;n.sandboxApi=d2t(n.sandboxApi,t)}};$Pe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=SPe;followLogs(e,t,n,r,a){return this.managedStream?VPe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=hPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:mW(vW(gW(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,p=Date.now(),m=yW(i,T=>{u+=T,t?.onStdout?.(T)}),y=new AbortController,b=this.followLogs(r,o,T=>{f&&(p=Date.now(),m.push(T))},T=>{f&&(p=Date.now(),d+=T,t?.onStderr?.(T))},y.signal),v=!1,S,w=b.then(()=>{},T=>{v||(S=T)}),I;try{I=await this.awaitStreamedExit(r,o,b,()=>p,t?.timeoutMs)}finally{v=!0,y.abort(),await Promise.race([w,Nh(this.streamTimings.drainMs)]),f=!1,S===void 0&&m.flush()}if(S!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=Kb(R,i)}catch{throw S}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw S;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=Kb(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:I,stdout:u,stderr:d}}let{stdout:c,stderr:l}=Kb(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Kb(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let m=Date.now()-r();if(m>=i.drainMs)break;await Promise.race([c,Nh(i.drainMs-m)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,p=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(p!==void 0&&Date.now()>=p)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await Nh(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=hPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:mW(vW(gW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=yW(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...Kb(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await Nh(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},zPe=class{constructor(e){this.sandbox=e}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=Q1t(e),n=e2t(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return(await this.sandbox.fs.listFiles(e)).map(t=>({name:t.name,path:e.endsWith("/")?`${e}${t.name}`:`${e}/${t.name}`,type:t.isDir?"dir":"file"}))}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},oW=class{constructor(e,t,n){this.sandbox=e,this.commands=new $Pe(e,t,n),this.files=new zPe(e)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),IW(this.sandbox)}async updateNetwork(e){let t=MPe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw DPe(n)?new Kl("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},xW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:SW,pollMs:bPe};snapshotDeleteTiming={timeoutMs:OPe,pollMs:APe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new f2t(t,e.managedToolboxUrl):new gy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${EM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new xPe;if(e.bootCommand!==void 0)throw new IPe;for(let f of e.phaseNetworkPolicies??[])BT(f);let t=BT(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:yPe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new xM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new oW(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&kPe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new xM(s);if(f&&p==="inactive"&&(p=(await fW(this.client,s,f)).state),f&&fPe.has(p??"")&&(pW(s)?d=await pPe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${p}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&p==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof xM||f instanceof Iy)throw f;let p=bW[s]??s,m=u!==void 0&&!l;m?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${p}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${p}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let y=()=>this.client.snapshot.create({name:s,image:kh.base(p),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:v=>console.log(`[daytona] ${v}`)}),b=async()=>{await y(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!m)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await y(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(v){if(!PPe(v)||l)throw v;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(y){if(y instanceof UT||y instanceof Iy)throw y;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${y instanceof Error?y.message:y}`);try{c=await this.client.create({image:p,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw UPe(p)?new wPe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new oW(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await RPe(this.client,e,this.snapshotConflictTiming);if(t===_W)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await fW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(fPe.has(t.state??"")&&pW(e)&&await pPe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new oW(n,this.sandboxUsers.get(e),this.managedStream)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return GPe(this.listStream(e),e)}listStream(e){let t=e?.state?h2t(e.state):void 0,n={limit:_Pe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};m2t=GPe;g2t=vW,y2t=mW,v2t=BT,b2t=MPe,S2t=DPe,_2t=UPe,w2t=IW,I2t=BPe,x2t=fW,E2t=RPe,T2t=PPe,k2t=pW,O2t=bW,A2t=gW,P2t=CPe,R2t=Kb,C2t=yW,N2t=LPe,M2t=VPe,D2t=qPe});var JPe=_(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0});kM.Metadata=void 0;kM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=Xb(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)TW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else TW(a,i),n.set(a,[i]);return r},append(a,i){a=Xb(a),TW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=Xb(a),n.delete(a)},get(a){var i;return a=Xb(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=Xb(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=Xb(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=U2t(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function Xb(e){return e.toLowerCase()}function TW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function U2t(e){return Symbol.iterator in e}});var OM=_(LT=>{"use strict";Object.defineProperty(LT,"__esModule",{value:!0});LT.Status=void 0;var B2t;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(B2t=LT.Status||(LT.Status={}))});var WPe=_(HPe=>{"use strict";Object.defineProperty(HPe,"__esModule",{value:!0})});var YPe=_(jPe=>{"use strict";Object.defineProperty(jPe,"__esModule",{value:!0})});var XPe=_(KPe=>{"use strict";Object.defineProperty(KPe,"__esModule",{value:!0})});var ZPe=_(AM=>{"use strict";Object.defineProperty(AM,"__esModule",{value:!0});AM.composeClientMiddleware=void 0;function F2t(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}AM.composeClientMiddleware=F2t});var tRe=_(Mh=>{"use strict";Mh.__esModule=void 0;Mh.__esModule=!0;var L2t=typeof Object.setPrototypeOf=="function",V2t=typeof Object.getPrototypeOf=="function",q2t=typeof Object.defineProperty=="function",$2t=typeof Object.create=="function",z2t=typeof Object.prototype.hasOwnProperty=="function",G2t=function(t,n){L2t?Object.setPrototypeOf(t,n):t.__proto__=n};Mh.setPrototypeOf=G2t;var J2t=function(t){return V2t?Object.getPrototypeOf(t):t.__proto__||t.prototype};Mh.getPrototypeOf=J2t;var QPe=!1,H2t=function e(t,n,r){if(q2t&&!QPe)try{Object.defineProperty(t,n,r)}catch{QPe=!0,e(t,n,r)}else t[n]=r.value};Mh.defineProperty=H2t;var eRe=function(t,n){return z2t?t.hasOwnProperty(t,n):t[n]===void 0};Mh.hasOwnProperty=eRe;var W2t=function(t,n){if($2t)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)eRe(n,i)&&(a[i]=n[i].value);return a};Mh.objectCreate=W2t});var OW=_(Zb=>{"use strict";Zb.__esModule=void 0;Zb.__esModule=!0;var RM=tRe(),j2t=RM.setPrototypeOf,Y2t=RM.getPrototypeOf,kW=RM.defineProperty,K2t=RM.objectCreate,X2t=new Error().toString()==="[object Error]",PM="";function VT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?PM||"Error":o[1]}(),r=n==="Error",a=r?PM:n,i=Error.apply(this,arguments);if(j2t(i,Y2t(this)),!(i instanceof t)||!(i instanceof VT)){var i=this;Error.apply(this,arguments),kW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(kW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?VT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return X2t&&kW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}PM=VT.name||"ExtendableError";VT.prototype=K2t(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});Zb.ExtendableError=VT;Zb.default=Zb.ExtendableError});var nRe=_(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ClientError=void 0;var Z2t=OW(),Q2t=OM(),AW=class e extends Z2t.ExtendableError{constructor(t,n,r){super(`${t} ${Q2t.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};CM.ClientError=AW});var iRe=_(rRe=>{"use strict";Object.defineProperty(rRe,"__esModule",{value:!0})});var sRe=_(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0})});var oRe=_(NM=>{"use strict";Object.defineProperty(NM,"__esModule",{value:!0});NM.composeServerMiddleware=void 0;function eMt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}NM.composeServerMiddleware=eMt});var cRe=_(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0});MM.ServerError=void 0;var tMt=OW(),nMt=OM(),PW=class e extends tMt.ExtendableError{constructor(t,n){super(`${nMt.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};MM.ServerError=PW});var Xc=_($a=>{"use strict";var rMt=$a&&$a.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Xl=$a&&$a.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&rMt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(JPe(),$a);Xl(OM(),$a);Xl(WPe(),$a);Xl(YPe(),$a);Xl(XPe(),$a);Xl(ZPe(),$a);Xl(nRe(),$a);Xl(iRe(),$a);Xl(sRe(),$a);Xl(oRe(),$a);Xl(cRe(),$a)});var Yt=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Zc.Propagate=Zc.LogVerbosity=Zc.Status=void 0;var lRe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(lRe||(Zc.Status=lRe={}));var uRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(uRe||(Zc.LogVerbosity=uRe={}));var dRe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(dRe||(Zc.Propagate=dRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var RW=_((pwn,iMt)=>{iMt.exports={name:"@grpc/grpc-js",version:"1.14.4",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=_(hc=>{"use strict";var CW,NW,MW,DW;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=mMt;hc.isTracerEnabled=pRe;var Dh=Yt(),aMt=require("process"),sMt=RW().version,oMt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},xy=oMt,Qb=Dh.LogVerbosity.ERROR,cMt=(NW=(CW=process.env.GRPC_NODE_VERBOSITY)!==null&&CW!==void 0?CW:process.env.GRPC_VERBOSITY)!==null&&NW!==void 0?NW:"";switch(cMt.toUpperCase()){case"DEBUG":Qb=Dh.LogVerbosity.DEBUG;break;case"INFO":Qb=Dh.LogVerbosity.INFO;break;case"ERROR":Qb=Dh.LogVerbosity.ERROR;break;case"NONE":Qb=Dh.LogVerbosity.NONE;break;default:}var lMt=()=>xy;hc.getLogger=lMt;var uMt=e=>{xy=e};hc.setLogger=uMt;var dMt=e=>{Qb=e};hc.setLoggerVerbosity=dMt;var fMt=(e,...t)=>{let n;if(e>=Qb){switch(e){case Dh.LogVerbosity.DEBUG:n=xy.debug;break;case Dh.LogVerbosity.INFO:n=xy.info;break;case Dh.LogVerbosity.ERROR:n=xy.error;break}n||(n=xy.error),n&&n.bind(xy)(...t)}};hc.log=fMt;var pMt=(DW=(MW=process.env.GRPC_NODE_TRACE)!==null&&MW!==void 0?MW:process.env.GRPC_TRACE)!==null&&DW!==void 0?DW:"",UW=new Set,fRe=new Set;for(let e of pMt.split(","))e.startsWith("-")?fRe.add(e.substring(1)):UW.add(e);var hMt=UW.has("all");function mMt(e,t,n){pRe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+sMt+" "+aMt.pid+" | "+t+" | "+n)}function pRe(e){return!fRe.has(e)&&(hMt||UW.has(e))}});var UM=_(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.getErrorMessage=gMt;DM.getErrorCode=yMt;function gMt(e){return e instanceof Error?e.message:String(e)}function yMt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=_(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.Metadata=void 0;var vMt=hr(),bMt=Yt(),SMt=UM(),_Mt=/^[:0-9a-z_.-]+$/,wMt=/^[ -~]*$/;function IMt(e){return _Mt.test(e)}function xMt(e){return wMt.test(e)}function mRe(e){return e.endsWith("-bin")}function EMt(e){return!e.startsWith("grpc-")}function BM(e){return e.toLowerCase()}function hRe(e,t){if(!IMt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(mRe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!xMt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var BW=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=BM(t),hRe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=BM(t),hRe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=BM(t),this.internalRepr.delete(t)}get(t){return t=BM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(TMt));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{mRe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(EMt(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,SMt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,vMt.log)(bMt.LogVerbosity.ERROR,s)}}return n}};FM.Metadata=BW;var TMt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var VM=_(LM=>{"use strict";Object.defineProperty(LM,"__esModule",{value:!0});LM.CallCredentials=void 0;var qW=ma();function kMt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var eS=class e{static createFromMetadataGenerator(t){return new LW(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;kMt(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new qW.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new VW}};LM.CallCredentials=eS;var FW=class e extends eS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new qW.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},LW=class e extends eS{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new FW([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},VW=class e extends eS{generateMetadata(t){return Promise.resolve(new qW.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var zW=_(qT=>{"use strict";Object.defineProperty(qT,"__esModule",{value:!0});qT.CIPHER_SUITES=void 0;qT.getDefaultRootsData=AMt;var OMt=require("fs");qT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var gRe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,$W=null;function AMt(){return gRe?($W===null&&($W=OMt.readFileSync(gRe)),$W):null}});var no=_(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});tS.parseUri=RMt;tS.splitHostPort=CMt;tS.combineHostPort=NMt;tS.uriToString=MMt;var PMt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function RMt(e){let t=PMt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var yRe=/^\d+$/;function CMt(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return yRe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?yRe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function NMt(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function MMt(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Zl=_(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});up.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;up.registerResolver=DMt;up.registerDefaultScheme=UMt;up.createResolver=BMt;up.getDefaultAuthority=FMt;up.mapUriDefaultScheme=LMt;var JW=no();up.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var nS={},GW=null;function DMt(e,t){nS[e]=t}function UMt(e){GW=e}function BMt(e,t,n){if(e.scheme!==void 0&&e.scheme in nS)return new nS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,JW.uriToString)(e)}`)}function FMt(e){if(e.scheme!==void 0&&e.scheme in nS)return nS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,JW.uriToString)(e)}`)}function LMt(e){return e.scheme===void 0||!(e.scheme in nS)?GW!==null?{scheme:GW,authority:void 0,path:(0,JW.uriToString)(e)}:null:e}});var rS=_(zT=>{"use strict";Object.defineProperty(zT,"__esModule",{value:!0});zT.ChannelCredentials=void 0;zT.createCertificateProviderChannelCredentials=zMt;var $T=require("tls"),zM=VM(),WW=zW(),vRe=no(),VMt=Zl(),qMt=hr(),$Mt=Yt();function HW(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var Ey=class{compose(t){return new KW(this,t)}static createSsl(t,n,r,a){var i;if(HW(t,"Root certificate"),HW(n,"Private key"),HW(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,$T.createSecureContext)({ca:(i=t??(0,WW.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:WW.CIPHER_SUITES});return new qM(s,a??{})}static createFromSecureContext(t,n){return new qM(t,n??{})}static createInsecure(){return new jW}};zT.ChannelCredentials=Ey;var jW=class e extends Ey{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??zM.CallCredentials.createEmpty(),destroy(){}}}};function bRe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,vRe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,VMt.getDefaultAuthority)(o),l=(0,vRe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:$T.checkServerIdentity;s.checkServerIdentity=(p,m)=>f(d,m),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var YW=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,$T.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},qM=class e extends Ey{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=bRe(this.secureContext,this.verifyOptions,t,n);return new YW(a,r??zM.CallCredentials.createEmpty())}},$M=class e extends Ey{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??zM.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,$T.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:WW.CIPHER_SUITES})}catch(r){return(0,qMt.log)($Mt.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};$M.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=bRe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,$T.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function zMt(e,t,n){return new $M(e,t,n??{})}var KW=class e extends Ey{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??zM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Bh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=HMt;Td.registerLoadBalancerType=WMt;Td.registerDefaultLoadBalancerType=jMt;Td.createLoadBalancer=YMt;Td.isLoadBalancerNameRegistered=KMt;Td.parseLoadBalancingConfig=SRe;Td.getDefaultConfig=XMt;Td.selectLbConfigFromList=ZMt;var GMt=hr(),JMt=Yt();function HMt(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var Uh={},GT=null;function WMt(e,t,n){Uh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function jMt(e){GT=e}function YMt(e,t){let n=e.getLoadBalancerName();return n in Uh?new Uh[n].LoadBalancer(t):null}function KMt(e){return e in Uh}function SRe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in Uh)try{return Uh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function XMt(){if(!GT)throw new Error("No default load balancer type registered");return new Uh[GT].LoadBalancingConfig}function ZMt(e,t=!1){for(let n of e)try{return SRe(n)}catch(r){(0,GMt.log)(JMt.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&GT?new Uh[GT].LoadBalancingConfig:null}});var XW=_(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0});JT.validateRetryThrottling=_Re;JT.validateServiceConfig=wRe;JT.extractAndSelectServiceConfig=cDt;var QMt=require("os"),GM=Yt(),JM=/^\d+(\.\d{1,9})?s$/,eDt="node";function tDt(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function nDt(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!JM.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!JM.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(GM.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(GM.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function rDt(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!JM.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(GM.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(GM.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function iDt(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(tDt(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&JM.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=nDt(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=rDt(e.hedgingPolicy));return n}function _Re(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function aDt(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function wRe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(aDt(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(iDt(r));"retryThrottling"in e&&(t.retryThrottling=_Re(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function sDt(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:wRe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function oDt(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=sDt(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===QMt.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===eDt&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function cDt(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return oDt(a,t)}return null}});var ro=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.ConnectivityState=void 0;var IRe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(IRe||(HM.ConnectivityState=IRe={}))});var dp=_(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});Fh.QueuePicker=Fh.UnavailablePicker=Fh.PickResultType=void 0;var lDt=ma(),uDt=Yt(),WM;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(WM||(Fh.PickResultType=WM={}));var ZW=class{constructor(t){this.status=Object.assign({code:uDt.Status.UNAVAILABLE,details:"No connection established",metadata:new lDt.Metadata},t)}pick(t){return{pickResultType:WM.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Fh.UnavailablePicker=ZW;var QW=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:WM.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Fh.QueuePicker=QW});var iS=_(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.BackoffTimeout=void 0;var dDt=Yt(),fDt=hr(),pDt="backoff",hDt=1e3,mDt=1.6,gDt=12e4,yDt=.2;function vDt(e,t){return Math.random()*(t-e)+e}var jM=class e{constructor(t,n){this.callback=t,this.initialDelay=hDt,this.multiplier=mDt,this.maxDelay=gDt,this.jitter=yDt,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){fDt.trace(dDt.LogVerbosity.DEBUG,pDt,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+vDt(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};YM.BackoffTimeout=jM;jM.nextId=0});var XM=_(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ChildLoadBalancerHandler=void 0;var bDt=Bh(),SDt=ro(),_Dt="child_load_balancer_helper",e7=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===SDt.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,bDt.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return _Dt}};KM.ChildLoadBalancerHandler=e7});var TRe=_(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ResolvingLoadBalancer=void 0;var wDt=Bh(),IDt=XW(),No=ro(),xRe=Zl(),HT=dp(),xDt=iS(),t7=Yt(),EDt=ma(),TDt=hr(),kDt=Yt(),ODt=no(),ADt=XM(),PDt="resolving_load_balancer";function ERe(e){TDt.trace(kDt.LogVerbosity.DEBUG,PDt,e)}var RDt=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function CDt(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function NDt(e,t,n,r){for(let a of n)if(CDt(e,t,a,r))return a;return null}function MDt(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of RDt){let l=NDt(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:t7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:t7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var n7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new HT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,IDt.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(No.ConnectivityState.IDLE,new HT.QueuePicker(this),null),this.childLoadBalancer=new ADt.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(ERe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,xRe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new xDt.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,wDt.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:t7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new EDt.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[xRe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:MDt(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===No.ConnectivityState.IDLE&&this.updateState(No.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){ERe((0,ODt.uriToString)(this.target)+" "+No.ConnectivityState[this.currentState]+" -> "+No.ConnectivityState[t]),t===No.ConnectivityState.IDLE&&(n=new HT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===No.ConnectivityState.IDLE&&(this.updateState(No.ConnectivityState.TRANSIENT_FAILURE,new HT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===No.ConnectivityState.IDLE||this.currentState===No.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new HT.QueuePicker(this),this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};ZM.ResolvingLoadBalancer=n7});var kRe=_(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});WT.recognizedOptions=void 0;WT.channelOptionsEqual=DDt;WT.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function DDt(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Mo=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=YT;Ql.subchannelAddressEqual=QM;Ql.subchannelAddressToString=ARe;Ql.stringToSubchannelAddress=BDt;Ql.endpointEqual=FDt;Ql.endpointToString=LDt;Ql.endpointHasAddress=PRe;var ORe=require("net");function YT(e){return"port"in e}function QM(e,t){return!e&&!t?!0:!e||!t?!1:YT(e)?YT(t)&&e.host===t.host&&e.port===t.port:!YT(t)&&e.path===t.path}function ARe(e){return YT(e)?(0,ORe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var UDt=443;function BDt(e,t){return(0,ORe.isIP)(e)?{host:e,port:t??UDt}:{path:e}}function FDt(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!QM(e.addresses[n],t.addresses[n]))return!1;return!0}function LDt(e){return"["+e.addresses.map(ARe).join(", ")+"]"}function PRe(e,t){for(let n of e.addresses)if(QM(n,t))return!0;return!1}function jT(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(QM(n,a)){r=!0;break}if(!r)return!1}return!0}var r7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(PRe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)jT(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(jT(t,n.key))return n.value}set(t,n){for(let r of this.map)if(jT(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(jT(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(jT(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Ql.EndpointMap=r7});var RRe=_(d7=>{"use strict";Object.defineProperty(d7,"t",{value:!0});var eD=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},i7=class extends eD{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},a7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},s7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},o7=class extends s7{};function Ty(){throw new RangeError("Iterator access denied!")}var c7=class extends o7{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?i7:eD,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&Ty(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&Ty();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},l7=class extends a7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&Ty(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&Ty(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&Ty(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&Ty(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},eu=class e extends l7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&Ty();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},u7=class extends c7{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new eu(this.C.i||this.C,this.C,this)}end(){return new eu(this.C,this.C,this)}rBegin(){return new eu(this.C.h||this.C,this.C,this,1)}rEnd(){return new eu(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new eu(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new eu(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new eu(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new eu(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new eu(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};d7.OrderedMap=u7});var nD=_(tD=>{"use strict";Object.defineProperty(tD,"__esModule",{value:!0});tD.registerAdminService=VDt;tD.addAdminServicesToServer=qDt;var CRe=[];function VDt(e,t){CRe.push({getServiceDefinition:e,getHandlers:t})}function qDt(e){for(let{getServiceDefinition:t,getHandlers:n}of CRe)e.addService(t(),n())}});var NRe=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=zDt;var $Dt=require("events"),g7=require("stream"),KT=Yt();function zDt(e,t){let n=`${e.code} ${KT.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
217
+ `,r="",a=i=>{for(let s=Math.min(i.length,n.length);s>0;s--)if(n.startsWith(i.slice(i.length-s)))return s;return 0};return{push(i){r+=i;let s=a(r);s!==r.length&&(t(r.slice(0,r.length-s)),r=r.slice(r.length-s))},flush(){let i=r===n||r===e?"":r;r="",i&&t(i)}}}function vW(e,t,n,r){let a=e;return t&&(a=`cd '${t.replace(/'/g,"'\\''")}' && ${a}`),n&&Object.keys(n).length>0&&(a=`${Object.entries(n).filter(([,i])=>i!=null).map(([i,s])=>`export ${i}='${String(s).replace(/'/g,"'\\''")}'`).join("; ")}; ${a}`),r==="root"&&(a=`echo ${Buffer.from(a).toString("base64")} | base64 -d | sudo -n bash`),a}function NPe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function o2t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!NPe(e)}function c2t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function l2t(e){return/^[^:]+:\d+$/.test(e)}function u2t(e){return e.startsWith("*.")&&e.length>2&&!e.slice(2).includes("*")}function BT(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return e?{networkBlockAll:!1}:{}}let t=e.allowedDestinations??[];if(t.length===0)return{networkBlockAll:!0};for(let i of t){if(i.trim()==="")throw new Kl("invalid-destination",`network.allowedDestinations contains an empty destination (${JSON.stringify(i)}). Every entry must be a hostname, *.wildcard domain, IPv4 address, or IPv4 CIDR \u2014 remove the blank entry (an empty allowlist would open the sandbox, not seal it).`,i);if(i.includes(","))throw new Kl("invalid-destination",`network.allowedDestinations entry "${i}" contains a comma. Daytona's allowlists are sent as one comma-joined string, so a comma inside an entry would smuggle extra destinations past the list caps \u2014 pass one destination per array entry.`,i)}let n=[],r=[];for(let i of t)if(NPe(i))n.push(i.includes("/")?i:`${i}/32`);else{if(o2t(i))throw new Kl("invalid-ipv4",`"${i}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,i);if(c2t(i))throw new Kl("ipv6-unsupported",`Daytona's network allowlist supports IPv4 CIDRs only; cannot allow IPv6 destination "${i}".`,i);if(l2t(i))throw new Kl("port-unsupported",`Daytona's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${i}" and list just the host or IP.`,i);if(i.includes("*")&&!u2t(i))throw new Kl("wildcard-hostname",`Daytona's domain allowlist supports exactly one wildcard form \u2014 a "*." prefix ("*.example.com" allows example.com and its subdomains) \u2014 and cannot express "${i}". Use a *.prefix wildcard, a concrete hostname, or an IPv4 CIDR instead.`,i);r.push(i)}if(n.length>0&&r.length>0)throw new Kl("mixed-allowlist",`Daytona's networkAllowList (IPv4 CIDRs) and domainAllowList (DNS names) are mutually exclusive \u2014 at most one may be non-empty per sandbox, and this policy names both kinds (CIDRs: ${n.join(", ")}; domains: ${r.join(", ")}). List only IPs/CIDRs or only hostnames for this sandbox.`);if(r.length>0){let i=[...new Set(r)];if(i.length>lW)throw new Kl("allowlist-too-large",`Daytona allows at most ${lW} entries in its domain allowlist; this policy names ${i.length} domains (${i.join(", ")}). Consolidate under *.prefix wildcards or reduce the list.`);return{networkBlockAll:!1,domainAllowList:i.join(",")}}let a=[...new Set(n)];if(a.length>cW)throw new Kl("allowlist-too-large",`Daytona allows at most ${cW} entries in its network allowlist; this policy resolved to ${a.length} CIDRs (${a.join(", ")}). Aggregate destinations into broader CIDRs or reduce the list.`);return{networkBlockAll:!1,networkAllowList:a.join(",")}}function MPe(e){let t=BT(e);return t.networkAllowList!==void 0||t.domainAllowList!==void 0?{networkBlockAll:!1,networkAllowList:t.networkAllowList??"",domainAllowList:t.domainAllowList??""}:{networkBlockAll:t.networkBlockAll===!0,networkAllowList:"",domainAllowList:""}}function DPe(e){let t=wW(e),n=(e instanceof Error?e.message:String(e)).toLowerCase(),r=n.includes("network policy")||n.includes("network settings")||n.includes("network configuration"),a=n.includes("tier")||n.includes("plan")||n.includes("upgrade")||n.includes("not allowed")||n.includes("not permitted")||n.includes("cannot override");return(t===402||t===403)&&(a||r)?!0:r&&a}function UPe(e){let t=e.indexOf("/");if(t<0)return;let n=e.substring(0,t);return n.includes(".")||n.includes(":")||n==="localhost"?n:void 0}function IW(e){return{sandboxId:e.id,image:e.snapshot??"",name:e.name,metadata:e.labels??{},startedAt:e.createdAt??""}}function BPe(e){if(e==="started")return"running";if(e==="stopped"||e==="archived"||e==="paused")return"paused"}function FPe(e,t){if(!e||typeof e!="object")return;let n=e;if(typeof n.toolboxProxyUrl=="string"&&(n.toolboxProxyUrl=t),Array.isArray(n.items))for(let r of n.items)FPe(r,t)}function d2t(e,t){return new Proxy(e,{get(n,r,a){if(r==="getToolboxProxyUrl")return async()=>({data:{url:t}});let i=Reflect.get(n,r,a);return typeof i!="function"?i:function(...s){let o=i.apply(n,s);return o instanceof Promise?o.then(c=>(FPe(c?.data,t),c)):o}}})}function p2t(e,t){let n=new Uint8Array(new ArrayBuffer(e.length+t.length));return n.set(e,0),n.set(t,e.length),n}function mPe(e,t,n){e:for(let r=n;r+t.length<=e.length;r++){for(let a=0;a<t.length;a++)if(e[r+a]!==t[a])continue e;return r}return-1}function LPe(e,t){let n=new TextDecoder("utf-8"),r=new TextDecoder("utf-8"),a=new Uint8Array(0),i="stdout",s=o=>{o.length!==0&&(i==="stdout"?e(n.decode(o,{stream:!0})):t(r.decode(o,{stream:!0})))};return{push(o){for(a=p2t(a,o);;){let c=mPe(a,oy,0),l=mPe(a,cy,0),u=-1,d="stdout",f=0;if(c!==-1&&(l===-1||c<l)?(u=c,d="stdout",f=oy.length):l!==-1&&(u=l,d="stderr",f=cy.length),u===-1){let p=Math.max(0,a.length-(Ph-1));s(a.subarray(0,p)),a=a.slice(p);return}s(a.subarray(0,u)),i=d,a=a.slice(u+f)}},flush(){s(a),a=new Uint8Array(0);let o=n.decode();o&&e(o);let c=r.decode();c&&t(c)}}}async function VPe(e,t,n,r,a,i,s){let o=`${e.toolboxUrl.replace(/\/+$/,"")}/${encodeURIComponent(t)}/process/session/${encodeURIComponent(n)}/command/${encodeURIComponent(r)}/logs?follow=true`,c=await fetch(o,{headers:{Authorization:`Bearer ${e.apiKey}`,accept:"application/octet-stream"},...s?{signal:s}:{}});if(!c.ok)throw new Error(`Daytona managed log follow failed: ${c.status} ${await c.text()}`);if(!c.body)return;let l=LPe(a,i),u=c.body.getReader();try{for(;;){let{done:d,value:f}=await u.read();if(d)break;f&&l.push(f)}}finally{l.flush(),await u.cancel().catch(()=>{})}}function qPe(e){let t=e.stdout||"",n=e.stderr||"",r=e.output||"";return!t&&!n&&r?{stdout:r,stderr:""}:{stdout:t,stderr:n}}function h2t(e){let t=[];for(let n of e)n==="running"&&t.push("started"),n==="paused"&&t.push("stopped","archived","paused");return t}async function GPe(e,t){let n=t?.limit,r=[],a=0,i=new Set;try{for await(let s of e){if(n!==void 0&&r.length>=n)return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!0,error:`stopped at the requested limit of ${n} with more sandboxes available`};if(a+=1,a>IM)return{sandboxes:r,complete:!1,pagesFetched:IM,stoppedAtLimit:!1,error:`sandbox list exceeded ${IM} sandboxes scanned`};if(t?.state){let o=BPe(s.state);if(o===void 0||!t.state.includes(o))continue}i.has(s.id)||(i.add(s.id),r.push(IW(s)))}}catch(s){return{sandboxes:r,complete:!1,pagesFetched:a,stoppedAtLimit:!1,error:`sandbox list failed: ${s instanceof Error?s.message:String(s)}`}}return{sandboxes:r,complete:!0,pagesFetched:a,stoppedAtLimit:!1}}function TM(e={}){let t=e.apiKey??process.env.DAYTONA_API_KEY;if(!t)throw new Error("Daytona API key required. Set DAYTONA_API_KEY environment variable or pass apiKey in config. Get your key at https://app.daytona.io/dashboard/keys");return new xW({...e,apiKey:t})}var gPe,EM,bW,yPe,cW,lW,vPe,Z1t,SW,bPe,SPe,Nh,_Pe,IM,Kl,wPe,t2t,xM,IPe,xPe,n2t,EPe,dW,TPe,dPe,Iy,UT,_W,kPe,i2t,fPe,a2t,OPe,APe,f2t,$Pe,zPe,oW,xW,m2t,g2t,y2t,v2t,b2t,S2t,_2t,w2t,I2t,x2t,E2t,T2t,k2t,O2t,A2t,P2t,R2t,C2t,N2t,M2t,D2t,FT=Q(()=>{"use strict";uPe();gPe=require("crypto"),EM="c-880c264ce574",bW={[`evolve-all-${EM}`]:`evolvingmachines/evolve-all:${EM}`,"evolve-all":"evolvingmachines/evolve-all"},yPe=10,cW=10,lW=20,vPe=18e4,Z1t=2e3,SW=6e5,bPe=5e3,SPe={pollMinMs:250,pollMaxMs:2e3,drainMs:1e3,killGraceMs:15e3,settleMs:6e4},Nh=e=>new Promise(t=>setTimeout(t,Math.max(0,e))),_Pe=100,IM=1e4;Kl=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="DaytonaNetworkPolicyError",this.reason=e,this.destination=n}},wPe=class extends Error{image;constructor(e,t){let n=t instanceof Error?t.message:String(t??"unknown error");super(`Failed to pull image "${e}" on Daytona: ${n}. Private registry images require the registry pre-registered in the Daytona dashboard (Registries page) before sandbox creation \u2014 Daytona has no per-call image pull secret; AWS ECR registrations name an IAM role Daytona assumes (no password). Register the registry at https://app.daytona.io, then retry. Also ensure the image is linux/amd64 and pinned to a tag or digest (floating tags like "latest" are rejected by Daytona's snapshot builder).`),this.name="DaytonaImagePullError",this.image=e}},t2t=class extends Error{snapshot;constructor(e){super(`Daytona cannot constrain the GPU type for "${e}": the snapshot already exists and pins its resources \u2014 pre-build a snapshot with the desired GPU type under its own name.`),this.name="DaytonaGpuTypeError",this.snapshot=e}},xM=class extends Error{snapshot;constructor(e){super(`Daytona snapshot "${e}" already exists and pins its cpu/memory/disk sizing \u2014 create-from-snapshot cannot resize it, so the requested \`resources\` cannot be enforced. Pre-build a snapshot with the desired sizing under its own name (sizing-addressed), or omit \`resources\` to accept the snapshot's pinned sizing.`),this.name="DaytonaResourcesError",this.snapshot=e}},IPe=class extends Error{constructor(){super("Daytona takes no create-time boot command: it never runs an image entrypoint or any argv at boot (harbor daytona/environment.py:706-708 works around exactly that, starting dockerd by hand). The boot is already inert \u2014 run the process by exec after create."),this.name="DaytonaBootCommandError"}},xPe=class extends Error{constructor(){super("Daytona has no separate idle timeout: auto-stop IS its only clock and it already measures inactivity, so `timeoutMs` is what sets it (autoStopInterval). Set the inactivity bound with `timeoutMs`; a hard bound on the process itself is enforced in-box instead (see withInBoxTimeout)."),this.name="DaytonaIdleTimeoutError"}},n2t=new Set(["pending_build","building_snapshot","pulling_snapshot"]);EPe=class extends Error{phase;state;sandboxId;constructor(e,t,n){super(`Daytona sandbox boot abandoned during ${e} (provider state ${t??"not yet reported"}, sandbox ${n??"not yet created"})`),this.name="DaytonaBootAbortedError",this.phase=e,this.state=t,this.sandboxId=n}},dW="evolve_boot",TPe=5e3,dPe=30;Iy=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" exists but could not be activated: ${t}. Daytona deactivates snapshots unused for 2 weeks; activation normally completes in seconds. Retry, or activate it manually in the Daytona dashboard (Snapshots page).`),this.name="DaytonaSnapshotActivationError",this.snapshot=e}};UT=class extends Error{snapshot;constructor(e,t){super(`Daytona snapshot "${e}" is being created by another process and this run could not wait it out: ${t}.`),this.name="DaytonaSnapshotConflictError",this.snapshot=e}},_W=Symbol("daytona-snapshot-gone"),kPe=new Set(["pending","pulling","building","snapshotting"]),i2t=3;fPe=new Set(["error","build_failed"]),a2t=new Set(["latest","lts","stable"]);OPe=6e4,APe=2e3;f2t=class extends gy{constructor(e,t){super(e);let n=this;n.sandboxApi=d2t(n.sandboxApi,t)}};$Pe=class{constructor(e,t,n){this.sandbox=e,this.user=t,this.managedStream=n}streamTimings=SPe;followLogs(e,t,n,r,a){return this.managedStream?VPe(this.managedStream,this.sandbox.id,e,t,n,r,a):this.sandbox.process.getSessionCommandLogs(e,t,n,r)}async run(e,t){let n=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,r=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(r);try{let a=!!(t?.onStdout||t?.onStderr),i=hPe(),s=await this.sandbox.process.executeSessionCommand(r,{command:mW(vW(gW(e,i),t?.cwd,t?.envs,this.user),n),runAsync:a},n),o=s.cmdId;if(a&&!o)throw new Error("Daytona returned no command id for an async command \u2014 cannot stream it or read its exit code");if(a&&o){let u="",d="",f=!0,p=Date.now(),m=yW(i,T=>{u+=T,t?.onStdout?.(T)}),y=new AbortController,b=this.followLogs(r,o,T=>{f&&(p=Date.now(),m.push(T))},T=>{f&&(p=Date.now(),d+=T,t?.onStderr?.(T))},y.signal),v=!1,S,w=b.then(()=>{},T=>{v||(S=T)}),I;try{I=await this.awaitStreamedExit(r,o,b,()=>p,t?.timeoutMs)}finally{v=!0,y.abort(),await Promise.race([w,Nh(this.streamTimings.drainMs)]),f=!1,S===void 0&&m.flush()}if(S!==void 0){let T;try{let R=await this.sandbox.process.getSessionCommandLogs(r,o);T=Kb(R,i)}catch{throw S}if(!T.stdout.startsWith(u)||!T.stderr.startsWith(d))throw S;let k=T.stdout.slice(u.length),O=T.stderr.slice(d.length);u=T.stdout,d=T.stderr,k&&t?.onStdout?.(k),O&&t?.onStderr?.(O)}else if(!u&&!d)try{let T=await this.sandbox.process.getSessionCommandLogs(r,o),k=Kb(T,i);u=k.stdout,d=k.stderr,u&&t?.onStdout?.(u),d&&t?.onStderr?.(d)}catch{}return{exitCode:I,stdout:u,stderr:d}}let{stdout:c,stderr:l}=Kb(s,i);if(!c&&!l&&o)try{let u=await this.sandbox.process.getSessionCommandLogs(r,o),d=Kb(u,i);c=d.stdout,l=d.stderr||l}catch{}return{exitCode:s.exitCode??0,stdout:c,stderr:l}}finally{try{await this.sandbox.process.deleteSession(r)}catch{}}}async awaitStreamedExit(e,t,n,r,a){let i=this.streamTimings,s,o,c=n.then(()=>{s=Date.now()},d=>{s=Date.now(),o=d}),l=a!==void 0&&a>0?Date.now()+a+i.killGraceMs:void 0,u=i.pollMinMs;for(;;){let d=await this.sandbox.process.getSessionCommand(e,t);if(d.exitCode!==void 0&&d.exitCode!==null){for(;s===void 0;){let m=Date.now()-r();if(m>=i.drainMs)break;await Promise.race([c,Nh(i.drainMs-m)])}return d.exitCode}let f=s!==void 0?s+i.settleMs:void 0,p=l!==void 0&&f!==void 0?Math.min(l,f):l??f;if(p!==void 0&&Date.now()>=p)throw o!==void 0?o:new Error(`Daytona reported no exit code for command ${t} after `+(s!==void 0?"its log stream closed":`${a}ms`));await Nh(u),u=Math.min(u*2,i.pollMaxMs)}}async spawn(e,t){let n=`evolve-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await this.sandbox.process.createSession(n);let r=t?.timeoutMs?Math.floor(t.timeoutMs/1e3):void 0,a=Date.now(),i=t?.timeoutMs,s=hPe(),o=(await this.sandbox.process.executeSessionCommand(n,{command:mW(vW(gW(e,s),t?.cwd,t?.envs,this.user),r),runAsync:!0},r)).cmdId;if(o&&(t?.onStdout||t?.onStderr)){let l=yW(s,t.onStdout||(()=>{}));this.followLogs(n,o,u=>l.push(u),t.onStderr||(()=>{})).catch(()=>{}).finally(()=>l.flush())}let c=this.sandbox;return{processId:n,wait:async()=>{if(!o)return{exitCode:0,stdout:"",stderr:""};for(;;){if(i&&Date.now()-a>=i){try{await c.process.deleteSession(n)}catch{}return{exitCode:124,stdout:"",stderr:"operation timed out"}}try{let l=await c.process.getSessionCommand(n,o);if(l.exitCode!==void 0)try{let u=await c.process.getSessionCommandLogs(n,o);return{exitCode:l.exitCode,...Kb(u,s)}}catch{return{exitCode:l.exitCode,stdout:"",stderr:""}}}catch(l){let u=l instanceof Error?l.message.toLowerCase():String(l).toLowerCase();if(u.includes("not found")){let d=u.includes("sandbox");try{await c.refreshData(),d=!1}catch(f){(f instanceof Error?f.message.toLowerCase():String(f).toLowerCase()).includes("not found")&&(d=!0)}return{exitCode:-1,stdout:"",stderr:d?"sandbox deleted during run":"session terminated"}}throw l}await Nh(500)}},kill:async()=>{try{return await c.process.deleteSession(n),!0}catch{return!1}}}}async list(){try{return(await this.sandbox.process.listSessions()).map(e=>({processId:e.sessionId||"",cmd:"",args:[],envs:{}}))}catch{return[]}}async kill(e){try{return await this.sandbox.process.deleteSession(e),!0}catch{return!1}}},zPe=class{constructor(e){this.sandbox=e}async read(e){let t=new Uint8Array(await this.sandbox.fs.downloadFile(e));if(!t.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{}return t}async write(e,t){let n;if(typeof t=="string")n=Buffer.from(t,"utf-8");else if(Buffer.isBuffer(t))n=t;else if(t instanceof ArrayBuffer)n=Buffer.from(t);else if(t instanceof Uint8Array)n=Buffer.from(t);else throw new Error(`Unsupported content type: ${typeof t}`);await this.sandbox.fs.uploadFile(n,e)}async writeBatch(e){let t=e.map(n=>{let r;if(typeof n.data=="string")r=Buffer.from(n.data,"utf-8");else if(Buffer.isBuffer(n.data))r=n.data;else if(n.data instanceof ArrayBuffer)r=Buffer.from(n.data);else if(n.data instanceof Uint8Array)r=Buffer.from(n.data);else throw new Error(`Unsupported content type: ${typeof n.data}`);return{source:r,destination:n.path}});await this.sandbox.fs.uploadFiles(t)}async writeFromPath(e,t){await this.sandbox.fs.uploadFile(t,e)}async makeDir(e){await this.sandbox.fs.createFolder(e,"755")}async exists(e){try{let t=Q1t(e),n=e2t(e);return(await this.sandbox.fs.listFiles(t)).some(r=>r.name===n)}catch{return!1}}async list(e){return(await this.sandbox.fs.listFiles(e)).map(t=>({name:t.name,path:e.endsWith("/")?`${e}${t.name}`:`${e}/${t.name}`,type:t.isDir?"dir":"file"}))}async remove(e){await this.sandbox.fs.deleteFile(e,!0)}async rename(e,t){await this.sandbox.fs.moveFiles(e,t)}},oW=class{constructor(e,t,n){this.sandbox=e,this.commands=new $Pe(e,t,n),this.files=new zPe(e)}commands;files;get sandboxId(){return this.sandbox.id}async getHost(e){return(await this.sandbox.getPreviewLink(e)).url}async isRunning(){try{await this.sandbox.refreshData()}catch{return!1}return this.sandbox.state==="started"}async getInfo(){return await this.sandbox.refreshData(),IW(this.sandbox)}async updateNetwork(e){let t=MPe(e);try{await this.sandbox.updateNetworkSettings(t)}catch(n){throw DPe(n)?new Kl("org-tier-forbidden",`Daytona refused to change this sandbox's network policy: organizations on Tier 1 or Tier 2 cannot override network policy at the sandbox level. Raise the organization's tier, or run this workload on a provider whose plan permits runtime policy changes (underlying error: ${n instanceof Error?n.message:String(n)}).`):n}}async kill(){await this.sandbox.delete()}async pause(){await this.sandbox.stop()}},xW=class{providerType="daytona";name="Daytona";client;defaultTimeoutMs;snapshotName;sandboxUsers=new Map;managedStream;snapshotConflictTiming={timeoutMs:SW,pollMs:bPe};snapshotDeleteTiming={timeoutMs:OPe,pollMs:APe};constructor(e){let t={apiKey:e.apiKey,apiUrl:e.apiUrl,target:e.target,useDeprecatedPolling:!0};this.client=e.managedToolboxUrl?new f2t(t,e.managedToolboxUrl):new gy(t),e.managedToolboxUrl&&(this.managedStream={toolboxUrl:e.managedToolboxUrl,apiKey:e.apiKey}),this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.snapshotName=e.snapshotName??(e.managedToolboxUrl?"evolve-all":`evolve-all-${EM}`)}async create(e){if(e.idleTimeoutMs!==void 0)throw new xPe;if(e.bootCommand!==void 0)throw new IPe;for(let f of e.phaseNetworkPolicies??[])BT(f);let t=BT(e.network),n=e.user,r=n&&n!=="root"?n:void 0,a=e.timeoutMs??this.defaultTimeoutMs,i=Math.max(1,Math.ceil(a/6e4)),s=e.image||this.snapshotName,o={envVars:e.envs,labels:e.metadata,autoStopInterval:i,autoDeleteInterval:yPe,...r?{user:r}:{},...t},c,l=e.resources!==void 0&&(e.resources.cpu!==void 0||e.resources.memory!==void 0||e.resources.disk!==void 0||e.resources.gpu!==void 0||e.resources.gpuTypes!==void 0);if(this.managedStream){if(l)throw new xM(s);let f=await this.client.create({snapshot:s,...o},{timeout:600});return e.workingDirectory&&await f.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(f.id,n),new oW(f,n,this.managedStream)}let u,d;try{let f=await this.client.snapshot.get(s),p=f?.state;if(f&&kPe.has(p??"")&&(u=p),f&&(p==="active"||p==="inactive")&&l)throw new xM(s);if(f&&p==="inactive"&&(p=(await fW(this.client,s,f)).state),f&&fPe.has(p??"")&&(pW(s)?d=await pPe(this.client,s,f,this.snapshotDeleteTiming):console.warn(`[daytona] Snapshot "${s}" is dead (state "${p}") but this provider cannot rebuild that name \u2014 delete it in the Daytona dashboard (Snapshots page), or rebuild it with the tooling that created it.`)),f&&p==="active")console.log(`[daytona] Using cached snapshot: ${s}`),c=await this.client.create({snapshot:s,...o},{timeout:600});else throw new Error("Snapshot not active")}catch(f){if(f instanceof xM||f instanceof Iy)throw f;let p=bW[s]??s,m=u!==void 0&&!l;m?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") \u2014 joining that build rather than starting a second one.`):u!==void 0?console.log(`[daytona] Snapshot "${s}" is mid-build (state "${u}") and cannot carry the requested sizing \u2014 pulling image directly instead: ${p}`):(console.log(`[daytona] Snapshot "${s}" not found, building from image: ${p}`),console.log("[daytona] First run will take a few minutes (this only happens once)..."));try{if(d===!1)throw new Error(`dead snapshot "${s}" was not confirmed removed \u2014 not racing its removal`);let y=()=>this.client.snapshot.create({name:s,image:kh.base(p),resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{onLogs:v=>console.log(`[daytona] ${v}`)}),b=async()=>{await y(),console.log(`[daytona] Snapshot "${s}" ready (rebuilt here after a dead build).`)};if(u!==void 0){if(!m)throw new Error(`snapshot "${s}" is mid-build (state "${u}") and cannot be resized`);await this.joinInFlightSnapshotBuild(s)&&await b()}else try{await y(),console.log(`[daytona] Snapshot "${s}" ready (built here).`)}catch(v){if(!PPe(v)||l)throw v;await this.joinInFlightSnapshotBuild(s)&&await b()}c=await this.client.create({snapshot:s,...o},{timeout:600})}catch(y){if(y instanceof UT||y instanceof Iy)throw y;console.warn(`[daytona] Snapshot creation failed, falling back to direct image: ${y instanceof Error?y.message:y}`);try{c=await this.client.create({image:p,...o,resources:{cpu:e.resources?.cpu??4,memory:e.resources?.memory??4,disk:e.resources?.disk??10,...(e.resources?.gpu??0)>0?{gpu:e.resources.gpu}:{},...e.resources?.gpuTypes?.length?{gpuType:e.resources.gpuTypes}:{}}},{timeout:600,onSnapshotCreateLogs:b=>console.log(`[daytona] ${b}`)})}catch(b){throw UPe(p)?new wPe(p,b):b}}}return e.workingDirectory&&await c.fs.createFolder(e.workingDirectory,"755"),n&&this.sandboxUsers.set(c.id,n),new oW(c,n,this.managedStream)}async joinInFlightSnapshotBuild(e){let t=await RPe(this.client,e,this.snapshotConflictTiming);if(t===_W)return!0;if(t.state==="active")return console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(t.state==="inactive")return await fW(this.client,e,t),console.log(`[daytona] Snapshot "${e}" ready (built by another process) \u2014 reusing it.`),!1;if(fPe.has(t.state??"")&&pW(e)&&await pPe(this.client,e,t,this.snapshotDeleteTiming))return!0;throw new Error(`the in-flight build of snapshot "${e}" ended in state "${t.state??"unknown"}"`)}async connect(e,t){let n=await this.client.get(e);return n.state!=="started"&&await n.start(),new oW(n,this.sandboxUsers.get(e),this.managedStream)}async list(e){let t=await this.paginate(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.paginate(e);return n}async paginate(e){return GPe(this.listStream(e),e)}listStream(e){let t=e?.state?h2t(e.state):void 0,n={limit:_Pe,...e?.metadata?{labels:e.metadata}:{},...t&&t.length>0?{states:t}:{}};return this.client.list(n)}};m2t=GPe;g2t=vW,y2t=mW,v2t=BT,b2t=MPe,S2t=DPe,_2t=UPe,w2t=IW,I2t=BPe,x2t=fW,E2t=RPe,T2t=PPe,k2t=pW,O2t=bW,A2t=gW,P2t=CPe,R2t=Kb,C2t=yW,N2t=LPe,M2t=VPe,D2t=qPe});var JPe=_(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0});kM.Metadata=void 0;kM.Metadata=function(t){let n=new Map,r={set(a,i){if(a=Xb(a),Array.isArray(i))if(i.length===0)n.delete(a);else{for(let s of i)TW(a,s);n.set(a,a.endsWith("-bin")?i:[i.join(", ")])}else TW(a,i),n.set(a,[i]);return r},append(a,i){a=Xb(a),TW(a,i);let s=n.get(a);return s==null&&(s=[],n.set(a,s)),s.push(i),a.endsWith("-bin")||n.set(a,[s.join(", ")]),r},delete(a){a=Xb(a),n.delete(a)},get(a){var i;return a=Xb(a),(i=n.get(a))===null||i===void 0?void 0:i[0]},getAll(a){var i;return a=Xb(a),(i=n.get(a))!==null&&i!==void 0?i:[]},has(a){return a=Xb(a),n.has(a)},[Symbol.iterator](){return n[Symbol.iterator]()}};if(t!=null){let a=U2t(t)?t:Object.entries(t);for(let[i,s]of a)r.set(i,s)}return r};function Xb(e){return e.toLowerCase()}function TW(e,t){if(!/^[0-9a-z_.-]+$/.test(e))throw new Error(`Metadata key '${e}' contains illegal characters`);if(e.endsWith("-bin")){if(!(t instanceof Uint8Array))throw new Error(`Metadata key '${e}' ends with '-bin', thus it must have binary value`)}else{if(typeof t!="string")throw new Error(`Metadata key '${e}' doesn't end with '-bin', thus it must have string value`);if(!/^[ -~]*$/.test(t))throw new Error(`Metadata value '${t}' of key '${e}' contains illegal characters`)}}function U2t(e){return Symbol.iterator in e}});var OM=_(LT=>{"use strict";Object.defineProperty(LT,"__esModule",{value:!0});LT.Status=void 0;var B2t;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(B2t=LT.Status||(LT.Status={}))});var WPe=_(HPe=>{"use strict";Object.defineProperty(HPe,"__esModule",{value:!0})});var YPe=_(jPe=>{"use strict";Object.defineProperty(jPe,"__esModule",{value:!0})});var XPe=_(KPe=>{"use strict";Object.defineProperty(KPe,"__esModule",{value:!0})});var ZPe=_(AM=>{"use strict";Object.defineProperty(AM,"__esModule",{value:!0});AM.composeClientMiddleware=void 0;function F2t(e,t){return(n,r)=>t(Object.assign(Object.assign({},n),{next:(a,i)=>e(Object.assign(Object.assign({},n),{request:a}),i)}),r)}AM.composeClientMiddleware=F2t});var tRe=_(Mh=>{"use strict";Mh.__esModule=void 0;Mh.__esModule=!0;var L2t=typeof Object.setPrototypeOf=="function",V2t=typeof Object.getPrototypeOf=="function",q2t=typeof Object.defineProperty=="function",$2t=typeof Object.create=="function",z2t=typeof Object.prototype.hasOwnProperty=="function",G2t=function(t,n){L2t?Object.setPrototypeOf(t,n):t.__proto__=n};Mh.setPrototypeOf=G2t;var J2t=function(t){return V2t?Object.getPrototypeOf(t):t.__proto__||t.prototype};Mh.getPrototypeOf=J2t;var QPe=!1,H2t=function e(t,n,r){if(q2t&&!QPe)try{Object.defineProperty(t,n,r)}catch{QPe=!0,e(t,n,r)}else t[n]=r.value};Mh.defineProperty=H2t;var eRe=function(t,n){return z2t?t.hasOwnProperty(t,n):t[n]===void 0};Mh.hasOwnProperty=eRe;var W2t=function(t,n){if($2t)return Object.create(t,n);var r=function(){};r.prototype=t;var a=new r;if(typeof n>"u")return a;if(typeof n=="null")throw new Error("PropertyDescriptors must not be null.");if(typeof n=="object")for(var i in n)eRe(n,i)&&(a[i]=n[i].value);return a};Mh.objectCreate=W2t});var OW=_(Zb=>{"use strict";Zb.__esModule=void 0;Zb.__esModule=!0;var RM=tRe(),j2t=RM.setPrototypeOf,Y2t=RM.getPrototypeOf,kW=RM.defineProperty,K2t=RM.objectCreate,X2t=new Error().toString()==="[object Error]",PM="";function VT(e){var t=this.constructor,n=t.name||function(){var o=t.toString().match(/^function\s*([^\s(]+)/);return o===null?PM||"Error":o[1]}(),r=n==="Error",a=r?PM:n,i=Error.apply(this,arguments);if(j2t(i,Y2t(this)),!(i instanceof t)||!(i instanceof VT)){var i=this;Error.apply(this,arguments),kW(i,"message",{configurable:!0,enumerable:!1,value:e,writable:!0})}if(kW(i,"name",{configurable:!0,enumerable:!1,value:a,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(i,r?VT:t),i.stack===void 0){var s=new Error(e);s.name=i.name,i.stack=s.stack}return X2t&&kW(i,"toString",{configurable:!0,enumerable:!1,value:function(){return(this.name||"Error")+(typeof this.message>"u"?"":": "+this.message)},writable:!0}),i}PM=VT.name||"ExtendableError";VT.prototype=K2t(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}});Zb.ExtendableError=VT;Zb.default=Zb.ExtendableError});var nRe=_(CM=>{"use strict";Object.defineProperty(CM,"__esModule",{value:!0});CM.ClientError=void 0;var Z2t=OW(),Q2t=OM(),AW=class e extends Z2t.ExtendableError{constructor(t,n,r){super(`${t} ${Q2t.Status[n]}: ${r}`),this.path=t,this.code=n,this.details=r,this.name="ClientError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ClientError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ClientError"]===!0||t.name==="ClientError"&&t["@@nice-grpc"]===!0)}};CM.ClientError=AW});var iRe=_(rRe=>{"use strict";Object.defineProperty(rRe,"__esModule",{value:!0})});var sRe=_(aRe=>{"use strict";Object.defineProperty(aRe,"__esModule",{value:!0})});var oRe=_(NM=>{"use strict";Object.defineProperty(NM,"__esModule",{value:!0});NM.composeServerMiddleware=void 0;function eMt(e,t){return(n,r)=>e(Object.assign(Object.assign({},n),{next:(a,i)=>t(Object.assign(Object.assign({},n),{request:a}),i)}),r)}NM.composeServerMiddleware=eMt});var cRe=_(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0});MM.ServerError=void 0;var tMt=OW(),nMt=OM(),PW=class e extends tMt.ExtendableError{constructor(t,n){super(`${nMt.Status[t]}: ${n}`),this.code=t,this.details=n,this.name="ServerError",Object.defineProperty(this,"@@nice-grpc",{value:!0}),Object.defineProperty(this,"@@nice-grpc:ServerError",{value:!0})}static[Symbol.hasInstance](t){return this!==e?this.prototype.isPrototypeOf(t):typeof t=="object"&&t!==null&&(t.constructor===e||t["@@nice-grpc:ServerError"]===!0||t.name==="ServerError"&&t["@@nice-grpc"]===!0)}};MM.ServerError=PW});var Xc=_($a=>{"use strict";var rMt=$a&&$a.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Xl=$a&&$a.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&rMt(t,e,n)};Object.defineProperty($a,"__esModule",{value:!0});Xl(JPe(),$a);Xl(OM(),$a);Xl(WPe(),$a);Xl(YPe(),$a);Xl(XPe(),$a);Xl(ZPe(),$a);Xl(nRe(),$a);Xl(iRe(),$a);Xl(sRe(),$a);Xl(oRe(),$a);Xl(cRe(),$a)});var Yt=_(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=Zc.Propagate=Zc.LogVerbosity=Zc.Status=void 0;var lRe;(function(e){e[e.OK=0]="OK",e[e.CANCELLED=1]="CANCELLED",e[e.UNKNOWN=2]="UNKNOWN",e[e.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",e[e.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",e[e.NOT_FOUND=5]="NOT_FOUND",e[e.ALREADY_EXISTS=6]="ALREADY_EXISTS",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",e[e.ABORTED=10]="ABORTED",e[e.OUT_OF_RANGE=11]="OUT_OF_RANGE",e[e.UNIMPLEMENTED=12]="UNIMPLEMENTED",e[e.INTERNAL=13]="INTERNAL",e[e.UNAVAILABLE=14]="UNAVAILABLE",e[e.DATA_LOSS=15]="DATA_LOSS",e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED"})(lRe||(Zc.Status=lRe={}));var uRe;(function(e){e[e.DEBUG=0]="DEBUG",e[e.INFO=1]="INFO",e[e.ERROR=2]="ERROR",e[e.NONE=3]="NONE"})(uRe||(Zc.LogVerbosity=uRe={}));var dRe;(function(e){e[e.DEADLINE=1]="DEADLINE",e[e.CENSUS_STATS_CONTEXT=2]="CENSUS_STATS_CONTEXT",e[e.CENSUS_TRACING_CONTEXT=4]="CENSUS_TRACING_CONTEXT",e[e.CANCELLATION=8]="CANCELLATION",e[e.DEFAULTS=65535]="DEFAULTS"})(dRe||(Zc.Propagate=dRe={}));Zc.DEFAULT_MAX_SEND_MESSAGE_LENGTH=-1;Zc.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH=4*1024*1024});var RW=_((pwn,iMt)=>{iMt.exports={name:"@grpc/grpc-js",version:"1.14.4",description:"gRPC Library for Node - pure JS implementation",homepage:"https://grpc.io/",repository:"https://github.com/grpc/grpc-node/tree/master/packages/grpc-js",main:"build/src/index.js",engines:{node:">=12.10.0"},keywords:[],author:{name:"Google Inc."},types:"build/src/index.d.ts",license:"Apache-2.0",devDependencies:{"@grpc/proto-loader":"file:../proto-loader","@types/gulp":"^4.0.17","@types/gulp-mocha":"0.0.37","@types/lodash":"^4.14.202","@types/mocha":"^10.0.6","@types/ncp":"^2.0.8","@types/node":">=20.11.20","@types/pify":"^5.0.4","@types/semver":"^7.5.8","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@typescript-eslint/typescript-estree":"^7.1.0","clang-format":"^1.8.0",eslint:"^8.42.0","eslint-config-prettier":"^8.8.0","eslint-plugin-node":"^11.1.0","eslint-plugin-prettier":"^4.2.1",execa:"^2.0.3",gulp:"^4.0.2","gulp-mocha":"^6.0.0",lodash:"^4.17.21",madge:"^5.0.1","mocha-jenkins-reporter":"^0.4.1",ncp:"^2.0.0",pify:"^4.0.1",prettier:"^2.8.8",rimraf:"^3.0.2",semver:"^7.6.0","ts-node":"^10.9.2",typescript:"^5.3.3"},contributors:[{name:"Google Inc."}],scripts:{build:"npm run compile",clean:"rimraf ./build",compile:"tsc -p .",format:'clang-format -i -style="{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}" src/*.ts test/*.ts',lint:"eslint src/*.ts test/*.ts",prepare:"npm run copy-protos && npm run generate-types && npm run generate-test-types && npm run compile",test:"gulp test",check:"npm run lint",fix:"eslint --fix src/*.ts test/*.ts",pretest:"npm run generate-types && npm run generate-test-types && npm run compile",posttest:"npm run check && madge -c ./build/src","generate-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs proto/ proto/xds/ proto/protoc-gen-validate/ -O src/generated/ --grpcLib ../index channelz.proto xds/service/orca/v3/orca.proto","generate-test-types":"proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto echo_service.proto","copy-protos":"node ./copy-protos"},dependencies:{"@grpc/proto-loader":"^0.8.0","@js-sdsl/ordered-map":"^4.4.2"},files:["src/**/*.ts","build/src/**/*.{js,d.ts,js.map}","proto/**/*.proto","proto/**/LICENSE","LICENSE","deps/envoy-api/envoy/api/v2/**/*.proto","deps/envoy-api/envoy/config/**/*.proto","deps/envoy-api/envoy/service/**/*.proto","deps/envoy-api/envoy/type/**/*.proto","deps/udpa/udpa/**/*.proto","deps/googleapis/google/api/*.proto","deps/googleapis/google/rpc/*.proto","deps/protoc-gen-validate/validate/**/*.proto"]}});var hr=_(hc=>{"use strict";var CW,NW,MW,DW;Object.defineProperty(hc,"__esModule",{value:!0});hc.log=hc.setLoggerVerbosity=hc.setLogger=hc.getLogger=void 0;hc.trace=mMt;hc.isTracerEnabled=pRe;var Dh=Yt(),aMt=require("process"),sMt=RW().version,oMt={error:(e,...t)=>{console.error("E "+e,...t)},info:(e,...t)=>{console.error("I "+e,...t)},debug:(e,...t)=>{console.error("D "+e,...t)}},xy=oMt,Qb=Dh.LogVerbosity.ERROR,cMt=(NW=(CW=process.env.GRPC_NODE_VERBOSITY)!==null&&CW!==void 0?CW:process.env.GRPC_VERBOSITY)!==null&&NW!==void 0?NW:"";switch(cMt.toUpperCase()){case"DEBUG":Qb=Dh.LogVerbosity.DEBUG;break;case"INFO":Qb=Dh.LogVerbosity.INFO;break;case"ERROR":Qb=Dh.LogVerbosity.ERROR;break;case"NONE":Qb=Dh.LogVerbosity.NONE;break;default:}var lMt=()=>xy;hc.getLogger=lMt;var uMt=e=>{xy=e};hc.setLogger=uMt;var dMt=e=>{Qb=e};hc.setLoggerVerbosity=dMt;var fMt=(e,...t)=>{let n;if(e>=Qb){switch(e){case Dh.LogVerbosity.DEBUG:n=xy.debug;break;case Dh.LogVerbosity.INFO:n=xy.info;break;case Dh.LogVerbosity.ERROR:n=xy.error;break}n||(n=xy.error),n&&n.bind(xy)(...t)}};hc.log=fMt;var pMt=(DW=(MW=process.env.GRPC_NODE_TRACE)!==null&&MW!==void 0?MW:process.env.GRPC_TRACE)!==null&&DW!==void 0?DW:"",UW=new Set,fRe=new Set;for(let e of pMt.split(","))e.startsWith("-")?fRe.add(e.substring(1)):UW.add(e);var hMt=UW.has("all");function mMt(e,t,n){pRe(t)&&(0,hc.log)(e,new Date().toISOString()+" | v"+sMt+" "+aMt.pid+" | "+t+" | "+n)}function pRe(e){return!fRe.has(e)&&(hMt||UW.has(e))}});var UM=_(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.getErrorMessage=gMt;DM.getErrorCode=yMt;function gMt(e){return e instanceof Error?e.message:String(e)}function yMt(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="number"?e.code:null}});var ma=_(FM=>{"use strict";Object.defineProperty(FM,"__esModule",{value:!0});FM.Metadata=void 0;var vMt=hr(),bMt=Yt(),SMt=UM(),_Mt=/^[:0-9a-z_.-]+$/,wMt=/^[ -~]*$/;function IMt(e){return _Mt.test(e)}function xMt(e){return wMt.test(e)}function mRe(e){return e.endsWith("-bin")}function EMt(e){return!e.startsWith("grpc-")}function BM(e){return e.toLowerCase()}function hRe(e,t){if(!IMt(e))throw new Error('Metadata key "'+e+'" contains illegal characters');if(t!=null)if(mRe(e)){if(!Buffer.isBuffer(t))throw new Error("keys that end with '-bin' must have Buffer values")}else{if(Buffer.isBuffer(t))throw new Error("keys that don't end with '-bin' must have String values");if(!xMt(t))throw new Error('Metadata string value "'+t+'" contains illegal characters')}}var BW=class e{constructor(t={}){this.internalRepr=new Map,this.opaqueData=new Map,this.options=t}set(t,n){t=BM(t),hRe(t,n),this.internalRepr.set(t,[n])}add(t,n){t=BM(t),hRe(t,n);let r=this.internalRepr.get(t);r===void 0?this.internalRepr.set(t,[n]):r.push(n)}remove(t){t=BM(t),this.internalRepr.delete(t)}get(t){return t=BM(t),this.internalRepr.get(t)||[]}getMap(){let t={};for(let[n,r]of this.internalRepr)if(r.length>0){let a=r[0];t[n]=Buffer.isBuffer(a)?Buffer.from(a):a}return t}clone(){let t=new e(this.options),n=t.internalRepr;for(let[r,a]of this.internalRepr){let i=a.map(s=>Buffer.isBuffer(s)?Buffer.from(s):s);n.set(r,i)}return t}merge(t){for(let[n,r]of t.internalRepr){let a=(this.internalRepr.get(n)||[]).concat(r);this.internalRepr.set(n,a)}}setOptions(t){this.options=t}getOptions(){return this.options}toHttp2Headers(){let t={};for(let[n,r]of this.internalRepr)n.startsWith(":")||(t[n]=r.map(TMt));return t}toJSON(){let t={};for(let[n,r]of this.internalRepr)t[n]=r;return t}setOpaque(t,n){this.opaqueData.set(t,n)}getOpaque(t){return this.opaqueData.get(t)}static fromHttp2Headers(t){let n=new e;for(let r of Object.keys(t)){if(r.charAt(0)===":")continue;let a=t[r];try{mRe(r)?Array.isArray(a)?a.forEach(i=>{n.add(r,Buffer.from(i,"base64"))}):a!==void 0&&(EMt(r)?a.split(",").forEach(i=>{n.add(r,Buffer.from(i.trim(),"base64"))}):n.add(r,Buffer.from(a,"base64"))):Array.isArray(a)?a.forEach(i=>{n.add(r,i)}):a!==void 0&&n.add(r,a)}catch(i){let s=`Failed to add metadata entry ${r}: ${a}. ${(0,SMt.getErrorMessage)(i)}. For more information see https://github.com/grpc/grpc-node/issues/1173`;(0,vMt.log)(bMt.LogVerbosity.ERROR,s)}}return n}};FM.Metadata=BW;var TMt=e=>Buffer.isBuffer(e)?e.toString("base64"):e});var VM=_(LM=>{"use strict";Object.defineProperty(LM,"__esModule",{value:!0});LM.CallCredentials=void 0;var qW=ma();function kMt(e){return"getRequestHeaders"in e&&typeof e.getRequestHeaders=="function"}var eS=class e{static createFromMetadataGenerator(t){return new LW(t)}static createFromGoogleCredential(t){return e.createFromMetadataGenerator((n,r)=>{let a;kMt(t)?a=t.getRequestHeaders(n.service_url):a=new Promise((i,s)=>{t.getRequestMetadata(n.service_url,(o,c)=>{if(o){s(o);return}if(!c){s(new Error("Headers not set by metadata plugin"));return}i(c)})}),a.then(i=>{let s=new qW.Metadata;for(let o of Object.keys(i))s.add(o,i[o]);r(null,s)},i=>{r(i)})})}static createEmpty(){return new VW}};LM.CallCredentials=eS;var FW=class e extends eS{constructor(t){super(),this.creds=t}async generateMetadata(t){let n=new qW.Metadata,r=await Promise.all(this.creds.map(a=>a.generateMetadata(t)));for(let a of r)n.merge(a);return n}compose(t){return new e(this.creds.concat([t]))}_equals(t){return this===t?!0:t instanceof e?this.creds.every((n,r)=>n._equals(t.creds[r])):!1}},LW=class e extends eS{constructor(t){super(),this.metadataGenerator=t}generateMetadata(t){return new Promise((n,r)=>{this.metadataGenerator(t,(a,i)=>{i!==void 0?n(i):r(a)})})}compose(t){return new FW([this,t])}_equals(t){return this===t?!0:t instanceof e?this.metadataGenerator===t.metadataGenerator:!1}},VW=class e extends eS{generateMetadata(t){return Promise.resolve(new qW.Metadata)}compose(t){return t}_equals(t){return t instanceof e}}});var zW=_(qT=>{"use strict";Object.defineProperty(qT,"__esModule",{value:!0});qT.CIPHER_SUITES=void 0;qT.getDefaultRootsData=AMt;var OMt=require("fs");qT.CIPHER_SUITES=process.env.GRPC_SSL_CIPHER_SUITES;var gRe=process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH,$W=null;function AMt(){return gRe?($W===null&&($W=OMt.readFileSync(gRe)),$W):null}});var no=_(tS=>{"use strict";Object.defineProperty(tS,"__esModule",{value:!0});tS.parseUri=RMt;tS.splitHostPort=CMt;tS.combineHostPort=NMt;tS.uriToString=MMt;var PMt=/^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;function RMt(e){let t=PMt.exec(e);return t===null?null:{scheme:t[1],authority:t[2],path:t[3]}}var yRe=/^\d+$/;function CMt(e){if(e.startsWith("[")){let t=e.indexOf("]");if(t===-1)return null;let n=e.substring(1,t);if(n.indexOf(":")===-1)return null;if(e.length>t+1)if(e[t+1]===":"){let r=e.substring(t+2);return yRe.test(r)?{host:n,port:+r}:null}else return null;else return{host:n}}else{let t=e.split(":");return t.length===2?yRe.test(t[1])?{host:t[0],port:+t[1]}:null:{host:e}}}function NMt(e){return e.port===void 0?e.host:e.host.includes(":")?`[${e.host}]:${e.port}`:`${e.host}:${e.port}`}function MMt(e){let t="";return e.scheme!==void 0&&(t+=e.scheme+":"),e.authority!==void 0&&(t+="//"+e.authority+"/"),t+=e.path,t}});var Zl=_(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});up.CHANNEL_ARGS_CONFIG_SELECTOR_KEY=void 0;up.registerResolver=DMt;up.registerDefaultScheme=UMt;up.createResolver=BMt;up.getDefaultAuthority=FMt;up.mapUriDefaultScheme=LMt;var JW=no();up.CHANNEL_ARGS_CONFIG_SELECTOR_KEY="grpc.internal.config_selector";var nS={},GW=null;function DMt(e,t){nS[e]=t}function UMt(e){GW=e}function BMt(e,t,n){if(e.scheme!==void 0&&e.scheme in nS)return new nS[e.scheme](e,t,n);throw new Error(`No resolver could be created for target ${(0,JW.uriToString)(e)}`)}function FMt(e){if(e.scheme!==void 0&&e.scheme in nS)return nS[e.scheme].getDefaultAuthority(e);throw new Error(`Invalid target ${(0,JW.uriToString)(e)}`)}function LMt(e){return e.scheme===void 0||!(e.scheme in nS)?GW!==null?{scheme:GW,authority:void 0,path:(0,JW.uriToString)(e)}:null:e}});var rS=_(zT=>{"use strict";Object.defineProperty(zT,"__esModule",{value:!0});zT.ChannelCredentials=void 0;zT.createCertificateProviderChannelCredentials=zMt;var $T=require("tls"),zM=VM(),WW=zW(),vRe=no(),VMt=Zl(),qMt=hr(),$Mt=Yt();function HW(e,t){if(e&&!(e instanceof Buffer))throw new TypeError(`${t}, if provided, must be a Buffer.`)}var Ey=class{compose(t){return new KW(this,t)}static createSsl(t,n,r,a){var i;if(HW(t,"Root certificate"),HW(n,"Private key"),HW(r,"Certificate chain"),n&&!r)throw new Error("Private key must be given with accompanying certificate chain");if(!n&&r)throw new Error("Certificate chain must be given with accompanying private key");let s=(0,$T.createSecureContext)({ca:(i=t??(0,WW.getDefaultRootsData)())!==null&&i!==void 0?i:void 0,key:n??void 0,cert:r??void 0,ciphers:WW.CIPHER_SUITES});return new qM(s,a??{})}static createFromSecureContext(t,n){return new qM(t,n??{})}static createInsecure(){return new jW}};zT.ChannelCredentials=Ey;var jW=class e extends Ey{constructor(){super()}compose(t){throw new Error("Cannot compose insecure credentials")}_isSecure(){return!1}_equals(t){return t instanceof e}_createSecureConnector(t,n,r){return{connect(a){return Promise.resolve({socket:a,secure:!1})},waitForReady:()=>Promise.resolve(),getCallCredentials:()=>r??zM.CallCredentials.createEmpty(),destroy(){}}}};function bRe(e,t,n,r){var a,i;let s={secureContext:e},o=n;if("grpc.http_connect_target"in r){let d=(0,vRe.parseUri)(r["grpc.http_connect_target"]);d&&(o=d)}let c=(0,VMt.getDefaultAuthority)(o),l=(0,vRe.splitHostPort)(c),u=(a=l?.host)!==null&&a!==void 0?a:c;if(s.host=u,t.checkServerIdentity&&(s.checkServerIdentity=t.checkServerIdentity),t.rejectUnauthorized!==void 0&&(s.rejectUnauthorized=t.rejectUnauthorized),s.ALPNProtocols=["h2"],r["grpc.ssl_target_name_override"]){let d=r["grpc.ssl_target_name_override"],f=(i=s.checkServerIdentity)!==null&&i!==void 0?i:$T.checkServerIdentity;s.checkServerIdentity=(p,m)=>f(d,m),s.servername=d}else s.servername=u;return r["grpc-node.tls_enable_trace"]&&(s.enableTrace=!0),s}var YW=class{constructor(t,n){this.connectionOptions=t,this.callCredentials=n}connect(t){let n=Object.assign({socket:t},this.connectionOptions);return new Promise((r,a)=>{let i=(0,$T.connect)(n,()=>{var s;if((!((s=this.connectionOptions.rejectUnauthorized)!==null&&s!==void 0)||s)&&!i.authorized){a(i.authorizationError);return}r({socket:i,secure:!0})});i.on("error",s=>{a(s)})})}waitForReady(){return Promise.resolve()}getCallCredentials(){return this.callCredentials}destroy(){}},qM=class e extends Ey{constructor(t,n){super(),this.secureContext=t,this.verifyOptions=n}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.secureContext===t.secureContext&&this.verifyOptions.checkServerIdentity===t.verifyOptions.checkServerIdentity:!1}_createSecureConnector(t,n,r){let a=bRe(this.secureContext,this.verifyOptions,t,n);return new YW(a,r??zM.CallCredentials.createEmpty())}},$M=class e extends Ey{constructor(t,n,r){super(),this.caCertificateProvider=t,this.identityCertificateProvider=n,this.verifyOptions=r,this.refcount=0,this.latestCaUpdate=void 0,this.latestIdentityUpdate=void 0,this.caCertificateUpdateListener=this.handleCaCertificateUpdate.bind(this),this.identityCertificateUpdateListener=this.handleIdentityCertitificateUpdate.bind(this),this.secureContextWatchers=[]}_isSecure(){return!0}_equals(t){var n,r;return this===t?!0:t instanceof e?this.caCertificateProvider===t.caCertificateProvider&&this.identityCertificateProvider===t.identityCertificateProvider&&((n=this.verifyOptions)===null||n===void 0?void 0:n.checkServerIdentity)===((r=t.verifyOptions)===null||r===void 0?void 0:r.checkServerIdentity):!1}ref(){var t;this.refcount===0&&(this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.addIdentityCertificateListener(this.identityCertificateUpdateListener)),this.refcount+=1}unref(){var t;this.refcount-=1,this.refcount===0&&(this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener),(t=this.identityCertificateProvider)===null||t===void 0||t.removeIdentityCertificateListener(this.identityCertificateUpdateListener))}_createSecureConnector(t,n,r){return this.ref(),new e.SecureConnectorImpl(this,t,n,r??zM.CallCredentials.createEmpty())}maybeUpdateWatchers(){if(this.hasReceivedUpdates()){for(let t of this.secureContextWatchers)t(this.getLatestSecureContext());this.secureContextWatchers=[]}}handleCaCertificateUpdate(t){this.latestCaUpdate=t,this.maybeUpdateWatchers()}handleIdentityCertitificateUpdate(t){this.latestIdentityUpdate=t,this.maybeUpdateWatchers()}hasReceivedUpdates(){return!(this.latestCaUpdate===void 0||this.identityCertificateProvider&&this.latestIdentityUpdate===void 0)}getSecureContext(){return this.hasReceivedUpdates()?Promise.resolve(this.getLatestSecureContext()):new Promise(t=>{this.secureContextWatchers.push(t)})}getLatestSecureContext(){var t,n;if(!this.latestCaUpdate||this.identityCertificateProvider!==null&&!this.latestIdentityUpdate)return null;try{return(0,$T.createSecureContext)({ca:this.latestCaUpdate.caCertificate,key:(t=this.latestIdentityUpdate)===null||t===void 0?void 0:t.privateKey,cert:(n=this.latestIdentityUpdate)===null||n===void 0?void 0:n.certificate,ciphers:WW.CIPHER_SUITES})}catch(r){return(0,qMt.log)($Mt.LogVerbosity.ERROR,"Failed to createSecureContext with error "+r.message),null}}};$M.SecureConnectorImpl=class{constructor(e,t,n,r){this.parent=e,this.channelTarget=t,this.options=n,this.callCredentials=r}connect(e){return new Promise((t,n)=>{let r=this.parent.getLatestSecureContext();if(!r){n(new Error("Failed to load credentials"));return}e.closed&&n(new Error("Socket closed while loading credentials"));let a=bRe(r,this.parent.verifyOptions,this.channelTarget,this.options),i=Object.assign({socket:e},a),s=()=>{n(new Error("Socket closed"))},o=l=>{n(l)},c=(0,$T.connect)(i,()=>{var l;if(c.removeListener("close",s),c.removeListener("error",o),(!((l=this.parent.verifyOptions.rejectUnauthorized)!==null&&l!==void 0)||l)&&!c.authorized){n(c.authorizationError);return}t({socket:c,secure:!0})});c.once("close",s),c.once("error",o)})}async waitForReady(){await this.parent.getSecureContext()}getCallCredentials(){return this.callCredentials}destroy(){this.parent.unref()}};function zMt(e,t,n){return new $M(e,t,n??{})}var KW=class e extends Ey{constructor(t,n){if(super(),this.channelCredentials=t,this.callCredentials=n,!t._isSecure())throw new Error("Cannot compose insecure credentials")}compose(t){let n=this.callCredentials.compose(t);return new e(this.channelCredentials,n)}_isSecure(){return!0}_equals(t){return this===t?!0:t instanceof e?this.channelCredentials._equals(t.channelCredentials)&&this.callCredentials._equals(t.callCredentials):!1}_createSecureConnector(t,n,r){let a=this.callCredentials.compose(r??zM.CallCredentials.createEmpty());return this.channelCredentials._createSecureConnector(t,n,a)}}});var Bh=_(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.createChildChannelControlHelper=HMt;Td.registerLoadBalancerType=WMt;Td.registerDefaultLoadBalancerType=jMt;Td.createLoadBalancer=YMt;Td.isLoadBalancerNameRegistered=KMt;Td.parseLoadBalancingConfig=SRe;Td.getDefaultConfig=XMt;Td.selectLbConfigFromList=ZMt;var GMt=hr(),JMt=Yt();function HMt(e,t){var n,r,a,i,s,o,c,l,u,d;return{createSubchannel:(r=(n=t.createSubchannel)===null||n===void 0?void 0:n.bind(t))!==null&&r!==void 0?r:e.createSubchannel.bind(e),updateState:(i=(a=t.updateState)===null||a===void 0?void 0:a.bind(t))!==null&&i!==void 0?i:e.updateState.bind(e),requestReresolution:(o=(s=t.requestReresolution)===null||s===void 0?void 0:s.bind(t))!==null&&o!==void 0?o:e.requestReresolution.bind(e),addChannelzChild:(l=(c=t.addChannelzChild)===null||c===void 0?void 0:c.bind(t))!==null&&l!==void 0?l:e.addChannelzChild.bind(e),removeChannelzChild:(d=(u=t.removeChannelzChild)===null||u===void 0?void 0:u.bind(t))!==null&&d!==void 0?d:e.removeChannelzChild.bind(e)}}var Uh={},GT=null;function WMt(e,t,n){Uh[e]={LoadBalancer:t,LoadBalancingConfig:n}}function jMt(e){GT=e}function YMt(e,t){let n=e.getLoadBalancerName();return n in Uh?new Uh[n].LoadBalancer(t):null}function KMt(e){return e in Uh}function SRe(e){let t=Object.keys(e);if(t.length!==1)throw new Error("Provided load balancing config has multiple conflicting entries");let n=t[0];if(n in Uh)try{return Uh[n].LoadBalancingConfig.createFromJson(e[n])}catch(r){throw new Error(`${n}: ${r.message}`)}else throw new Error(`Unrecognized load balancing config name ${n}`)}function XMt(){if(!GT)throw new Error("No default load balancer type registered");return new Uh[GT].LoadBalancingConfig}function ZMt(e,t=!1){for(let n of e)try{return SRe(n)}catch(r){(0,GMt.log)(JMt.LogVerbosity.DEBUG,"Config parsing failed with error",r.message);continue}return t&&GT?new Uh[GT].LoadBalancingConfig:null}});var XW=_(JT=>{"use strict";Object.defineProperty(JT,"__esModule",{value:!0});JT.validateRetryThrottling=_Re;JT.validateServiceConfig=wRe;JT.extractAndSelectServiceConfig=cDt;var QMt=require("os"),GM=Yt(),JM=/^\d+(\.\d{1,9})?s$/,eDt="node";function tDt(e){if("service"in e&&e.service!==""){if(typeof e.service!="string")throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof e.service}`);if("method"in e&&e.method!==""){if(typeof e.method!="string")throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof e.service}`);return{service:e.service,method:e.method}}else return{service:e.service}}else{if("method"in e&&e.method!==void 0)throw new Error("Invalid method config name: method set with empty or unset service");return{}}}function nDt(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config retry policy: maxAttempts must be an integer at least 2");if(!("initialBackoff"in e)||typeof e.initialBackoff!="string"||!JM.test(e.initialBackoff))throw new Error("Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("maxBackoff"in e)||typeof e.maxBackoff!="string"||!JM.test(e.maxBackoff))throw new Error("Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s");if(!("backoffMultiplier"in e)||typeof e.backoffMultiplier!="number"||e.backoffMultiplier<=0)throw new Error("Invalid method config retry policy: backoffMultiplier must be a number greater than 0");if(!("retryableStatusCodes"in e&&Array.isArray(e.retryableStatusCodes)))throw new Error("Invalid method config retry policy: retryableStatusCodes is required");if(e.retryableStatusCodes.length===0)throw new Error("Invalid method config retry policy: retryableStatusCodes must be non-empty");for(let t of e.retryableStatusCodes)if(typeof t=="number"){if(!Object.values(GM.Status).includes(t))throw new Error("Invalid method config retry policy: retryableStatusCodes value not in status code range")}else if(typeof t=="string"){if(!Object.values(GM.Status).includes(t.toUpperCase()))throw new Error("Invalid method config retry policy: retryableStatusCodes value not a status code name")}else throw new Error("Invalid method config retry policy: retryableStatusCodes value must be a string or number");return{maxAttempts:e.maxAttempts,initialBackoff:e.initialBackoff,maxBackoff:e.maxBackoff,backoffMultiplier:e.backoffMultiplier,retryableStatusCodes:e.retryableStatusCodes}}function rDt(e){if(!("maxAttempts"in e)||!Number.isInteger(e.maxAttempts)||e.maxAttempts<2)throw new Error("Invalid method config hedging policy: maxAttempts must be an integer at least 2");if("hedgingDelay"in e&&(typeof e.hedgingDelay!="string"||!JM.test(e.hedgingDelay)))throw new Error("Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s");if("nonFatalStatusCodes"in e&&Array.isArray(e.nonFatalStatusCodes))for(let n of e.nonFatalStatusCodes)if(typeof n=="number"){if(!Object.values(GM.Status).includes(n))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not in status code range")}else if(typeof n=="string"){if(!Object.values(GM.Status).includes(n.toUpperCase()))throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value not a status code name")}else throw new Error("Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number");let t={maxAttempts:e.maxAttempts};return e.hedgingDelay&&(t.hedgingDelay=e.hedgingDelay),e.nonFatalStatusCodes&&(t.nonFatalStatusCodes=e.nonFatalStatusCodes),t}function iDt(e){var t;let n={name:[]};if(!("name"in e)||!Array.isArray(e.name))throw new Error("Invalid method config: invalid name array");for(let r of e.name)n.name.push(tDt(r));if("waitForReady"in e){if(typeof e.waitForReady!="boolean")throw new Error("Invalid method config: invalid waitForReady");n.waitForReady=e.waitForReady}if("timeout"in e)if(typeof e.timeout=="object"){if(!("seconds"in e.timeout)||typeof e.timeout.seconds!="number")throw new Error("Invalid method config: invalid timeout.seconds");if(!("nanos"in e.timeout)||typeof e.timeout.nanos!="number")throw new Error("Invalid method config: invalid timeout.nanos");n.timeout=e.timeout}else if(typeof e.timeout=="string"&&JM.test(e.timeout)){let r=e.timeout.substring(0,e.timeout.length-1).split(".");n.timeout={seconds:r[0]|0,nanos:((t=r[1])!==null&&t!==void 0?t:0)|0}}else throw new Error("Invalid method config: invalid timeout");if("maxRequestBytes"in e){if(typeof e.maxRequestBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxRequestBytes=e.maxRequestBytes}if("maxResponseBytes"in e){if(typeof e.maxResponseBytes!="number")throw new Error("Invalid method config: invalid maxRequestBytes");n.maxResponseBytes=e.maxResponseBytes}if("retryPolicy"in e){if("hedgingPolicy"in e)throw new Error("Invalid method config: retryPolicy and hedgingPolicy cannot both be specified");n.retryPolicy=nDt(e.retryPolicy)}else"hedgingPolicy"in e&&(n.hedgingPolicy=rDt(e.hedgingPolicy));return n}function _Re(e){if(!("maxTokens"in e)||typeof e.maxTokens!="number"||e.maxTokens<=0||e.maxTokens>1e3)throw new Error("Invalid retryThrottling: maxTokens must be a number in (0, 1000]");if(!("tokenRatio"in e)||typeof e.tokenRatio!="number"||e.tokenRatio<=0)throw new Error("Invalid retryThrottling: tokenRatio must be a number greater than 0");return{maxTokens:+e.maxTokens.toFixed(3),tokenRatio:+e.tokenRatio.toFixed(3)}}function aDt(e){if(!(typeof e=="object"&&e!==null))throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof e}`);let t=Object.keys(e);if(t.length>1)throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${t}`);if(t.length===0)throw new Error("Invalid loadBalancingConfig: load balancing policy name required");return{[t[0]]:e[t[0]]}}function wRe(e){let t={loadBalancingConfig:[],methodConfig:[]};if("loadBalancingPolicy"in e)if(typeof e.loadBalancingPolicy=="string")t.loadBalancingPolicy=e.loadBalancingPolicy;else throw new Error("Invalid service config: invalid loadBalancingPolicy");if("loadBalancingConfig"in e)if(Array.isArray(e.loadBalancingConfig))for(let r of e.loadBalancingConfig)t.loadBalancingConfig.push(aDt(r));else throw new Error("Invalid service config: invalid loadBalancingConfig");if("methodConfig"in e&&Array.isArray(e.methodConfig))for(let r of e.methodConfig)t.methodConfig.push(iDt(r));"retryThrottling"in e&&(t.retryThrottling=_Re(e.retryThrottling));let n=[];for(let r of t.methodConfig)for(let a of r.name){for(let i of n)if(a.service===i.service&&a.method===i.method)throw new Error(`Invalid service config: duplicate name ${a.service}/${a.method}`);n.push(a)}return t}function sDt(e){if(!("serviceConfig"in e))throw new Error("Invalid service config choice: missing service config");let t={serviceConfig:wRe(e.serviceConfig)};if("clientLanguage"in e)if(Array.isArray(e.clientLanguage)){t.clientLanguage=[];for(let r of e.clientLanguage)if(typeof r=="string")t.clientLanguage.push(r);else throw new Error("Invalid service config choice: invalid clientLanguage")}else throw new Error("Invalid service config choice: invalid clientLanguage");if("clientHostname"in e)if(Array.isArray(e.clientHostname)){t.clientHostname=[];for(let r of e.clientHostname)if(typeof r=="string")t.clientHostname.push(r);else throw new Error("Invalid service config choice: invalid clientHostname")}else throw new Error("Invalid service config choice: invalid clientHostname");if("percentage"in e)if(typeof e.percentage=="number"&&0<=e.percentage&&e.percentage<=100)t.percentage=e.percentage;else throw new Error("Invalid service config choice: invalid percentage");let n=["clientLanguage","percentage","clientHostname","serviceConfig"];for(let r in e)if(!n.includes(r))throw new Error(`Invalid service config choice: unexpected field ${r}`);return t}function oDt(e,t){if(!Array.isArray(e))throw new Error("Invalid service config list");for(let n of e){let r=sDt(n);if(!(typeof r.percentage=="number"&&t>r.percentage)){if(Array.isArray(r.clientHostname)){let a=!1;for(let i of r.clientHostname)i===QMt.hostname()&&(a=!0);if(!a)continue}if(Array.isArray(r.clientLanguage)){let a=!1;for(let i of r.clientLanguage)i===eDt&&(a=!0);if(!a)continue}return r.serviceConfig}}throw new Error("No matching service config found")}function cDt(e,t){for(let n of e)if(n.length>0&&n[0].startsWith("grpc_config=")){let r=n.join("").substring(12),a=JSON.parse(r);return oDt(a,t)}return null}});var ro=_(HM=>{"use strict";Object.defineProperty(HM,"__esModule",{value:!0});HM.ConnectivityState=void 0;var IRe;(function(e){e[e.IDLE=0]="IDLE",e[e.CONNECTING=1]="CONNECTING",e[e.READY=2]="READY",e[e.TRANSIENT_FAILURE=3]="TRANSIENT_FAILURE",e[e.SHUTDOWN=4]="SHUTDOWN"})(IRe||(HM.ConnectivityState=IRe={}))});var dp=_(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});Fh.QueuePicker=Fh.UnavailablePicker=Fh.PickResultType=void 0;var lDt=ma(),uDt=Yt(),WM;(function(e){e[e.COMPLETE=0]="COMPLETE",e[e.QUEUE=1]="QUEUE",e[e.TRANSIENT_FAILURE=2]="TRANSIENT_FAILURE",e[e.DROP=3]="DROP"})(WM||(Fh.PickResultType=WM={}));var ZW=class{constructor(t){this.status=Object.assign({code:uDt.Status.UNAVAILABLE,details:"No connection established",metadata:new lDt.Metadata},t)}pick(t){return{pickResultType:WM.TRANSIENT_FAILURE,subchannel:null,status:this.status,onCallStarted:null,onCallEnded:null}}};Fh.UnavailablePicker=ZW;var QW=class{constructor(t,n){this.loadBalancer=t,this.childPicker=n,this.calledExitIdle=!1}pick(t){return this.calledExitIdle||(process.nextTick(()=>{this.loadBalancer.exitIdle()}),this.calledExitIdle=!0),this.childPicker?this.childPicker.pick(t):{pickResultType:WM.QUEUE,subchannel:null,status:null,onCallStarted:null,onCallEnded:null}}};Fh.QueuePicker=QW});var iS=_(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0});YM.BackoffTimeout=void 0;var dDt=Yt(),fDt=hr(),pDt="backoff",hDt=1e3,mDt=1.6,gDt=12e4,yDt=.2;function vDt(e,t){return Math.random()*(t-e)+e}var jM=class e{constructor(t,n){this.callback=t,this.initialDelay=hDt,this.multiplier=mDt,this.maxDelay=gDt,this.jitter=yDt,this.running=!1,this.hasRef=!0,this.startTime=new Date,this.endTime=new Date,this.id=e.getNextId(),n&&(n.initialDelay&&(this.initialDelay=n.initialDelay),n.multiplier&&(this.multiplier=n.multiplier),n.jitter&&(this.jitter=n.jitter),n.maxDelay&&(this.maxDelay=n.maxDelay)),this.trace("constructed initialDelay="+this.initialDelay+" multiplier="+this.multiplier+" jitter="+this.jitter+" maxDelay="+this.maxDelay),this.nextDelay=this.initialDelay,this.timerId=setTimeout(()=>{},0),clearTimeout(this.timerId)}static getNextId(){return this.nextId++}trace(t){fDt.trace(dDt.LogVerbosity.DEBUG,pDt,"{"+this.id+"} "+t)}runTimer(t){var n,r;this.trace("runTimer(delay="+t+")"),this.endTime=this.startTime,this.endTime.setMilliseconds(this.endTime.getMilliseconds()+t),clearTimeout(this.timerId),this.timerId=setTimeout(()=>{this.trace("timer fired"),this.running=!1,this.callback()},t),this.hasRef||(r=(n=this.timerId).unref)===null||r===void 0||r.call(n)}runOnce(){this.trace("runOnce()"),this.running=!0,this.startTime=new Date,this.runTimer(this.nextDelay);let t=Math.min(this.nextDelay*this.multiplier,this.maxDelay),n=t*this.jitter;this.nextDelay=t+vDt(-n,n)}stop(){this.trace("stop()"),clearTimeout(this.timerId),this.running=!1}reset(){if(this.trace("reset() running="+this.running),this.nextDelay=this.initialDelay,this.running){let t=new Date,n=this.startTime;n.setMilliseconds(n.getMilliseconds()+this.nextDelay),clearTimeout(this.timerId),t<n?this.runTimer(n.getTime()-t.getTime()):this.running=!1}}isRunning(){return this.running}ref(){var t,n;this.hasRef=!0,(n=(t=this.timerId).ref)===null||n===void 0||n.call(t)}unref(){var t,n;this.hasRef=!1,(n=(t=this.timerId).unref)===null||n===void 0||n.call(t)}getEndTime(){return this.endTime}};YM.BackoffTimeout=jM;jM.nextId=0});var XM=_(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0});KM.ChildLoadBalancerHandler=void 0;var bDt=Bh(),SDt=ro(),_Dt="child_load_balancer_helper",e7=class{constructor(t){this.channelControlHelper=t,this.currentChild=null,this.pendingChild=null,this.latestConfig=null,this.ChildPolicyHelper=class{constructor(n){this.parent=n,this.child=null}createSubchannel(n,r){return this.parent.channelControlHelper.createSubchannel(n,r)}updateState(n,r,a){var i;if(this.calledByPendingChild()){if(n===SDt.ConnectivityState.CONNECTING)return;(i=this.parent.currentChild)===null||i===void 0||i.destroy(),this.parent.currentChild=this.parent.pendingChild,this.parent.pendingChild=null}else if(!this.calledByCurrentChild())return;this.parent.channelControlHelper.updateState(n,r,a)}requestReresolution(){var n;let r=(n=this.parent.pendingChild)!==null&&n!==void 0?n:this.parent.currentChild;this.child===r&&this.parent.channelControlHelper.requestReresolution()}setChild(n){this.child=n}addChannelzChild(n){this.parent.channelControlHelper.addChannelzChild(n)}removeChannelzChild(n){this.parent.channelControlHelper.removeChannelzChild(n)}calledByPendingChild(){return this.child===this.parent.pendingChild}calledByCurrentChild(){return this.child===this.parent.currentChild}}}configUpdateRequiresNewPolicyInstance(t,n){return t.getLoadBalancerName()!==n.getLoadBalancerName()}updateAddressList(t,n,r,a){let i;if(this.currentChild===null||this.latestConfig===null||this.configUpdateRequiresNewPolicyInstance(this.latestConfig,n)){let s=new this.ChildPolicyHelper(this),o=(0,bDt.createLoadBalancer)(n,s);s.setChild(o),this.currentChild===null?(this.currentChild=o,i=this.currentChild):(this.pendingChild&&this.pendingChild.destroy(),this.pendingChild=o,i=this.pendingChild)}else this.pendingChild===null?i=this.currentChild:i=this.pendingChild;return this.latestConfig=n,i.updateAddressList(t,n,r,a)}exitIdle(){this.currentChild&&(this.currentChild.exitIdle(),this.pendingChild&&this.pendingChild.exitIdle())}resetBackoff(){this.currentChild&&(this.currentChild.resetBackoff(),this.pendingChild&&this.pendingChild.resetBackoff())}destroy(){this.currentChild&&(this.currentChild.destroy(),this.currentChild=null),this.pendingChild&&(this.pendingChild.destroy(),this.pendingChild=null)}getTypeName(){return _Dt}};KM.ChildLoadBalancerHandler=e7});var TRe=_(ZM=>{"use strict";Object.defineProperty(ZM,"__esModule",{value:!0});ZM.ResolvingLoadBalancer=void 0;var wDt=Bh(),IDt=XW(),No=ro(),xRe=Zl(),HT=dp(),xDt=iS(),t7=Yt(),EDt=ma(),TDt=hr(),kDt=Yt(),ODt=no(),ADt=XM(),PDt="resolving_load_balancer";function ERe(e){TDt.trace(kDt.LogVerbosity.DEBUG,PDt,e)}var RDt=["SERVICE_AND_METHOD","SERVICE","EMPTY"];function CDt(e,t,n,r){for(let a of n.name)switch(r){case"EMPTY":if(!a.service&&!a.method)return!0;break;case"SERVICE":if(a.service===e&&!a.method)return!0;break;case"SERVICE_AND_METHOD":if(a.service===e&&a.method===t)return!0}return!1}function NDt(e,t,n,r){for(let a of n)if(CDt(e,t,a,r))return a;return null}function MDt(e){return{invoke(t,n){var r,a;let i=t.split("/").filter(c=>c.length>0),s=(r=i[0])!==null&&r!==void 0?r:"",o=(a=i[1])!==null&&a!==void 0?a:"";if(e&&e.methodConfig)for(let c of RDt){let l=NDt(s,o,e.methodConfig,c);if(l)return{methodConfig:l,pickInformation:{},status:t7.Status.OK,dynamicFilterFactories:[]}}return{methodConfig:{name:[]},pickInformation:{},status:t7.Status.OK,dynamicFilterFactories:[]}},unref(){}}}var n7=class{constructor(t,n,r,a,i){this.target=t,this.channelControlHelper=n,this.channelOptions=r,this.onSuccessfulResolution=a,this.onFailedResolution=i,this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new HT.QueuePicker(this),this.latestChildErrorMessage=null,this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1,r["grpc.service_config"]?this.defaultServiceConfig=(0,IDt.validateServiceConfig)(JSON.parse(r["grpc.service_config"])):this.defaultServiceConfig={loadBalancingConfig:[],methodConfig:[]},this.updateState(No.ConnectivityState.IDLE,new HT.QueuePicker(this),null),this.childLoadBalancer=new ADt.ChildLoadBalancerHandler({createSubchannel:n.createSubchannel.bind(n),requestReresolution:()=>{this.backoffTimeout.isRunning()?(ERe("requestReresolution delayed by backoff timer until "+this.backoffTimeout.getEndTime().toISOString()),this.continueResolving=!0):this.updateResolution()},updateState:(o,c,l)=>{this.latestChildState=o,this.latestChildPicker=c,this.latestChildErrorMessage=l,this.updateState(o,c,l)},addChannelzChild:n.addChannelzChild.bind(n),removeChannelzChild:n.removeChannelzChild.bind(n)}),this.innerResolver=(0,xRe.createResolver)(t,this.handleResolverResult.bind(this),r);let s={initialDelay:r["grpc.initial_reconnect_backoff_ms"],maxDelay:r["grpc.max_reconnect_backoff_ms"]};this.backoffTimeout=new xDt.BackoffTimeout(()=>{this.continueResolving?(this.updateResolution(),this.continueResolving=!1):this.updateState(this.latestChildState,this.latestChildPicker,this.latestChildErrorMessage)},s),this.backoffTimeout.unref()}handleResolverResult(t,n,r,a){var i,s;this.backoffTimeout.stop(),this.backoffTimeout.reset();let o=!0,c=null;if(r===null?c=this.defaultServiceConfig:r.ok?c=r.value:this.previousServiceConfig!==null?c=this.previousServiceConfig:(o=!1,this.handleResolutionFailure(r.error)),c!==null){let l=(i=c?.loadBalancingConfig)!==null&&i!==void 0?i:[],u=(0,wDt.selectLbConfigFromList)(l,!0);u===null?(o=!1,this.handleResolutionFailure({code:t7.Status.UNAVAILABLE,details:"All load balancer options in service config are not compatible",metadata:new EDt.Metadata})):o=this.childLoadBalancer.updateAddressList(t,u,Object.assign(Object.assign({},this.channelOptions),n),a)}return o&&this.onSuccessfulResolution(c,(s=n[xRe.CHANNEL_ARGS_CONFIG_SELECTOR_KEY])!==null&&s!==void 0?s:MDt(c)),o}updateResolution(){this.innerResolver.updateResolution(),this.currentState===No.ConnectivityState.IDLE&&this.updateState(No.ConnectivityState.CONNECTING,this.latestChildPicker,this.latestChildErrorMessage),this.backoffTimeout.runOnce()}updateState(t,n,r){ERe((0,ODt.uriToString)(this.target)+" "+No.ConnectivityState[this.currentState]+" -> "+No.ConnectivityState[t]),t===No.ConnectivityState.IDLE&&(n=new HT.QueuePicker(this,n)),this.currentState=t,this.channelControlHelper.updateState(t,n,r)}handleResolutionFailure(t){this.latestChildState===No.ConnectivityState.IDLE&&(this.updateState(No.ConnectivityState.TRANSIENT_FAILURE,new HT.UnavailablePicker(t),t.details),this.onFailedResolution(t))}exitIdle(){(this.currentState===No.ConnectivityState.IDLE||this.currentState===No.ConnectivityState.TRANSIENT_FAILURE)&&(this.backoffTimeout.isRunning()?this.continueResolving=!0:this.updateResolution()),this.childLoadBalancer.exitIdle()}updateAddressList(t,n){throw new Error("updateAddressList not supported on ResolvingLoadBalancer")}resetBackoff(){this.backoffTimeout.reset(),this.childLoadBalancer.resetBackoff()}destroy(){this.childLoadBalancer.destroy(),this.innerResolver.destroy(),this.backoffTimeout.reset(),this.backoffTimeout.stop(),this.latestChildState=No.ConnectivityState.IDLE,this.latestChildPicker=new HT.QueuePicker(this),this.currentState=No.ConnectivityState.IDLE,this.previousServiceConfig=null,this.continueResolving=!1}getTypeName(){return"resolving_load_balancer"}};ZM.ResolvingLoadBalancer=n7});var kRe=_(WT=>{"use strict";Object.defineProperty(WT,"__esModule",{value:!0});WT.recognizedOptions=void 0;WT.channelOptionsEqual=DDt;WT.recognizedOptions={"grpc.ssl_target_name_override":!0,"grpc.primary_user_agent":!0,"grpc.secondary_user_agent":!0,"grpc.default_authority":!0,"grpc.keepalive_time_ms":!0,"grpc.keepalive_timeout_ms":!0,"grpc.keepalive_permit_without_calls":!0,"grpc.service_config":!0,"grpc.max_concurrent_streams":!0,"grpc.initial_reconnect_backoff_ms":!0,"grpc.max_reconnect_backoff_ms":!0,"grpc.use_local_subchannel_pool":!0,"grpc.max_send_message_length":!0,"grpc.max_receive_message_length":!0,"grpc.enable_http_proxy":!0,"grpc.enable_channelz":!0,"grpc.dns_min_time_between_resolutions_ms":!0,"grpc.enable_retries":!0,"grpc.per_rpc_retry_buffer_size":!0,"grpc.retry_buffer_size":!0,"grpc.max_connection_age_ms":!0,"grpc.max_connection_age_grace_ms":!0,"grpc-node.max_session_memory":!0,"grpc.service_config_disable_resolution":!0,"grpc.client_idle_timeout_ms":!0,"grpc-node.tls_enable_trace":!0,"grpc.lb.ring_hash.ring_size_cap":!0,"grpc-node.retry_max_attempts_limit":!0,"grpc-node.flow_control_window":!0,"grpc.server_call_metric_recording":!0};function DDt(e,t){let n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let a=0;a<n.length;a+=1)if(n[a]!==r[a]||e[n[a]]!==t[r[a]])return!1;return!0}});var Mo=_(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.EndpointMap=void 0;Ql.isTcpSubchannelAddress=YT;Ql.subchannelAddressEqual=QM;Ql.subchannelAddressToString=ARe;Ql.stringToSubchannelAddress=BDt;Ql.endpointEqual=FDt;Ql.endpointToString=LDt;Ql.endpointHasAddress=PRe;var ORe=require("net");function YT(e){return"port"in e}function QM(e,t){return!e&&!t?!0:!e||!t?!1:YT(e)?YT(t)&&e.host===t.host&&e.port===t.port:!YT(t)&&e.path===t.path}function ARe(e){return YT(e)?(0,ORe.isIPv6)(e.host)?"["+e.host+"]:"+e.port:e.host+":"+e.port:e.path}var UDt=443;function BDt(e,t){return(0,ORe.isIP)(e)?{host:e,port:t??UDt}:{path:e}}function FDt(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n=0;n<e.addresses.length;n++)if(!QM(e.addresses[n],t.addresses[n]))return!1;return!0}function LDt(e){return"["+e.addresses.map(ARe).join(", ")+"]"}function PRe(e,t){for(let n of e.addresses)if(QM(n,t))return!0;return!1}function jT(e,t){if(e.addresses.length!==t.addresses.length)return!1;for(let n of e.addresses){let r=!1;for(let a of t.addresses)if(QM(n,a)){r=!0;break}if(!r)return!1}return!0}var r7=class{constructor(){this.map=new Set}get size(){return this.map.size}getForSubchannelAddress(t){for(let n of this.map)if(PRe(n.key,t))return n.value}deleteMissing(t){let n=[];for(let r of this.map){let a=!1;for(let i of t)jT(i,r.key)&&(a=!0);a||(n.push(r.value),this.map.delete(r))}return n}get(t){for(let n of this.map)if(jT(t,n.key))return n.value}set(t,n){for(let r of this.map)if(jT(t,r.key)){r.value=n;return}this.map.add({key:t,value:n})}delete(t){for(let n of this.map)if(jT(t,n.key)){this.map.delete(n);return}}has(t){for(let n of this.map)if(jT(t,n.key))return!0;return!1}clear(){this.map.clear()}*keys(){for(let t of this.map)yield t.key}*values(){for(let t of this.map)yield t.value}*entries(){for(let t of this.map)yield[t.key,t.value]}};Ql.EndpointMap=r7});var RRe=_(d7=>{"use strict";Object.defineProperty(d7,"t",{value:!0});var eD=class{constructor(t,n,r=1){this.i=void 0,this.h=void 0,this.o=void 0,this.u=t,this.l=n,this.p=r}I(){let t=this,n=t.o.o===t;if(n&&t.p===1)t=t.h;else if(t.i)for(t=t.i;t.h;)t=t.h;else{if(n)return t.o;let r=t.o;for(;r.i===t;)t=r,r=t.o;t=r}return t}B(){let t=this;if(t.h){for(t=t.h;t.i;)t=t.i;return t}else{let n=t.o;for(;n.h===t;)t=n,n=t.o;return t.h!==n?n:t}}_(){let t=this.o,n=this.h,r=n.i;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.i=this,this.o=n,this.h=r,r&&(r.o=this),n}g(){let t=this.o,n=this.i,r=n.h;return t.o===this?t.o=n:t.i===this?t.i=n:t.h=n,n.o=t,n.h=this,this.o=n,this.i=r,r&&(r.o=this),n}},i7=class extends eD{constructor(){super(...arguments),this.M=1}_(){let t=super._();return this.O(),t.O(),t}g(){let t=super.g();return this.O(),t.O(),t}O(){this.M=1,this.i&&(this.M+=this.i.M),this.h&&(this.M+=this.h.M)}},a7=class{constructor(t=0){this.iteratorType=t}equals(t){return this.T===t.T}},s7=class{constructor(){this.m=0}get length(){return this.m}size(){return this.m}empty(){return this.m===0}},o7=class extends s7{};function Ty(){throw new RangeError("Iterator access denied!")}var c7=class extends o7{constructor(t=function(r,a){return r<a?-1:r>a?1:0},n=!1){super(),this.v=void 0,this.A=t,this.enableIndex=n,this.N=n?i7:eD,this.C=new this.N}R(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)t=t.h;else if(a>0)r=t,t=t.i;else return t}return r}K(t,n){let r=this.C;for(;t;)this.A(t.u,n)<=0?t=t.h:(r=t,t=t.i);return r}L(t,n){let r=this.C;for(;t;){let a=this.A(t.u,n);if(a<0)r=t,t=t.h;else if(a>0)t=t.i;else return t}return r}k(t,n){let r=this.C;for(;t;)this.A(t.u,n)<0?(r=t,t=t.h):t=t.i;return r}P(t){for(;;){let n=t.o;if(n===this.C)return;if(t.p===1){t.p=0;return}if(t===n.i){let r=n.h;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n._():n._();else if(r.h&&r.h.p===1){r.p=n.p,n.p=0,r.h.p=0,n===this.v?this.v=n._():n._();return}else r.i&&r.i.p===1?(r.p=1,r.i.p=0,r.g()):(r.p=1,t=n)}else{let r=n.i;if(r.p===1)r.p=0,n.p=1,n===this.v?this.v=n.g():n.g();else if(r.i&&r.i.p===1){r.p=n.p,n.p=0,r.i.p=0,n===this.v?this.v=n.g():n.g();return}else r.h&&r.h.p===1?(r.p=1,r.h.p=0,r._()):(r.p=1,t=n)}}}S(t){if(this.m===1){this.clear();return}let n=t;for(;n.i||n.h;){if(n.h)for(n=n.h;n.i;)n=n.i;else n=n.i;let a=t.u;t.u=n.u,n.u=a;let i=t.l;t.l=n.l,n.l=i,t=n}this.C.i===n?this.C.i=n.o:this.C.h===n&&(this.C.h=n.o),this.P(n);let r=n.o;if(n===r.i?r.i=void 0:r.h=void 0,this.m-=1,this.v.p=0,this.enableIndex)for(;r!==this.C;)r.M-=1,r=r.o}U(t){let n=typeof t=="number"?t:void 0,r=typeof t=="function"?t:void 0,a=typeof t>"u"?[]:void 0,i=0,s=this.v,o=[];for(;o.length||s;)if(s)o.push(s),s=s.i;else{if(s=o.pop(),i===n)return s;a&&a.push(s),r&&r(s,i,this),i+=1,s=s.h}return a}j(t){for(;;){let n=t.o;if(n.p===0)return;let r=n.o;if(n===r.i){let a=r.h;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.h){if(t.p=0,t.i&&(t.i.o=n),t.h&&(t.h.o=r),n.h=t.i,r.i=t.h,t.i=n,t.h=r,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r.g():r.g(),r.p=1;return}}else{let a=r.i;if(a&&a.p===1){if(a.p=n.p=0,r===this.v)return;r.p=1,t=r;continue}else if(t===n.i){if(t.p=0,t.i&&(t.i.o=r),t.h&&(t.h.o=n),r.h=t.i,n.i=t.h,t.i=r,t.h=n,r===this.v)this.v=t,this.C.o=t;else{let i=r.o;i.i===r?i.i=t:i.h=t}t.o=r.o,n.o=t,r.o=t,r.p=1}else{n.p=0,r===this.v?this.v=r._():r._(),r.p=1;return}}this.enableIndex&&(n.O(),r.O(),t.O());return}}q(t,n,r){if(this.v===void 0)return this.m+=1,this.v=new this.N(t,n,0),this.v.o=this.C,this.C.o=this.C.i=this.C.h=this.v,this.m;let a,i=this.C.i,s=this.A(i.u,t);if(s===0)return i.l=n,this.m;if(s>0)i.i=new this.N(t,n),i.i.o=i,a=i.i,this.C.i=a;else{let o=this.C.h,c=this.A(o.u,t);if(c===0)return o.l=n,this.m;if(c<0)o.h=new this.N(t,n),o.h.o=o,a=o.h,this.C.h=a;else{if(r!==void 0){let l=r.T;if(l!==this.C){let u=this.A(l.u,t);if(u===0)return l.l=n,this.m;if(u>0){let d=l.I(),f=this.A(d.u,t);if(f===0)return d.l=n,this.m;f<0&&(a=new this.N(t,n),d.h===void 0?(d.h=a,a.o=d):(l.i=a,a.o=l))}}}if(a===void 0)for(a=this.v;;){let l=this.A(a.u,t);if(l>0){if(a.i===void 0){a.i=new this.N(t,n),a.i.o=a,a=a.i;break}a=a.i}else if(l<0){if(a.h===void 0){a.h=new this.N(t,n),a.h.o=a,a=a.h;break}a=a.h}else return a.l=n,this.m}}}if(this.enableIndex){let o=a.o;for(;o!==this.C;)o.M+=1,o=o.o}return this.j(a),this.m+=1,this.m}H(t,n){for(;t;){let r=this.A(t.u,n);if(r<0)t=t.h;else if(r>0)t=t.i;else return t}return t||this.C}clear(){this.m=0,this.v=void 0,this.C.o=void 0,this.C.i=this.C.h=void 0}updateKeyByIterator(t,n){let r=t.T;if(r===this.C&&Ty(),this.m===1)return r.u=n,!0;let a=r.B().u;if(r===this.C.i)return this.A(a,n)>0?(r.u=n,!0):!1;let i=r.I().u;return r===this.C.h?this.A(i,n)<0?(r.u=n,!0):!1:this.A(i,n)>=0||this.A(a,n)<=0?!1:(r.u=n,!0)}eraseElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return this.S(n),this.m}eraseElementByKey(t){if(this.m===0)return!1;let n=this.H(this.v,t);return n===this.C?!1:(this.S(n),!0)}eraseElementByIterator(t){let n=t.T;n===this.C&&Ty();let r=n.h===void 0;return t.iteratorType===0?r&&t.next():(!r||n.i===void 0)&&t.next(),this.S(n),t}getHeight(){if(this.m===0)return 0;function t(n){return n?Math.max(t(n.i),t(n.h))+1:0}return t(this.v)}},l7=class extends a7{constructor(t,n,r){super(r),this.T=t,this.C=n,this.iteratorType===0?(this.pre=function(){return this.T===this.C.i&&Ty(),this.T=this.T.I(),this},this.next=function(){return this.T===this.C&&Ty(),this.T=this.T.B(),this}):(this.pre=function(){return this.T===this.C.h&&Ty(),this.T=this.T.B(),this},this.next=function(){return this.T===this.C&&Ty(),this.T=this.T.I(),this})}get index(){let t=this.T,n=this.C.o;if(t===this.C)return n?n.M-1:0;let r=0;for(t.i&&(r+=t.i.M);t!==n;){let a=t.o;t===a.h&&(r+=1,a.i&&(r+=a.i.M)),t=a}return r}isAccessible(){return this.T!==this.C}},eu=class e extends l7{constructor(t,n,r,a){super(t,n,a),this.container=r}get pointer(){this.T===this.C&&Ty();let t=this;return new Proxy([],{get(n,r){return r==="0"?t.T.u:r==="1"?t.T.l:(n[0]=t.T.u,n[1]=t.T.l,n[r])},set(n,r,a){if(r!=="1")throw new TypeError("prop must be 1");return t.T.l=a,!0}})}copy(){return new e(this.T,this.C,this.container,this.iteratorType)}},u7=class extends c7{constructor(t=[],n,r){super(n,r);let a=this;t.forEach(function(i){a.setElement(i[0],i[1])})}begin(){return new eu(this.C.i||this.C,this.C,this)}end(){return new eu(this.C,this.C,this)}rBegin(){return new eu(this.C.h||this.C,this.C,this,1)}rEnd(){return new eu(this.C,this.C,this,1)}front(){if(this.m===0)return;let t=this.C.i;return[t.u,t.l]}back(){if(this.m===0)return;let t=this.C.h;return[t.u,t.l]}lowerBound(t){let n=this.R(this.v,t);return new eu(n,this.C,this)}upperBound(t){let n=this.K(this.v,t);return new eu(n,this.C,this)}reverseLowerBound(t){let n=this.L(this.v,t);return new eu(n,this.C,this)}reverseUpperBound(t){let n=this.k(this.v,t);return new eu(n,this.C,this)}forEach(t){this.U(function(n,r,a){t([n.u,n.l],r,a)})}setElement(t,n,r){return this.q(t,n,r)}getElementByPos(t){if(t<0||t>this.m-1)throw new RangeError;let n=this.U(t);return[n.u,n.l]}find(t){let n=this.H(this.v,t);return new eu(n,this.C,this)}getElementByKey(t){return this.H(this.v,t).l}union(t){let n=this;return t.forEach(function(r){n.setElement(r[0],r[1])}),this.m}*[Symbol.iterator](){let t=this.m,n=this.U();for(let r=0;r<t;++r){let a=n[r];yield[a.u,a.l]}}};d7.OrderedMap=u7});var nD=_(tD=>{"use strict";Object.defineProperty(tD,"__esModule",{value:!0});tD.registerAdminService=VDt;tD.addAdminServicesToServer=qDt;var CRe=[];function VDt(e,t){CRe.push({getServiceDefinition:e,getHandlers:t})}function qDt(e){for(let{getServiceDefinition:t,getHandlers:n}of CRe)e.addService(t(),n())}});var NRe=_(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.ClientDuplexStreamImpl=tu.ClientWritableStreamImpl=tu.ClientReadableStreamImpl=tu.ClientUnaryCallImpl=void 0;tu.callErrorFromStatus=zDt;var $Dt=require("events"),g7=require("stream"),KT=Yt();function zDt(e,t){let n=`${e.code} ${KT.Status[e.code]}: ${e.details}`,a=`${new Error(n).stack}
218
218
  for call at
219
219
  ${t}`;return Object.assign(new Error(n),e,{stack:a})}var f7=class extends $Dt.EventEmitter{constructor(){super()}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(KT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}};tu.ClientUnaryCallImpl=f7;var p7=class extends g7.Readable{constructor(t){super({objectMode:!0}),this.deserialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(KT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}};tu.ClientReadableStreamImpl=p7;var h7=class extends g7.Writable{constructor(t){super({objectMode:!0}),this.serialize=t}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(KT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};tu.ClientWritableStreamImpl=h7;var m7=class extends g7.Duplex{constructor(t,n){super({objectMode:!0}),this.serialize=t,this.deserialize=n}cancel(){var t;(t=this.call)===null||t===void 0||t.cancelWithStatus(KT.Status.CANCELLED,"Cancelled on client")}getPeer(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getPeer())!==null&&n!==void 0?n:"unknown"}getAuthContext(){var t,n;return(n=(t=this.call)===null||t===void 0?void 0:t.getAuthContext())!==null&&n!==void 0?n:null}_read(t){var n;(n=this.call)===null||n===void 0||n.startRead()}_write(t,n,r){var a;let i={callback:r},s=Number(n);Number.isNaN(s)||(i.flags=s),(a=this.call)===null||a===void 0||a.sendMessageWithContext(i,t)}_final(t){var n;(n=this.call)===null||n===void 0||n.halfClose(),t()}};tu.ClientDuplexStreamImpl=m7});var Oy=_(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});ky.InterceptingListenerImpl=void 0;ky.statusOrFromValue=JDt;ky.statusOrFromError=HDt;ky.isInterceptingListener=WDt;var GDt=ma();function JDt(e){return{ok:!0,value:e}}function HDt(e){var t;return{ok:!1,error:Object.assign(Object.assign({},e),{metadata:(t=e.metadata)!==null&&t!==void 0?t:new GDt.Metadata})}}function WDt(e){return e.onReceiveMetadata!==void 0&&e.onReceiveMetadata.length===1}var y7=class{constructor(t,n){this.listener=t,this.nextListener=n,this.processingMetadata=!1,this.hasPendingMessage=!1,this.processingMessage=!1,this.pendingStatus=null}processPendingMessage(){this.hasPendingMessage&&(this.nextListener.onReceiveMessage(this.pendingMessage),this.pendingMessage=null,this.hasPendingMessage=!1)}processPendingStatus(){this.pendingStatus&&this.nextListener.onReceiveStatus(this.pendingStatus)}onReceiveMetadata(t){this.processingMetadata=!0,this.listener.onReceiveMetadata(t,n=>{this.processingMetadata=!1,this.nextListener.onReceiveMetadata(n),this.processPendingMessage(),this.processPendingStatus()})}onReceiveMessage(t){this.processingMessage=!0,this.listener.onReceiveMessage(t,n=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessage=n,this.hasPendingMessage=!0):(this.nextListener.onReceiveMessage(n),this.processPendingStatus())})}onReceiveStatus(t){this.listener.onReceiveStatus(t,n=>{this.processingMetadata||this.processingMessage?this.pendingStatus=n:this.nextListener.onReceiveStatus(n)})}};ky.InterceptingListenerImpl=y7});var x7=_(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});nu.InterceptingCall=nu.RequesterBuilder=nu.ListenerBuilder=nu.InterceptorConfigurationError=void 0;nu.getInterceptingCall=XDt;var jDt=ma(),MRe=Oy(),DRe=Yt(),URe=UM(),ZT=class e extends Error{constructor(t){super(t),this.name="InterceptorConfigurationError",Error.captureStackTrace(this,e)}};nu.InterceptorConfigurationError=ZT;var b7=class{constructor(){this.metadata=void 0,this.message=void 0,this.status=void 0}withOnReceiveMetadata(t){return this.metadata=t,this}withOnReceiveMessage(t){return this.message=t,this}withOnReceiveStatus(t){return this.status=t,this}build(){return{onReceiveMetadata:this.metadata,onReceiveMessage:this.message,onReceiveStatus:this.status}}};nu.ListenerBuilder=b7;var S7=class{constructor(){this.start=void 0,this.message=void 0,this.halfClose=void 0,this.cancel=void 0}withStart(t){return this.start=t,this}withSendMessage(t){return this.message=t,this}withHalfClose(t){return this.halfClose=t,this}withCancel(t){return this.cancel=t,this}build(){return{start:this.start,sendMessage:this.message,halfClose:this.halfClose,cancel:this.cancel}}};nu.RequesterBuilder=S7;var v7={onReceiveMetadata:(e,t)=>{t(e)},onReceiveMessage:(e,t)=>{t(e)},onReceiveStatus:(e,t)=>{t(e)}},XT={start:(e,t,n)=>{n(e,t)},sendMessage:(e,t)=>{t(e)},halfClose:e=>{e()},cancel:e=>{e()}},_7=class{constructor(t,n){var r,a,i,s;this.nextCall=t,this.processingMetadata=!1,this.pendingMessageContext=null,this.processingMessage=!1,this.pendingHalfClose=!1,n?this.requester={start:(r=n.start)!==null&&r!==void 0?r:XT.start,sendMessage:(a=n.sendMessage)!==null&&a!==void 0?a:XT.sendMessage,halfClose:(i=n.halfClose)!==null&&i!==void 0?i:XT.halfClose,cancel:(s=n.cancel)!==null&&s!==void 0?s:XT.cancel}:this.requester=XT}cancelWithStatus(t,n){this.requester.cancel(()=>{this.nextCall.cancelWithStatus(t,n)})}getPeer(){return this.nextCall.getPeer()}processPendingMessage(){this.pendingMessageContext&&(this.nextCall.sendMessageWithContext(this.pendingMessageContext,this.pendingMessage),this.pendingMessageContext=null,this.pendingMessage=null)}processPendingHalfClose(){this.pendingHalfClose&&this.nextCall.halfClose()}start(t,n){var r,a,i,s,o,c;let l={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:u=>{},onReceiveMessage:(s=(i=n?.onReceiveMessage)===null||i===void 0?void 0:i.bind(n))!==null&&s!==void 0?s:u=>{},onReceiveStatus:(c=(o=n?.onReceiveStatus)===null||o===void 0?void 0:o.bind(n))!==null&&c!==void 0?c:u=>{}};this.processingMetadata=!0,this.requester.start(t,l,(u,d)=>{var f,p,m;this.processingMetadata=!1;let y;if((0,MRe.isInterceptingListener)(d))y=d;else{let b={onReceiveMetadata:(f=d.onReceiveMetadata)!==null&&f!==void 0?f:v7.onReceiveMetadata,onReceiveMessage:(p=d.onReceiveMessage)!==null&&p!==void 0?p:v7.onReceiveMessage,onReceiveStatus:(m=d.onReceiveStatus)!==null&&m!==void 0?m:v7.onReceiveStatus};y=new MRe.InterceptingListenerImpl(b,l)}this.nextCall.start(u,y),this.processPendingMessage(),this.processPendingHalfClose()})}sendMessageWithContext(t,n){this.processingMessage=!0,this.requester.sendMessage(n,r=>{this.processingMessage=!1,this.processingMetadata?(this.pendingMessageContext=t,this.pendingMessage=n):(this.nextCall.sendMessageWithContext(t,r),this.processPendingHalfClose())})}sendMessage(t){this.sendMessageWithContext({},t)}startRead(){this.nextCall.startRead()}halfClose(){this.requester.halfClose(()=>{this.processingMetadata||this.processingMessage?this.pendingHalfClose=!0:this.nextCall.halfClose()})}getAuthContext(){return this.nextCall.getAuthContext()}};nu.InterceptingCall=_7;function YDt(e,t,n){var r,a;let i=(r=n.deadline)!==null&&r!==void 0?r:1/0,s=n.host,o=(a=n.parent)!==null&&a!==void 0?a:null,c=n.propagate_flags,l=n.credentials,u=e.createCall(t,i,s,o,c);return l&&u.setCredentials(l),u}var rD=class{constructor(t,n){this.call=t,this.methodDefinition=n}cancelWithStatus(t,n){this.call.cancelWithStatus(t,n)}getPeer(){return this.call.getPeer()}sendMessageWithContext(t,n){let r;try{r=this.methodDefinition.requestSerialize(n)}catch(a){this.call.cancelWithStatus(DRe.Status.INTERNAL,`Request message serialization failure: ${(0,URe.getErrorMessage)(a)}`);return}this.call.sendMessageWithContext(t,r)}sendMessage(t){this.sendMessageWithContext({},t)}start(t,n){let r=null;this.call.start(t,{onReceiveMetadata:a=>{var i;(i=n?.onReceiveMetadata)===null||i===void 0||i.call(n,a)},onReceiveMessage:a=>{var i;let s;try{s=this.methodDefinition.responseDeserialize(a)}catch(o){r={code:DRe.Status.INTERNAL,details:`Response message parsing error: ${(0,URe.getErrorMessage)(o)}`,metadata:new jDt.Metadata},this.call.cancelWithStatus(r.code,r.details);return}(i=n?.onReceiveMessage)===null||i===void 0||i.call(n,s)},onReceiveStatus:a=>{var i,s;r?(i=n?.onReceiveStatus)===null||i===void 0||i.call(n,r):(s=n?.onReceiveStatus)===null||s===void 0||s.call(n,a)}})}startRead(){this.call.startRead()}halfClose(){this.call.halfClose()}getAuthContext(){return this.call.getAuthContext()}},w7=class extends rD{constructor(t,n){super(t,n)}start(t,n){var r,a;let i=!1,s={onReceiveMetadata:(a=(r=n?.onReceiveMetadata)===null||r===void 0?void 0:r.bind(n))!==null&&a!==void 0?a:o=>{},onReceiveMessage:o=>{var c;i=!0,(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,o)},onReceiveStatus:o=>{var c,l;i||(c=n?.onReceiveMessage)===null||c===void 0||c.call(n,null),(l=n?.onReceiveStatus)===null||l===void 0||l.call(n,o)}};super.start(t,s),this.call.startRead()}},I7=class extends rD{};function KDt(e,t,n){let r=YDt(e,n.path,t);return n.responseStream?new I7(r,n):new w7(r,n)}function XDt(e,t,n,r){if(e.clientInterceptors.length>0&&e.clientInterceptorProviders.length>0)throw new ZT("Both interceptors and interceptor_providers were passed as options to the client constructor. Only one of these is allowed.");if(e.callInterceptors.length>0&&e.callInterceptorProviders.length>0)throw new ZT("Both interceptors and interceptor_providers were passed as call options. Only one of these is allowed.");let a=[];e.callInterceptors.length>0||e.callInterceptorProviders.length>0?a=[].concat(e.callInterceptors,e.callInterceptorProviders.map(o=>o(t))).filter(o=>o):a=[].concat(e.clientInterceptors,e.clientInterceptorProviders.map(o=>o(t))).filter(o=>o);let i=Object.assign({},n,{method_definition:t});return a.reduceRight((o,c)=>l=>c(l,o),o=>KDt(r,o,t))(i)}});var k7=_(aD=>{"use strict";Object.defineProperty(aD,"__esModule",{value:!0});aD.Client=void 0;var kd=NRe(),ZDt=O7(),QDt=ro(),Lh=Yt(),aS=ma(),iD=x7(),ru=Symbol(),sS=Symbol(),oS=Symbol(),fp=Symbol();function E7(e){return typeof e=="function"}function cS(e){var t;return((t=e.stack)===null||t===void 0?void 0:t.split(`
220
220
  `).slice(1).join(`
@@ -250,7 +250,7 @@ const app = await modal.apps.fromName("my-app");
250
250
  modal.sandboxes.experimentalList({ appId: app.appId });`);let t=e.tags?Object.entries(e.tags).map(([r,a])=>({tagName:r,tagValue:a})):[],n;for(;;){let r=await this.#e.cpClient.sandboxListV2({appId:e.appId,beforeTimestamp:n,includeFinished:!1,tags:t});if(!r.sandboxes||r.sandboxes.length===0)return;for(let a of r.sandboxes)yield new iv(this.#e,a.id,{isV2:!0});n=r.sandboxes[r.sandboxes.length-1].createdAt}}},a9e=class{constructor(e,t,n,r){this.host=e,this.port=t,this.unencryptedHost=n,this.unencryptedPort=r}get url(){let e=`https://${this.host}`;return this.port!==443&&(e+=`:${this.port}`),e}get tlsSocket(){return[this.host,this.port]}get tcpSocket(){if(!this.unencryptedHost||this.unencryptedPort===void 0)throw new wt("This tunnel is not configured for unencrypted TCP.");return[this.unencryptedHost,this.unencryptedPort]}};iv=class l9e{#e;sandboxId;#t;#n;#r;#a;#s;#l;#u;#c;#p;#d;#h=!0;#m;#g;constructor(t,n,r={}){this.#e=t,this.sandboxId=n,this.#c=r.isV2??!1,this.#l=r.taskId||void 0,this.#u=r.tunnels}get stdin(){return this.#f("stdin"),this.#t||(this.#t=n9e(I8t(this.#e.cpClient,this.sandboxId))),this.#t}get stdout(){if(this.#f("stdout"),!this.#n){this.#a=new AbortController;let t=RU(fHe(this.#e.cpClient,this.sandboxId,1,this.#a.signal),()=>this.#a?.abort());this.#n=Aw(t.pipeThrough(new TextDecoderStream))}return this.#n}get stderr(){if(this.#f("stderr"),!this.#r){this.#s=new AbortController;let t=RU(fHe(this.#e.cpClient,this.sandboxId,2,this.#s.signal),()=>this.#s?.abort());this.#r=Aw(t.pipeThrough(new TextDecoderStream))}return this.#r}get filesystem(){return this.#i(),this.#m||(this.#m=new e9e((t,n)=>this.#y(t,n))),this.#m}get experimentalSidecars(){return this.#i(),this.#g||(this.#g=new o8t({client:this.#e,exec:(t,n,r)=>this.#y(t,n,r),commandRouter:()=>this.#o()})),this.#g}async setTags(t){this.#i(),this.#f("setTags");let n=Object.entries(t).map(([r,a])=>({tagName:r,tagValue:a}));try{await this.#e.cpClient.sandboxTagsSet({environmentName:this.#e.environmentName(),sandboxId:this.sandboxId,tags:n})}catch(r){throw r instanceof Fs.ClientError&&r.code===Fs.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}}async getTags(){this.#i(),this.#f("getTags");let t;try{t=await this.#e.cpClient.sandboxTagsGet({sandboxId:this.sandboxId})}catch(r){throw r instanceof Fs.ClientError&&r.code===Fs.Status.INVALID_ARGUMENT?new wt(r.details||r.message):r}let n={};for(let r of t.tags)n[r.tagName]=r.tagValue;return n}async exec(t,n){return this.#y(t,n)}async#y(t,n,r){this.#i(),o9e(t),FU(n?.env??{});let[a,i]=dX(n?.secrets??[]);Object.assign(a,n?.env??{}),await Dw(this.#e,i);let s={...n,env:a,secrets:i},[o,c]=await this.#o(),l=nv(),u=b8t(o,l,t,s,r);await c.execStart(u),this.#e.logger.debug("Created ContainerProcess","exec_id",l,"sandbox_id",this.sandboxId,"container_id",r??"","command",t);let d=n?.timeoutMs?Date.now()+n.timeoutMs:null;return new w8t(o,l,c,n,d)}async#o(){this.#i();let t=await this.#I(),n=await this.#x(t);return[t,n]}#i(){if(!this.#h)throw new AU}#f(t){if(this.#c)throw new wt(`Sandbox.${t} is not supported for V2 sandboxes`)}#v(t){let n={sandboxId:this.sandboxId,timeout:t};return this.#c?this.#e.cpClient.sandboxWaitV2(n):this.#e.cpClient.sandboxWait(n)}#b(){let t={sandboxId:this.sandboxId};return this.#c?this.#e.cpClient.sandboxGetTaskIdV2(t):this.#e.cpClient.sandboxGetTaskId(t)}#S(t){let n={sandboxId:this.sandboxId,timeout:t/1e3};return this.#c?this.#e.cpClient.sandboxGetTunnelsV2(n):this.#e.cpClient.sandboxGetTunnels(n)}async#_(){let t={sandboxId:this.sandboxId};if(this.#c){await this.#e.cpClient.sandboxTerminateV2(t);return}await this.#e.cpClient.sandboxTerminate(t)}static#w=600;async#I(){if(this.#l!==void 0)return this.#l;for(let t=0;t<l9e.#w;t++){let n=await this.#b();if(n.taskResult)throw n.taskResult.status===1||!n.taskResult.exception?new Error(`Sandbox ${this.sandboxId} has already completed`):new Error(`Sandbox ${this.sandboxId} has already completed with result: exception:"${n.taskResult.exception}"`);if(n.taskId)return this.#l=n.taskId,this.#l;await(0,fX.setTimeout)(500)}throw new Error(`Timed out waiting for task ID for Sandbox ${this.sandboxId}`)}async#x(t){if(this.#p!==void 0)return this.#p;if(this.#d!==void 0)return this.#d;let n=(async()=>{let r=await V6t.tryInit(this.#e.cpClient,t,this.sandboxId,this.#c,this.#e.logger,this.#e.profile);if(!r)throw new Error("Command router access is not available for this sandbox");if(!this.#h)throw r.close(),new AU;return this.#p=r,r})();this.#d=n;try{return await n}catch(r){throw this.#d===n&&(this.#d=void 0),r}}async createConnectToken(t){this.#i(),this.#f("createConnectToken");let n=t?.port??8080;if(!Number.isInteger(n)||n<1||n>65535)throw new wt(`createConnectToken() expects \`port\` in [1, 65535], got ${n}`);let r=await this.#e.cpClient.sandboxCreateConnectToken({sandboxId:this.sandboxId,userMetadata:t?.userMetadata,port:n});return{url:r.url,token:r.token}}async terminate(t){this.#i(),await this.#_();let n;return t?.wait&&(n=await this.wait()),this.#l=void 0,this.detach(),n}detach(){this.#p?.close(),this.#h=!1,this.#p=void 0,this.#d=void 0}async wait(){for(;;){let t=await this.#v(10);if(t.result){let n=Pw(t.result);return this.#e.logger.debug("Sandbox wait completed","sandbox_id",this.sandboxId,"status",t.result.status,"return_code",n),n}}}async waitUntilReady(t=3e5){if(this.#i(),t<=0)throw new wt(`timeoutMs must be positive, got ${t}`);let[n,r]=await this.#o();await r.sandboxWaitUntilReady(n,t)}async tunnels(t=5e4){if(this.#i(),this.#u)return this.#u;let n=await this.#S(t);if(n.result?.status===4)throw new vHt;this.#u={};for(let r of n.tunnels)this.#u[r.containerPort]=new a9e(r.host,r.port,r.unencryptedHost,r.unencryptedPort);return this.#u}async snapshotFilesystem(t){this.#i();let n=uHe(t?.ttlMs),r=t?.timeoutMs||55e3,[a,i]=await this.#o(),s=kX.create({taskId:a,snapshotId:nv(),ttlSeconds:n}),o=await i.snapshotFilesystem(s,{timeoutMs:r});if(!o.imageId)throw new Error("Sandbox snapshot filesystem response missing `imageId`");return new uv(this.#e,o.imageId,"")}async mountImage(t,n,r){this.#i();let[a,i]=await this.#o();if(n&&!n.imageId)throw new Error("Image must be built before mounting. Call `image.build(app)` first.");let s=n?.imageId??"",o=S8t(a,t,s,r);await i.mountDirectory(o)}async unmountImage(t){this.#i();let[n,r]=await this.#o(),a=new TextEncoder().encode(t),i=OX.create({taskId:n,path:a});await r.unmountDirectory(i)}async updateNetworkPolicy(t){if(this.#i(),t.outboundCidrAllowlist===void 0||t.outboundDomainAllowlist===void 0)throw new wt("updateNetworkPolicy currently requires both outboundCidrAllowlist and outboundDomainAllowlist to be set");let[n,r]=await this.#o(),a=EX.create({taskId:n,networkAccess:oo.create({networkAccessType:3,allowedCidrs:t.outboundCidrAllowlist,allowedDomains:t.outboundDomainAllowlist})});await r.setNetworkAccess(a)}async reloadVolumes(t){if(this.#i(),t?.timeoutMs!==void 0&&t.timeoutMs<0)throw new wt("`timeoutMs` must not be negative");let n=t?.timeoutMs||55e3,[r,a]=await this.#o();await a.reloadVolumes(xX.create({taskId:r}),{timeoutMs:n})}async snapshotDirectory(t,n){this.#i();let r=uHe(n?.ttlMs),a=n?.timeoutMs||55e3,[i,s]=await this.#o(),o=_8t(i,t,nv(),r,n),c=await s.snapshotDirectory(o,{timeoutMs:a});if(!c.imageId)throw new Error("Sandbox snapshot directory response missing `imageId`");return new uv(this.#e,c.imageId,"")}async poll(){this.#i();let t=await this.#v(0);return Pw(t.result)}},w8t=class{stdin;stdout;stderr;#e;#t;#n;#r;constructor(e,t,n,r,a){this.#e=e,this.#t=t,this.#n=n,this.#r=a??null;let i=r?.mode??"text",s=r?.stdout??"pipe",o=r?.stderr??"pipe";this.stdin=n9e(x8t(n,e,t));let c=s==="ignore"?ReadableStream.from([]):RU(pHe(n,e,t,1,this.#r)),l=o==="ignore"?ReadableStream.from([]):RU(pHe(n,e,t,2,this.#r));i==="text"?(this.stdout=Aw(c.pipeThrough(new TextDecoderStream)),this.stderr=Aw(l.pipeThrough(new TextDecoderStream))):(this.stdout=Aw(c),this.stderr=Aw(l))}async closeStdin(){await this.#n.execStdinWrite(this.#e,this.#t,0,new Uint8Array(0),!0).catch(()=>{})}async wait(){let e=await this.#n.execWait(this.#e,this.#t,this.#r);if(e.code!==void 0)return e.code;if(e.signal!==void 0)return 128+e.signal;throw new wt("Unexpected exit status")}}});var p9e=_((akn,f9e)=>{f9e.exports=require("events")});var m9e=_((okn,h9e)=>{h9e.exports=class{constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}});var PX=_((lkn,y9e)=>{var g9e=m9e();y9e.exports=class{constructor(t){this.hwm=t||16,this.head=new g9e(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(t){if(this.length++,!this.head.push(t)){let n=this.head;this.head=n.next=new g9e(2*this.head.buffer.length),this.head.push(t)}}shift(){this.length!==0&&this.length--;let t=this.tail.shift();if(t===void 0&&this.tail.next){let n=this.tail.next;return this.tail.next=null,this.tail=n,this.tail.shift()}return t}peek(){let t=this.tail.peek();return t===void 0&&this.tail.next?this.tail.next.peek():t}isEmpty(){return this.length===0}}});var Uw=_((ukn,v9e)=>{function E8t(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function T8t(e){return Buffer.isEncoding(e)}function k8t(e,t,n){return Buffer.alloc(e,t,n)}function O8t(e){return Buffer.allocUnsafe(e)}function A8t(e){return Buffer.allocUnsafeSlow(e)}function P8t(e,t){return Buffer.byteLength(e,t)}function R8t(e,t){return Buffer.compare(e,t)}function C8t(e,t){return Buffer.concat(e,t)}function N8t(e,t,n,r,a){return cr(e).copy(t,n,r,a)}function M8t(e,t){return cr(e).equals(t)}function D8t(e,t,n,r,a){return cr(e).fill(t,n,r,a)}function U8t(e,t,n){return Buffer.from(e,t,n)}function B8t(e,t,n,r){return cr(e).includes(t,n,r)}function F8t(e,t,n,r){return cr(e).indexOf(t,n,r)}function L8t(e,t,n,r){return cr(e).lastIndexOf(t,n,r)}function V8t(e){return cr(e).swap16()}function q8t(e){return cr(e).swap32()}function $8t(e){return cr(e).swap64()}function cr(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function z8t(e,t,n,r){return cr(e).toString(t,n,r)}function G8t(e,t,n,r,a){return cr(e).write(t,n,r,a)}function J8t(e,t){return cr(e).readDoubleBE(t)}function H8t(e,t){return cr(e).readDoubleLE(t)}function W8t(e,t){return cr(e).readFloatBE(t)}function j8t(e,t){return cr(e).readFloatLE(t)}function Y8t(e,t){return cr(e).readInt32BE(t)}function K8t(e,t){return cr(e).readInt32LE(t)}function X8t(e,t){return cr(e).readUInt32BE(t)}function Z8t(e,t){return cr(e).readUInt32LE(t)}function Q8t(e,t,n){return cr(e).writeDoubleBE(t,n)}function eWt(e,t,n){return cr(e).writeDoubleLE(t,n)}function tWt(e,t,n){return cr(e).writeFloatBE(t,n)}function nWt(e,t,n){return cr(e).writeFloatLE(t,n)}function rWt(e,t,n){return cr(e).writeInt32BE(t,n)}function iWt(e,t,n){return cr(e).writeInt32LE(t,n)}function aWt(e,t,n){return cr(e).writeUInt32BE(t,n)}function sWt(e,t,n){return cr(e).writeUInt32LE(t,n)}v9e.exports={isBuffer:E8t,isEncoding:T8t,alloc:k8t,allocUnsafe:O8t,allocUnsafeSlow:A8t,byteLength:P8t,compare:R8t,concat:C8t,copy:N8t,equals:M8t,fill:D8t,from:U8t,includes:B8t,indexOf:F8t,lastIndexOf:L8t,swap16:V8t,swap32:q8t,swap64:$8t,toBuffer:cr,toString:z8t,write:G8t,readDoubleBE:J8t,readDoubleLE:H8t,readFloatBE:W8t,readFloatLE:j8t,readInt32BE:Y8t,readInt32LE:K8t,readUInt32BE:X8t,readUInt32LE:Z8t,writeDoubleBE:Q8t,writeDoubleLE:eWt,writeFloatBE:tWt,writeFloatLE:nWt,writeInt32BE:rWt,writeInt32LE:iWt,writeUInt32BE:aWt,writeUInt32LE:sWt}});var S9e=_((fkn,b9e)=>{var oWt=Uw();b9e.exports=class{constructor(t){this.encoding=t}get remaining(){return 0}decode(t){return oWt.toString(t,this.encoding)}flush(){return""}}});var w9e=_((hkn,_9e)=>{var cWt=Uw();_9e.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(t){if(this.bytesNeeded===0){let r=!0;for(let a=Math.max(0,t.byteLength-4),i=t.byteLength;a<i&&r;a++)r=t[a]<=127;if(r)return cWt.toString(t,"utf8")}let n="";for(let r=0,a=t.byteLength;r<a;r++){let i=t[r];if(this.bytesNeeded===0){i<=127?n+=String.fromCharCode(i):(this.bytesSeen=1,i>=194&&i<=223?(this.bytesNeeded=2,this.codePoint=i&31):i>=224&&i<=239?(i===224?this.lowerBoundary=160:i===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=i&15):i>=240&&i<=244?(i===240&&(this.lowerBoundary=144),i===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=i&7):n+="\uFFFD");continue}if(i<this.lowerBoundary||i>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,n+="\uFFFD";continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|i&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(n+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return n}flush(){let t=this.bytesNeeded>0?"\uFFFD":"";return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t}}});var x9e=_((gkn,I9e)=>{var lWt=S9e(),uWt=w9e();I9e.exports=class{constructor(t="utf8"){switch(this.encoding=dWt(t),this.encoding){case"utf8":this.decoder=new uWt;break;case"utf16le":case"base64":throw new Error("Unsupported encoding: "+this.encoding);default:this.decoder=new lWt(this.encoding)}}get remaining(){return this.decoder.remaining}push(t){return typeof t=="string"?t:this.decoder.decode(t)}write(t){return this.push(t)}end(t){let n="";return t&&(n=this.push(t)),n+=this.decoder.flush(),n}};function dWt(e){switch(e=e.toLowerCase(),e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:throw new Error("Unknown encoding: "+e)}}});var HX=_((ykn,W9e)=>{var{EventEmitter:fWt}=p9e(),HU=new Error("Stream was destroyed"),RX=new Error("Premature close"),P9e=PX(),pWt=x9e(),CX=typeof queueMicrotask>"u"?e=>global.process.nextTick(e):queueMicrotask,si=(1<<29)-1,ef=1,LX=2,yv=4,sO=8,R9e=si^ef,hWt=si^LX,dO=16,Bw=32,Vw=64,gm=128,fO=256,VX=512,vv=1024,NX=2048,qX=4096,$X=8192,zu=16384,mm=32768,WU=65536,bv=131072,C9e=fO|VX,mWt=dO|WU,gWt=Vw|dO,yWt=qX|gm,zX=fO|bv,vWt=si^dO,bWt=si^Vw,SWt=si^(Vw|WU),E9e=si^WU,_Wt=si^fO,wWt=si^(gm|$X),IWt=si^vv,T9e=si^C9e,N9e=si^mm,xWt=si^Bw,M9e=si^bv,EWt=si^zX,Np=1<<18,Lw=2<<18,pO=4<<18,Sv=8<<18,hO=16<<18,ym=32<<18,MX=64<<18,Fw=128<<18,GX=256<<18,_v=512<<18,jU=1024<<18,TWt=si^(Np|GX),D9e=si^pO,kWt=si^(Np|_v),OWt=si^hO,AWt=si^Sv,U9e=si^Fw,PWt=si^Lw,B9e=si^jU,oO=dO|Np,F9e=si^oO,JX=zu|ym,tf=yv|sO|LX,_c=tf|ef,L9e=tf|JX,RWt=D9e&bWt,YU=Fw|mm,CWt=YU&F9e,V9e=_c|CWt,NWt=_c|vv|zu,k9e=_c|zu|gm,MWt=_c|vv|gm,DWt=_c|qX|gm|$X,UWt=_c|dO|vv|zu|WU|bv,BWt=tf|vv|zu,FWt=Bw|_c|mm|Vw,LWt=mm|ef,VWt=_c|_v|ym,qWt=Sv|hO,q9e=Sv|Np,$Wt=Sv|hO|_c|Np,O9e=_c|Np|Sv|jU,zWt=pO|Np,GWt=Np|GX,JWt=_c|_v|q9e|ym,HWt=hO|tf|_v|ym,WWt=Lw|_c|Fw|pO,jWt=_v|ym|tf,qU=Symbol.asyncIterator||Symbol("asyncIterator"),$U=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapWritable:a,byteLength:i,byteLengthWritable:s}={}){this.stream=t,this.queue=new P9e,this.highWaterMark=n,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=s||i||H9e,this.map=a||r,this.afterWrite=XWt.bind(this),this.afterUpdateNextTick=e7t.bind(this)}get ended(){return(this.stream._duplexState&ym)!==0}push(t){return this.stream._duplexState&jWt?!1:(this.map!==null&&(t=this.map(t)),this.buffered+=this.byteLength(t),this.queue.push(t),this.buffered<this.highWaterMark?(this.stream._duplexState|=Sv,!0):(this.stream._duplexState|=qWt,!1))}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=AWt),t}end(t){typeof t=="function"?this.stream.once("finish",t):t!=null&&this.push(t),this.stream._duplexState=(this.stream._duplexState|_v)&D9e}autoBatch(t,n){let r=[],a=this.stream;for(r.push(t);(a._duplexState&O9e)===q9e;)r.push(a._writableState.shift());if(a._duplexState&_c)return n(null);a._writev(r,n)}update(){let t=this.stream;t._duplexState|=Lw;do{for(;(t._duplexState&O9e)===Sv;){let n=this.shift();t._duplexState|=GWt,t._write(n,this.afterWrite)}t._duplexState&zWt||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=PWt}updateNonPrimary(){let t=this.stream;if((t._duplexState&JWt)===_v){t._duplexState=t._duplexState|Np,t._final(KWt.bind(this));return}if((t._duplexState&tf)===yv){t._duplexState&YU||(t._duplexState|=oO,t._destroy($9e.bind(this)));return}(t._duplexState&V9e)===ef&&(t._duplexState=(t._duplexState|oO)&R9e,t._open(z9e.bind(this)))}continueUpdate(){return this.stream._duplexState&Fw?(this.stream._duplexState&=U9e,!0):!1}updateCallback(){(this.stream._duplexState&WWt)===pO?this.update():this.updateNextTick()}updateNextTick(){this.stream._duplexState&Fw||(this.stream._duplexState|=Fw,this.stream._duplexState&Lw||CX(this.afterUpdateNextTick))}},DX=class{constructor(t,{highWaterMark:n=16384,map:r=null,mapReadable:a,byteLength:i,byteLengthReadable:s}={}){this.stream=t,this.queue=new P9e,this.highWaterMark=n===0?1:n,this.buffered=0,this.readAhead=n>0,this.error=null,this.pipeline=null,this.byteLength=s||i||H9e,this.map=a||r,this.pipeTo=null,this.afterRead=ZWt.bind(this),this.afterUpdateNextTick=QWt.bind(this)}get ended(){return(this.stream._duplexState&zu)!==0}pipe(t,n){if(this.pipeTo!==null)throw new Error("Can only pipe to one destination");if(typeof n!="function"&&(n=null),this.stream._duplexState|=VX,this.pipeTo=t,this.pipeline=new BX(this.stream,t,n),n&&this.stream.on("error",A9e),uO(t))t._writableState.pipeline=this.pipeline,n&&t.on("error",A9e),t.on("finish",this.pipeline.finished.bind(this.pipeline));else{let r=this.pipeline.done.bind(this.pipeline,t),a=this.pipeline.done.bind(this.pipeline,t,null);t.on("error",r),t.on("close",a),t.on("finish",this.pipeline.finished.bind(this.pipeline))}t.on("drain",YWt.bind(this)),this.stream.emit("piping",t),t.emit("pipe",this.stream)}push(t){let n=this.stream;return t===null?(this.highWaterMark=0,n._duplexState=(n._duplexState|vv)&SWt,!1):this.map!==null&&(t=this.map(t),t===null)?(n._duplexState&=E9e,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(t),this.queue.push(t),n._duplexState=(n._duplexState|gm)&E9e,this.buffered<this.highWaterMark)}shift(){let t=this.queue.shift();return this.buffered-=this.byteLength(t),this.buffered===0&&(this.stream._duplexState&=wWt),t}unshift(t){let n=[this.map!==null?this.map(t):t];for(;this.buffered>0;)n.push(this.shift());for(let r=0;r<n.length-1;r++){let a=n[r];this.buffered+=this.byteLength(a),this.queue.push(a)}this.push(n[n.length-1])}read(){let t=this.stream;if((t._duplexState&k9e)===gm){let n=this.shift();return this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=T9e),t._duplexState&NX&&t.emit("data",n),n}return this.readAhead===!1&&(t._duplexState|=bv,this.updateNextTick()),null}drain(){let t=this.stream;for(;(t._duplexState&k9e)===gm&&t._duplexState&C9e;){let n=this.shift();this.pipeTo!==null&&this.pipeTo.write(n)===!1&&(t._duplexState&=T9e),t._duplexState&NX&&t.emit("data",n)}}update(){let t=this.stream;t._duplexState|=Bw;do{for(this.drain();this.buffered<this.highWaterMark&&(t._duplexState&UWt)===bv;)t._duplexState|=mWt,t._read(this.afterRead),this.drain();(t._duplexState&DWt)===yWt&&(t._duplexState|=$X,t.emit("readable")),t._duplexState&gWt||this.updateNonPrimary()}while(this.continueUpdate()===!0);t._duplexState&=xWt}updateNonPrimary(){let t=this.stream;if((t._duplexState&MWt)===vv&&(t._duplexState=(t._duplexState|zu)&IWt,t.emit("end"),(t._duplexState&L9e)===JX&&(t._duplexState|=yv),this.pipeTo!==null&&this.pipeTo.end()),(t._duplexState&tf)===yv){t._duplexState&YU||(t._duplexState|=oO,t._destroy($9e.bind(this)));return}(t._duplexState&V9e)===ef&&(t._duplexState=(t._duplexState|oO)&R9e,t._open(z9e.bind(this)))}continueUpdate(){return this.stream._duplexState&mm?(this.stream._duplexState&=N9e,!0):!1}updateCallback(){(this.stream._duplexState&FWt)===Vw?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&LWt||(this.stream._duplexState|=mm,this.stream._duplexState&Bw||CX(this.afterUpdateNextTick))}updateNextTick(){this.stream._duplexState&mm||(this.stream._duplexState|=mm,this.stream._duplexState&Bw||CX(this.afterUpdateNextTick))}},UX=class{constructor(t){this.data=null,this.afterTransform=n7t.bind(t),this.afterFinal=null}},BX=class{constructor(t,n,r){this.from=t,this.to=n,this.afterPipe=r,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(t,n){if(n&&(this.error=n),t===this.to&&(this.to=null,this.from!==null)){(!(this.from._duplexState&zu)||!this.pipeToFinished)&&this.from.destroy(this.error||new Error("Writable stream closed prematurely"));return}if(t===this.from&&(this.from=null,this.to!==null)){t._duplexState&zu||this.to.destroy(this.error||new Error("Readable stream closed before ending"));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function YWt(){this.stream._duplexState|=VX,this.updateCallback()}function KWt(e){let t=this.stream;e&&t.destroy(e),t._duplexState&tf||(t._duplexState|=ym,t.emit("finish")),(t._duplexState&L9e)===JX&&(t._duplexState|=yv),t._duplexState&=kWt,t._duplexState&Lw?this.updateNextTick():this.update()}function $9e(e){let t=this.stream;!e&&this.error!==HU&&(e=this.error),e&&t.emit("error",e),t._duplexState|=sO,t.emit("close");let n=t._readableState,r=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),r!==null){for(;r.drains!==null&&r.drains.length>0;)r.drains.shift().resolve(!1);r.pipeline!==null&&r.pipeline.done(t,e)}}function XWt(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=TWt,this.drains!==null&&t7t(this.drains),(t._duplexState&$Wt)===hO&&(t._duplexState&=OWt,(t._duplexState&MX)===MX&&t.emit("drain")),this.updateCallback()}function ZWt(e){e&&this.stream.destroy(e),this.stream._duplexState&=vWt,this.readAhead===!1&&!(this.stream._duplexState&fO)&&(this.stream._duplexState&=M9e),this.updateCallback()}function QWt(){this.stream._duplexState&Bw||(this.stream._duplexState&=N9e,this.update())}function e7t(){this.stream._duplexState&Lw||(this.stream._duplexState&=U9e,this.update())}function t7t(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function z9e(e){let t=this.stream;e&&t.destroy(e),t._duplexState&yv||(t._duplexState&NWt||(t._duplexState|=Vw),t._duplexState&VWt||(t._duplexState|=pO),t.emit("open")),t._duplexState&=F9e,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function n7t(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function r7t(e){this._readableState!==null&&(e==="data"&&(this._duplexState|=NX|zX,this._readableState.updateNextTick()),e==="readable"&&(this._duplexState|=qX,this._readableState.updateNextTick())),this._writableState!==null&&e==="drain"&&(this._duplexState|=MX,this._writableState.updateNextTick())}var cO=class extends fWt{constructor(t){super(),this._duplexState=0,this._readableState=null,this._writableState=null,t&&(t.open&&(this._open=t.open),t.destroy&&(this._destroy=t.destroy),t.predestroy&&(this._predestroy=t.predestroy),t.signal&&t.signal.addEventListener("abort",p7t.bind(this))),this.on("newListener",r7t)}_open(t){t(null)}_destroy(t){t(null)}_predestroy(){}get readable(){return this._readableState!==null?!0:void 0}get writable(){return this._writableState!==null?!0:void 0}get destroyed(){return(this._duplexState&sO)!==0}get destroying(){return(this._duplexState&tf)!==0}destroy(t){this._duplexState&tf||(t||(t=HU),this._duplexState=(this._duplexState|yv)&RWt,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=t),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=t),this._duplexState|=LX,this._predestroy(),this._duplexState&=hWt,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},zU=class e extends cO{constructor(t){super(t),this._duplexState|=ef|ym|bv,this._readableState=new DX(this,t),t&&(this._readableState.readAhead===!1&&(this._duplexState&=M9e),t.read&&(this._read=t.read),t.eagerOpen&&this._readableState.updateNextTick(),t.encoding&&this.setEncoding(t.encoding))}setEncoding(t){let n=new pWt(t),r=this._readableState.map||s7t;return this._readableState.map=a,this;function a(i){let s=n.push(i);return s===""&&(i.byteLength!==0||n.remaining>0)?null:r(s)}}_read(t){t(null)}pipe(t,n){return this._readableState.updateNextTick(),this._readableState.pipe(t,n),t}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(t){return this._readableState.updateNextTickIfOpen(),this._readableState.push(t)}unshift(t){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(t)}resume(){return this._duplexState|=zX,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?EWt:_Wt,this}static _fromAsyncIterator(t,n){let r,a=new e({...n,read(s){t.next().then(i).then(s.bind(null,null)).catch(s)},predestroy(){r=t.return()},destroy(s){if(!r)return s(null);r.then(s.bind(null,null)).catch(s)}});return a;function i(s){s.done?a.push(null):a.push(s.value)}}static from(t,n){if(u7t(t))return t;if(t[qU])return this._fromAsyncIterator(t[qU](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(a){this.push(r===t.length?null:t[r++]),a(null)}})}static isBackpressured(t){return(t._duplexState&BWt)!==0||t._readableState.buffered>=t._readableState.highWaterMark}static isPaused(t){return(t._duplexState&fO)===0}[qU](){let t=this,n=null,r=null,a=null;return this.on("error",l=>{n=l}),this.on("readable",i),this.on("close",s),{[qU](){return this},next(){return new Promise(function(l,u){r=l,a=u;let d=t.read();d!==null?o(d):t._duplexState&sO&&o(null)})},return(){return c(null)},throw(l){return c(l)}};function i(){r!==null&&o(t.read())}function s(){r!==null&&o(null)}function o(l){a!==null&&(n?a(n):l===null&&!(t._duplexState&zu)?a(HU):r({value:l,done:l===null}),a=r=null)}function c(l){return t.destroy(l),new Promise((u,d)=>{if(t._duplexState&sO)return u({value:void 0,done:!0});t.once("close",function(){l?d(l):u({value:void 0,done:!0})})})}}},GU=class extends cO{constructor(t){super(t),this._duplexState|=ef|zu,this._writableState=new $U(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final),t.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=jU}uncork(){this._duplexState&=B9e,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}static isBackpressured(t){return(t._duplexState&HWt)!==0}static drained(t){if(t.destroyed)return Promise.resolve(!1);let n=t._writableState,a=(h7t(t)?Math.min(1,n.queue.length):n.queue.length)+(t._duplexState&GX?1:0);return a===0?Promise.resolve(!0):(n.drains===null&&(n.drains=[]),new Promise(i=>{n.drains.push({writes:a,resolve:i})}))}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},lO=class extends zU{constructor(t){super(t),this._duplexState=ef|this._duplexState&bv,this._writableState=new $U(this,t),t&&(t.writev&&(this._writev=t.writev),t.write&&(this._write=t.write),t.final&&(this._final=t.final))}cork(){this._duplexState|=jU}uncork(){this._duplexState&=B9e,this._writableState.updateNextTick()}_writev(t,n){n(null)}_write(t,n){this._writableState.autoBatch(t,n)}_final(t){t(null)}write(t){return this._writableState.updateNextTick(),this._writableState.push(t)}end(t){return this._writableState.updateNextTick(),this._writableState.end(t),this}},JU=class extends lO{constructor(t){super(t),this._transformState=new UX(this),t&&(t.transform&&(this._transform=t.transform),t.flush&&(this._flush=t.flush))}_write(t,n){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=t:this._transform(t,this._transformState.afterTransform)}_read(t){if(this._transformState.data!==null){let n=this._transformState.data;this._transformState.data=null,t(null),this._transform(n,this._transformState.afterTransform)}else t(null)}destroy(t){super.destroy(t),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(t,n){n(null,t)}_flush(t){t(null)}_final(t){this._transformState.afterFinal=t,this._flush(i7t.bind(this))}},FX=class extends JU{};function i7t(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function a7t(...e){return new Promise((t,n)=>G9e(...e,r=>{if(r)return n(r);t()}))}function G9e(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]=="function"?n.pop():null;if(n.length<2)throw new Error("Pipeline requires at least 2 streams");let a=n[0],i=null,s=null;for(let l=1;l<n.length;l++)i=n[l],uO(a)?a.pipe(i,c):(o(a,!0,l>1,c),a.pipe(i)),a=i;if(r){let l=!1,u=uO(i)||!!(i._writableState&&i._writableState.autoDestroy);i.on("error",d=>{s===null&&(s=d)}),i.on("finish",()=>{l=!0,u||r(s)}),u&&i.on("close",()=>r(s||(l?null:RX)))}return i;function o(l,u,d,f){l.on("error",f),l.on("close",p);function p(){if(u&&l._readableState&&!l._readableState.ended||d&&l._writableState&&!l._writableState.ended)return f(RX)}}function c(l){if(!(!l||s)){s=l;for(let u of n)u.destroy(l)}}}function s7t(e){return e}function J9e(e){return!!e._readableState||!!e._writableState}function uO(e){return typeof e._duplexState=="number"&&J9e(e)}function o7t(e){return!!e._readableState&&e._readableState.ended}function c7t(e){return!!e._writableState&&e._writableState.ended}function l7t(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===HU?null:n}function u7t(e){return uO(e)&&e.readable}function d7t(e){return(e._duplexState&ef)!==ef||(e._duplexState&YU)!==0}function f7t(e){return typeof e=="object"&&e!==null&&typeof e.byteLength=="number"}function H9e(e){return f7t(e)?e.byteLength:1024}function A9e(){}function p7t(){this.destroy(new Error("Stream aborted."))}function h7t(e){return e._writev!==GU.prototype._writev&&e._writev!==lO.prototype._writev}W9e.exports={pipeline:G9e,pipelinePromise:a7t,isStream:J9e,isStreamx:uO,isEnded:o7t,isFinished:c7t,isDisturbed:d7t,getStreamError:l7t,Stream:cO,Writable:GU,Readable:zU,Duplex:lO,Transform:JU,PassThrough:FX}});var YX=_($w=>{var Pn=Uw(),m7t="0000000000000000000",g7t="7777777777777777777",KU=48,j9e=Pn.from([117,115,116,97,114,0]),y7t=Pn.from([KU,KU]),v7t=Pn.from([117,115,116,97,114,32]),b7t=Pn.from([32,0]),S7t=4095,mO=257,jX=263;$w.decodeLongPath=function(t,n){return qw(t,0,t.length,n)};$w.encodePax=function(t){let n="";t.name&&(n+=WX(" path="+t.name+`
251
251
  `)),t.linkname&&(n+=WX(" linkpath="+t.linkname+`
252
252
  `));let r=t.pax;if(r)for(let a in r)n+=WX(" "+a+"="+r[a]+`
253
- `);return Pn.from(n)};$w.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(Pn.toString(t.subarray(0,r)),10);if(!a)return n;let i=Pn.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};$w.encode=function(t){let n=Pn.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Pn.byteLength(r)!==r.length)return null;for(;Pn.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return Pn.byteLength(r)>100||Pn.byteLength(a)>155||t.linkname&&Pn.byteLength(t.linkname)>100?null:(Pn.write(n,r),Pn.write(n,bm(t.mode&S7t,6),100),Pn.write(n,bm(t.uid,6),108),Pn.write(n,bm(t.gid,6),116),k7t(t.size,n,124),Pn.write(n,bm(t.mtime.getTime()/1e3|0,11),136),n[156]=KU+E7t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(j9e,n,mO),Pn.copy(y7t,n,jX),t.uname&&Pn.write(n,t.uname,265),t.gname&&Pn.write(n,t.gname,297),Pn.write(n,bm(t.devmajor||0,6),329),Pn.write(n,bm(t.devminor||0,6),337),a&&Pn.write(n,a,345),Pn.write(n,bm(K9e(n),6),148),n)};$w.decode=function(t,n,r){let a=t[156]===0?0:t[156]-KU,i=qw(t,0,100,n),s=vm(t,100,8),o=vm(t,108,8),c=vm(t,116,8),l=vm(t,124,12),u=vm(t,136,12),d=x7t(a),f=t[157]===0?null:qw(t,157,100,n),p=qw(t,265,32),m=qw(t,297,32),y=vm(t,329,8),b=vm(t,337,8),v=K9e(t);if(v===8*32)return null;if(v!==vm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(_7t(t))t[345]&&(i=qw(t,345,155,n)+"/"+i);else if(!w7t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:p,gname:m,devmajor:y,devminor:b,pax:null}};function _7t(e){return Pn.equals(j9e,e.subarray(mO,mO+6))}function w7t(e){return Pn.equals(v7t,e.subarray(mO,mO+6))&&Pn.equals(b7t,e.subarray(jX,jX+2))}function I7t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function x7t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function E7t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function Y9e(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function K9e(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function bm(e,t){return e=e.toString(8),e.length>t?g7t.slice(0,t)+" ":m7t.slice(0,t-e.length)+e+" "}function T7t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function k7t(e,t,n){e.toString(8).length>11?T7t(e,t,n):Pn.write(t,bm(e,11),n)}function O7t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function vm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return O7t(e);{for(;t<e.length&&e[t]===32;)t++;let r=I7t(Y9e(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(Pn.toString(e.subarray(t,r)),8)}}function qw(e,t,n,r){return Pn.toString(e.subarray(t,Y9e(e,0,t,t+n)),r)}function WX(e){let t=Pn.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var tKe=_((bkn,eKe)=>{var{Writable:A7t,Readable:P7t,getStreamError:X9e}=HX(),R7t=PX(),Z9e=Uw(),zw=YX(),C7t=Z9e.alloc(0),XX=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new R7t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return C7t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return Z9e.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},ZX=class extends P7t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(X9e(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=Q9e(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},QX=class extends A7t{constructor(t){super(t),t||(t={}),this._buffer=new XX,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=KX,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=zw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=zw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=zw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=zw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?zw.decodePax(t):Object.assign({},this._paxGlobal,zw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=Q9e(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new ZX(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=KX,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(X9e(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let p=i;i=null,p(f)}function c(f,p){if(t)return p(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=p,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,p,m){i=m,p.on("error",KX),n?(n({value:p,done:!1}),n=r=null):a=p}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((p,m)=>{if(s.destroyed)return p({value:void 0,done:!0});s.once("close",function(){f?m(f):p({value:void 0,done:!0})})})}}};eKe.exports=function(t){return new QX(t)};function KX(){}function Q9e(e){return e&=511,e&&512-e}});var rKe=_((Skn,eZ)=>{var nKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{eZ.exports=require("fs").constants||nKe}catch{eZ.exports=nKe}});var cKe=_((_kn,oKe)=>{var{Readable:N7t,Writable:M7t,getStreamError:iKe}=HX(),wv=Uw(),Gw=rKe(),XU=YX(),D7t=493,U7t=420,aKe=wv.alloc(1024),nZ=class extends M7t{constructor(t,n,r){super({mapWritable:F7t,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?wv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?wv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),sKe(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return iKe(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},rZ=class extends N7t{constructor(t){super(t),this._drain=tZ,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=tZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=B7t(t.mode)),t.mode||(t.mode=t.type==="directory"?D7t:U7t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=wv.from(n));let a=new nZ(this,t,r);return wv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(aKe),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=XU.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=XU.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(XU.encode(r)),this.push(n),sKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(XU.encode(r))}_doDrain(){let t=this._drain;this._drain=tZ,t()}_predestroy(){let t=iKe(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};oKe.exports=function(t){return new rZ(t)};function B7t(e){switch(e&Gw.S_IFMT){case Gw.S_IFBLK:return"block-device";case Gw.S_IFCHR:return"character-device";case Gw.S_IFDIR:return"directory";case Gw.S_IFIFO:return"fifo";case Gw.S_IFLNK:return"symlink"}return"file"}function tZ(){}function sKe(e,t){t&=511,t&&e.push(aKe.subarray(0,512-t))}function F7t(e){return wv.isBuffer(e)?e:wv.from(e)}});var aZ=_(iZ=>{iZ.extract=tKe();iZ.pack=cKe()});var OKe={};Ju(OKe,{EVOLVE_IMAGE_VERSION:()=>ZU,MODAL_MAX_LIFETIME_MS:()=>dZ,MODAL_MAX_LIST_SANDBOXES:()=>uZ,MODAL_STDIN_CHUNK_BYTES:()=>gO,ModalBootCommandError:()=>vKe,ModalCommands:()=>EKe,ModalFiles:()=>TKe,ModalIdleTimeoutError:()=>sZ,ModalNetworkPolicyError:()=>lZ,ModalProvider:()=>hZ,ModalResourcesError:()=>cZ,ModalSandboxLifetimeError:()=>mKe,ModalVolumeError:()=>QU,_testBuildSandboxInfo:()=>e5t,_testCollectSandboxes:()=>t5t,_testDynamicNetworkPolicyParams:()=>K7t,_testImageMap:()=>j7t,_testMapBootCommand:()=>i5t,_testMapIdleTimeout:()=>r5t,_testMapNetworkPolicy:()=>Y7t,_testMapResources:()=>Z7t,_testMapVolumeMounts:()=>a5t,_testRequiresDynamicNetwork:()=>X7t,_testResolveImageRegistry:()=>Q7t,_testValidateTimeout:()=>n5t,_testWrapCommand:()=>W7t,createModalProvider:()=>tB});async function*L7t(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function gKe(e){if(e>dZ)throw new mKe(e)}function yKe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new sZ(e,"it must be a positive number of milliseconds");if(e>dZ)throw new sZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function bKe(e){if(e===void 0)return{};if(e.length===0)throw new vKe(`an empty argv is Modal's own "no args" wire shape and would boot the image's ENTRYPOINT/CMD \u2014 omit bootCommand to boot the image's command`);return{command:[...e]}}function SKe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new QU("invalid-mount-path",n,r.name,`Modal Volume mount path ${JSON.stringify(n)} is invalid: it must be an absolute in-box path other than "/"`);let a=r.name?.trim()??"";if(a.length===0)throw new QU("invalid-name",n,r.name??"",`Modal Volume mounted at ${n} has a blank name`);t.push({mountPath:n,name:a,readOnly:r.readOnly===!0,createIfMissing:r.createIfMissing===!0})}return t}function oZ(e,t,n,r){let a="";r&&Object.keys(r).length>0&&(a=Object.entries(r).filter(([,o])=>o!=null).map(([o,c])=>`export ${o}='${String(c).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let i=n?`cd '${n.replace(/'/g,"'\\''")}' && ${a}${e}`:`${a}${e}`;if(t==="root")return["bash","-c",i];let s=Buffer.from(i).toString("base64");return["su",t,"-c",`echo ${s} | base64 -d | bash`]}function _Ke(e){if(e?.disk!==void 0)throw new cZ(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new cZ("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??V7t,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):q7t,...t!==void 0?{gpu:t}:{}}}function wKe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function $7t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!wKe(e)}function z7t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function G7t(e){return/^[^:]+:\d+$/.test(e)}function fZ(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(wKe(a))n.push(a.includes("/")?a:`${a}/32`);else{if($7t(a))throw new lZ("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(z7t(a))n.push(a.includes("/")?a:`${a}/128`);else{if(G7t(a))throw new lZ("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function eB(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=fZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:H7t(t.outboundDomainAllowlist??[])}}function H7t(e){return e.length>0?e:[J7t]}function IKe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function xKe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function pZ(e,t,n){let{[pKe]:r,[hKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}async function kKe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=uZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${uZ} sandboxes`};let a=await r.getTags();n.push(pZ(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function tB(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new hZ({...e,tokenId:t,tokenSecret:n})}var dKe,ZU,fKe,dZ,gO,lKe,pKe,hKe,mKe,sZ,vKe,QU,cZ,V7t,q7t,lZ,J7t,uZ,EKe,TKe,uKe,hZ,W7t,j7t,Y7t,K7t,X7t,Z7t,Q7t,e5t,t5t,n5t,r5t,i5t,a5t,nB=Q(()=>{"use strict";d9e();dKe=Ve(aZ(),1),ZU="c-fae503a880ec",fKe={[`evolve-all-${ZU}`]:`evolvingmachines/evolve-all:${ZU}`,"evolve-all":"evolvingmachines/evolve-all"},dZ=1440*60*1e3,gO=8*1024*1024;lKe="user",pKe="evolve.image",hKe="evolve.startedAt",mKe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};sZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};vKe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};QU=class extends Error{reason;mountPath;volumeName;constructor(e,t,n,r,a){super(r,a===void 0?void 0:{cause:a}),this.name="ModalVolumeError",this.reason=e,this.mountPath=t,this.volumeName=n}};cZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},V7t=4,q7t=4096;lZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};J7t="sealed.invalid";uZ=1e4,EKe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=oZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=oZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),a="",i="",s=this.accumulateStreams(r,t?.onStdout?o=>{t.onStdout(o)}:void 0,t?.onStderr?o=>{t.onStderr(o)}:void 0).then(({stdout:o,stderr:c})=>{a=o,i=c}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await s,{exitCode:await r.wait(),stdout:a,stderr:i}),kill:async()=>!1}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
253
+ `);return Pn.from(n)};$w.decodePax=function(t){let n={};for(;t.length;){let r=0;for(;r<t.length&&t[r]!==32;)r++;let a=parseInt(Pn.toString(t.subarray(0,r)),10);if(!a)return n;let i=Pn.toString(t.subarray(r+1,a-1)),s=i.indexOf("=");if(s===-1)return n;n[i.slice(0,s)]=i.slice(s+1),t=t.subarray(a)}return n};$w.encode=function(t){let n=Pn.alloc(512),r=t.name,a="";if(t.typeflag===5&&r[r.length-1]!=="/"&&(r+="/"),Pn.byteLength(r)!==r.length)return null;for(;Pn.byteLength(r)>100;){let i=r.indexOf("/");if(i===-1)return null;a+=a?"/"+r.slice(0,i):r.slice(0,i),r=r.slice(i+1)}return Pn.byteLength(r)>100||Pn.byteLength(a)>155||t.linkname&&Pn.byteLength(t.linkname)>100?null:(Pn.write(n,r),Pn.write(n,bm(t.mode&S7t,6),100),Pn.write(n,bm(t.uid,6),108),Pn.write(n,bm(t.gid,6),116),k7t(t.size,n,124),Pn.write(n,bm(t.mtime.getTime()/1e3|0,11),136),n[156]=KU+E7t(t.type),t.linkname&&Pn.write(n,t.linkname,157),Pn.copy(j9e,n,mO),Pn.copy(y7t,n,jX),t.uname&&Pn.write(n,t.uname,265),t.gname&&Pn.write(n,t.gname,297),Pn.write(n,bm(t.devmajor||0,6),329),Pn.write(n,bm(t.devminor||0,6),337),a&&Pn.write(n,a,345),Pn.write(n,bm(K9e(n),6),148),n)};$w.decode=function(t,n,r){let a=t[156]===0?0:t[156]-KU,i=qw(t,0,100,n),s=vm(t,100,8),o=vm(t,108,8),c=vm(t,116,8),l=vm(t,124,12),u=vm(t,136,12),d=x7t(a),f=t[157]===0?null:qw(t,157,100,n),p=qw(t,265,32),m=qw(t,297,32),y=vm(t,329,8),b=vm(t,337,8),v=K9e(t);if(v===8*32)return null;if(v!==vm(t,148,8))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(_7t(t))t[345]&&(i=qw(t,345,155,n)+"/"+i);else if(!w7t(t)){if(!r)throw new Error("Invalid tar header: unknown format.")}return a===0&&i&&i[i.length-1]==="/"&&(a=5),{name:i,mode:s,uid:o,gid:c,size:l,mtime:new Date(1e3*u),type:d,linkname:f,uname:p,gname:m,devmajor:y,devminor:b,pax:null}};function _7t(e){return Pn.equals(j9e,e.subarray(mO,mO+6))}function w7t(e){return Pn.equals(v7t,e.subarray(mO,mO+6))&&Pn.equals(b7t,e.subarray(jX,jX+2))}function I7t(e,t,n){return typeof e!="number"?n:(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0)}function x7t(e){switch(e){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function E7t(e){switch(e){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function Y9e(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function K9e(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function bm(e,t){return e=e.toString(8),e.length>t?g7t.slice(0,t)+" ":m7t.slice(0,t-e.length)+e+" "}function T7t(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function k7t(e,t,n){e.toString(8).length>11?T7t(e,t,n):Pn.write(t,bm(e,11),n)}function O7t(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let s=e[r];t?n.push(s):n.push(255-s)}let a=0,i=n.length;for(r=0;r<i;r++)a+=n[r]*Math.pow(256,r);return t?a:-1*a}function vm(e,t,n){if(e=e.subarray(t,t+n),t=0,e[t]&128)return O7t(e);{for(;t<e.length&&e[t]===32;)t++;let r=I7t(Y9e(e,32,t,e.length),e.length,e.length);for(;t<r&&e[t]===0;)t++;return r===t?0:parseInt(Pn.toString(e.subarray(t,r)),8)}}function qw(e,t,n,r){return Pn.toString(e.subarray(t,Y9e(e,0,t,t+n)),r)}function WX(e){let t=Pn.byteLength(e),n=Math.floor(Math.log(t)/Math.log(10))+1;return t+n>=Math.pow(10,n)&&n++,t+n+e}});var tKe=_((bkn,eKe)=>{var{Writable:A7t,Readable:P7t,getStreamError:X9e}=HX(),R7t=PX(),Z9e=Uw(),zw=YX(),C7t=Z9e.alloc(0),XX=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new R7t,this._offset=0}push(t){this.buffered+=t.byteLength,this.queue.push(t)}shiftFirst(t){return this._buffered===0?null:this._next(t)}shift(t){if(t>this.buffered)return null;if(t===0)return C7t;let n=this._next(t);if(t===n.byteLength)return n;let r=[n];for(;(t-=n.byteLength)>0;)n=this._next(t),r.push(n);return Z9e.concat(r)}_next(t){let n=this.queue.peek(),r=n.byteLength-this._offset;if(t>=r){let a=this._offset?n.subarray(this._offset,n.byteLength):n;return this.queue.shift(),this._offset=0,this.buffered-=r,this.shifted+=r,a}return this.buffered-=t,this.shifted+=t,n.subarray(this._offset,this._offset+=t)}},ZX=class extends P7t{constructor(t,n,r){super(),this.header=n,this.offset=r,this._parent=t}_read(t){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),t(null)}_predestroy(){this._parent.destroy(X9e(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=Q9e(this.header.size),this._parent._update())}_destroy(t){this._detach(),t(null)}},QX=class extends A7t{constructor(t){super(t),t||(t={}),this._buffer=new XX,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=KX,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=t.filenameEncoding||"utf-8",this._allowUnknownFormat=!!t.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(t){if(this._locked=!1,t){this.destroy(t),this._continueWrite(t);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=zw.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(t){return this._continueWrite(t),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory"?(this.emit("entry",this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&(this._header.name=this._gnuLongPath,this._gnuLongPath=null),this._gnuLongLinkPath&&(this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null),this._pax&&(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,this._pax=null)}_decodeLongHeader(t){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=zw.decodeLongPath(t,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=zw.decodeLongPath(t,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=zw.decodePax(t);break;case"pax-header":this._pax=this._paxGlobal===null?zw.decodePax(t):Object.assign({},this._paxGlobal,zw.decodePax(t));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=Q9e(this._header.size);let t=this._buffer.shift(this._header.size);try{this._decodeLongHeader(t)}catch(n){return this._continueWrite(n),!1}return!0}_consumeStream(){let t=this._buffer.shiftFirst(this._missing);if(t===null)return!1;this._missing-=t.byteLength;let n=this._stream.push(t);return this._missing===0?(this._stream.push(null),n&&this._stream._detach(),n&&this._locked===!1):n}_createStream(){return new ZX(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let t=this._buffer.shiftFirst(this._missing);t!==null&&(this._missing-=t.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(t){let n=this._callback;this._callback=KX,n(t)}_write(t,n){this._callback=n,this._buffer.push(t),this._update()}_final(t){this._finished=this._missing===0&&this._buffer.buffered===0,t(this._finished?null:new Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(t){this._stream&&this._stream.destroy(X9e(this)),t(null)}[Symbol.asyncIterator](){let t=null,n=null,r=null,a=null,i=null,s=this;return this.on("entry",l),this.on("error",f=>{t=f}),this.on("close",u),{[Symbol.asyncIterator](){return this},next(){return new Promise(c)},return(){return d(null)},throw(f){return d(f)}};function o(f){if(!i)return;let p=i;i=null,p(f)}function c(f,p){if(t)return p(t);if(a){f({value:a,done:!1}),a=null;return}n=f,r=p,o(null),s._finished&&n&&(n({value:void 0,done:!0}),n=r=null)}function l(f,p,m){i=m,p.on("error",KX),n?(n({value:p,done:!1}),n=r=null):a=p}function u(){o(t),n&&(t?r(t):n({value:void 0,done:!0}),n=r=null)}function d(f){return s.destroy(f),o(f),new Promise((p,m)=>{if(s.destroyed)return p({value:void 0,done:!0});s.once("close",function(){f?m(f):p({value:void 0,done:!0})})})}}};eKe.exports=function(t){return new QX(t)};function KX(){}function Q9e(e){return e&=511,e&&512-e}});var rKe=_((Skn,eZ)=>{var nKe={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{eZ.exports=require("fs").constants||nKe}catch{eZ.exports=nKe}});var cKe=_((_kn,oKe)=>{var{Readable:N7t,Writable:M7t,getStreamError:iKe}=HX(),wv=Uw(),Gw=rKe(),XU=YX(),D7t=493,U7t=420,aKe=wv.alloc(1024),nZ=class extends M7t{constructor(t,n,r){super({mapWritable:F7t,eagerOpen:!0}),this.written=0,this.header=n,this._callback=r,this._linkname=null,this._isLinkname=n.type==="symlink"&&!n.linkname,this._isVoid=n.type!=="file"&&n.type!=="contiguous-file",this._finished=!1,this._pack=t,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(t){this._openCallback=t,this._pack._stream===this&&this._continueOpen()}_continuePack(t){if(this._callback===null)return;let n=this._callback;this._callback=null,n(t)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let t=this._openCallback;if(this._openCallback=null,t!==null){if(this._pack.destroying)return t(new Error("pack stream destroyed"));if(this._pack._finalized)return t(new Error("pack stream is already finalized"));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),t(null)}}_write(t,n){if(this._isLinkname)return this._linkname=this._linkname?wv.concat([this._linkname,t]):t,n(null);if(this._isVoid)return t.byteLength>0?n(new Error("No body allowed for this entry")):n();if(this.written+=t.byteLength,this._pack.push(t))return n();this._pack._drain=n}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?wv.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header)),sKe(this._pack,this.header.size),this._pack._done(this))}_final(t){if(this.written!==this.header.size)return t(new Error("Size mismatch"));this._finish(),t(null)}_getError(){return iKe(this)||new Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(t){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),t()}},rZ=class extends N7t{constructor(t){super(t),this._drain=tZ,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(t,n,r){if(this._finalized||this.destroying)throw new Error("already finalized or destroyed");typeof n=="function"&&(r=n,n=null),r||(r=tZ),(!t.size||t.type==="symlink")&&(t.size=0),t.type||(t.type=B7t(t.mode)),t.mode||(t.mode=t.type==="directory"?D7t:U7t),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof n=="string"&&(n=wv.from(n));let a=new nZ(this,t,r);return wv.isBuffer(n)?(t.size=n.byteLength,a.write(n),a.end(),a):(a._isVoid,a)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(aKe),this.push(null))}_done(t){t===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(t){if(!t.pax){let n=XU.encode(t);if(n){this.push(n);return}}this._encodePax(t)}_encodePax(t){let n=XU.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:"PaxHeader",mode:t.mode,uid:t.uid,gid:t.gid,size:n.byteLength,mtime:t.mtime,type:"pax-header",linkname:t.linkname&&"PaxHeader",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(XU.encode(r)),this.push(n),sKe(this,n.byteLength),r.size=t.size,r.type=t.type,this.push(XU.encode(r))}_doDrain(){let t=this._drain;this._drain=tZ,t()}_predestroy(){let t=iKe(this);for(this._stream&&this._stream.destroy(t);this._pending.length;){let n=this._pending.shift();n.destroy(t),n._continueOpen()}this._doDrain()}_read(t){this._doDrain(),t()}};oKe.exports=function(t){return new rZ(t)};function B7t(e){switch(e&Gw.S_IFMT){case Gw.S_IFBLK:return"block-device";case Gw.S_IFCHR:return"character-device";case Gw.S_IFDIR:return"directory";case Gw.S_IFIFO:return"fifo";case Gw.S_IFLNK:return"symlink"}return"file"}function tZ(){}function sKe(e,t){t&=511,t&&e.push(aKe.subarray(0,512-t))}function F7t(e){return wv.isBuffer(e)?e:wv.from(e)}});var aZ=_(iZ=>{iZ.extract=tKe();iZ.pack=cKe()});var OKe={};Ju(OKe,{EVOLVE_IMAGE_VERSION:()=>ZU,MODAL_MAX_LIFETIME_MS:()=>dZ,MODAL_MAX_LIST_SANDBOXES:()=>uZ,MODAL_STDIN_CHUNK_BYTES:()=>gO,ModalBootCommandError:()=>vKe,ModalCommands:()=>EKe,ModalFiles:()=>TKe,ModalIdleTimeoutError:()=>sZ,ModalNetworkPolicyError:()=>lZ,ModalProvider:()=>hZ,ModalResourcesError:()=>cZ,ModalSandboxLifetimeError:()=>mKe,ModalVolumeError:()=>QU,_testBuildSandboxInfo:()=>e5t,_testCollectSandboxes:()=>t5t,_testDynamicNetworkPolicyParams:()=>K7t,_testImageMap:()=>j7t,_testMapBootCommand:()=>i5t,_testMapIdleTimeout:()=>r5t,_testMapNetworkPolicy:()=>Y7t,_testMapResources:()=>Z7t,_testMapVolumeMounts:()=>a5t,_testRequiresDynamicNetwork:()=>X7t,_testResolveImageRegistry:()=>Q7t,_testValidateTimeout:()=>n5t,_testWrapCommand:()=>W7t,createModalProvider:()=>tB});async function*L7t(e){let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;r&&(yield r)}}finally{t.releaseLock()}}function gKe(e){if(e>dZ)throw new mKe(e)}function yKe(e){if(e===void 0)return{};if(!Number.isFinite(e)||e<=0)throw new sZ(e,"it must be a positive number of milliseconds");if(e>dZ)throw new sZ(e,"it exceeds Modal's 24h lifetime cap, so the sandbox would always die of the lifetime first");return{idleTimeoutMs:e}}function bKe(e){if(e===void 0)return{};if(e.length===0)throw new vKe(`an empty argv is Modal's own "no args" wire shape and would boot the image's ENTRYPOINT/CMD \u2014 omit bootCommand to boot the image's command`);return{command:[...e]}}function SKe(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e)){if(!n.startsWith("/")||n==="/")throw new QU("invalid-mount-path",n,r.name,`Modal Volume mount path ${JSON.stringify(n)} is invalid: it must be an absolute in-box path other than "/"`);let a=r.name?.trim()??"";if(a.length===0)throw new QU("invalid-name",n,r.name??"",`Modal Volume mounted at ${n} has a blank name`);t.push({mountPath:n,name:a,readOnly:r.readOnly===!0,createIfMissing:r.createIfMissing===!0})}return t}function oZ(e,t,n,r){let a="";r&&Object.keys(r).length>0&&(a=Object.entries(r).filter(([,o])=>o!=null).map(([o,c])=>`export ${o}='${String(c).replace(/'/g,"'\\''")}'`).join("; ")+"; ");let i=n?`cd '${n.replace(/'/g,"'\\''")}' && ${a}${e}`:`${a}${e}`;if(t==="root")return["bash","-c",i];let s=Buffer.from(i).toString("base64");return["su",t,"-c",`echo ${s} | base64 -d | bash`]}function _Ke(e){if(e?.disk!==void 0)throw new cZ(`Modal's JS SDK has no create-time disk-size parameter, so a ${e.disk} GiB disk request cannot be enforced. Drop \`resources.disk\` (containers get Modal's default disk quota) or run on a provider that sizes disk.`);if((e?.gpu===void 0||e.gpu<=0)&&e?.gpuTypes?.length)throw new cZ("resources.gpuTypes was set without a positive resources.gpu count \u2014 declare how many GPUs to reserve, or drop gpuTypes.");let t=e?.gpu!==void 0&&e.gpu>0?`${e.gpuTypes?.length?e.gpuTypes[0]:"any"}:${e.gpu}`:void 0;return{cpu:e?.cpu??V7t,memoryMiB:e?.memory!==void 0?Math.ceil(e.memory*1024):q7t,...t!==void 0?{gpu:t}:{}}}function wKe(e){let t=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,3}))?$/.exec(e);return!(!t||[t[1],t[2],t[3],t[4]].some(n=>Number(n)>255)||t[5]!==void 0&&Number(t[5])>32)}function $7t(e){return/^\d{1,3}(\.\d{1,3}){3}(\/\d+)?$/.test(e)&&!wKe(e)}function z7t(e){return e.startsWith("[")?!0:(e.match(/:/g)?.length??0)>=2}function G7t(e){return/^[^:]+:\d+$/.test(e)}function fZ(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{}}let t=e.allowedDestinations??[];if(t.length===0)return{blockNetwork:!0};let n=[],r=[];for(let a of t)if(wKe(a))n.push(a.includes("/")?a:`${a}/32`);else{if($7t(a))throw new lZ("invalid-ipv4",`"${a}" is not a valid IPv4 address or CIDR (octets must be 0-255, prefix 0-32). Fix the address or list a hostname instead.`,a);if(z7t(a))n.push(a.includes("/")?a:`${a}/128`);else{if(G7t(a))throw new lZ("port-unsupported",`Modal's network allowlist filters hosts and IPs only and cannot match a port; drop the ":<port>" from "${a}" and list just the host or IP.`,a);r.push(a)}}return{outboundCidrAllowlist:n,outboundDomainAllowlist:r}}function eB(e){if(!e||e.outbound==="open"){if(e?.allowedDestinations?.length)throw new Error("network.allowedDestinations is only valid when outbound is blocked");return{outboundCidrAllowlist:["0.0.0.0/0"],outboundDomainAllowlist:["*"]}}let t=fZ(e);return{outboundCidrAllowlist:t.outboundCidrAllowlist??[],outboundDomainAllowlist:H7t(t.outboundDomainAllowlist??[])}}function H7t(e){return e.length>0?e:[J7t]}function IKe(e,t){if(!t||t.length===0)return!1;let n=a=>a===void 0?"open|":`${a.outbound}|${[...new Set(a.allowedDestinations??[])].sort().join(",")}`,r=n(e);return t.some(a=>n(a)!==r)}function xKe(e){let t=e.split("/")[0];return/^\d{12}\.dkr\.ecr\.[a-z0-9-]+\.amazonaws\.com$/.test(t)?"aws-ecr":t==="gcr.io"||t.endsWith(".gcr.io")||t.endsWith("-docker.pkg.dev")?"gcp-artifact-registry":"registry"}function pZ(e,t,n){let{[pKe]:r,[hKe]:a,...i}=t;return{sandboxId:e,image:r??n??"",metadata:i,startedAt:a??""}}async function kKe(e,t){let n=[];try{for await(let r of e()){if(t!==void 0&&n.length>=t)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!0,error:`stopped at the requested limit of ${t} with more sandboxes available`};if(n.length>=uZ)return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list exceeded ${uZ} sandboxes`};let a=await r.getTags();n.push(pZ(r.sandboxId,a))}}catch(r){return{sandboxes:n,complete:!1,pagesFetched:n.length,stoppedAtLimit:!1,error:`sandbox list failed: ${r instanceof Error?r.message:String(r)}`}}return{sandboxes:n,complete:!0,pagesFetched:n.length,stoppedAtLimit:!1}}function tB(e={}){let t=e.tokenId??process.env.MODAL_TOKEN_ID,n=e.tokenSecret??process.env.MODAL_TOKEN_SECRET;if(!t||!n)throw new Error("Modal credentials required. Set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET environment variables, or pass tokenId/tokenSecret in config. Get your token at https://modal.com/settings/tokens");return new hZ({...e,tokenId:t,tokenSecret:n})}var dKe,ZU,fKe,dZ,gO,lKe,pKe,hKe,mKe,sZ,vKe,QU,cZ,V7t,q7t,lZ,J7t,uZ,EKe,TKe,uKe,hZ,W7t,j7t,Y7t,K7t,X7t,Z7t,Q7t,e5t,t5t,n5t,r5t,i5t,a5t,nB=Q(()=>{"use strict";d9e();dKe=Ve(aZ(),1),ZU="c-880c264ce574",fKe={[`evolve-all-${ZU}`]:`evolvingmachines/evolve-all:${ZU}`,"evolve-all":"evolvingmachines/evolve-all"},dZ=1440*60*1e3,gO=8*1024*1024;lKe="user",pKe="evolve.image",hKe="evolve.startedAt",mKe=class extends Error{requestedTimeoutMs;constructor(e){let t=(e/36e5).toFixed(1);super(`Modal sandboxes have a hard 24h lifetime cap; requested timeout was ${t}h. For sessions longer than 24h, persist progress with Evolve checkpoints and resume in a fresh sandbox instead of extending the timeout.`),this.name="ModalSandboxLifetimeError",this.requestedTimeoutMs=e}};sZ=class extends Error{requestedIdleTimeoutMs;constructor(e,t){super(`Modal idleTimeoutMs of ${e}ms is invalid: ${t}`),this.name="ModalIdleTimeoutError",this.requestedIdleTimeoutMs=e}};vKe=class extends Error{constructor(e){super(`Modal bootCommand is invalid: ${e}`),this.name="ModalBootCommandError"}};QU=class extends Error{reason;mountPath;volumeName;constructor(e,t,n,r,a){super(r,a===void 0?void 0:{cause:a}),this.name="ModalVolumeError",this.reason=e,this.mountPath=t,this.volumeName=n}};cZ=class extends Error{constructor(e){super(e),this.name="ModalResourcesError"}},V7t=4,q7t=4096;lZ=class extends Error{reason;destination;constructor(e,t,n){super(t),this.name="ModalNetworkPolicyError",this.reason=e,this.destination=n}};J7t="sealed.invalid";uZ=1e4,EKe=class{constructor(e,t){this.sandbox=e,this.user=t}async run(e,t){let n=oZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),{stdout:a,stderr:i}=await this.accumulateStreams(r,t?.onStdout,t?.onStderr);return{exitCode:await r.wait(),stdout:a,stderr:i}}async spawn(e,t){let n=oZ(e,this.user,t?.cwd,t?.envs),r=await this.sandbox.exec(n,{timeoutMs:t?.timeoutMs}),a="",i="",s=this.accumulateStreams(r,t?.onStdout?o=>{t.onStdout(o)}:void 0,t?.onStderr?o=>{t.onStderr(o)}:void 0).then(({stdout:o,stderr:c})=>{a=o,i=c}).catch(()=>{});return{processId:`modal-${Date.now()}-${Math.random().toString(36).slice(2)}`,wait:async()=>(await s,{exitCode:await r.wait(),stdout:a,stderr:i}),kill:async()=>!1}}async list(){let e=await this.sandbox.exec(["ps","-eo","pid,comm,args"],{timeoutMs:1e4});return await e.wait(),(await e.stdout.readText()).trim().split(`
254
254
  `).slice(1).map(t=>{let n=t.trim().split(/\s+/);return{processId:n[0],cmd:n[1]||"",args:n.slice(2),envs:{}}})}async connect(e,t){throw new Error("Modal does not support connecting to existing processes")}async sendStdin(e,t){throw new Error("Modal does not support sendStdin by process ID")}async kill(e){return await(await this.sandbox.exec(["kill","-9",e],{timeoutMs:1e4})).wait()===0}async accumulateStreams(e,t,n){let r="",a="",i=[];return i.push((async()=>{try{for await(let s of e.stdout){let o=typeof s=="string"?s:new TextDecoder().decode(s);r+=o,t?.(o)}}catch{}})()),i.push((async()=>{try{for await(let s of e.stderr){let o=typeof s=="string"?s:new TextDecoder().decode(s);a+=o,n?.(o)}}catch{}})()),await Promise.all(i),{stdout:r,stderr:a}}},TKe=class{constructor(e,t){this.sandbox=e,this.user=t}async chownToUser(e,t=!1){if(this.user==="root")return;let n=t?["chown","-R",`${this.user}:${this.user}`,e]:["chown",`${this.user}:${this.user}`,e];await(await this.sandbox.exec(n,{timeoutMs:t?3e4:1e4})).wait()}async writeStdinChunked(e,t){for(let n=0;n<t.length;n+=gO)await e.writeBytes(t.subarray(n,n+gO))}async writeStdinCoalesced(e,t){let n=[],r=0,a=async()=>{if(r===0)return;let i=n.length===1?n[0]:Buffer.concat(n,r);n=[],r=0,await this.writeStdinChunked(e,i)};for await(let i of t)n.push(i),r+=i.length,r>=gO&&await a();await a()}async read(e){let t=await this.sandbox.exec(["cat",e],{timeoutMs:3e5,mode:"binary"}),n=await t.wait();if(n!==0){let a=await t.stderr.readText();throw new Error(`Failed to read file ${e}: ${a||`exit code ${n}`}`)}let r=await t.stdout.readBytes();if(!r.includes(0))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r)}catch{}return r}async write(e,t){let n=this.toBuffer(t),r=e.substring(0,e.lastIndexOf("/"));r&&await this.makeDir(r);let a=e.replace(/'/g,"'\\''"),i=await this.sandbox.exec(["bash","-c",`cat > '${a}'`],{mode:"binary"});await this.writeStdinChunked(i.stdin,new Uint8Array(n)),await i.stdin.getWriter().close(),await i.wait(),await this.chownToUser(e)}async writeBatch(e){let t=(0,dKe.pack)(),n=new Set;for(let a of e){let i=this.toBuffer(a.data),s=a.path.startsWith("/")?a.path.slice(1):a.path;t.entry({name:s},i);let o=a.path.substring(0,a.path.lastIndexOf("/"));o&&n.add(o)}t.finalize();let r=await this.sandbox.exec(["tar","-xf","-","-C","/"],{mode:"binary"});if(await this.writeStdinCoalesced(r.stdin,t),await r.stdin.getWriter().close(),await r.wait(),n.size>0){let a=Array.from(n),i=new Set(a.map(s=>s.split("/").slice(0,4).join("/")));for(let s of i)await this.chownToUser(s,!0)}}async makeDir(e){await(await this.sandbox.exec(["mkdir","-p",e],{timeoutMs:1e4})).wait(),await this.chownToUser(e,!0)}async exists(e){return await(await this.sandbox.exec(["test","-e",e],{timeoutMs:1e4})).wait()===0}async list(e){let t=e.replace(/'/g,"'\\''"),n=await this.sandbox.exec(["bash","-c",`ls -la '${t}' | tail -n +2`],{timeoutMs:3e4});await n.wait();let r=await n.stdout.readText(),a=[];for(let i of r.trim().split(`
255
255
  `)){if(!i)continue;let s=i.split(/\s+/);if(s.length<9)continue;let o=s[0],c=s.slice(8).join(" ");c==="."||c===".."||a.push({name:c,path:e.endsWith("/")?`${e}${c}`:`${e}/${c}`,type:o.startsWith("d")?"dir":"file"})}return a}async remove(e){await(await this.sandbox.exec(["rm","-rf",e],{timeoutMs:3e4})).wait()}async rename(e,t){await(await this.sandbox.exec(["mv",e,t],{timeoutMs:3e4})).wait()}async readStream(e){return(await this.sandbox.exec(["cat",e],{timeoutMs:3e5,mode:"binary"})).stdout}async writeStream(e,t){let n=e.substring(0,e.lastIndexOf("/"));n&&await this.makeDir(n);let r=e.replace(/'/g,"'\\''"),a=await this.sandbox.exec(["bash","-c",`cat > '${r}'`],{mode:"binary"});await this.writeStdinCoalesced(a.stdin,L7t(t)),await a.stdin.getWriter().close(),await a.wait(),await this.chownToUser(e)}async writeFromPath(e,t){let{createReadStream:n}=await import("fs"),{Readable:r}=await import("stream"),a=r.toWeb(n(t,{highWaterMark:gO}));await this.writeStream(e,a)}async uploadUrl(e,t){throw new Error("Modal does not support pre-signed upload URLs")}async downloadUrl(e,t){throw new Error("Modal does not support pre-signed download URLs")}async watchDir(e,t,n){throw new Error("Modal does not support watchDir")}toBuffer(e){if(typeof e=="string")return Buffer.from(e,"utf-8");if(e instanceof Buffer)return e;if(e instanceof ArrayBuffer||e instanceof Uint8Array)return Buffer.from(e);throw new Error(`Unsupported data type: ${typeof e}`)}},uKe=class{constructor(e,t,n){this.sandbox=e,this.commands=new EKe(e,n),this.files=new TKe(e,n),this.image=t}commands;files;image;get sandboxId(){return this.sandbox.sandboxId}async getHost(e){let t=(await this.sandbox.tunnels())[e];if(!t)throw new Error(`No tunnel found for port ${e}`);return t.url}async isRunning(){try{return await this.sandbox.poll()===null}catch{return!1}}async getInfo(){let e=await this.sandbox.getTags();return pZ(this.sandbox.sandboxId,e,this.image)}async updateNetwork(e){await this.sandbox.updateNetworkPolicy(eB(e))}async kill(){try{await this.sandbox.terminate()}catch{await new Promise(e=>setTimeout(e,500)),await this.sandbox.terminate()}}async pause(){throw new Error("Modal does not support pause/resume. Persist progress with Evolve checkpoints and resume in a fresh sandbox, or use kill() to terminate.")}},hZ=class{providerType="modal";name="Modal";supportsBootCommand=!0;supportsVolumes=!0;client;appName;defaultTimeoutMs;imageName;imageSecretName;_app;sandboxUsers=new Map;constructor(e){!e.endpoint&&process.env.MODAL_SERVER_URL?.startsWith("unix:")?process.env.MODAL_SERVER_URL="https://api.modal.com:443":e.endpoint&&(process.env.MODAL_SERVER_URL=e.endpoint),this.client=new zYe({tokenId:e.tokenId,tokenSecret:e.tokenSecret}),this.appName=e.appName??"evolve-sandbox",this.defaultTimeoutMs=e.defaultTimeoutMs??36e5,this.imageName=e.imageName??`evolve-all-${ZU}`,this.imageSecretName=e.imageSecretName}async getApp(){return this._app||(this._app=await this.client.apps.fromName(this.appName,{createIfMissing:!0})),this._app}async resolveImage(e){let t=xKe(e);if(t==="registry"){let r=this.imageSecretName?await this.client.secrets.fromName(this.imageSecretName):void 0;return this.client.images.fromRegistry(e,r)}if(!this.imageSecretName)throw new Error(`Private registry image "${e}" requires config.imageSecretName \u2014 the name of a Modal Secret holding registry credentials (AWS ECR: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION with read-only ECR IAM). Create one at https://modal.com/secrets`);let n=t==="aws-ecr"?await this.client.secrets.fromName(this.imageSecretName,{requiredKeys:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"]}):await this.client.secrets.fromName(this.imageSecretName);return t==="aws-ecr"?this.client.images.fromAwsEcr(e,n):this.client.images.fromGcpArtifactRegistry(e,n)}async resolveAndBuildImage(e){let t=fKe[e]??e;if(!/[/:@]/.test(t))try{return{tag:t,image:await this.client.images.fromName(t)}}catch(a){if(!(a instanceof Or))throw a}let n=await this.getApp(),r=await this.resolveImage(t);return{tag:t,image:await r.build(n)}}async publishImageAs(e,t){if(!e.trim())throw new Error("publishImageAs requires a non-empty alias to publish under");let{image:n}=await this.resolveAndBuildImage(t||this.imageName);return await n.publish(e),e}async prepareImage(e){await this.resolveAndBuildImage(e||this.imageName)}async create(e){let t=e.timeoutMs??this.defaultTimeoutMs;gKe(t);let n=yKe(e.idleTimeoutMs),r=bKe(e.bootCommand),a=SKe(e.volumes);for(let b of e.phaseNetworkPolicies??[])eB(b);let i=IKe(e.network,e.phaseNetworkPolicies)?eB(e.network):fZ(e.network),s=_Ke(e.resources),o=e.user??lKe,c=await this.getApp(),{tag:l,image:u}=await this.resolveAndBuildImage(e.image||this.imageName),d=await this.resolveVolumes(a),f=e.envs?Object.fromEntries(Object.entries(e.envs).filter(([,b])=>b!=null)):void 0,p=f&&Object.keys(f).length>0?f:void 0,m={...e.metadata,[pKe]:l,[hKe]:new Date().toISOString()},y=await this.client.sandboxes.create(c,u,{cpu:s.cpu,memoryMiB:s.memoryMiB,...s.gpu!==void 0?{gpu:s.gpu}:{},timeoutMs:t,...n,...r,workdir:e.workingDirectory,env:p,tags:m,...i,...d!==void 0?{volumes:d}:{}});return e.workingDirectory&&o!=="root"&&await(await y.exec(["chown","-R",`${o}:${o}`,e.workingDirectory],{timeoutMs:3e4})).wait(),this.sandboxUsers.set(y.sandboxId,o),new uKe(y,l,o)}async resolveVolumes(e){if(e.length===0)return;let t={};for(let n of e){let r;try{r=await this.client.volumes.fromName(n.name,{createIfMissing:n.createIfMissing})}catch(a){let i=a instanceof Error?a.message:String(a),s=a instanceof Or||a instanceof Error&&a.name==="NotFoundError";throw new QU(s?"not-found":"resolve-failed",n.mountPath,n.name,s?`Modal Volume "${n.name}" (to mount at ${n.mountPath}) does not exist and createIfMissing was not set: ${i}`:`Modal Volume "${n.name}" (to mount at ${n.mountPath}) could not be resolved: ${i}`,a)}t[n.mountPath]=r.withMountOptions({readOnly:n.readOnly})}return t}async connect(e,t){let n=await this.client.sandboxes.fromId(e),r=this.sandboxUsers.get(e)??lKe;return new uKe(n,void 0,r)}async list(e){let t=await this.walk(e);if(t.error&&!t.stoppedAtLimit)throw new Error(t.error);return t.sandboxes}async listAll(e){let{stoppedAtLimit:t,...n}=await this.walk(e);return n}async walk(e){if(e?.state&&!e.state.includes("running"))return{sandboxes:[],complete:!0,pagesFetched:0,stoppedAtLimit:!1};let t;try{t=await this.getApp()}catch(n){return{sandboxes:[],complete:!1,pagesFetched:0,stoppedAtLimit:!1,error:`sandbox list failed: ${n instanceof Error?n.message:String(n)}`}}return kKe(()=>this.client.sandboxes.list({appId:t.appId,tags:e?.metadata}),e?.limit)}async listSandboxIds(){let e=new Set;try{let t=await this.getApp();for await(let n of this.client.sandboxes.list({appId:t.appId}))e.add(n.sandboxId);return{ids:e,complete:!0}}catch{return{ids:new Set,complete:!1}}}};W7t=oZ,j7t=fKe,Y7t=fZ,K7t=eB,X7t=IKe,Z7t=_Ke,Q7t=xKe,e5t=pZ,t5t=kKe,n5t=gKe,r5t=yKe,i5t=bKe,a5t=SKe});var UKe={};Ju(UKe,{MAX_INLINE_ARCHIVE_BYTES:()=>DKe,crc32Fallback:()=>NKe,extractTarGz:()=>g5t,shouldStore:()=>CKe,tarGzTopLevelName:()=>y5t,tarGzipDirectory:()=>m5t,tarGzipDirectoryToFile:()=>MKe});async function o5t(e){let t=[],n=async r=>{let a=r===""?e:(0,Mp.join)(e,r),i=await(0,Ya.readdir)(a,{withFileTypes:!0});i.sort((s,o)=>s.name<o.name?-1:s.name>o.name?1:0);for(let s of i){if(s5t.has(s.name))continue;let o=r===""?s.name:`${r}/${s.name}`,c=(0,Mp.join)(a,s.name),l=await(0,Ya.lstat)(c);l.isSymbolicLink()||(l.isDirectory()?await n(o):l.isFile()&&t.push({rel:o,abs:c,mode:l.mode&73?493:420,size:l.size}))}};return await n(""),t.sort((r,a)=>r.rel<a.rel?-1:r.rel>a.rel?1:0)}async function CKe(e,t){if(t<c5t)return!1;let n=await(0,Ya.open)(e,"r"),r;try{let a=Buffer.allocUnsafe(AKe),{bytesRead:i}=await n.read(a,0,AKe,0);r=a.subarray(0,i)}finally{await n.close()}return r.length===0?!1:(0,nf.deflateRawSync)(r,{level:1}).length*20>=r.length*19}function NKe(e,t=0){let n=~t;for(let r=0;r<e.length;r++)n=d5t[(n^e[r])&255]^n>>>8;return~n>>>0}async function h5t(e){let t=Symbol("pending"),n=await Promise.race([e,Promise.resolve(t)]);return n===t?null:n}async function MKe(e,t){let n=await o5t(e),r=(0,yO.pack)(),a=(0,xv.createWriteStream)(t);a.on("error",()=>{}),r.on("error",()=>{});let i=new p5t(a),s=r[Symbol.asyncIterator](),o=null,c=()=>o??=s.next();try{for(let{rel:l,abs:u,mode:d,size:f}of n){await i.setStored(await CKe(u,f));let p=r.entry({name:l,size:f,mode:d,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"}),m=(0,Iv.pipeline)((0,xv.createReadStream)(u),p),y=!1,b=null;for(m.then(()=>{},()=>{}).then(()=>{y=!0,b?.(PKe)});;){if(!y){let S=await new Promise((w,I)=>{b=w,c().then(w,I)});if(b=null,S===PKe)continue;if(o=null,S.done)break;await i.write(S.value);continue}await new Promise(S=>setImmediate(S));let v=await h5t(c());if(v===null||(o=null,v.done))break;await i.write(v.value)}await m}for(r.finalize();;){let l=await c();if(o=null,l.done)break;await i.write(l.value)}await i.close(),a.end(),await(0,Iv.finished)(a)}catch(l){throw o?.catch(()=>{}),r.destroy(),a.destroy(),l}}async function m5t(e,t=DKe){let n=await(0,Ya.mkdtemp)((0,Mp.join)((0,RKe.tmpdir)(),"evolve-tar-"));try{let r=(0,Mp.join)(n,"archive.tar.gz");await MKe(e,r);let{size:a}=await(0,Ya.stat)(r);if(a>t)throw new Error(`directory ${e} tars to ${a} bytes compressed \u2014 over the ${t}-byte cap for in-memory archives. Only the sandbox skill mount uses this path; a skill folder this large is not mountable.`);return await(0,Ya.readFile)(r)}finally{await(0,Ya.rm)(n,{recursive:!0,force:!0})}}async function g5t(e,t,n){let r=(0,yO.extract)(),a=[],i=(async()=>{for await(let s of r){let o=s.header.name,c=o.split("/").filter(u=>u!==""&&u!==".");if(o.startsWith("/")||o.includes("\\")||c.length===0||c.some(u=>u===".."))throw new Error(`refusing to extract "${o}": the path escapes the target directory`);if(c[0]!==n)throw new Error(`refusing to extract "${o}": entry outside ${n}/`);if(s.header.type==="directory"){await(0,Ya.mkdir)((0,Mp.join)(t,...c),{recursive:!0}),s.resume();continue}if(s.header.type!=="file")throw new Error(`refusing to extract "${o}": unsupported entry type "${s.header.type}"`);let l=(0,Mp.join)(t,...c);await(0,Ya.mkdir)((0,Mp.dirname)(l),{recursive:!0}),await(0,Iv.pipeline)(s,(0,xv.createWriteStream)(l)),a.push(c.join("/"))}})();try{await Promise.all([(0,Iv.pipeline)((0,xv.createReadStream)(e),(0,nf.createGunzip)(),r),i])}catch(s){throw r.destroy(),s}return a}async function y5t(e){let t=(0,yO.extract)(),n=null,r=(async()=>{for await(let a of t){let i=a.header.name,s=i.split("/").filter(o=>o!==""&&o!==".");if(i.startsWith("/")||i.includes("\\")||s.length===0||s.some(o=>o===".."))throw new Error(`refusing to extract "${i}": the path escapes the target directory`);if(n===null)n=s[0];else if(s[0]!==n)throw new Error(`refusing to extract "${i}": the archive holds more than one top-level directory (${n}/)`);a.resume()}})();try{await Promise.all([(0,Iv.pipeline)((0,xv.createReadStream)(e),(0,nf.createGunzip)(),t),r])}catch(a){throw t.destroy(),a}if(n===null)throw new Error("refusing to extract: the archive holds no entries");return n}var nf,xv,Ya,RKe,Mp,Iv,yO,s5t,c5t,AKe,l5t,u5t,mZ,d5t,f5t,p5t,PKe,DKe,BKe=Q(()=>{"use strict";nf=Ve(require("zlib"),1),xv=require("fs"),Ya=require("fs/promises"),RKe=require("os"),Mp=require("path"),Iv=require("stream/promises"),yO=Ve(aZ(),1),s5t=new Set([".git",".DS_Store",".venv"]);c5t=64*1024,AKe=128*1024,l5t=65535,u5t=1024*1024,mZ=32*1024;d5t=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n}return e})(),f5t=nf.default.crc32??NKe,p5t=class rB{constructor(t){this.sink=t}static HEADER=Buffer.from([31,139,8,0,0,0,0,0,0,255]);static FINAL_BLOCK=Buffer.from([1,0,0,255,255]);crc=0;plainLength=0;held=[];heldBytes=0;window=null;stored=!1;started=!1;async setStored(t){t!==this.stored&&(await this.drainHeld(!0),this.stored=t)}async write(t){this.started||(this.started=!0,await this.out(rB.HEADER)),this.held.push(t),this.heldBytes+=t.length,await this.drainHeld(!1)}async close(){this.started||(this.started=!0,await this.out(rB.HEADER)),await this.drainHeld(!0),await this.out(rB.FINAL_BLOCK);let t=Buffer.allocUnsafe(8);t.writeUInt32LE(this.crc>>>0,0),t.writeUInt32LE(this.plainLength%4294967296,4),await this.out(t)}async drainHeld(t){let n=this.stored?l5t:u5t;for(;this.heldBytes>=n||t&&this.heldBytes>0;){let r=this.held.length===1?this.held[0]:Buffer.concat(this.held,this.heldBytes),a=Math.min(n,r.length),i=r.subarray(a);this.held=i.length>0?[i]:[],this.heldBytes=i.length,await this.emitBlock(r.subarray(0,a))}}async emitBlock(t){if(this.crc=f5t(t,this.crc),this.plainLength+=t.length,this.stored){let n=Buffer.allocUnsafe(5+t.length);n[0]=0,n.writeUInt16LE(t.length,1),n.writeUInt16LE(t.length^65535,3),t.copy(n,5),await this.out(n)}else await this.out((0,nf.deflateRawSync)(t,{level:9,finishFlush:nf.constants.Z_SYNC_FLUSH,...this.window?{dictionary:this.window}:{}}));this.window=t.length>=mZ?Buffer.from(t.subarray(t.length-mZ)):this.window?Buffer.concat([this.window,t]).subarray(-mZ):Buffer.from(t)}out(t){return new Promise((n,r)=>{this.sink.write(t,a=>a==null?n():r(a))})}},PKe=Symbol("feed settled");DKe=256*1024*1024});var qKe={};Ju(qKe,{ManagedModalProvider:()=>_5t,ManagedModalWriteLimitError:()=>FKe,_testManagedModalSandbox:()=>w5t});function v5t(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof Uint8Array)return new Uint8Array(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw new Error(`Unsupported data type: ${typeof e}`)}function VKe(e){return{sandboxId:e.sandboxId,image:e.image??"",metadata:e.metadata??{},startedAt:e.startedAt??""}}var FKe,LKe,b5t,S5t,gZ,_5t,w5t,$Ke=Q(()=>{"use strict";FKe=class extends Error{bytes;constructor(e,t){super(`Managed Modal ${e} body is ${t} bytes; the managed door caps every request at 1048576 bytes (1 MiB) of wire bytes, base64 inflation included. Split the payload into smaller writes.`),this.name="ManagedModalWriteLimitError",this.bytes=t}};LKe=class{constructor(e){this.config=e}async request(e,t,n){let r=await fetch(`${this.config.baseUrl}${t}`,{...n,headers:{authorization:`Bearer ${this.config.apiKey}`,...n.headers??{}}});if(!r.ok){let a="";try{a=(await r.json())?.error??""}catch{}throw new Error(`Managed Modal ${e} failed (${r.status})${a?`: ${a}`:""}`)}return r}json(e){return{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}}},b5t=class{constructor(e,t){this.door=e,this.sandboxId=t}async run(e,t){let n=await this.door.request("exec",`/sandboxes/${encodeURIComponent(this.sandboxId)}/exec`,this.door.json({command:e,...t?.cwd?{cwd:t.cwd}:{},...t?.envs?{envs:t.envs}:{},...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}})),r="",a="",i,s=o=>{if(!o.trim())return;let c;try{c=JSON.parse(o)}catch{throw new Error(`Managed Modal exec stream carried a garbled record: ${o}`)}c.stream==="stdout"&&typeof c.data=="string"?(r+=c.data,t?.onStdout?.(c.data)):c.stream==="stderr"&&typeof c.data=="string"?(a+=c.data,t?.onStderr?.(c.data)):i=c};if(n.body){let o=n.body.getReader(),c=new TextDecoder,l="";for(;;){let{done:u,value:d}=await o.read();if(u)break;l+=c.decode(d,{stream:!0});let f;for(;(f=l.indexOf(`
256
256
  `))!==-1;)s(l.slice(0,f)),l=l.slice(f+1)}l+=c.decode(),s(l)}else for(let o of(await n.text()).split(`
@@ -500,7 +500,7 @@ async def list_checkpoints(
500
500
  await store.close()
501
501
 
502
502
 
503
- __version__ = '0.0.55.dev1310'
503
+ __version__ = '0.0.55.dev1348'
504
504
 
505
505
  __all__ = [
506
506
  # Main classes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: evolve-sdk
3
- Version: 0.0.55.dev1310
3
+ Version: 0.0.55.dev1348
4
4
  Summary: Pythonic SDK for multi-agent orchestration in E2B sandboxes
5
5
  Author-email: "Swarmlink, Inc." <brandomagnani@evolvingmachines.ai>
6
6
  License: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "evolve-sdk"
7
- version = "0.0.55.dev1310"
7
+ version = "0.0.55.dev1348"
8
8
  description = "Pythonic SDK for multi-agent orchestration in E2B sandboxes"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"